run method

Future<T?> run(
  1. Iterable<String> args, {
  2. Map<String, String>? env,
  3. ContextProvider? provider,
})

Runs a command line by parsing args and env (and configBroker, when available) and running the last command on the command line.

Returns a Future with the result. Synchronous work runs immediately, and a synchronous command result is still delivered on the future.

Resolves the global configuration and the individual command configurations before invoking the commands or their middlewares. Throws a UsageException on args parse errors and configuration resolution errors. All discovered parse and resolution errors are included in the message of that exception.

The caller may provide a ContextProvider, otherwise a default, empty one is created and used.

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 is invoked. When every middleware returns the result of its next handler, the result is that of the last command.

An action option ends that chain at the command that defined it. Middleware runs up through that command, and the option runs instead of any command.

When --help or -h is present, prints usage for the last command and returns null without running any command. Middleware still runs through the runner, which defines --help.

To make a subcommand which is named like an option, simply define it like the following example. But typically it is better to define an action option instead.

 CommandImpl.leafWithRunFunction(
   name: 'version',
   aliases: ['--version', '-v'],
   description: 'Display the version',
   run: (CommandContext context) {
     print('version 1.0.0');
   },
 );

Throws ConfigDefinitionError if any command or option definition is invalid, before running any middleware or commands.

Throws UsageException if any configuration input including arguments, environment variables, and configuration files is invalid, unless UsageExceptionSettings.noUsageException is true.

Implementation

Future<T?> run(
  final Iterable<String> args, {
  final Map<String, String>? env,
  final ContextProvider? provider,
}) async {
  try {
    return await Future.sync(
      () => _run(args, env: env, customProvider: provider),
    );
  } on TypeError catch (error, stackTrace) {
    stderr.writeln(
      ">>> If this happens, O and T may need to be bound explicitly, due to limitations in Dart's generic type inference.\n"
      '    E.g. `CommandRunner<OptionDefinition, int>(...)`\n'
      '${error.runtimeType}: $error\n'
      '$stackTrace',
    );
    rethrow;
  }
}