OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library args.command_runner; |
| 6 |
| 7 import 'dart:async'; |
| 8 import 'dart:collection'; |
| 9 import 'dart:math' as math; |
| 10 |
| 11 import 'src/arg_parser.dart'; |
| 12 import 'src/arg_results.dart'; |
| 13 import 'src/help_command.dart'; |
| 14 import 'src/usage_exception.dart'; |
| 15 import 'src/utils.dart'; |
| 16 |
| 17 export 'src/usage_exception.dart'; |
| 18 |
| 19 /// A class for invoking [Commands] based on raw command-line arguments. |
| 20 class CommandRunner { |
| 21 /// The name of the executable being run. |
| 22 /// |
| 23 /// Used for error reporting and [usage]. |
| 24 final String executableName; |
| 25 |
| 26 /// A short description of this executable. |
| 27 final String description; |
| 28 |
| 29 /// A single-line template for how to invoke this executable. |
| 30 /// |
| 31 /// Defaults to "$executableName <command> [arguments]". Subclasses can |
| 32 /// override this for a more specific template. |
| 33 String get invocation => "$executableName <command> [arguments]"; |
| 34 |
| 35 /// Generates a string displaying usage information for the executable. |
| 36 /// |
| 37 /// This includes usage for the global arguments as well as a list of |
| 38 /// top-level commands. |
| 39 String get usage => "$description\n\n$_usageWithoutDescription"; |
| 40 |
| 41 /// An optional footer for [usage]. |
| 42 /// |
| 43 /// If a subclass overrides this to return a string, it will automatically be |
| 44 /// added to the end of [usage]. |
| 45 final String usageFooter = null; |
| 46 |
| 47 /// Returns [usage] with [description] removed from the beginning. |
| 48 String get _usageWithoutDescription { |
| 49 var usage = ''' |
| 50 Usage: $invocation |
| 51 |
| 52 Global options: |
| 53 ${argParser.usage} |
| 54 |
| 55 ${_getCommandUsage(_commands)} |
| 56 |
| 57 Run "$executableName help <command>" for more information about a command.'''; |
| 58 |
| 59 if (usageFooter != null) usage += "\n$usageFooter"; |
| 60 return usage; |
| 61 } |
| 62 |
| 63 /// An unmodifiable view of all top-level commands defined for this runner. |
| 64 Map<String, Command> get commands => new UnmodifiableMapView(_commands); |
| 65 final _commands = new Map<String, Command>(); |
| 66 |
| 67 /// The top-level argument parser. |
| 68 /// |
| 69 /// Global options should be registered with this parser; they'll end up |
| 70 /// available via [Command.globalResults]. Commands should be registered with |
| 71 /// [addCommand] rather than directly on the parser. |
| 72 final argParser = new ArgParser(); |
| 73 |
| 74 CommandRunner(this.executableName, this.description) { |
| 75 argParser.addFlag('help', |
| 76 abbr: 'h', negatable: false, help: 'Print this usage information.'); |
| 77 addCommand(new HelpCommand()); |
| 78 } |
| 79 |
| 80 /// Prints the usage information for this runner. |
| 81 /// |
| 82 /// This is called internally by [run] and can be overridden by subclasses to |
| 83 /// control how output is displayed or integrate with a logging system. |
| 84 void printUsage() => print(usage); |
| 85 |
| 86 /// Throws a [UsageException] with [message]. |
| 87 void usageException(String message) => |
| 88 throw new UsageException(message, _usageWithoutDescription); |
| 89 |
| 90 /// Adds [Command] as a top-level command to this runner. |
| 91 void addCommand(Command command) { |
| 92 var names = [command.name]..addAll(command.aliases); |
| 93 for (var name in names) { |
| 94 _commands[name] = command; |
| 95 argParser.addCommand(name, command.argParser); |
| 96 } |
| 97 command._runner = this; |
| 98 } |
| 99 |
| 100 /// Parses [args] and invokes [Command.run] on the chosen command. |
| 101 /// |
| 102 /// This always returns a [Future] in case the command is asynchronous. The |
| 103 /// [Future] will throw a [UsageError] if [args] was invalid. |
| 104 Future run(Iterable<String> args) => |
| 105 new Future.sync(() => runCommand(parse(args))); |
| 106 |
| 107 /// Parses [args] and returns the result, converting a [FormatException] to a |
| 108 /// [UsageException]. |
| 109 /// |
| 110 /// This is notionally a protected method. It may be overridden or called from |
| 111 /// subclasses, but it shouldn't be called externally. |
| 112 ArgResults parse(Iterable<String> args) { |
| 113 try { |
| 114 // TODO(nweiz): if arg parsing fails for a command, print that command's |
| 115 // usage, not the global usage. |
| 116 return argParser.parse(args); |
| 117 } on FormatException catch (error) { |
| 118 usageException(error.message); |
| 119 } |
| 120 } |
| 121 |
| 122 /// Runs the command specified by [topLevelResults]. |
| 123 /// |
| 124 /// This is notionally a protected method. It may be overridden or called from |
| 125 /// subclasses, but it shouldn't be called externally. |
| 126 /// |
| 127 /// It's useful to override this to handle global flags and/or wrap the entire |
| 128 /// command in a block. For example, you might handle the `--verbose` flag |
| 129 /// here to enable verbose logging before running the command. |
| 130 Future runCommand(ArgResults topLevelResults) { |
| 131 return new Future.sync(() { |
| 132 var argResults = topLevelResults; |
| 133 var commands = _commands; |
| 134 var command; |
| 135 var commandString = executableName; |
| 136 |
| 137 while (commands.isNotEmpty) { |
| 138 if (argResults.command == null) { |
| 139 if (argResults.rest.isEmpty) { |
| 140 if (command == null) { |
| 141 // No top-level command was chosen. |
| 142 printUsage(); |
| 143 return new Future.value(); |
| 144 } |
| 145 |
| 146 command.usageException('Missing subcommand for "$commandString".'); |
| 147 } else { |
| 148 if (command == null) { |
| 149 usageException( |
| 150 'Could not find a command named "${argResults.rest[0]}".'); |
| 151 } |
| 152 |
| 153 command.usageException('Could not find a subcommand named ' |
| 154 '"${argResults.rest[0]}" for "$commandString".'); |
| 155 } |
| 156 } |
| 157 |
| 158 // Step into the command. |
| 159 argResults = argResults.command; |
| 160 command = commands[argResults.name]; |
| 161 command._globalResults = topLevelResults; |
| 162 command._argResults = argResults; |
| 163 commands = command._subcommands; |
| 164 commandString += " ${argResults.name}"; |
| 165 |
| 166 if (argResults['help']) { |
| 167 command.printUsage(); |
| 168 return new Future.value(); |
| 169 } |
| 170 } |
| 171 |
| 172 // Make sure there aren't unexpected arguments. |
| 173 if (!command.takesArguments && argResults.rest.isNotEmpty) { |
| 174 command.usageException( |
| 175 'Command "${argResults.name}" does not take any arguments.'); |
| 176 } |
| 177 |
| 178 return command.run(); |
| 179 }); |
| 180 } |
| 181 } |
| 182 |
| 183 /// A single command. |
| 184 /// |
| 185 /// A command is known as a "leaf command" if it has no subcommands and is meant |
| 186 /// to be run. Leaf commands must override [run]. |
| 187 /// |
| 188 /// A command with subcommands is known as a "branch command" and cannot be run |
| 189 /// itself. It should call [addSubcommand] (often from the constructor) to |
| 190 /// register subcommands. |
| 191 abstract class Command { |
| 192 /// The name of this command. |
| 193 String get name; |
| 194 |
| 195 /// A short description of this command. |
| 196 String get description; |
| 197 |
| 198 /// A single-line template for how to invoke this command (e.g. `"pub get |
| 199 /// [package]"`). |
| 200 String get invocation { |
| 201 var parents = [name]; |
| 202 for (var command = parent; command != null; command = command.parent) { |
| 203 parents.add(command.name); |
| 204 } |
| 205 parents.add(runner.executableName); |
| 206 |
| 207 var invocation = parents.reversed.join(" "); |
| 208 return _subcommands.isNotEmpty |
| 209 ? "$invocation <subcommand> [arguments]" |
| 210 : "$invocation [arguments]"; |
| 211 } |
| 212 |
| 213 /// The command's parent command, if this is a subcommand. |
| 214 /// |
| 215 /// This will be `null` until [Command.addSubcommmand] has been called with |
| 216 /// this command. |
| 217 Command get parent => _parent; |
| 218 Command _parent; |
| 219 |
| 220 /// The command runner for this command. |
| 221 /// |
| 222 /// This will be `null` until [CommandRunner.addCommand] has been called with |
| 223 /// this command or one of its parents. |
| 224 CommandRunner get runner { |
| 225 if (parent == null) return _runner; |
| 226 return parent.runner; |
| 227 } |
| 228 CommandRunner _runner; |
| 229 |
| 230 /// The parsed global argument results. |
| 231 /// |
| 232 /// This will be `null` until just before [Command.run] is called. |
| 233 ArgResults get globalResults => _globalResults; |
| 234 ArgResults _globalResults; |
| 235 |
| 236 /// The parsed argument results for this command. |
| 237 /// |
| 238 /// This will be `null` until just before [Command.run] is called. |
| 239 ArgResults get argResults => _argResults; |
| 240 ArgResults _argResults; |
| 241 |
| 242 /// The argument parser for this command. |
| 243 /// |
| 244 /// Options for this command should be registered with this parser (often in |
| 245 /// the constructor); they'll end up available via [argResults]. Subcommands |
| 246 /// should be registered with [addSubcommand] rather than directly on the |
| 247 /// parser. |
| 248 final argParser = new ArgParser(); |
| 249 |
| 250 /// Generates a string displaying usage information for this command. |
| 251 /// |
| 252 /// This includes usage for the command's arguments as well as a list of |
| 253 /// subcommands, if there are any. |
| 254 String get usage => "$description\n\n$_usageWithoutDescription"; |
| 255 |
| 256 /// An optional footer for [usage]. |
| 257 /// |
| 258 /// If a subclass overrides this to return a string, it will automatically be |
| 259 /// added to the end of [usage]. |
| 260 final String usageFooter = null; |
| 261 |
| 262 /// Returns [usage] with [description] removed from the beginning. |
| 263 String get _usageWithoutDescription { |
| 264 var buffer = new StringBuffer() |
| 265 ..writeln('Usage: $invocation') |
| 266 ..writeln(argParser.usage); |
| 267 |
| 268 if (_subcommands.isNotEmpty) { |
| 269 buffer.writeln(); |
| 270 buffer.writeln(_getCommandUsage(_subcommands, isSubcommand: true)); |
| 271 } |
| 272 |
| 273 buffer.writeln(); |
| 274 buffer.write('Run "${runner.executableName} help" to see global options.'); |
| 275 |
| 276 if (usageFooter != null) { |
| 277 buffer.writeln(); |
| 278 buffer.write(usageFooter); |
| 279 } |
| 280 |
| 281 return buffer.toString(); |
| 282 } |
| 283 |
| 284 /// An unmodifiable view of all sublevel commands of this command. |
| 285 Map<String, Command> get subcommands => new UnmodifiableMapView(_subcommands); |
| 286 final _subcommands = new Map<String, Command>(); |
| 287 |
| 288 /// Whether or not this command should be hidden from help listings. |
| 289 /// |
| 290 /// This is intended to be overridden by commands that want to mark themselves |
| 291 /// hidden. |
| 292 /// |
| 293 /// By default, leaf commands are always visible. Branch commands are visible |
| 294 /// as long as any of their leaf commands are visible. |
| 295 bool get hidden { |
| 296 // Leaf commands are visible by default. |
| 297 if (_subcommands.isEmpty) return false; |
| 298 |
| 299 // Otherwise, a command is hidden if all of its subcommands are. |
| 300 return _subcommands.values.every((subcommand) => subcommand.hidden); |
| 301 } |
| 302 |
| 303 /// Whether or not this command takes positional arguments in addition to |
| 304 /// options. |
| 305 /// |
| 306 /// If false, [CommandRunner.run] will throw a [UsageException] if arguments |
| 307 /// are provided. Defaults to true. |
| 308 /// |
| 309 /// This is intended to be overridden by commands that don't want to receive |
| 310 /// arguments. It has no effect for branch commands. |
| 311 final takesArguments = true; |
| 312 |
| 313 /// Alternate names for this command. |
| 314 /// |
| 315 /// These names won't be used in the documentation, but they will work when |
| 316 /// invoked on the command line. |
| 317 /// |
| 318 /// This is intended to be overridden. |
| 319 final aliases = const <String>[]; |
| 320 |
| 321 Command() { |
| 322 argParser.addFlag('help', |
| 323 abbr: 'h', negatable: false, help: 'Print this usage information.'); |
| 324 } |
| 325 |
| 326 /// Runs this command. |
| 327 /// |
| 328 /// If this returns a [Future], [CommandRunner.run] won't complete until the |
| 329 /// returned [Future] does. Otherwise, the return value is ignored. |
| 330 run() { |
| 331 throw new UnimplementedError("Leaf command $this must implement run()."); |
| 332 } |
| 333 |
| 334 /// Adds [Command] as a subcommand of this. |
| 335 void addSubcommand(Command command) { |
| 336 var names = [command.name]..addAll(command.aliases); |
| 337 for (var name in names) { |
| 338 _subcommands[name] = command; |
| 339 argParser.addCommand(name, command.argParser); |
| 340 } |
| 341 command._parent = this; |
| 342 } |
| 343 |
| 344 /// Prints the usage information for this command. |
| 345 /// |
| 346 /// This is called internally by [run] and can be overridden by subclasses to |
| 347 /// control how output is displayed or integrate with a logging system. |
| 348 void printUsage() => print(usage); |
| 349 |
| 350 /// Throws a [UsageException] with [message]. |
| 351 void usageException(String message) => |
| 352 throw new UsageException(message, _usageWithoutDescription); |
| 353 } |
| 354 |
| 355 /// Returns a string representation of [commands] fit for use in a usage string. |
| 356 /// |
| 357 /// [isSubcommand] indicates whether the commands should be called "commands" or |
| 358 /// "subcommands". |
| 359 String _getCommandUsage(Map<String, Command> commands, |
| 360 {bool isSubcommand: false}) { |
| 361 // Don't include aliases. |
| 362 var names = |
| 363 commands.keys.where((name) => !commands[name].aliases.contains(name)); |
| 364 |
| 365 // Filter out hidden ones, unless they are all hidden. |
| 366 var visible = names.where((name) => !commands[name].hidden); |
| 367 if (visible.isNotEmpty) names = visible; |
| 368 |
| 369 // Show the commands alphabetically. |
| 370 names = names.toList()..sort(); |
| 371 var length = names.map((name) => name.length).reduce(math.max); |
| 372 |
| 373 var buffer = |
| 374 new StringBuffer('Available ${isSubcommand ? "sub" : ""}commands:'); |
| 375 for (var name in names) { |
| 376 buffer.writeln(); |
| 377 buffer.write(' ${padRight(name, length)} ' |
| 378 '${commands[name].description.split("\n").first}'); |
| 379 } |
| 380 |
| 381 return buffer.toString(); |
| 382 } |
OLD | NEW |