Skip to content

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

@SamVanheer

Description

@SamVanheer

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:

private static IEnumerable<string> Formats { get; } = new List<string>
{
    "foo",
    "bar"
};

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

private static List<string> 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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions