Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
43 changes: 25 additions & 18 deletions src/System.CommandLine/Argument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,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 @@ -105,14 +103,15 @@ private protected override string DefaultName
}
}

internal List<Action<ArgumentResult>> Validators => _validators ??= new ();
internal IReadOnlyList<Action<ArgumentResult>> Validators
=> _validators is null ? Array.Empty<Action<ArgumentResult>>() : _validators;

/// <summary>
/// Adds a custom validator to the argument. Validators can be used
/// to provide custom errors based on user input.
/// </summary>
/// <param name="validate">The action to validate the parsed argument.</param>
public void AddValidator(Action<ArgumentResult> validate) => Validators.Add(validate);
public void AddValidator(Action<ArgumentResult> validate) => (_validators ??= new()).Add(validate);
Copy link
Member

Choose a reason for hiding this comment

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

There are other places that call Validator.Add, which would now add the Action to the Array.Empty<Action>.

Validators.Add(validate);

option.Argument.Validators.Add(Validate.FileExists);

Copy link
Member

Choose a reason for hiding this comment

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

Now that #1966 is merged, this shoud go on Argument<T>.


/// <summary>
/// Gets the default value for the argument.
Expand Down Expand Up @@ -179,16 +178,6 @@ public void SetDefaultValueFactory(Func<ArgumentResult, object?> defaultValueFac
Arity = ArgumentArity.Zero
};

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 Expand Up @@ -244,12 +233,30 @@ public Argument AddCompletions(Func<CompletionContext, IEnumerable<CompletionIte
/// <returns>The configured argument.</returns>
public Argument AcceptOnlyFromAmong(params string[] values)
{
AllowedValues?.Clear();
AddAllowedValues(values);
Completions.Clear();
Completions.Add(values);
if (values is not null && values.Length > 0)
{
AddValidator(UnrecognizedArgumentError);
Completions.Clear();
Completions.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 (!values.Contains(token.Value))
{
argumentResult.ErrorMessage = argumentResult.LocalizationResources.UnrecognizedArgument(token.Value, values);
}
}
}
}
}

/// <summary>
Expand Down
5 changes: 1 addition & 4 deletions src/System.CommandLine/Option.cs
Original file line number Diff line number Diff line change
Expand Up @@ -242,10 +242,7 @@ public override IEnumerable<CompletionItem> GetCompletions(CompletionContext con
/// <returns>The configured option.</returns>
public Option AcceptOnlyFromAmong(params string[] values)
{
Argument.AllowedValues?.Clear();
Argument.AddAllowedValues(values);
Argument.Completions.Clear();
Argument.Completions.Add(values);
Argument.AcceptOnlyFromAmong(values);

return this;
}
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 @@ -505,9 +505,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;
}
}
}