dotnet / dotnet/command-line-api

No way to distinguish between ParseArgument invoked for user-supplied input and default value

Open
#1,287 8 comments 0 reactions 0 assignees View on GitHub
waiting-on-feedback
Dominant language
C#
Stars
3.7k
Forks
428
PR merge metrics
No merged PRs in 30d

Description

When using an option that has a custom parser with `isDefault` set to true, the custom parser cannot distinguish between being invoked to provide a default value and being invoked to parse input that has no tokens.

Example:
```csharp
private static IEnumerable Formats { get; } = new List
{
"foo",
"bar"
};

var option = new Option>("--formats",
parseArgument: ParseFormats,
isDefault: true,
description: "Narrows the operation to process only files with these formats. Supported formats: "
+ string.Join(", ", Formats)));

private static List ParseFormats(ArgumentResult result)
{
var formats = result.Tokens.Select(t => t.Value).ToList();

var invalidFormats = formats.Where(t => !Formats.Contains(t));

if (invalidFormats.Any())
{
result.ErrorMessage = $"One or more formats are invalid: {string.Join(", ", invalidFormats)}";
}
//Not provided or no formats specified on the command line
else if (formats.Count == 0)
{
return Formats.ToList();
}

return formats;
}
```

(Formats cannot be an enum here because the list in the actual code is constructed from a list of objects providing a string property)

In this case the parser cannot constrain input to require one or more tokens because this will also be the case when getting a default value.

Some way to know when it's being invoked for a default value would be nice.

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.