Skip to content

Remove Argument.AllowedValues, use Validator to implement the logic #1959

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Dec 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/System.CommandLine.Tests/ParsingValidationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,34 @@ public void When_FromAmong_is_used_for_multiple_arguments_and_invalid_input_is_p
.Be(LocalizationResources.Instance.UnrecognizedArgument("not-key1", new[] { "key1", "key2" }));
}

[Fact]
public void When_FromAmong_is_used_multiple_times_only_the_most_recently_provided_values_are_taken_into_account()
{
Argument<string> argument = new("key");
argument.AcceptOnlyFromAmong("key1");

var command = new Command("set")
{
argument
};

var result = command.Parse("set key2");

result.Errors
.Should()
.ContainSingle()
.Which
.Message
.Should()
.Be(LocalizationResources.Instance.UnrecognizedArgument("key2", new[] { "key1" }));

argument.AcceptOnlyFromAmong("key2");

result = command.Parse("set key2");

result.Errors.Should().BeEmpty();
}

[Fact]
public void When_FromAmong_is_used_for_multiple_arguments_and_invalid_input_is_provided_for_the_second_one_then_the_error_is_informative()
{
Expand Down
12 changes: 0 additions & 12 deletions src/System.CommandLine/Argument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ protected Argument(string? name = null, string? description = null)
Description = description;
}

internal HashSet<string>? AllowedValues { get; private set; }

/// <summary>
/// Gets or sets the arity of the argument.
/// </summary>
Expand Down Expand Up @@ -127,16 +125,6 @@ private protected override string DefaultName

internal virtual bool HasCustomParser => false;

internal void AddAllowedValues(IReadOnlyList<string> values)
{
if (AllowedValues is null)
{
AllowedValues = new HashSet<string>();
}

AllowedValues.UnionWith(values);
}

/// <inheritdoc />
public override IEnumerable<CompletionItem> GetCompletions(CompletionContext context)
{
Expand Down
29 changes: 23 additions & 6 deletions src/System.CommandLine/Argument{T}.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Generic;
using System.CommandLine.Binding;
using System.CommandLine.Completions;
using System.CommandLine.Parsing;
using System.IO;

Expand Down Expand Up @@ -179,12 +177,31 @@ public void SetDefaultValueFactory(Func<ArgumentResult, T> defaultValueFactory)
/// <returns>The configured argument.</returns>
public Argument<T> AcceptOnlyFromAmong(params string[] values)
{
AllowedValues?.Clear();
AddAllowedValues(values);
CompletionSources.Clear();
CompletionSources.Add(values);
if (values is not null && values.Length > 0)
{
Validators.Clear();
Validators.Add(UnrecognizedArgumentError);
CompletionSources.Clear();
CompletionSources.Add(values);
}

return this;

void UnrecognizedArgumentError(ArgumentResult argumentResult)
{
for (var i = 0; i < argumentResult.Tokens.Count; i++)
{
var token = argumentResult.Tokens[i];

if (token.Symbol is null || token.Symbol == this)
{
if (Array.IndexOf(values, token.Value) < 0)
{
argumentResult.ErrorMessage = argumentResult.LocalizationResources.UnrecognizedArgument(token.Value, values);
}
}
}
}
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion src/System.CommandLine/Parsing/ArgumentResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public void OnlyTake(int numberOfTokens)

if (!string.IsNullOrWhiteSpace(ErrorMessage))
{
return new ParseError(ErrorMessage!, this);
return new ParseError(ErrorMessage!, Parent is OptionResult option ? option : this);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change is not obvious. Before this change, the SymbolResult of ParseError for an Argument with unmatched tokens owned by an Option was the OptionResult, not ArgumentResult:

argumentResult.Parent?.UnrecognizedArgumentError(argument) ??

but this was true only "non-custom errors" (user defined, coming from validators):

argumentResult.CustomError(argument);

Without this change, one test was failing:

  Failed System.CommandLine.Tests.ParseDiagramTests.Parse_result_diagram_displays_unmatched_tokens [283 ms]
  Error Message:
   Expected string to be
"[ command ![ -x <ar> ] ]", but
"[ command [ -x !<ar> ] ]" differs near "[ -" (index 10).

Since we hide the Option.Argument from the user, I think it's reasonable to use the OptionResult in such cases for all validations.

}
}

Expand Down
4 changes: 1 addition & 3 deletions src/System.CommandLine/Parsing/ParseResultVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -506,9 +506,7 @@ private void ValidateAndConvertArgumentResult(ArgumentResult argumentResult)
{
var argument = argumentResult.Argument;

var parseError =
argumentResult.Parent?.UnrecognizedArgumentError(argument) ??
argumentResult.CustomError(argument);
var parseError = argumentResult.CustomError(argument);

if (parseError is { })
{
Expand Down
24 changes: 0 additions & 24 deletions src/System.CommandLine/Parsing/SymbolResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,29 +185,5 @@ internal ArgumentResult GetOrCreateDefaultArgumentResult(Argument argument) =>

/// <inheritdoc/>
public override string ToString() => $"{GetType().Name}: {this.Token()} {string.Join(" ", Tokens.Select(t => t.Value))}";

internal ParseError? UnrecognizedArgumentError(Argument argument)
{
if (argument.AllowedValues?.Count > 0 &&
Tokens.Count > 0)
{
for (var i = 0; i < Tokens.Count; i++)
{
var token = Tokens[i];

if (token.Symbol is null || token.Symbol == argument)
{
if (!argument.AllowedValues.Contains(token.Value))
{
return new ParseError(
LocalizationResources.UnrecognizedArgument(token.Value, argument.AllowedValues),
this);
}
}
}
}

return null;
}
}
}