How to tell if built-in help handler was called instead of user SetHandler?
I have a WPF application that I want to do some cleanup after the CommandLine invoke call, but I have no way of knowing if --help was invoked or one of my command line arguments was invoke.
...
var rc = rootCommand.SetHandler((context) => {
var result = context.ParseResults;
//do something...
}
rootCommand.Invoke(e.Args);
// OK... now I want to know... did SetHandler get called or was built in Help Handler called (myapp --help)...
if (help called) {
close app...
}
else {
do something else...
}
COuld you at least return a code that says that help was invoked?
If I save "ParseResult result" to a global variable... then it will be null if Help Handler is called instead? Is that the correct way of handling this?
CommandLineBuilderExtensions.UseHelp adds a help option and a middleware function that shows help if the help option was used. I can imagine a few ways to detect it:
- Find the help Option instance somehow. After invocation, check whether the help option was used, in the same way as the help middleware does. However, this is made more difficult because both CommandLineBuilder.HelpOption and class HelpOption are internal.
- Call a UseHelp method that takes an
Action<HelpContext> customizeparameter. If the delegate is called then presumably the help option was used. - Add your own middleware that executes after the help middleware. If the help option is used, then the help middleware does not call your middleware, and you can detect that. Directives like
[parse]can also prevent your middleware from being called, but perhaps that's even better for your purposes.
On the other hand, if you have only a root command and no subcommands, then you can just make the handler itself set a flag or even run the cleanups right there.
If the cleanup is only necessary when your command handler(s) have been invoked, wouldn't it make sense to let the command handlers themselves do the cleanup as last step of whatever actions they do? Or asked differently: What is it that forces you to do the cleanup outside the command handlers?
With #2071 :
ParseResult parseResult = rootCommand.Parse(args);
if (parseResult.Action is HelpAction)
{
}
else
{
}