dotnet / command-line-api

Command line parsing, invocation, and rendering of terminal output.
https://github.com/dotnet/command-line-api/wiki
MIT License
3.38k stars 381 forks source link

Is there a way to determine if the help option has been specified in the command line options programmatically? #1397

Open llu23 opened 3 years ago

llu23 commented 3 years ago

I could parse it with all the possible -h, --help, /? ect.. but wondering it there is already a way

jonsequitur commented 3 years ago

If help was requested, regardless of what the user passed on the command line, the following should work:

ParseResult.CommandResult.Children.GetByAlias("-h")

This assumes "-h" is a valid help alias. It's possible to customize the help aliases.

elgonzo commented 3 years ago

@jonsequitur

how would this be used in practice?

The following simple approach doesn't work

var parseResult = myRootCommand.Parse(args);
parseResult.CommandResult.Children.GetByAlias("-h");

because the Command.Parse extension methods don't set up the defaults as the CommmandBuilder.UseDefaults method would do. Thus the command won't have the help option, with the parser failing to identify any help alias: https://github.com/dotnet/command-line-api/blob/43be76901630aae866657dd5ec1978a5d48d5b09/src/System.CommandLine/CommandExtensions.cs#L58-L67

To me this feels like a bug, as i believe Command.Parse should operate with the same (internal) CommandBuilder/Parser configuration as Command.Invoke does.

(As a workaround / alternative solution one could "manually" create a CommandBuilder with defaults and obtain a parser from it; pretty much like the CommandExtensions.GetInvocationPipeline method does.)