Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1)

Side by Side Diff: pkg/args/lib/command_runner.dart

Issue 797473002: Add a CommandRunner class for dispatching commands to args. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Code review changes Created 6 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « pkg/args/README.md ('k') | pkg/args/lib/src/help_command.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(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.globalOptions]. 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);
Sean Eagan 2014/12/16 17:41:05 This needs to hook into [usage], or you need to ex
nweiz 2014/12/17 00:04:59 It used to hook into [usage], but based on Bob's f
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 [topLevelOptions].
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 topLevelOptions) {
132 return new Future.sync(() {
133 var options = topLevelOptions;
134 var commands = _commands;
135 var command;
136 var commandString = executableName;
137
138 while (commands.isNotEmpty) {
139 if (options.command == null) {
140 if (options.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 "${options.rest[0]}".');
152 }
153
154 command.usageException('Could not find a subcommand named '
155 '"${options.rest[0]}" for "$commandString".');
156 }
157 }
158
159 // Step into the command.
160 var parent = command;
161 options = options.command;
162 command = commands[options.name];
163 command._globalOptions = topLevelOptions;
164 command._options = options;
165 commands = command._subcommands;
166 commandString += " ${options.name}";
167
168 if (options['help']) {
169 command.printUsage();
170 return new Future.value();
171 }
172 }
173
174 // Make sure there aren't unexpected arguments.
175 if (!command.takesArguments && options.rest.isNotEmpty) {
176 command.usageException(
177 'Command "${options.name}" does not take any arguments.');
178 }
179
180 return command.run();
181 });
182 }
183 }
184
185 /// A single command.
186 ///
187 /// A command is known as a "leaf command" if it has no subcommands and is meant
188 /// to be run. Leaf commands must override [run].
189 ///
190 /// A command with subcommands is known as a "branch command" and cannot be run
191 /// itself. It should call [addSubcommand] (often from the constructor) to
192 /// register subcommands.
193 abstract class Command {
194 /// The name of this command.
195 String get name;
196
197 /// A short description of this command.
198 String get description;
199
200 /// A single-line template for how to invoke this command (e.g. `"pub get
201 /// [package]"`).
202 String get invocation {
203 var parents = [name];
204 for (var command = parent; command != null; command = command.parent) {
205 parents.add(command.name);
206 }
207 parents.add(runner.executableName);
208
209 var invocation = parents.reversed.join(" ");
210 return _subcommands.isNotEmpty ?
211 "$invocation <subcommand> [arguments]" :
212 "$invocation [arguments]";
213 }
214
215 /// The command's parent command, if this is a subcommand.
216 ///
217 /// This will be `null` until [Command.addSubcommmand] has been called with
218 /// this command.
219 Command get parent => _parent;
220 Command _parent;
221
222 /// The command runner for this command.
223 ///
224 /// This will be `null` until [CommandRunner.addCommand] has been called with
225 /// this command or one of its parents.
226 CommandRunner get runner {
227 if (parent == null) return _runner;
228 return parent.runner;
229 }
230 CommandRunner _runner;
231
232 /// The parsed global options.
233 ///
234 /// This will be `null` until just before [Command.run] is called.
235 ArgResults get globalOptions => _globalOptions;
236 ArgResults _globalOptions;
237
238 /// The parsed options for this command.
239 ///
240 /// This will be `null` until just before [Command.run] is called.
241 ArgResults get options => _options;
242 ArgResults _options;
243
244 /// The argument parser for this command.
245 ///
246 /// Options for this command should be registered with this parser (often in
247 /// the constructor); they'll end up available via [options]. Subcommands
248 /// should be registered with [addSubcommand] rather than directly on the
249 /// parser.
250 final argParser = new ArgParser();
251
252 /// Generates a string displaying usage information for this command.
253 ///
254 /// This includes usage for the command's arguments as well as a list of
255 /// subcommands, if there are any.
256 String get usage => "$description\n\n$_usageWithoutDescription";
257
258 /// An optional footer for [usage].
259 ///
260 /// If a subclass overrides this to return a string, it will automatically be
261 /// added to the end of [usage].
262 final String usageFooter = null;
263
264 /// Returns [usage] with [description] removed from the beginning.
265 String get _usageWithoutDescription {
266 var buffer = new StringBuffer()
267 ..writeln('Usage: $invocation')
268 ..writeln(argParser.usage);
269
270 if (_subcommands.isNotEmpty) {
271 buffer.writeln();
272 buffer.writeln(_getCommandUsage(_subcommands, isSubcommand: true));
273 }
274
275 buffer.writeln();
276 buffer.write('Run "${runner.executableName} help" to see global options.');
277
278 if (usageFooter != null) {
279 buffer.writeln();
280 buffer.write(usageFooter);
281 }
282
283 return buffer.toString();
284 }
285
286 /// An unmodifiable view of all sublevel commands of this command.
287 Map<String, Command> get subcommands =>
288 new UnmodifiableMapView(_subcommands);
289 final _subcommands = new Map<String, Command>();
290
291 /// Whether or not this command should be hidden from help listings.
292 ///
293 /// This is intended to be overridden by commands that want to mark themselves
294 /// hidden.
295 ///
296 /// By default, leaf commands are always visible. Branch commands are visible
297 /// as long as any of their leaf commands are visible.
298 bool get hidden {
299 // Leaf commands are visible by default.
300 if (_subcommands.isEmpty) return false;
301
302 // Otherwise, a command is hidden if all of its subcommands are.
303 return _subcommands.values.every((subcommand) => subcommand.hidden);
304 }
305
306 /// Whether or not this command takes positional arguments in addition to
307 /// options.
308 ///
309 /// If false, [CommandRunner.run] will throw a [UsageException] if arguments
310 /// are provided. Defaults to true.
311 ///
312 /// This is intended to be overridden by commands that don't want to receive
313 /// arguments. It has no effect for branch commands.
314 final takesArguments = true;
315
316 /// Alternate names for this command.
317 ///
318 /// These names won't be used in the documentation, but they will work when
319 /// invoked on the command line.
320 ///
321 /// This is intended to be overridden.
322 final aliases = const <String>[];
323
324 Command() {
325 argParser.addFlag('help', abbr: 'h', negatable: false,
326 help: 'Print this usage information.');
327 }
328
329 /// Runs this command.
330 ///
331 /// If this returns a [Future], [CommandRunner.run] won't complete until the
332 /// returned [Future] does. Otherwise, the return value is ignored.
333 run() {
334 throw new UnimplementedError("Leaf command $this must implement run().");
335 }
336
337 /// Adds [Command] as a subcommand of this.
338 void addSubcommand(Command command) {
339 var names = [command.name]..addAll(command.aliases);
340 for (var name in names) {
341 _subcommands[name] = command;
342 argParser.addCommand(name, command.argParser);
343 }
344 command._parent = this;
345 }
346
347 /// Prints the usage information for this command.
348 ///
349 /// This is called internally by [run] and can be overridden by subclasses to
350 /// control how output is displayed or integrate with a logging system.
351 void printUsage() => print(usage);
352
353 /// Throws a [UsageException] with [message].
354 void usageException(String message) =>
355 throw new UsageException(message, _usageWithoutDescription);
356 }
357
358 /// Returns a string representation of [commands] fit for use in a usage string.
359 ///
360 /// [isSubcommand] indicates whether the commands should be called "commands" or
361 /// "subcommands".
362 String _getCommandUsage(Map<String, Command> commands,
363 {bool isSubcommand: false}) {
364 // Don't include aliases.
365 var names = commands.keys
366 .where((name) => !commands[name].aliases.contains(name));
367
368 // Filter out hidden ones, unless they are all hidden.
369 var visible = names.where((name) => !commands[name].hidden);
370 if (visible.isNotEmpty) names = visible;
371
372 // Show the commands alphabetically.
373 names = names.toList()..sort();
374 var length = names.map((name) => name.length).reduce(math.max);
375
376 var buffer = new StringBuffer(
377 'Available ${isSubcommand ? "sub" : ""}commands:');
378 for (var name in names) {
379 buffer.writeln();
380 buffer.write(' ${padRight(name, length)} '
381 '${commands[name].description.split("\n").first}');
382 }
383
384 return buffer.toString();
385 }
OLDNEW
« no previous file with comments | « pkg/args/README.md ('k') | pkg/args/lib/src/help_command.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698