Table of Contents

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
object
CommandLineApplication
Implements
Derived
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

helpTextGenerator IHelpTextGenerator

The help text generator to use.

console IConsole

The console implementation to use.

workingDirectory string

The current working directory.

CommandLineApplication(IConsole)

Initializes a new instance of CommandLineApplication.

public CommandLineApplication(IConsole console)

Parameters

console IConsole

The console implementation to use.

CommandLineApplication(IConsole, string)

Initializes a new instance of CommandLineApplication.

public CommandLineApplication(IConsole console, string workingDirectory)

Parameters

console IConsole

The console implementation to use.

workingDirectory string

The 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

bool

Arguments

Required command-line arguments.

public IReadOnlyList<CommandArgument> Arguments { get; }

Property Value

IReadOnlyList<CommandArgument>

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

bool

Remarks

Commands

Subcommands.

public IReadOnlyCollection<CommandLineApplication> Commands { get; }

Property Value

IReadOnlyCollection<CommandLineApplication>

Conventions

Gets a builder that can be used to apply conventions to

public IConventionBuilder Conventions { get; }

Property Value

IConventionBuilder

Description

A description of the command.

public string? Description { get; set; }

Property Value

string

Error

The writer used to display generated error messages.

public TextWriter Error { get; set; }

Property Value

TextWriter

ExtendedHelpText

Additional text that appears at the bottom of generated help text.

public string? ExtendedHelpText { get; set; }

Property Value

string

FullName

The full name of the command to show in the help text.

public string? FullName { get; set; }

Property Value

string

HelpTextGenerator

The help text generator to use.

public IHelpTextGenerator HelpTextGenerator { get; set; }

Property Value

IHelpTextGenerator

IsShowingInformation

True when OptionHelp or OptionVersion was matched.

public bool IsShowingInformation { get; protected set; }

Property Value

bool

LongVersionGetter

The long-form of the version to display in generated help text.

public Func<string?>? LongVersionGetter { get; set; }

Property Value

Func<string>

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

bool

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

string

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

IEnumerable<string>

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

CommandOption

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

CommandOption

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

IReadOnlyCollection<CommandOption>

OptionsComparison

The way arguments and options are matched.

public StringComparison OptionsComparison { get; set; }

Property Value

StringComparison

Out

The writer used to display generated help text.

public TextWriter Out { get; set; }

Property Value

TextWriter

Parent

Defaults to null. A link to the parent command if this is instance is a subcommand.

public CommandLineApplication? Parent { get; set; }

Property Value

CommandLineApplication

RemainingArguments

When initialized when UnrecognizedArgumentHandling is StopParsingAndCollect, this will contain any unrecognized arguments.

public IReadOnlyList<string> RemainingArguments { get; }

Property Value

IReadOnlyList<string>

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

ResponseFileHandling

ShortVersionGetter

The short-form of the version to display in generated help text.

public Func<string?>? ShortVersionGetter { get; set; }

Property Value

Func<string>

ShowInHelpText

Determines if this command appears in generated help text.

public bool ShowInHelpText { get; set; }

Property Value

bool

UnrecognizedArgumentHandling

Configures what the parser should do when it runs into an unexpected argument.

public UnrecognizedArgumentHandling UnrecognizedArgumentHandling { get; set; }

Property Value

UnrecognizedArgumentHandling

UsePagerForHelpText

Whether a Pager should be used to display help text.

public bool UsePagerForHelpText { get; set; }

Property Value

bool

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

Func<ValidationResult, int>

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

ICollection<ICommandValidator>

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.

Value parsers are currently only used by the Attribute API.
public ValueParserProvider ValueParsers { get; }

Property Value

ValueParserProvider

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

string

Methods

AddArgument(CommandArgument)

Add an argument to the definition of this command.

public void AddArgument(CommandArgument argument)

Parameters

argument CommandArgument

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

name string

The name. Must not be null or empty.

AddOption(CommandOption)

Add an option to the definition of this command

public void AddOption(CommandOption option)

Parameters

option CommandOption

AddSubcommand(CommandLineApplication)

Add a subcommand

public void AddSubcommand(CommandLineApplication subcommand)

Parameters

subcommand CommandLineApplication

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

