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

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

Issue 10335007: First pass at a generic reusable command line option parser. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 8 years, 7 months 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 | « no previous file | lib/args/example.dart » ('j') | lib/unittest/unittest.dart » ('J')
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2012, 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');
6
7 #import('utils.dart');
8
9 /// Creates a new [ArgParser] which can be used to parse and validate options
10 /// from a list of command-line argument strings. It supports [GNU][] and
11 /// [POSIX][] style options.
12 ///
13 /// ## Defining options ##
14 ///
15 /// To use this library, you create an [ArgParser] object which will contain
16 /// the set of options you support:
17 ///
18 /// var parser = new ArgParser();
19 ///
20 /// Then you define a set of options on that parser using [addOption()] and
21 /// [addFlag()]. The minimal way to create an option is:
22 ///
23 /// parser.addOption('name');
24 ///
25 /// This creates an option named "name". Options must be given a value on the
26 /// command line. If you have a simple on/off option, you can instead use a
27 /// flag:
28 ///
29 /// parser.addFlag('name');
30 ///
31 /// (From here on out "option" will refer to both "regular" options and flags.
32 /// In cases where the distinction matters, we'll use "non-flag option".)
33 ///
34 /// Options may have an optional single-character abbreviation:
35 ///
36 /// parser.addOption('mode', abbr: 'm');
37 /// parser.addFlag('verbose', abbr: 'v');
38 ///
39 /// They may also specify a default value. If provided, then when you later
40 /// query for the option, in the parsed results, the default value will be
41 /// returned if it wasn't provided by the arguments:
42 ///
43 /// parser.addOption('mode', defaultsTo: 'debug');
44 /// parser.addFlag('verbose', defaultsTo: false);
45 ///
46 /// The default value for non-flag options can be any [String]. For flags, it
47 /// must be a [bool].
48 ///
49 /// To validate non-flag options, you may provide an allowed set of values. When
50 /// you do, it will throw an [ArgFormatException] when you parse the arguments
51 /// if the value for an option is not in the allowed set.
52 ///
53 /// parser.addOption('mode', allowed: ['debug', 'release']);
54 ///
55 /// You can provide a callback when you define an option. When you later parse
56 /// a set of arguments, the callback for that option will be invoked with the
57 /// value provided for it.
58 ///
59 /// parser.addOption('mode', callback: (mode) => print('Got mode $mode));
60 /// parser.addFlag('verbose', callback: (verbose) {
61 /// if (verbose) print('Verbose');
62 /// });
63 ///
64 /// The callback for each option will *always* be called
65 /// when you parse a set of arguments. If the option isn't provided in the args,
66 /// the callback will be passed the default value, or `null` if there is none
67 /// set.
68 ///
69 /// ## Parsing arguments ##
70 ///
71 /// Once you have an [ArgParser] set up with some options and flags, you use it
72 /// by calling [ArgParser.parse()] with a set of arguments:
73 ///
74 /// var results = parser.parse(['some', 'command', 'line', 'args']);
75 ///
76 /// These will usually come from `new Options().arguments`, but you can pass in
77 /// any list of strings. It returns an instance of [ArgResults]. This is a
78 /// map-like object that will return the value of any parsed option.
79 ///
80 /// var parser = new ArgParser();
81 /// parser.addOption('mode');
82 /// parser.addFlag('verbose', defaultsTo: true);
83 /// var results = parser.parser('['--mode', 'debug', 'something', 'else']);
84 ///
85 /// print(results['mode']); // debug
86 /// print(results['verbose']); // true
87 ///
88 /// The [parse()] method will stop as soon as it reaches `--` or anything that
89 /// it doesn't recognize as an option, flag, or option value. If there are still
90 /// arguments left, they will be provided to you in
91 /// [ArgResults.remainingArguments].
92 ///
93 /// print(results.remainingArguments); // ['something', 'else']
94 ///
95 /// ## Specifying options ##
96 ///
97 /// To actually pass in options and flags on the command line, use GNU or POSIX
98 /// style. If you define an option like:
99 ///
100 /// parser.addOption('name', abbr: 'n');
101 ///
102 /// Then a value for it can be specified on the command line using any of:
103 ///
104 /// --name=somevalue
105 /// --name somevalue
106 /// -nsomevalue
107 /// -n somevalue
108 ///
109 /// Given this flag:
110 ///
111 /// parser.addFlag('name', abbr: 'n');
112 ///
113 /// You can set it on using one of:
114 ///
115 /// --name
116 /// -n
117 ///
118 /// Or set it off using:
119 ///
120 /// --no-name
121 ///
122 /// ## Usage ##
123 ///
124 /// This library can also be used to automatically generate nice usage help
125 /// text like you get when you run a program with `--help`. To use this, you
126 /// will also want to provide some help text when you create your options. To
127 /// define help text for the entire option, do:
128 ///
129 /// parser.addOption('mode', help: 'The compiler configuration',
130 /// allowed: ['debug', 'release']);
131 /// parser.addFlag('verbose', help: 'Show additional diagnostic info');
132 ///
133 /// For non-flag options, you can also provide detailed help for each expected
134 /// value using a map:
135 ///
136 /// parser.addOption('arch', help: 'The architecture to compile for',
137 /// allowedHelp: {
138 /// 'ia32': 'Intel x86',
139 /// 'arm': 'ARM Holding 32-bit chip'
140 /// });
141 ///
142 /// If you define a set of options like the above, then calling this:
143 ///
144 /// print(parser.getUsage());
145 ///
146 /// Will display something like:
147 ///
148 /// --mode The compiler configuration
149 /// [debug, release]
150 ///
151 /// --[no-]verbose Show additional diagnostic info
152 /// --arch The architecture to compile for
153 ///
154 /// [arm] ARM Holding 32-bit chip
155 /// [ia32] Intel x86
156 ///
157 /// [posix]: http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap12. html#tag_12_02
158 /// [gnu]: http://www.gnu.org/prep/standards/standards.html#Command_002dLine-Int erfaces
159 class ArgParser {
160 static final _SOLO_OPT = const RegExp(@'^-([a-z0-9])$');
161 static final _ABBR_OPT = const RegExp(@'^-([a-z0-9]+)(.*)$');
162 static final _LONG_OPT = const RegExp(@'^--([a-z\-_0-9]+)(=(.*))?$');
163
164 final Map<String, _Option> _options;
165
166 /// The names of the options, in the order that they were added. This way we
167 /// can generate usage information in the same order.
168 final List<String> _optionNames;
169
170 /// The current argument list being parsed. Set by [parse()].
171 List<String> _args;
172
173 /// Index of the current argument being parsed in [_args].
174 int _current;
175
176 /// Creates a new ArgParser.
177 ArgParser()
178 : _options = <_Option>{},
179 _optionNames = <String>[] {
180 }
181
182 /// Defines a flag. Throws an [IllegalArgumentException] if:
183 ///
184 /// * There is already an option with name [name].
185 /// * There is already an option using abbreviation [abbr].
186 void addFlag(String name, [String abbr, String help, bool defaultsTo,
187 void callback(bool value)]) {
188 _addOption(name, abbr, help, null, null, defaultsTo, callback,
189 isFlag: true);
190 }
191
192 /// Defines a value-taking option. Throws an [IllegalArgumentException] if:
193 ///
194 /// * There is already an option with name [name].
195 /// * There is already an option using abbreviation [abbr].
196 void addOption(String name, [String abbr, String help, List<String> allowed,
197 Map<String, String> allowedHelp, String defaultsTo,
198 void callback(bool value)]) {
199 _addOption(name, abbr, help, allowed, allowedHelp, defaultsTo, callback,
200 isFlag: false);
201 }
202
203 void _addOption(String name, [String abbr, String help, List<String> allowed,
204 Map<String, String> allowedHelp, defaultsTo,
205 void callback(bool value), bool isFlag]) {
206 // Make sure the name isn't in use.
207 if (_options.containsKey(name)) {
208 throw new IllegalArgumentException('Duplicate option "$name".');
209 }
210
211 // Make sure the abbreviation isn't too long or in use.
212 if (abbr != null) {
213 if (abbr.length > 1) {
214 throw new IllegalArgumentException(
215 'Abbreviation "$abbr" is longer than one character.');
216 }
217
218 var existing = _findByAbbr(abbr);
219 if (existing != null) {
220 throw new IllegalArgumentException(
221 'Abbreviation "$abbr" is already used by "${existing.name}".');
222 }
223 }
224
225 _options[name] = new _Option(name, abbr, help, allowed, allowedHelp,
226 defaultsTo, callback, isFlag: isFlag);
227 _optionNames.add(name);
228 }
229
230 /// Parses [args], a list of command-line arguments, matches them against the
231 /// flags and options defined by this parser, and returns the result.
232 ArgResults parse(List<String> args) {
233 _args = args;
234 _current = 0;
235 var results = {};
236
237 // Initialize flags to their defaults.
238 _options.forEach((name, option) {
239 results[name] = option.defaultValue;
240 });
241
242 // Parse the args.
243 for (_current = 0; _current < args.length; _current++) {
244 var arg = args[_current];
245
246 if (arg == '--') {
247 // Reached the argument terminator, so stop here.
248 _current++;
249 break;
250 }
251
252 // Try to parse the current argument as an option. Note that the order
253 // here matters.
254 if (_parseSoloOption(results)) continue;
255 if (_parseAbbreviation(results)) continue;
256 if (_parseLongOption(results)) continue;
257
258 // If we got here, the argument doesn't look like an option, so stop.
259 break;
260 }
261
262 // Invoke the callbacks.
263 for (var name in _optionNames) {
264 var option = _options[name];
265 if (option.callback != null) option.callback(results[name]);
266 }
267
268 // Add in the leftover arguments we didn't parse.
269 return new ArgResults(results,
270 _args.getRange(_current, _args.length - _current));
271 }
272
273 /// Generates a string displaying usage imformation for the defined options.
274 /// This is basically the help text shown on the command line.
275 String getUsage() {
276 return new _Usage(this).generate();
277 }
278
279 /// Called during parsing to validate the arguments. Throws an
280 /// [ArgFormatException] if [condition] is `false`.
281 _validate(bool condition, String message) {
282 if (!condition) throw new ArgFormatException(message);
283 }
284
285 /// Validates and stores [value] as the value for [option].
286 _setOption(Map results, _Option option, value) {
287 // See if it's one of the allowed values.
288 if (option.allowed != null) {
289 _validate(option.allowed.some((allow) => allow == value),
290 '"$value" is not an allowed value for option "${option.name}".');
291 }
292
293 results[option.name] = value;
294 }
295
296 /// Pulls the value for [options] from the next argument in [args] (where the
297 /// current option is at index [i]. Validates that there is a valid value
298 /// there.
299 void _readNextArgAsValue(Map results, _Option option) {
300 _current++;
301 // Take the option argument from the next command line arg.
302 _validate(_current < _args.length,
303 'Missing argument for "${option.name}".');
304
305 // Make sure it isn't an option itself.
306 _validate(!_ABBR_OPT.hasMatch(_args[_current]) &&
307 !_LONG_OPT.hasMatch(_args[_current]),
308 'Missing argument for "${option.name}".');
309
310 _setOption(results, option, _args[_current]);
311 }
312
313 /// Tries to parse the current argument as a "solo" option, which is a single
314 /// hyphen followed by a single letter. We treat this specially from
315 /// collapsed abbreviations (like "-abc") to handle the possible value that
316 /// may follow it.
317 bool _parseSoloOption(Map results) {
318 var soloOpt = _SOLO_OPT.firstMatch(_args[_current]);
319 if (soloOpt == null) return false;
320
321 var option = _findByAbbr(soloOpt[1]);
322 _validate(option != null,
323 'Could not find an option or flag "-${soloOpt[1]}".');
324
325 if (option.isFlag) {
326 _setOption(results, option, true);
327 } else {
328 _readNextArgAsValue(results, option);
329 }
330
331 return true;
332 }
333
334 /// Tries to parse the current argument as a series of collapsed abbreviations
335 /// (like "-abc") or a single abbreviation with the value directly attached
336 /// to it (like "-mrelease").
337 bool _parseAbbreviation(Map results) {
338 var abbrOpt = _ABBR_OPT.firstMatch(_args[_current]);
339 if (abbrOpt == null) return false;
340
341 // If the first character is the abbreviation for an option, then the
342 // rest is the value.
343 var c = abbrOpt[1].substring(0, 1);
344 var first = _findByAbbr(c);
345 if (first == null) {
346 _validate(false, 'Could not find an option with short name "-$c".');
347 } else if (!first.isFlag) {
348 // The first character is an option, so the rest must be the value.
349 var value = '${abbrOpt[1].substring(1)}${abbrOpt[2]}';
350 _setOption(results, first, value);
351 } else {
352 // If we got some non-flag characters, then it must be a value, but
353 // if we got here, it's a flag, which is wrong.
354 _validate(abbrOpt[2] == '',
355 'Option "-$c" is a flag and cannot handle value '
356 '"${abbrOpt[1].substring(1)}${abbrOpt[2]}".');
357
358 // Not an option, so all characters should be flags.
359 for (var i = 0; i < abbrOpt[1].length; i++) {
360 var c = abbrOpt[1].substring(i, i + 1);
361 var option = _findByAbbr(c);
362 _validate(option != null,
363 'Could not find an option with short name "-$c".');
364
365 // In a list of short options, only the first can be a non-flag. If
366 // we get here we've checked that already.
367 _validate(option.isFlag,
368 'Option "-$c" must be a flag to be in a collapsed "-".');
369
370 _setOption(results, option, true);
371 }
372 }
373
374 return true;
375 }
376
377 /// Tries to parse the current argument as a long-form named option, which
378 /// may include a value like "--mode=release" or "--mode release".
379 bool _parseLongOption(Map results) {
380 var longOpt = _LONG_OPT.firstMatch(_args[_current]);
381 if (longOpt == null) return false;
382
383 var name = longOpt[1];
384 var option = _options[name];
385 if (option != null) {
386 if (option.isFlag) {
387 _validate(longOpt[3] == null,
388 'Flag option "$name" should not be given a value.');
389
390 _setOption(results, option, true);
391 } else {
392 // Option. Find the argument value.
393 if (longOpt[3] != null) {
394 // We have a value like --foo=bar.
395 _setOption(results, option, longOpt[3]);
396 } else {
397 _readNextArgAsValue(results, option);
398 }
399 }
400 } else if (name.startsWith('no-')) {
401 // See if it's a negated flag.
402 name = name.substring('no-'.length);
403 option = _options[name];
404 _validate(option != null, 'Could not find an option named "$name".');
405 _validate(option.isFlag, 'Cannot negate non-flag option "$name.');
406
407 _setOption(results, option, false);
408 } else {
409 _validate(option != null, 'Could not find an option named "$name".');
410 }
411
412 return true;
413 }
414
415 /// Finds the option whose abbreviation is [abbr], or `null` if no option has
416 /// that abbreviation.
417 _Option _findByAbbr(String abbr) {
418 for (var option in _options.getValues()) {
419 if (option.abbreviation == abbr) return option;
420 }
421
422 return null;
423 }
424 }
425
426 /// The results of parsing a series of command line arguments using
427 /// [ArgParser.parse()]. Includes the parsed options and any remaining unparsed
428 /// command line arguments.
429 class ArgResults {
430 final Map _options;
431
432 /// The remaining command-line arguments that were not parsed as options or
433 /// flags. If `--` was used to separate the options from the remaining
434 /// arguments, it will not be included in this list.
435 final List<String> remainingArgs;
436
437 /// Creates a new [ArgResults].
438 ArgResults(this._options, this.remainingArgs);
439
440 /// Gets the parsed command-line option named [name].
441 operator [](String name) {
442 if (!_options.containsKey(name)) {
443 throw new IllegalArgumentException(
444 'Could not find an option named "$name".');
445 }
446
447 return _options[name];
448 }
449 }
450
451 /// Exception thrown by [ArgParser.parse()] when the argument list isn't valid.
452 class ArgFormatException implements Exception {
453 final String message;
454 const ArgFormatException(this.message);
455 }
456
457 class _Option {
458 final String name;
459 final String abbreviation;
460 final List allowed;
461 final defaultValue;
462 final Function callback;
463 final String help;
464 final Map<String, String> allowedHelp;
465 final bool isFlag;
466
467 _Option(this.name, this.abbreviation, this.help, this.allowed,
468 this.allowedHelp, this.defaultValue, this.callback, [this.isFlag]);
469 }
470
471 class _Usage {
472 static final NUM_COLUMNS = 3; // Abbreviation, long name, help.
473
474 final ArgParser args;
475 StringBuffer buffer;
476 int currentColumn = 0;
477 List<int> columnWidths;
478 int numHelpLines = 0;
479 int newlinesNeeded = 0;
480
481 _Usage(this.args);
482
483 /// Generates a string displaying usage imformation for the defined options.
484 /// This is basically the help text shown on the command line.
485 String generate() {
486 buffer = new StringBuffer();
487
488 calculateColumnWidths();
489
490 for (var name in args._optionNames) {
491 var option = args._options[name];
492 write(0, getAbbreviation(option));
493 write(1, getLongOption(option));
494
495 if (option.help != null) write(2, option.help);
496
497 if (option.allowedHelp != null) {
498 var allowedNames = option.allowedHelp.getKeys();
499 allowedNames.sort((a, b) => a.compareTo(b));
500 newline();
501 for (var name in allowedNames) {
502 write(1, getAllowedTitle(name));
503 write(2, option.allowedHelp[name]);
504 }
505 newline();
506 } else if (option.allowed != null) {
507 write(2, buildAllowedList(option));
508 } else if (option.defaultValue != null) {
509 if (option.isFlag) {
510 write(2, '(defaults to ${option.defaultValue ? "on" : "off"})');
511 } else {
512 write(2, '(defaults to "${option.defaultValue}")');
513 }
514 }
515
516 // If any given option displays more than one line of text on the right
517 // column (i.e. help, default value, allowed options, etc.) then put a
518 // blank line after it. This gives space where it's useful while still
519 // keeping simple one-line options clumped together.
520 if (numHelpLines > 1) newline();
521 }
522
523 return buffer.toString();
524 }
525
526 String getAbbreviation(_Option option) {
527 if (option.abbreviation != null) {
528 return '-${option.abbreviation}, ';
529 } else {
530 return '';
531 }
532 }
533
534 String getLongOption(_Option option) {
535 if (option.isFlag) {
536 return '--[no-]${option.name}';
537 } else {
538 return '--${option.name}';
539 }
540 }
541
542 String getAllowedTitle(String allowed) {
543 return ' [$allowed]';
544 }
545
546 void calculateColumnWidths() {
547 int abbr = 0;
548 int title = 0;
549 for (var name in args._optionNames) {
550 var option = args._options[name];
551
552 // Make room in the first column if there are abbreviations.
553 abbr = Math.max(abbr, getAbbreviation(option).length);
554
555 // Make room for the option.
556 title = Math.max(title, getLongOption(option).length);
557
558 // Make room for the allowed help affects it.
559 if (option.allowedHelp != null) {
560 for (var allowed in option.allowedHelp.getKeys()) {
561 title = Math.max(title, getAllowedTitle(allowed).length);
562 }
563 }
564 }
565
566 // Leave a gutter between the columns.
567 title += 4;
568 columnWidths = [abbr, title];
569 }
570
571 newline() {
572 newlinesNeeded++;
573 currentColumn = 0;
574 numHelpLines = 0;
575 }
576
577 write(int column, String text) {
578 for (var line in text.split('\n')) {
579 writeLine(column, line);
580 }
581 }
582
583 writeLine(int column, String text) {
584 // Write any pending newlines. We do this lazily so that the last bit of
585 // usage doesn't have dangling newlines. We only write newlines right
586 // *before* we write some real content.
587 while (newlinesNeeded > 0) {
588 buffer.add('\n');
589 newlinesNeeded--;
590 }
591
592 // Advance until we are at the right column (which may mean wrapping around
593 // to the next line.
594 while (currentColumn != column) {
595 if (currentColumn < columnWidths.length) {
596 buffer.add(padRight('', columnWidths[currentColumn]));
597 } else {
598 buffer.add('\n');
599 }
600 currentColumn = (currentColumn + 1) % NUM_COLUMNS;
601 }
602
603 if (column < columnWidths.length) {
604 // Fixed-size column, so pad it.
605 buffer.add(padRight(text, columnWidths[column]));
606 } else {
607 // The last column, so just write it.
608 buffer.add(text);
609 }
610
611 // Advance to the next column.
612 currentColumn = (currentColumn + 1) % NUM_COLUMNS;
613
614 // If we reached the last column, we need to wrap to the next line.
615 if (column == NUM_COLUMNS - 1) newlinesNeeded++;
616
617 // Keep track of how many consecutive lines we've written in the last
618 // column.
619 if (column == NUM_COLUMNS - 1) {
620 numHelpLines++;
621 } else {
622 numHelpLines = 0;
623 }
624 }
625
626 buildAllowedList(_Option option) {
627 var allowedBuffer = new StringBuffer();
628 allowedBuffer.add('[');
629 bool first = true;
630 for (var allowed in option.allowed) {
631 if (!first) allowedBuffer.add(', ');
632 allowedBuffer.add(allowed);
633 if (allowed == option.defaultValue) {
634 allowedBuffer.add(' (default)');
635 }
636 first = false;
637 }
638 allowedBuffer.add(']');
639 return allowedBuffer.toString();
640 }
641 }
OLDNEW
« no previous file with comments | « no previous file | lib/args/example.dart » ('j') | lib/unittest/unittest.dart » ('J')

Powered by Google App Engine
This is Rietveld 408576698