dotnet / dotnet/command-line-api

Option of collection type with ArgumentArity.MaximumNumberOfValues = 1 parses incorrectly

Open
#1,970 1 comment 0 reactions 0 assignees View on GitHub
Area-Parser and Binder bug
Dominant language
C#
Stars
3.7k
Forks
428
PR merge metrics
No merged PRs in 30d

Description

System.CommandLine version: 2.0.0-beta6.25320.118

Parsing fails in the (rather) unusual circumstance of a collection-type option (like _Option\\>_) with an arity of _ExactlyOne_ or _ZeroOrOne_.

```C#
var opt = new Option>("--option1")
{
Arity = ArgumentArity.ZeroOrOne // or ArgumentArity.ExactlyOne
};

var rootCmd = new RootCommand
{
opt
};

var parseResult = rootCmd.Parse("--option1 str1");
var val = parseResult.GetValue(opt);
```

### Expected parse result
- ParseResult: `[ ConsoleApp1 [ --option1 ] ]`
- `parseResult.GetValue(opt)` returns a List\ instance with a single "str1" item in it.


### Actual result
- ParseResult: `[ ConsoleApp1 ![ --option1 ] ]` (note the exclamation mark)
- `parseResult.GetValue(opt)` throws `InvalidOperationException`

Exception message:
```
Cannot parse argument 'str1' for option '--option1' as expected type 'System.Collections.Generic.List`1[System.String]'.
```
Stack trace:
```
at System.CommandLine.Binding.ArgumentConverter.GetValueOrDefault[T](ArgumentConversionResult result)
at System.CommandLine.Parsing.OptionResult.GetValueOrDefault[T]()
at System.CommandLine.Parsing.SymbolResult.GetValue[T](Option`1 option)
at System.CommandLine.ParseResult.GetValue[T](Option`1 option)
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.