runCommand method

  1. @override
Future<int?> runCommand(
  1. ArgResults topLevelResults
)
inherited

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

@override
Future<int?> runCommand(args.ArgResults topLevelResults) async {
  var commands = this.commands;
  // print(topLevelResults);
  var argResults = topLevelResults;
  var commandString = executableName;
  args_command_runner.Command<int>? command;
  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 {
        final requested = argResults.rest[0];

        // Build up a help message containing similar commands, if found.
        final similarCommands = _similarCommandsText<int>(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!;
    // ignore: unnecessary_null_checks
    command = commands[argResults.name];
    commands = command!.subcommands;
    commandString += ' ${argResults.name}';

    if (argResults.options.contains('help') && argResults.flag('help')) {
      command.printUsage();
      return ExitCode.success.code;
    }
  }
  if (topLevelResults.command?.name == 'completion') {
    await super.runCommand(topLevelResults);
    return ExitCode.success.code;
  }

  logger.trace(
    '~ run command ${topLevelResults.command?.name}',
    commandName: topLevelResults.command?.name,
  );
  return await super.runCommand(topLevelResults);
}