|
1 | 1 | // Copyright (c) .NET Foundation and contributors. All rights reserved. |
2 | 2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. |
3 | 3 |
|
4 | | -using System.Collections.Generic; |
5 | 4 | using System.CommandLine.Binding; |
6 | | -using System.CommandLine.Completions; |
7 | 5 | using System.CommandLine.Parsing; |
8 | 6 | using System.IO; |
9 | 7 |
|
@@ -179,12 +177,31 @@ public void SetDefaultValueFactory(Func<ArgumentResult, T> defaultValueFactory) |
179 | 177 | /// <returns>The configured argument.</returns> |
180 | 178 | public Argument<T> AcceptOnlyFromAmong(params string[] values) |
181 | 179 | { |
182 | | - AllowedValues?.Clear(); |
183 | | - AddAllowedValues(values); |
184 | | - CompletionSources.Clear(); |
185 | | - CompletionSources.Add(values); |
| 180 | + if (values is not null && values.Length > 0) |
| 181 | + { |
| 182 | + Validators.Clear(); |
| 183 | + Validators.Add(UnrecognizedArgumentError); |
| 184 | + CompletionSources.Clear(); |
| 185 | + CompletionSources.Add(values); |
| 186 | + } |
186 | 187 |
|
187 | 188 | return this; |
| 189 | + |
| 190 | + void UnrecognizedArgumentError(ArgumentResult argumentResult) |
| 191 | + { |
| 192 | + for (var i = 0; i < argumentResult.Tokens.Count; i++) |
| 193 | + { |
| 194 | + var token = argumentResult.Tokens[i]; |
| 195 | + |
| 196 | + if (token.Symbol is null || token.Symbol == this) |
| 197 | + { |
| 198 | + if (Array.IndexOf(values, token.Value) < 0) |
| 199 | + { |
| 200 | + argumentResult.ErrorMessage = argumentResult.LocalizationResources.UnrecognizedArgument(token.Value, values); |
| 201 | + } |
| 202 | + } |
| 203 | + } |
| 204 | + } |
188 | 205 | } |
189 | 206 |
|
190 | 207 | /// <summary> |
|
0 commit comments