runCommand method
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
T? runCommand(ArgResults topLevelResults) {
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 {
if (command == null) {
usageException('Could not find a command named "${argResults.rest[0]}".');
}
command.usageException('Could not find a subcommand named '
'"${argResults.rest[0]}" for "$commandString".');
}
}
// 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['help']) {
command.printUsage();
return null;
}
}
if (topLevelResults['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 (command.run()) as T?;
}