Search code examples
c#.netsystem.commandline

How to exclude some enum values in System.CommandLine?


I have a System.CommandLine option like this (LogLevel is an enum):

    private static readonly Option<LogLevel> option = new(new[] { "--logLevel" })
    {
        Description = "The severity (log level)."
    };

The automatically generated help lists all the enum values as valid values for "--logLevel":

<Debug|Detailed|Error|Fatal|Info|Off|Silent|Warning>

But is it somehow possible to disallow some of them with System.CommandLine or even map strings on enum values (e.g. "W" is mapped to the enum value Warning)?


Solution

  • I found an answer in the Microsoft documentations:

    It works like this:

    var parser = new CommandLineBuilder(rootCommand)
            .UseDefaults()
            .UseHelp(ctx =>
            {
                ctx.HelpBuilder.CustomizeSymbol(foregroundColorOption,
                    firstColumnText: "--color <Black, White, Red, or Yellow>",
                    secondColumnText: "Specifies the foreground color. " +
                        "Choose a color that provides enough contrast " +
                        "with the background color. " +
                        "For example, a yellow foreground can't be read " +
                        "against a light mode background.");
            })
            .Build();
    
    await parser.InvokeAsync(args);
    

    foregroundColorOption is in this case the option and via firstColumnText, we can print whatever values of the enum we want to print.