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