Class CommandLineApplication
- Namespace
- McMaster.Extensions.CommandLineUtils
- Assembly
- McMaster.Extensions.CommandLineUtils.dll
Describes a set of command line arguments, options, and execution behavior. CommandLineApplication can be nested to support subcommands.
public class CommandLineApplication : IServiceProvider, IDisposable
- Inheritance
-
objectCommandLineApplication
- Implements
- Derived
-
CommandLineApplication<TModel>
- Extension Methods
Constructors
CommandLineApplication()
Initializes a new instance of CommandLineApplication.
public CommandLineApplication()
CommandLineApplication(IHelpTextGenerator, IConsole, string)
Initializes a new instance of CommandLineApplication.
public CommandLineApplication(IHelpTextGenerator helpTextGenerator, IConsole console, string workingDirectory)
Parameters
helpTextGeneratorIHelpTextGeneratorThe help text generator to use.
consoleIConsoleThe console implementation to use.
workingDirectorystringThe current working directory.
CommandLineApplication(IConsole)
Initializes a new instance of CommandLineApplication.
public CommandLineApplication(IConsole console)
Parameters
consoleIConsoleThe console implementation to use.
CommandLineApplication(IConsole, string)
Initializes a new instance of CommandLineApplication.
public CommandLineApplication(IConsole console, string workingDirectory)
Parameters
consoleIConsoleThe console implementation to use.
workingDirectorystringThe current working directory.
Properties
AllowArgumentSeparator
Determines if '--' can be used to separate known arguments and options from additional content passed to RemainingArguments.
public bool AllowArgumentSeparator { get; set; }
Property Value
Arguments
Required command-line arguments.
public IReadOnlyList<CommandArgument> Arguments { get; }
Property Value
ClusterOptions
One or more options of NoValue, followed by at most one option that takes values, should be accepted when grouped behind one '-' delimiter.
When true, the following are equivalent.
-abcXyellow
-abcX=yellow
-abcX:yellow
-abc -X=yellow
-ab -cX=yellow
-a -b -c -Xyellow
-a -b -c -X yellow
-a -b -c -X=yellow
-a -b -c -X:yellow
This defaults to true unless an option with a short name of two or more characters is added.
public bool ClusterOptions { get; set; }
Property Value
Remarks
Commands
Subcommands.
public IReadOnlyCollection<CommandLineApplication> Commands { get; }
Property Value
Conventions
Gets a builder that can be used to apply conventions to
public IConventionBuilder Conventions { get; }
Property Value
Description
A description of the command.
public string? Description { get; set; }
Property Value
Error
The writer used to display generated error messages.
public TextWriter Error { get; set; }
Property Value
ExtendedHelpText
Additional text that appears at the bottom of generated help text.
public string? ExtendedHelpText { get; set; }
Property Value
FullName
The full name of the command to show in the help text.
public string? FullName { get; set; }
Property Value
HelpTextGenerator
The help text generator to use.
public IHelpTextGenerator HelpTextGenerator { get; set; }
Property Value
IsShowingInformation
True when OptionHelp or OptionVersion was matched.
public bool IsShowingInformation { get; protected set; }
Property Value
LongVersionGetter
The long-form of the version to display in generated help text.
public Func<string?>? LongVersionGetter { get; set; }
Property Value
MakeSuggestionsInErrorMessage
When an invalid argument is given, make suggestions in the error message about similar, valid commands or options.
$ git pshu Specify --help for a list of available options and commands Unrecognized command or argument 'pshu'
Did you mean this? push
public bool MakeSuggestionsInErrorMessage { get; set; }
Property Value
Name
The short name of the command. When this is a subcommand, it is the name of the word used to invoke the subcommand.
public string? Name { get; set; }
Property Value
Names
All names by which the command can be referenced. This includes Name and an aliases added in AddName(string).
public IEnumerable<string> Names { get; }
Property Value
OptionHelp
The option used to determine if help text should be displayed. This is set by calling HelpOption(string).
public CommandOption? OptionHelp { get; }
Property Value
OptionNameValueSeparators
Characters used to separate the option name from the value.
By default, allowed separators are ' ' (space), :, and =
public char[] OptionNameValueSeparators { get; set; }
Property Value
- char[]
Examples
Given --name=value, = is the separator.
Remarks
Space actually implies multiple spaces due to the way most operating system shells parse command line arguments before starting a new process.
OptionVersion
The options used to determine if the command version should be displayed. This is set by calling VersionOption(string, Func<string?>?, Func<string?>?).
public CommandOption? OptionVersion { get; }
Property Value
Options
Available command-line options on this command. Use GetOptions() to get all available options, which may include inherited options.
public IReadOnlyCollection<CommandOption> Options { get; }
Property Value
OptionsComparison
The way arguments and options are matched.
public StringComparison OptionsComparison { get; set; }
Property Value
Out
The writer used to display generated help text.
public TextWriter Out { get; set; }
Property Value
Parent
Defaults to null. A link to the parent command if this is instance is a subcommand.
public CommandLineApplication? Parent { get; set; }
Property Value
RemainingArguments
When initialized when UnrecognizedArgumentHandling is StopParsingAndCollect, this will contain any unrecognized arguments.
public IReadOnlyList<string> RemainingArguments { get; }
Property Value
ResponseFileHandling
When enabled, the parser will treat any arguments beginning with '@' as a file path to a response file. A response file contains additional arguments that will be treated as if they were passed in on the command line.
Defaults to Disabled.
Nested response false are not supported.
public ResponseFileHandling ResponseFileHandling { get; set; }
Property Value
ShortVersionGetter
The short-form of the version to display in generated help text.
public Func<string?>? ShortVersionGetter { get; set; }
Property Value
ShowInHelpText
Determines if this command appears in generated help text.
public bool ShowInHelpText { get; set; }
Property Value
UnrecognizedArgumentHandling
Configures what the parser should do when it runs into an unexpected argument.
public UnrecognizedArgumentHandling UnrecognizedArgumentHandling { get; set; }
Property Value
UsePagerForHelpText
Whether a Pager should be used to display help text.
public bool UsePagerForHelpText { get; set; }
Property Value
ValidationErrorHandler
The action to call when the command executes, but there was an error validation options or arguments. The action can return a new validation result.
public Func<ValidationResult, int> ValidationErrorHandler { get; set; }
Property Value
Validators
A collection of validators that execute before invoking OnExecute(Func<int>). When validation fails, ValidationErrorHandler is invoked.
public ICollection<ICommandValidator> Validators { get; }
Property Value
ValueParsers
Gets the default value parser provider.
The value parsers control how argument values are converted from strings to other types. Additional value parsers can be added so that domain specific types can converted. In-built value parsers can also be replaced for precise control of all type conversion.
public ValueParserProvider ValueParsers { get; }
Property Value
WorkingDirectory
Defines the working directory of the application. Defaults to GetCurrentDirectory().
This will be used as the base path for opening response files when ResponseFileHandling is true.
public string WorkingDirectory { get; }
Property Value
Methods
AddArgument(CommandArgument)
Add an argument to the definition of this command.
public void AddArgument(CommandArgument argument)
Parameters
argumentCommandArgument
AddName(string)
Add another name for the command.
Additional names can be shorter, longer, or alternative names by which a command may be invoked on the command line.
public void AddName(string name)
Parameters
namestringThe name. Must not be null or empty.
AddOption(CommandOption)
Add an option to the definition of this command
public void AddOption(CommandOption option)
Parameters
optionCommandOption
AddSubcommand(CommandLineApplication)
Add a subcommand
public void AddSubcommand(CommandLineApplication subcommand)
Parameters
subcommandCommandLineApplication
Argument(string, string, Action<CommandArgument>, bool)
Adds a command line argument.
public CommandArgument Argument(string name, string description, Action<CommandArgument> configuration, bool multipleValues = false)
Parameters
namestringdescriptionstringconfigurationAction<CommandArgument>multipleValuesbool
Returns
Argument(string, string, bool)
Adds a command line argument
public CommandArgument Argument(string name, string description, bool multipleValues = false)
Parameters
Returns
Argument<T>(string, string, Action<CommandArgument<T>>, bool)
Adds a command line argument with values that should be parsable into T.
public CommandArgument<T> Argument<T>(string name, string description, Action<CommandArgument<T>> configuration, bool multipleValues = false)
Parameters
namestringdescriptionstringconfigurationAction<CommandArgument<T>>multipleValuesbool
Returns
Type Parameters
TThe type of the values on the option
Command(string, Action<CommandLineApplication>)
Adds a subcommand.
public CommandLineApplication Command(string name, Action<CommandLineApplication> configuration)
Parameters
namestringThe word used to invoke the subcommand.
configurationAction<CommandLineApplication>A callback to configure the created subcommand.
Returns
Command<TModel>(string, Action<CommandLineApplication<TModel>>)
Adds a subcommand with model of type TModel.
public CommandLineApplication<TModel> Command<TModel>(string name, Action<CommandLineApplication<TModel>> configuration) where TModel : class
Parameters
namestringThe word used to invoke the subcommand.
configurationAction<CommandLineApplication<TModel>>A callback used to configure the subcommand object.
Returns
- CommandLineApplication<TModel>
Type Parameters
TModelThe model type of the subcommand.
Dispose()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public virtual void Dispose()
Execute(params string[])
Parses an array of strings using Parse(params string[]).
If OptionHelp was matched, the generated help text is displayed in command line output.
If OptionVersion was matched, the generated version info is displayed in command line output.
If there were any validation errors produced from GetValidationResult(), ValidationErrorHandler is invoked.
If the parse result matches this command, the function passed to OnExecute(Func<int>) or OnExecuteAsync(Func<CancellationToken, Task<int>>) will be invoked.
public int Execute(params string[] args)
Parameters
argsstring[]
Returns
- int
The return code from the function passed to OnExecute(Func<int>) or OnExecuteAsync(Func<CancellationToken, Task<int>>).
ExecuteAsync(string[], CancellationToken)
Parses an array of strings using Parse(params string[]).
If OptionHelp was matched, the generated help text is displayed in command line output.
If OptionVersion was matched, the generated version info is displayed in command line output.
If there were any validation errors produced from GetValidationResult(), ValidationErrorHandler is invoked.
If the parse result matches this command, the function passed to OnExecute(Func<int>) or OnExecuteAsync(Func<CancellationToken, Task<int>>) will be invoked.
public Task<int> ExecuteAsync(string[] args, CancellationToken cancellationToken = default)
Parameters
argsstring[]cancellationTokenCancellationToken
Returns
- Task<int>
The return code from the function passed to OnExecute(Func<int>) or OnExecuteAsync(Func<CancellationToken, Task<int>>).
ExecuteAsync<TApp>(CommandLineContext, CancellationToken)
Creates an instance of TApp, matching Arguments
to all attributes on the type, and then invoking a method named "OnExecute" or "OnExecuteAsync" if it exists.
public static Task<int> ExecuteAsync<TApp>(CommandLineContext context, CancellationToken cancellationToken = default) where TApp : class
Parameters
contextCommandLineContextThe execution context.
cancellationTokenCancellationToken
Returns
Type Parameters
TAppA type that should be bound to the arguments.
Exceptions
- InvalidOperationException
Thrown when attributes are incorrectly configured.
- See Also
ExecuteAsync<TApp>(IConsole, params string[])
Creates an instance of TApp, matching args
to all attributes on the type, and then invoking a method named "OnExecute" or "OnExecuteAsync" if it exists.
public static Task<int> ExecuteAsync<TApp>(IConsole console, params string[] args) where TApp : class
Parameters
Returns
Type Parameters
TAppA type that should be bound to the arguments.
Exceptions
- InvalidOperationException
Thrown when attributes are incorrectly configured.
- See Also
ExecuteAsync<TApp>(params string[])
Creates an instance of TApp, matching args
to all attributes on the type, and then invoking a method named "OnExecute" or "OnExecuteAsync" if it exists.
public static Task<int> ExecuteAsync<TApp>(params string[] args) where TApp : class
Parameters
argsstring[]The arguments
Returns
Type Parameters
TAppA type that should be bound to the arguments.
Exceptions
- InvalidOperationException
Thrown when attributes are incorrectly configured.
- See Also
ExecuteAsync<TApp>(string[], CancellationToken)
Creates an instance of TApp, matching args
to all attributes on the type, and then invoking a method named "OnExecute" or "OnExecuteAsync" if it exists.
public static Task<int> ExecuteAsync<TApp>(string[] args, CancellationToken cancellationToken = default) where TApp : class
Parameters
argsstring[]The arguments
cancellationTokenCancellationToken
Returns
Type Parameters
TAppA type that should be bound to the arguments.
Exceptions
- InvalidOperationException
Thrown when attributes are incorrectly configured.
- See Also
Execute<TApp>(CommandLineContext)
Creates an instance of TApp, matching Arguments
to all attributes on the type, and then invoking a method named "OnExecute" or "OnExecuteAsync" if it exists.
public static int Execute<TApp>(CommandLineContext context) where TApp : class
Parameters
contextCommandLineContextThe execution context.
Returns
- int
The process exit code
Type Parameters
TAppA type that should be bound to the arguments.
Exceptions
- InvalidOperationException
Thrown when attributes are incorrectly configured.
- See Also
Execute<TApp>(IConsole, params string[])
Creates an instance of TApp, matching args
to all attributes on the type, and then invoking a method named "OnExecute" or "OnExecuteAsync" if it exists.
public static int Execute<TApp>(IConsole console, params string[] args) where TApp : class
Parameters
Returns
- int
The process exit code
Type Parameters
TAppA type that should be bound to the arguments.
Exceptions
- InvalidOperationException
Thrown when attributes are incorrectly configured.
- See Also
Execute<TApp>(params string[])
Creates an instance of TApp, matching args
to all attributes on the type, and then invoking a method named "OnExecute" or "OnExecuteAsync" if it exists.
public static int Execute<TApp>(params string[] args) where TApp : class
Parameters
argsstring[]The arguments
Returns
- int
The process exit code
Type Parameters
TAppA type that should be bound to the arguments.
Exceptions
- InvalidOperationException
Thrown when attributes are incorrectly configured.
- See Also
GetFullNameAndVersion()
Gets FullName and ShortVersionGetter.
public virtual string GetFullNameAndVersion()
Returns
GetHelpText()
Produces help text describing command usage.
public virtual string GetHelpText()
Returns
- string
The help text.
GetOptions()
Gets all command line options available to this command, including any inherited options.
public IEnumerable<CommandOption> GetOptions()
Returns
- IEnumerable<CommandOption>
Command line options.
GetValidationResult()
Validates arguments and options.
public ValidationResult? GetValidationResult()
Returns
- ValidationResult
The first validation result that is not Success if there is an error.
GetVersionText()
Produces text describing version of the command.
public virtual string GetVersionText()
Returns
- string
The version text.
HandleParseResult(ParseResult)
Handle the result of parsing command line arguments.
protected virtual void HandleParseResult(ParseResult parseResult)
Parameters
parseResultParseResultThe parse result.
HelpOption(string)
Helper method that adds a help option.
public CommandOption HelpOption(string template)
Parameters
templatestring
Returns
HelpOption(string, bool)
Helper method that adds a help option.
public CommandOption HelpOption(string template, bool inherited)
Parameters
Returns
OnExecute(Func<int>)
Defines a callback for when this command is invoked.
public void OnExecute(Func<int> invoke)
Parameters
OnExecuteAsync(Func<CancellationToken, Task<int>>)
Defines an asynchronous callback.
public void OnExecuteAsync(Func<CancellationToken, Task<int>> invoke)
Parameters
invokeFunc<CancellationToken, Task<int>>
OnParsingComplete(Action<ParseResult>)
Adds an action to be invoked when all command line arguments have been parsed and validated.
public void OnParsingComplete(Action<ParseResult> action)
Parameters
actionAction<ParseResult>The action to be invoked
Option(string, string, CommandOptionType)
Adds a command-line option.
public CommandOption Option(string template, string description, CommandOptionType optionType)
Parameters
templatestringdescriptionstringoptionTypeCommandOptionType
Returns
Option(string, string, CommandOptionType, Action<CommandOption>)
Adds a command-line option.
public CommandOption Option(string template, string description, CommandOptionType optionType, Action<CommandOption> configuration)
Parameters
templatestringdescriptionstringoptionTypeCommandOptionTypeconfigurationAction<CommandOption>
Returns
Option(string, string, CommandOptionType, Action<CommandOption>, bool)
Adds a command line option.
public CommandOption Option(string template, string description, CommandOptionType optionType, Action<CommandOption> configuration, bool inherited)
Parameters
templatestringdescriptionstringoptionTypeCommandOptionTypeconfigurationAction<CommandOption>inheritedbool
Returns
Option(string, string, CommandOptionType, bool)
Adds a command-line option.
public CommandOption Option(string template, string description, CommandOptionType optionType, bool inherited)
Parameters
templatestringdescriptionstringoptionTypeCommandOptionTypeinheritedbool
Returns
Option<T>(string, string, CommandOptionType, Action<CommandOption<T>>, bool)
Adds a command line option with values that should be parsable into T.
public CommandOption<T> Option<T>(string template, string description, CommandOptionType optionType, Action<CommandOption<T>> configuration, bool inherited)
Parameters
templatestringdescriptionstringoptionTypeCommandOptionTypeconfigurationAction<CommandOption<T>>inheritedbool
Returns
- CommandOption<T>
The option
Type Parameters
TThe type of the values on the option
Parse(params string[])
public ParseResult Parse(params string[] args)
Parameters
argsstring[]Command line arguments.
Returns
- ParseResult
The result of parsing.
ShowHelp()
Show full help.
public void ShowHelp()
ShowHelp(bool)
Show full help.
public void ShowHelp(bool usePager)
Parameters
usePagerboolUse a console pager to display help text, if possible.
ShowHint()
Show short hint that reminds users to use help option.
public virtual void ShowHint()
ShowRootCommandFullNameAndVersion()
Traverses up Parent and displays the result of GetFullNameAndVersion().
public void ShowRootCommandFullNameAndVersion()
ShowVersion()
Displays version information that includes FullName and LongVersionGetter.
public void ShowVersion()
VersionOption(string, Func<string?>?, Func<string?>?)
Helper method that adds a version option.
public CommandOption VersionOption(string template, Func<string?>? shortFormVersionGetter, Func<string?>? longFormVersionGetter = null)
Parameters
Returns
VersionOption(string, string?, string?)
Helper method that adds a version option from known versions strings.
public CommandOption VersionOption(string template, string? shortFormVersion, string? longFormVersion = null)