name string
description string
configuration Action<CommandArgument>
multipleValues bool

Returns

CommandArgument

Argument(string, string, bool)

Adds a command line argument

public CommandArgument Argument(string name, string description, bool multipleValues = false)

Parameters

name string
description string
multipleValues bool

Returns

CommandArgument

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

name string
description string
configuration Action<CommandArgument<T>>
multipleValues bool

Returns

CommandArgument<T>

Type Parameters

T

The type of the values on the option

Command(string, Action<CommandLineApplication>)

Adds a subcommand.

public CommandLineApplication Command(string name, Action<CommandLineApplication> configuration)

Parameters

name string

The word used to invoke the subcommand.

configuration Action<CommandLineApplication>

A callback to configure the created subcommand.

Returns

CommandLineApplication

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

name string

The word used to invoke the subcommand.

configuration Action<CommandLineApplication<TModel>>

A callback used to configure the subcommand object.

Returns

CommandLineApplication<TModel>

Type Parameters

TModel

The 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

args string[]

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

args string[]
cancellationToken CancellationToken

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

context CommandLineContext

The execution context.

cancellationToken CancellationToken

Returns

Task<int>

The process exit code

Type Parameters

TApp

A 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

console IConsole

The console to use

args string[]

The arguments

Returns

Task<int>

The process exit code

Type Parameters

TApp

A 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

args string[]

The arguments

Returns

Task<int>

The process exit code

Type Parameters

TApp

A 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

args string[]

The arguments

cancellationToken CancellationToken

Returns

Task<int>

The process exit code

Type Parameters

TApp

A 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

context CommandLineContext

The execution context.

Returns

int

The process exit code

Type Parameters

TApp

A 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

console IConsole

The console to use

args string[]

The arguments

Returns

int

The process exit code

Type Parameters

TApp

A 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

args string[]

The arguments

Returns

int

The process exit code

Type Parameters

TApp

A type that should be bound to the arguments.

Exceptions

InvalidOperationException

Thrown when attributes are incorrectly configured.

See Also

GetFullNameAndVersion()

public virtual string GetFullNameAndVersion()

Returns

string

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

parseResult ParseResult

The parse result.

HelpOption(string)

Helper method that adds a help option.

public CommandOption HelpOption(string template)

Parameters

template string

Returns

CommandOption

HelpOption(string, bool)

Helper method that adds a help option.

public CommandOption HelpOption(string template, bool inherited)

Parameters

template string
inherited bool

Returns

CommandOption

OnExecute(Func<int>)

Defines a callback for when this command is invoked.

public void OnExecute(Func<int> invoke)

Parameters

invoke Func<int>

OnExecuteAsync(Func<CancellationToken, Task<int>>)

Defines an asynchronous callback.

public void OnExecuteAsync(Func<CancellationToken, Task<int>> invoke)

Parameters

invoke Func<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

action Action<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

template string
description string
optionType CommandOptionType

Returns

CommandOption

Option(string, string, CommandOptionType, Action<CommandOption>)

Adds a command-line option.

public CommandOption Option(string template, string description, CommandOptionType optionType, Action<CommandOption> configuration)

Parameters

template string
description string
optionType CommandOptionType
configuration Action<CommandOption>

Returns

CommandOption

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

template string
description string
optionType CommandOptionType
configuration Action<CommandOption>
inherited bool

Returns

CommandOption

Option(string, string, CommandOptionType, bool)

Adds a command-line option.

public CommandOption Option(string template, string description, CommandOptionType optionType, bool inherited)

Parameters

template string
description string
optionType CommandOptionType
inherited bool

Returns

CommandOption

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

template string
description string
optionType CommandOptionType
configuration Action<CommandOption<T>>
inherited bool

Returns

CommandOption<T>

The option

Type Parameters

T

The type of the values on the option

Parse(params string[])

Parses an array of strings, matching them against Options, Arguments, and Commands.

public ParseResult Parse(params string[] args)

Parameters

args string[]

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

usePager bool

Use 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

template string
shortFormVersionGetter Func<string>
longFormVersionGetter Func<string>

Returns

CommandOption

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)

Parameters

template string
shortFormVersion string
longFormVersion string

Returns

CommandOption