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