handleSpecialCommands function
SpecialCommandResult
handleSpecialCommands(})
Check for and handle special commands (help, version).
Returns SpecialCommandResult.handled if a special command was processed and the caller should exit, or SpecialCommandResult.none to continue normal argument processing.
Supports:
tool help- Show tool helptool help :command- Show command helptool help command- Show command help (without colon)tool --helportool -h- Show tool helptool version- Show versiontool --versionortool -V- Show version
Parameters:
args- Command line argumentstool- Tool definition for generating helpprinter- Optional custom print function (defaults to print)toolHelpGenerator- Optional custom function to generate tool help textcommandHelpGenerator- Optional custom function to generate command help textversionGenerator- Optional custom function to generate version text
Example:
Future<void> main(List<String> args) async {
if (handleSpecialCommands(args, myTool) == SpecialCommandResult.handled) {
return;
}
// Continue normal processing...
}
Implementation
SpecialCommandResult handleSpecialCommands(
List<String> args,
ToolDefinition tool, {
void Function(String)? printer,
String Function(ToolDefinition)? toolHelpGenerator,
String Function(ToolDefinition, CommandDefinition)? commandHelpGenerator,
String Function(ToolDefinition)? versionGenerator,
}) {
printer ??= print;
toolHelpGenerator ??= generatePlainToolHelp;
commandHelpGenerator ??= (t, c) => generatePlainCommandHelp(t, c);
versionGenerator ??= (t) => '${t.name} v${t.version}';
if (args.isEmpty) {
printer(toolHelpGenerator(tool));
return SpecialCommandResult.handled;
}
final first = args.first.toLowerCase();
// Version command
if (first == 'version' ||
first == '--version' ||
first == '-version' ||
first == '-v') {
printer(versionGenerator(tool));
return SpecialCommandResult.handled;
}
// Help command
if (first == 'help' ||
first == '--help' ||
first == '-help' ||
first == '-h') {
if (args.length > 1 && first == 'help') {
// Command-specific help: help :command or help command or help topic
final target = args[1];
final cmdName = target.startsWith(':') ? target.substring(1) : target;
// Check help topics first (they don't need : prefix)
final topic = tool.helpTopics.cast<HelpTopic?>().firstWhere(
(t) => t!.name == cmdName,
orElse: () => null,
);
if (topic != null) {
printer(HelpGenerator.generateTopicHelp(topic, tool: tool));
} else {
_printCommandHelp(tool, cmdName, printer, commandHelpGenerator);
}
} else {
printer(toolHelpGenerator(tool));
}
return SpecialCommandResult.handled;
}
return SpecialCommandResult.none;
}