command-line-api icon indicating copy to clipboard operation
command-line-api copied to clipboard

Is there a built in validation for mutually exclusive options?

Open TPIvan opened this issue 3 years ago • 1 comments

I read the issue Mutually exclusive options #381 and from the discussion I have concluded that an API for mutually exclusive arguments will be done, but I cannot find any. Is my conclusion correct or should I write my own validation?

TPIvan avatar Jul 26 '22 09:07 TPIvan

It is possible, however the API is awkward. The previous code link in #381 is now referencing the wrong line number. The correct example test is here: https://github.com/dotnet/command-line-api/blob/1d98a75ce2b109a2d7c18d81fac3f279be095e4e/src/System.CommandLine.Tests/ParsingValidationTests.cs#L246-L272

Keboo avatar Sep 18 '22 05:09 Keboo

@Keboo Can you provide an example of an option that takes a value? Also, when the option is optional with a default value..

Overall, I think this is an understatement to say that the API is awkward. This "command validator" should provide easy access to parsed options, the same way as you get the options in the program. E.g. can you provide an invocation context to the validator maybe? Then we can get the actual option values.

chhh avatar Nov 04 '22 00:11 chhh

You can get option values and other information from within a validator:

var optionA = new Option<int>("-a");
var optionB = new Option<int>("-b");

var command = new RootCommand
{
    optionA,
    optionB,
};

command.AddValidator(result => 
{
    // get pasrsed values...
    var optionAValue = result.GetValueForOption(optionA);
    var optionBValue = result.GetValueForOption(optionB);

    // check if a default value was used instead of a value being provided by the user...
    var defaultValueWasUsed = result.FindResultFor(optionA).IsImplicit;
});

Note that FindResultFor will return null if there's no default value for the option and the user didn't specify anything.

jonsequitur avatar Nov 04 '22 01:11 jonsequitur

Thank you @jonsequitur , this works!

chhh avatar Nov 04 '22 17:11 chhh