CommandRunner<O extends OptionDefinition, T> class

A command runner for a command line application.

Runs a command line by parsing the command line arguments, environment variables, and configuration files, and running the commands on the command line.

Returns the result of the nested middleware chain for the commands on the command line. Each ancestor's middleware wraps the commands that follow it. Only the last command's run (or the action option's, if present) is invoked.

T is the return type of the run methods of this runner and the commands. CommandRunner.run returns the result of the nested middleware chain. When each middleware returns the result of its next handler, that is the result of the last command on the command line, or of the action option. This means that T must match across the runner and all its commands. Using int as T can be sensible in order to return the exit code that the command executable should return.

Usage

Built-in options and commands

The built-in global option --help / -h is predefined, as is --completion <shell> if the runner has no subcommands, see builtinPersistentOptions.

If the runner has subcommands, the built-in commands are added: help, and if completion is enabled, completion and__complete.

Action options

Action options are arguments that have the syntax of an option flag but run like a command. They are defined by an OptionDefinition with the ActionOptionMixin mixin. If present, they run instead of a command. A use case example is the --version option.

Pass-through arguments after --

To accept arguments written after --, pass DoubleDashHandling.passThroughRest. In addition, the command that receives them must set ignoreUnexpectedPositionalArgs to true. It can then read the list from Configuration.remainingPosArgs:

CommandRunner<OptionDefinition, void>(
  'tool',
  'Tools',
  parserSettings: const ParserSettings(
    doubleDashHandling: DoubleDashHandling.passThroughRest,
  ),
);
@override
bool get ignoreUnexpectedPositionalArgs => true;
...
// tool build -q -- --some --remaining
// context.config.remainingPosArgs == ['--some', '--remaining']

Pass-through commands

A command that overrides AbstractCommand.passThroughArgs passes every argument after it through unparsed, for example to another program. It reads them from Configuration.remainingPosArgs and completes them in AbstractCommand.completePassThroughArgs.

Design

Uses the concept of middlewares to customize the execution logic of the command tree. The legacy CommandRunner relied on method overrides to customize the execution logic. This middleware approach allows for cleaner composition.

Separates static configuration from dynamic execution. The command tree, options, middlewares, settings for usage output and error handling are configured statically. Execution performs configuration resolution and command execution and these do not mutate the CommandRunner, Command, or Option instances. This provides separation of concerns and makes the command code reentrant.

Phases and Error Handling

There are three phases to the execution of a command runner that are run in sequence and have distinct error handling:

  1. Validation: Checking the consistency of the commands and options
  2. Resolution: Resolving the configurations for the command line, env vars, and config files
  3. Execution: Running the command line and any middlewares

Configuration validation runs first and validates the consistency of all the defined commands and options. Validation errors are considered programming errors and if any errors are found a ConfigDefinitionError is thrown.

Configuration resolution runs next and resolves the current configurations for the command line, env vars, and config files. Resolution errors are user errors and if any errors are found, usage guidance is printed and a UsageException is thrown (under the default settings).

Command execution is last and runs the current command line and any middlewares defined in it. If any exceptions are thrown they will propagate to the original caller unless intercepted by a middleware.

Implemented types

Constructors

CommandRunner(String executableName, String description, {String? invocation, String? rootFooter, List<O>? globalOptions, List<Command<OptionDefinition, T>>? subcommands, List<CommandMiddleware<O, T>>? middlewares, bool? canRunAsLeafCommand, UsageGenerator? usageGenerator, ParserSettings? parserSettings, UsageOutputHandler? usageOutput, CompletionSettings? completion})
Creates a new command runner with the given executable name and description.

Properties

acceptsPartialCommandLine → bool
Whether this command accepts a partial command line, i.e. runs as the last command on the command line even if the command line is incomplete.
no setterinherited
aliasesDefinition → CommandAliasesDefinition
There are no aliases for the root command.
final
builtinPersistentOptions → List<BuiltinGlobalOption<Object>>
The built-in global options, e.g. --help.
no setter
canRunAsLeafCommand → bool
finalinherited
completion → CompletionSettings
The settings for the built-in shell completion support.
final
executableName → String
The name of the executable being run.
final
globalOptions → List<O>
The global option definitions (the root command's persistent options).
no setter
hashCode → int
The hash code for this object.
no setterinherited
hasParent → bool
no setterinherited
ignoreUnexpectedPositionalArgs → bool
Whether additional positional arguments (that don't match the defined positional options) are allowed after this command. Defaults to false.
no setterinherited
name → String
The name of the executable being run.
no setteroverride
options → List<O>
finalinherited
parent ↔ AbstractCommand<OptionDefinition, T>
Notionally protected; may only be called once. Throws a StateError if this command already has a parent.
getter/setter pairinherited
parserSettings → ParserSettings
Settings for scanning and parsing the command line.
final
passThroughArgs → bool
Whether every argument after this command is left unparsed, to be passed through to another program. Defaults to false.
no setterinherited
persistentOptions → List<O>
finalinherited
resolver → CommandResolver<O, T>
Resolves the configurations for each command on the command line.
latefinal
runner → CommandRunner<OptionDefinition, T>
Convenience method to get the root CommandRunner from any command.
no setterinherited
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
subcommands → List<Command<OptionDefinition, T>>
Returns the subcommands for this command. Injects the built-in subcommands (including help) if there is at least one subcommand and there is not already a subcommand with the same name present.
no setterinherited
usage → String
Generates a formatted string with usage information for this command.
no setterinherited
usageDefinition → CommandUsageDefinition
Describes usage documentation and visibility for this command.
final
usageGenerator → UsageGenerator
The usage string generator for this command.
finalinherited
usageOutput → UsageOutputHandler
The settings and behavior for the usage output - controls the help output and the usage exception output.
final

Methods

addMiddleware(Middleware<FutureOr<T?>, CommandContext<O, T>> middleware) → void
Adds a middleware to this command. Middlewares are invoked in the order they are added.
inherited
addOption(O option, {bool? persistent}) → void
Adds an option to this command. persistent indicates whether the option should be persistent across this command's subcommands.
inherited
addSubcommand(Command<OptionDefinition, T> subcommand) → void
Adds a subcommand to this command.
inherited
allOptions({bool onlyPersistent = false}) → List<OptionDefinition>
All the defined options of this command, depending on the passed flag.
completePassThroughArgs(CommandContext<O, T> context, List<String> words) → FutureOr<CompletionResponse>
Completes the arguments of this pass-through command, see passThroughArgs.
inherited
configBroker(CommandContext<OptionDefinition, T>? prevContext) → ConfigurationBroker<OptionDefinition>?
Provides the configuration broker for resolving the configuration for this command, if any. prevContext and its predecessor contexts are the resolved contexts of the parent commands.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
resolveCmd(ArgParseResult<OptionDefinition> parseResult, Map<String, String>? env, ContextProvider provider, CommandContext<OptionDefinition, T>? prevContext, {required CommandRunMode runMode}) → CommandContext<O, T>
Given a parsed command line, environmnent variables, a context provider, and the resolved command contexts of the parent commands, resolves the configuration for this command and returns a CommandContext for it.
resolveConfigurations(Iterable<String> args, Map<String, String>? env, ContextProvider provider) → CommandContext<O, T>?
Resolves the configurations for all commands on the command line and returns the list of contexts for the commands.
run(Iterable<String> args, {Map<String, String>? env, ContextProvider? provider}) → Future<T?>
Runs a command line by parsing args and env (and configBroker, when available) and running the last command on the command line.
runAsLeaf(CommandContext<O, T> context) → FutureOr<T?>
Runs this command runner when it is the last command on the command line.
runCommand(CommandContext<O, T> context, {CommandHandler<O, T>? runNextCommand}) → FutureOr<T?>
Runs this command, including its middlewares (hooks).
inherited
runCommandLine(CommandContext<O, T> contexts) → Future<T?>
Runs the command line: the middlewares of the commands on the command line, then the tail command or an action option.
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited