System.CommandLine mutally exclusive options

265 views Asked by At

I am using System.CommandLine and I wanted to create a mutually exclusive option. The user either has to use --ipAddresses and pass in list of one or more IP addresses OR use --ipAddressesCsv and pass in a file path containing the CSV file. I am wondering if its something possible to do with System.CommandLine.

This is my setup:

var ipAddressesOption = new Option<IEnumerable<IPAddress>>("--ipAddresses")
{
    Description = "The IP addresses",
    IsRequired = true,
    Arity = ArgumentArity.OneOrMore,
    AllowMultipleArgumentsPerToken = true,
};

var ipAddressesCsvOption = new Option<FileInfo?>("--ipAddressesCsv")
{
    Description = "CSV containing the IP addresses",
    IsRequired = true,
    Arity = ArgumentArity.ZeroOrOne,
    AllowMultipleArgumentsPerToken = false,
};
1

There are 1 answers

0
shingo On BEST ANSWER

Their suggestion in this issue is to use a validator, something like this:

command.AddValidator(result =>
{
    if (result.Children.Count(s => s.Symbol == ipAddressesOption ||
                                   s.Symbol == ipAddressesCsvOption) != 1)
        result.ErrorMessage =
                  "You must use either --ipAddresses or --ipAddressesCsv";
});