|
4 | 4 | using System.Collections.Generic; |
5 | 5 | using System.CommandLine.Parsing; |
6 | 6 | using System.IO; |
| 7 | +using System.Linq; |
7 | 8 |
|
8 | 9 | namespace System.CommandLine |
9 | 10 | { |
@@ -158,6 +159,44 @@ void UnrecognizedArgumentError(ArgumentResult argumentResult) |
158 | 159 | } |
159 | 160 | } |
160 | 161 |
|
| 162 | + /// <summary> |
| 163 | + /// Configures the argument to accept only the specified values using the specified comparer, and to suggest them as command line completions. |
| 164 | + /// </summary> |
| 165 | + /// <param name="argument">The argument to configure.</param> |
| 166 | + /// <param name="comparer">The comparer used to match argument values against the allowed values.</param> |
| 167 | + /// <param name="values">The values that are allowed for the argument.</param> |
| 168 | + public static Argument<T> AcceptOnlyFromAmong<T>( |
| 169 | + this Argument<T> argument, |
| 170 | + StringComparer comparer, |
| 171 | + params string[] values) |
| 172 | + { |
| 173 | + if (values is not null && values.Length > 0) |
| 174 | + { |
| 175 | + argument.Validators.Clear(); |
| 176 | + argument.Validators.Add(UnrecognizedArgumentError); |
| 177 | + argument.CompletionSources.Clear(); |
| 178 | + argument.CompletionSources.Add(values); |
| 179 | + } |
| 180 | + |
| 181 | + return argument; |
| 182 | + |
| 183 | + void UnrecognizedArgumentError(ArgumentResult argumentResult) |
| 184 | + { |
| 185 | + for (var i = 0; i < argumentResult.Tokens.Count; i++) |
| 186 | + { |
| 187 | + var token = argumentResult.Tokens[i]; |
| 188 | + |
| 189 | + if (token.Symbol is null || token.Symbol == argument) |
| 190 | + { |
| 191 | + if (!values.Contains(token.Value, comparer)) |
| 192 | + { |
| 193 | + argumentResult.AddError(LocalizationResources.UnrecognizedArgument(token.Value, values)); |
| 194 | + } |
| 195 | + } |
| 196 | + } |
| 197 | + } |
| 198 | + } |
| 199 | + |
161 | 200 | private static void FileOrDirectoryExists<T>(ArgumentResult result) |
162 | 201 | where T : FileSystemInfo |
163 | 202 | { |
|
0 commit comments