2

I know how to tell if an option that I've created was used and how to retrieve its value:

// Add the option:
var outputOption = new Option<string>(new[] { "-o", "--output" }, "Path to desired output folder.");
var rootCommand = new RootCommand("File Builder App");
rootCommand.AddOption(outputOption);

// See if the app was launched with the option and access its value:
rootCommand.SetHandler(o => Console.WriteLine(o is not null), outputOption);

However, there's the --help/-h/-? option that System.CommandLine adds automatically. Is there a way to tell it has been provided?

hribayz
  • 139
  • 9
  • In my case, an acceptable workaround would be to configure `System.CommandLine` to exit the app after the help is displayed, but I'm still interested to learn how to consume the `--help` option when the app is running. – hribayz Mar 27 '23 at 09:31
  • 1
    Why do you need to know that user used `help`? – Peter Csala Mar 27 '23 at 10:17
  • 1
    @PeterCsala Out of the box the app displays the help and continues. I want to do some cleanup and exit if the help was used. I think posix tools behave like that anyway so that's what the user would expect. But matching the arg manually from raw args is surprisingly cumbersome. – hribayz Mar 27 '23 at 10:43
  • `--help` exits too. `Invoke` will return without calling the handler if `--help` is used. That's already what the user expects. What kind of cleanup do you want to perform that can't be done after `Invoke` returns? By default `--help` only displays the descriptions, there's nothing to clean up – Panagiotis Kanavos May 24 '23 at 10:33

1 Answers1

0

Best I could muster so far was to use CommandLineBuilder(rootCommand) with UseHelp:

bool helpShown = false;

var parser = new CommandLineBuilder(rootCommand)
  .UseDefaults()
  .UseHelp(ctx => helpShown = true)
  .Build();

parser.Invoke(args);

if (helpShown)
{
   // do something when help was shown
}
lycandroid
  • 181
  • 10