runCommand method

Future<T?> runCommand(
  1. ArgResults topLevelResults
)

Runs the command specified by topLevelResults.

This is notionally a protected method. It may be overridden or called from subclasses, but it shouldn't be called externally.

It's useful to override this to handle global flags and/or wrap the entire command in a block. For example, you might handle the --verbose flag here to enable verbose logging before running the command.

This returns the return value of Command.run.

Implementation

Future<T?> runCommand(ArgResults topLevelResults) async {
  var argResults = topLevelResults;
  var commands = _commands;
  Command? command;
  var commandString = executableName;

  while (commands.isNotEmpty) {
    if (argResults.command == null) {
      if (argResults.rest.isEmpty) {
        if (command == null) {
          // No top-level command was chosen.
          printUsage();
          return null;
        }

        command.usageException('Missing subcommand for "$commandString".');
      } else {
        var requested = argResults.rest[0];

        // Build up a help message containing similar commands, if found.
        var similarCommands =
            _similarCommandsText(requested, commands.values);

        if (command == null) {
          usageException(
              'Could not find a command named "$requested".$similarCommands');
        }

        command.usageException('Could not find a subcommand named '
            '"$requested" for "$commandString".$similarCommands');
      }
    }

    // Step into the command.
    argResults = argResults.command!;
    command = commands[argResults.name]!;
    command._globalResults = topLevelResults;
    command._argResults = argResults;
    commands = command._subcommands as Map<String, Command<T>>;
    commandString += ' ${argResults.name}';

    if (argResults.options.contains('help') && argResults.flag('help')) {
      command.printUsage();
      return null;
    }
  }

  if (topLevelResults.flag('help')) {
    command!.printUsage();
    return null;
  }

  // Make sure there aren't unexpected arguments.
  if (!command!.takesArguments && argResults.rest.isNotEmpty) {
    command.usageException(
        'Command "${argResults.name}" does not take any arguments.');
  }

  return (await command.run()) as T?;
}