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

How to tell if built-in help handler was called instead of user SetHandler?

Open wm2015email opened this issue 3 years ago • 4 comments

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...
}

wm2015email avatar Aug 07 '22 15:08 wm2015email

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?

wm2015email avatar Aug 07 '22 15:08 wm2015email

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> customize parameter. 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.

KalleOlaviNiemitalo avatar Aug 07 '22 17:08 KalleOlaviNiemitalo

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.

KalleOlaviNiemitalo avatar Aug 07 '22 17:08 KalleOlaviNiemitalo

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?

elgonzo avatar Aug 07 '22 19:08 elgonzo

With #2071 :

ParseResult parseResult = rootCommand.Parse(args);
if (parseResult.Action is HelpAction)
{

}
else
{

}

adamsitnik avatar Mar 28 '23 08:03 adamsitnik