Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | 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 | 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. | 3 // BSD-style license that can be found in the LICENSE file. |
| 4 | 4 |
| 5 /** | 5 /** |
| 6 * This library lets you define parsers for parsing raw command-line arguments | 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. | 7 * into a set of options and values using [GNU][] and [POSIX][] style options. |
| 8 * | 8 * |
| 9 * ## Defining options ## | 9 * ## Defining options ## |
| 10 * | 10 * |
| (...skipping 127 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 138 * | 138 * |
| 139 * If you need multiple values, set the [allowMultiple] flag. In that | 139 * If you need multiple values, set the [allowMultiple] flag. In that |
| 140 * case the option can occur multiple times and when parsing arguments a | 140 * case the option can occur multiple times and when parsing arguments a |
| 141 * List of values will be returned: | 141 * List of values will be returned: |
| 142 * | 142 * |
| 143 * var parser = new ArgParser(); | 143 * var parser = new ArgParser(); |
| 144 * parser.addOption('mode', allowMultiple: true); | 144 * parser.addOption('mode', allowMultiple: true); |
| 145 * var results = parser.parse(['--mode', 'on', '--mode', 'off']); | 145 * var results = parser.parse(['--mode', 'on', '--mode', 'off']); |
| 146 * print(results['mode']); // prints '[on, off]' | 146 * print(results['mode']); // prints '[on, off]' |
| 147 * | 147 * |
| 148 * ## Usage ## | 148 * ## Defining commands ## |
| 149 * | |
| 150 * In addition to *options*, you can also define *commands*. A command is a | |
| 151 * named argument that has its own set of options. For example, when you run: | |
| 152 * | |
| 153 * $ git commit -a | |
| 154 * | |
| 155 * The executable is `git`, the command is `commit`, and the `-a` option is an | |
| 156 * option passed to the command. You can add a command like so: | |
| 157 * | |
| 158 * var parser = new ArgParser(); | |
| 159 * var command = parser.addCommand("commit"); | |
| 160 * command.addFlag('all', abbr: 'a'); | |
| 161 * | |
| 162 * It returns another [ArgParser] which you can use to define options and | |
| 163 * subcommands on that command. When an argument list is parsed, you can then | |
| 164 * determine which command was entered and what options were provided for it. | |
| 165 * | |
| 166 * var results = parser.parse(['commit', '-a']); | |
| 167 * print(results.command.name); // "commit" | |
| 168 * print(results.command['a']); // true | |
| 169 * | |
| 170 * ## Displaying usage ## | |
| 149 * | 171 * |
| 150 * This library can also be used to automatically generate nice usage help | 172 * This library can also be used to automatically generate nice usage help |
| 151 * text like you get when you run a program with `--help`. To use this, you | 173 * text like you get when you run a program with `--help`. To use this, you |
| 152 * will also want to provide some help text when you create your options. To | 174 * will also want to provide some help text when you create your options. To |
| 153 * define help text for the entire option, do: | 175 * define help text for the entire option, do: |
| 154 * | 176 * |
| 155 * parser.addOption('mode', help: 'The compiler configuration', | 177 * parser.addOption('mode', help: 'The compiler configuration', |
| 156 * allowed: ['debug', 'release']); | 178 * allowed: ['debug', 'release']); |
| 157 * parser.addFlag('verbose', help: 'Show additional diagnostic info'); | 179 * parser.addFlag('verbose', help: 'Show additional diagnostic info'); |
| 158 * | 180 * |
| (...skipping 13 matching lines...) Expand all Loading... | |
| 172 * Will display something like: | 194 * Will display something like: |
| 173 * | 195 * |
| 174 * --mode The compiler configuration | 196 * --mode The compiler configuration |
| 175 * [debug, release] | 197 * [debug, release] |
| 176 * | 198 * |
| 177 * --[no-]verbose Show additional diagnostic info | 199 * --[no-]verbose Show additional diagnostic info |
| 178 * --arch The architecture to compile for | 200 * --arch The architecture to compile for |
| 179 * | 201 * |
| 180 * [arm] ARM Holding 32-bit chip | 202 * [arm] ARM Holding 32-bit chip |
| 181 * [ia32] Intel x86 | 203 * [ia32] Intel x86 |
| 182 * | 204 * |
| 183 * To assist the formatting of the usage help, single line help text will | 205 * To assist the formatting of the usage help, single line help text will |
| 184 * be followed by a single new line. Options with multi-line help text | 206 * be followed by a single new line. Options with multi-line help text |
| 185 * will be followed by two new lines. This provides spatial diversity between | 207 * will be followed by two new lines. This provides spatial diversity between |
| 186 * options. | 208 * options. |
| 187 * | 209 * |
| 188 * [posix]: http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap12.h tml#tag_12_02 | 210 * [posix]: http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap12.h tml#tag_12_02 |
| 189 * [gnu]: http://www.gnu.org/prep/standards/standards.html#Command_002dLine-Inte rfaces | 211 * [gnu]: http://www.gnu.org/prep/standards/standards.html#Command_002dLine-Inte rfaces |
| 190 */ | 212 */ |
| 191 library args; | 213 library args; |
| 192 | 214 |
| 193 import 'dart:math'; | 215 import 'dart:math'; |
| 194 | 216 |
| 195 // TODO(rnystrom): Use "package:" URL here when test.dart can handle pub. | |
| 196 import 'src/utils.dart'; | 217 import 'src/utils.dart'; |
| 197 | 218 |
| 219 final _SOLO_OPT = new RegExp(r'^-([a-zA-Z0-9])$'); | |
| 220 final _ABBR_OPT = new RegExp(r'^-([a-zA-Z0-9]+)(.*)$'); | |
| 221 final _LONG_OPT = new RegExp(r'^--([a-zA-Z\-_0-9]+)(=(.*))?$'); | |
| 222 | |
| 198 /** | 223 /** |
| 199 * A class for taking a list of raw command line arguments and parsing out | 224 * A class for taking a list of raw command line arguments and parsing out |
| 200 * options and flags from them. | 225 * options and flags from them. |
| 201 */ | 226 */ |
| 202 class ArgParser { | 227 class ArgParser { |
| 203 static final _SOLO_OPT = new RegExp(r'^-([a-zA-Z0-9])$'); | 228 final Map<String, _Option> _options = <String, _Option>{}; |
| 204 static final _ABBR_OPT = new RegExp(r'^-([a-zA-Z0-9]+)(.*)$'); | 229 final Map<String, ArgParser> _commands = <String, ArgParser>{}; |
| 205 static final _LONG_OPT = new RegExp(r'^--([a-zA-Z\-_0-9]+)(=(.*))?$'); | |
| 206 | |
| 207 final Map<String, _Option> _options; | |
| 208 | 230 |
| 209 /** | 231 /** |
| 210 * The names of the options, in the order that they were added. This way we | 232 * The names of the options, in the order that they were added. This way we |
| 211 * can generate usage information in the same order. | 233 * can generate usage information in the same order. |
| 212 */ | 234 */ |
| 213 // TODO(rnystrom): Use an ordered map type, if one appears. | 235 // TODO(rnystrom): Use an ordered map type, if one appears. |
| 214 final List<String> _optionNames; | 236 final List<String> _optionNames = <String>[]; |
| 215 | |
| 216 /** The current argument list being parsed. Set by [parse()]. */ | |
| 217 List<String> _args; | |
| 218 | |
| 219 /** Index of the current argument being parsed in [_args]. */ | |
| 220 int _current; | |
| 221 | 237 |
| 222 /** Creates a new ArgParser. */ | 238 /** Creates a new ArgParser. */ |
| 223 ArgParser() | 239 ArgParser(); |
| 224 : _options = <String, _Option>{}, | 240 |
| 225 _optionNames = <String>[]; | 241 /** |
| 242 * Defines a command. A command is a named argument which may in turn | |
| 243 * define its own options and subcommands. Returns an [ArgParser] that can | |
| 244 * be used to define the command's options. | |
| 245 */ | |
|
nweiz
2013/01/11 00:06:06
When you have a sec, can you run your comment-fixi
Bob Nystrom
2013/01/11 17:59:49
I thought about that, but I'd like to do that in a
nweiz
2013/01/11 21:43:09
sgtm
| |
| 246 ArgParser addCommand(String name) { | |
| 247 // Make sure the name isn't in use. | |
| 248 if (_commands.containsKey(name)) { | |
| 249 throw new ArgumentError('Duplicate command "$name".'); | |
| 250 } | |
| 251 | |
| 252 var command = new ArgParser(); | |
| 253 _commands[name] = command; | |
| 254 return command; | |
| 255 } | |
| 226 | 256 |
| 227 /** | 257 /** |
| 228 * Defines a flag. Throws an [ArgumentError] if: | 258 * Defines a flag. Throws an [ArgumentError] if: |
| 229 * | 259 * |
| 230 * * There is already an option named [name]. | 260 * * There is already an option named [name]. |
| 231 * * There is already an option using abbreviation [abbr]. | 261 * * There is already an option using abbreviation [abbr]. |
| 232 */ | 262 */ |
| 233 void addFlag(String name, {String abbr, String help, bool defaultsTo: false, | 263 void addFlag(String name, {String abbr, String help, bool defaultsTo: false, |
| 234 bool negatable: true, void callback(bool value)}) { | 264 bool negatable: true, void callback(bool value)}) { |
| 235 _addOption(name, abbr, help, null, null, defaultsTo, callback, | 265 _addOption(name, abbr, help, null, null, defaultsTo, callback, |
| (...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 276 defaultsTo, callback, isFlag: isFlag, negatable: negatable, | 306 defaultsTo, callback, isFlag: isFlag, negatable: negatable, |
| 277 allowMultiple: allowMultiple); | 307 allowMultiple: allowMultiple); |
| 278 _optionNames.add(name); | 308 _optionNames.add(name); |
| 279 } | 309 } |
| 280 | 310 |
| 281 /** | 311 /** |
| 282 * Parses [args], a list of command-line arguments, matches them against the | 312 * Parses [args], a list of command-line arguments, matches them against the |
| 283 * flags and options defined by this parser, and returns the result. | 313 * flags and options defined by this parser, and returns the result. |
| 284 */ | 314 */ |
| 285 ArgResults parse(List<String> args) { | 315 ArgResults parse(List<String> args) { |
| 286 _args = args; | 316 return new _ArgParser(null, this, args).parse(); |
| 287 _current = 0; | 317 } |
| 288 var results = {}; | 318 |
| 319 /** | |
| 320 * Generates a string displaying usage information for the defined options. | |
| 321 * This is basically the help text shown on the command line. | |
| 322 */ | |
| 323 String getUsage() { | |
| 324 return new _Usage(this).generate(); | |
| 325 } | |
| 326 | |
| 327 /** | |
| 328 * Get the default value for an option. Useful after parsing to test | |
| 329 * if the user specified something other than the default. | |
| 330 */ | |
| 331 getDefault(String option) { | |
| 332 if (!_options.containsKey(option)) { | |
| 333 throw new ArgumentError('No option named $option'); | |
| 334 } | |
| 335 return _options[option].defaultValue; | |
| 336 } | |
| 337 | |
| 338 /** | |
| 339 * Finds the option whose abbreviation is [abbr], or `null` if no option has | |
| 340 * that abbreviation. | |
| 341 */ | |
| 342 _Option _findByAbbr(String abbr) { | |
| 343 for (var option in _options.values) { | |
| 344 if (option.abbreviation == abbr) return option; | |
| 345 } | |
| 346 | |
| 347 return null; | |
| 348 } | |
| 349 } | |
| 350 | |
| 351 /** | |
| 352 * The actual parsing class. Unlike [ArgParser] which is really more an "arg | |
| 353 * grammar", this is the class that does the parsing and holds the mutable | |
| 354 * state required during a parse. | |
| 355 */ | |
| 356 class _ArgParser { | |
|
nweiz
2013/01/11 00:06:06
There are getting to be a lot of classes in this f
Bob Nystrom
2013/01/11 17:59:49
Great idea. Done.
| |
| 357 /** | |
| 358 * If parser is parsing a command's options, this will be the name of the | |
| 359 * command. For top-level results, this returns `null`. | |
| 360 */ | |
| 361 final String commandName; | |
| 362 | |
| 363 /** | |
| 364 * The parser for the supercommand of this command parser, or `null` if this | |
| 365 * is the top-level parser. | |
| 366 */ | |
| 367 final _ArgParser parent; | |
| 368 | |
| 369 /** The grammar being parsed. */ | |
| 370 final ArgParser parser; | |
|
nweiz
2013/01/11 00:06:06
"grammar"? It's kind of confusing to read "parser"
Bob Nystrom
2013/01/11 17:59:49
Done.
| |
| 371 | |
| 372 /** The arguments being parsed. */ | |
| 373 final List<String> args; | |
| 374 | |
| 375 /** The accumulated parsed options. */ | |
| 376 final Map results = {}; | |
| 377 | |
| 378 _ArgParser(this.commandName, this.parser, this.args, [this.parent]); | |
| 379 | |
| 380 /** The current argument being parsed. */ | |
| 381 String get current => args[0]; | |
| 382 | |
| 383 /** Parses the arguments. This can only be called once. */ | |
| 384 ArgResults parse() { | |
| 385 var commandResults = null; | |
| 289 | 386 |
| 290 // Initialize flags to their defaults. | 387 // Initialize flags to their defaults. |
| 291 _options.forEach((name, option) { | 388 parser._options.forEach((name, option) { |
| 292 if (option.allowMultiple) { | 389 if (option.allowMultiple) { |
| 293 results[name] = []; | 390 results[name] = []; |
| 294 } else { | 391 } else { |
| 295 results[name] = option.defaultValue; | 392 results[name] = option.defaultValue; |
| 296 } | 393 } |
| 297 }); | 394 }); |
| 298 | 395 |
| 299 // Parse the args. | 396 // Parse the args. |
| 300 for (_current = 0; _current < args.length; _current++) { | 397 while (args.length > 0) { |
| 301 var arg = args[_current]; | 398 if (current == '--') { |
| 399 // Reached the argument terminator, so stop here. | |
| 400 args.removeAt(0); | |
| 401 break; | |
| 402 } | |
| 302 | 403 |
| 303 if (arg == '--') { | 404 // Try to parse the current argument as a command. This happens before |
| 304 // Reached the argument terminator, so stop here. | 405 // options so that commands can have option-like names. |
| 305 _current++; | 406 var command = parser._commands[current]; |
| 306 break; | 407 if (command != null) { |
| 408 var commandName = args.removeAt(0); | |
| 409 var commandParser = new _ArgParser(commandName, command, args, this); | |
| 410 commandResults = commandParser.parse(); | |
| 411 continue; | |
| 307 } | 412 } |
| 308 | 413 |
| 309 // Try to parse the current argument as an option. Note that the order | 414 // Try to parse the current argument as an option. Note that the order |
| 310 // here matters. | 415 // here matters. |
| 311 if (_parseSoloOption(results)) continue; | 416 if (parseSoloOption()) continue; |
| 312 if (_parseAbbreviation(results)) continue; | 417 if (parseAbbreviation(this)) continue; |
| 313 if (_parseLongOption(results)) continue; | 418 if (parseLongOption()) continue; |
| 314 | 419 |
| 315 // If we got here, the argument doesn't look like an option, so stop. | 420 // If we got here, the argument doesn't look like an option, so stop. |
| 316 break; | 421 break; |
| 317 } | 422 } |
| 318 | 423 |
| 319 // Set unspecified multivalued arguments to their default value, | 424 // Set unspecified multivalued arguments to their default value, |
| 320 // if any, and invoke the callbacks. | 425 // if any, and invoke the callbacks. |
| 321 for (var name in _optionNames) { | 426 for (var name in parser._optionNames) { |
| 322 var option = _options[name]; | 427 var option = parser._options[name]; |
| 323 if (option.allowMultiple && | 428 if (option.allowMultiple && |
| 324 results[name].length == 0 && | 429 results[name].length == 0 && |
| 325 option.defaultValue != null) { | 430 option.defaultValue != null) { |
| 326 results[name].add(option.defaultValue); | 431 results[name].add(option.defaultValue); |
| 327 } | 432 } |
| 328 if (option.callback != null) option.callback(results[name]); | 433 if (option.callback != null) option.callback(results[name]); |
| 329 } | 434 } |
| 330 | 435 |
| 331 // Add in the leftover arguments we didn't parse. | 436 // Add in the leftover arguments we didn't parse. |
| 332 return new ArgResults(results, | 437 // TODO(bob): How should "rest" be handled with commands? Which command on |
| 333 _args.getRange(_current, _args.length - _current)); | 438 // the stack gets them? |
|
nweiz
2013/01/11 00:06:06
The deepest command should get the rest of the arg
Bob Nystrom
2013/01/11 17:59:49
Done.
| |
| 439 return new ArgResults(results, commandName, commandResults, args); | |
| 334 } | 440 } |
| 335 | 441 |
| 336 /** | 442 /** |
| 337 * Generates a string displaying usage information for the defined options. | 443 * Pulls the value for [option] from the next argument in [args] (where the |
| 338 * This is basically the help text shown on the command line. | 444 * current option is at [index]. Validates that there is a valid value there. |
|
nweiz
2013/01/11 00:06:06
"[index]" -> "[index])".
Bob Nystrom
2013/01/11 17:59:49
Fixed. That doc was out of date. The old parser di
| |
| 339 */ | 445 */ |
| 340 String getUsage() { | 446 void readNextArgAsValue(_Option option) { |
| 341 return new _Usage(this).generate(); | 447 args.removeAt(0); |
| 448 | |
| 449 // Take the option argument from the next command line arg. | |
| 450 validate(args.length > 0, | |
| 451 'Missing argument for "${option.name}".'); | |
| 452 | |
| 453 // Make sure it isn't an option itself. | |
| 454 validate(!_ABBR_OPT.hasMatch(current) && !_LONG_OPT.hasMatch(current), | |
| 455 'Missing argument for "${option.name}".'); | |
|
nweiz
2013/01/11 00:06:06
You should run these validations before you remove
Bob Nystrom
2013/01/11 17:59:49
It's a little confusing. The first element in the
| |
| 456 | |
| 457 setOption(results, option, current); | |
| 342 } | 458 } |
| 343 | 459 |
| 344 /** | 460 /** |
| 345 * Called during parsing to validate the arguments. Throws a | |
| 346 * [FormatException] if [condition] is `false`. | |
| 347 */ | |
| 348 _validate(bool condition, String message) { | |
| 349 if (!condition) throw new FormatException(message); | |
| 350 } | |
| 351 | |
| 352 /** Validates and stores [value] as the value for [option]. */ | |
| 353 _setOption(Map results, _Option option, value) { | |
| 354 // See if it's one of the allowed values. | |
| 355 if (option.allowed != null) { | |
| 356 _validate(option.allowed.any((allow) => allow == value), | |
| 357 '"$value" is not an allowed value for option "${option.name}".'); | |
| 358 } | |
| 359 | |
| 360 if (option.allowMultiple) { | |
| 361 results[option.name].add(value); | |
| 362 } else { | |
| 363 results[option.name] = value; | |
| 364 } | |
| 365 } | |
| 366 | |
| 367 /** | |
| 368 * Pulls the value for [option] from the next argument in [_args] (where the | |
| 369 * current option is at index [_current]. Validates that there is a valid | |
| 370 * value there. | |
| 371 */ | |
| 372 void _readNextArgAsValue(Map results, _Option option) { | |
| 373 _current++; | |
| 374 // Take the option argument from the next command line arg. | |
| 375 _validate(_current < _args.length, | |
| 376 'Missing argument for "${option.name}".'); | |
| 377 | |
| 378 // Make sure it isn't an option itself. | |
| 379 _validate(!_ABBR_OPT.hasMatch(_args[_current]) && | |
| 380 !_LONG_OPT.hasMatch(_args[_current]), | |
| 381 'Missing argument for "${option.name}".'); | |
| 382 | |
| 383 _setOption(results, option, _args[_current]); | |
| 384 } | |
| 385 | |
| 386 /** | |
| 387 * Tries to parse the current argument as a "solo" option, which is a single | 461 * Tries to parse the current argument as a "solo" option, which is a single |
| 388 * hyphen followed by a single letter. We treat this differently than | 462 * hyphen followed by a single letter. We treat this differently than |
| 389 * collapsed abbreviations (like "-abc") to handle the possible value that | 463 * collapsed abbreviations (like "-abc") to handle the possible value that |
| 390 * may follow it. | 464 * may follow it. |
| 391 */ | 465 */ |
| 392 bool _parseSoloOption(Map results) { | 466 bool parseSoloOption() { |
| 393 var soloOpt = _SOLO_OPT.firstMatch(_args[_current]); | 467 var soloOpt = _SOLO_OPT.firstMatch(current); |
| 394 if (soloOpt == null) return false; | 468 if (soloOpt == null) return false; |
| 395 | 469 |
| 396 var option = _findByAbbr(soloOpt[1]); | 470 var option = parser._findByAbbr(soloOpt[1]); |
| 397 _validate(option != null, | 471 if (option == null) { |
| 398 'Could not find an option or flag "-${soloOpt[1]}".'); | 472 // Walk up to the parent command if possible. |
| 473 validate(parent != null, | |
| 474 'Could not find an option or flag "-${soloOpt[1]}".'); | |
| 475 return parent.parseSoloOption(); | |
| 476 } | |
| 399 | 477 |
| 400 if (option.isFlag) { | 478 if (option.isFlag) { |
| 401 _setOption(results, option, true); | 479 setOption(results, option, true); |
| 402 } else { | 480 } else { |
| 403 _readNextArgAsValue(results, option); | 481 readNextArgAsValue(option); |
| 404 } | 482 } |
| 405 | 483 |
| 484 args.removeAt(0); | |
| 406 return true; | 485 return true; |
| 407 } | 486 } |
| 408 | 487 |
| 409 /** | 488 /** |
| 410 * Tries to parse the current argument as a series of collapsed abbreviations | 489 * Tries to parse the current argument as a series of collapsed abbreviations |
| 411 * (like "-abc") or a single abbreviation with the value directly attached | 490 * (like "-abc") or a single abbreviation with the value directly attached |
| 412 * to it (like "-mrelease"). | 491 * to it (like "-mrelease"). |
| 413 */ | 492 */ |
| 414 bool _parseAbbreviation(Map results) { | 493 bool parseAbbreviation(_ArgParser innermostCommand) { |
| 415 var abbrOpt = _ABBR_OPT.firstMatch(_args[_current]); | 494 var abbrOpt = _ABBR_OPT.firstMatch(current); |
| 416 if (abbrOpt == null) return false; | 495 if (abbrOpt == null) return false; |
| 417 | 496 |
| 418 // If the first character is the abbreviation for a non-flag option, then | 497 // If the first character is the abbreviation for a non-flag option, then |
| 419 // the rest is the value. | 498 // the rest is the value. |
| 420 var c = abbrOpt[1].substring(0, 1); | 499 var c = abbrOpt[1].substring(0, 1); |
| 421 var first = _findByAbbr(c); | 500 var first = parser._findByAbbr(c); |
| 422 if (first == null) { | 501 if (first == null) { |
| 423 _validate(false, 'Could not find an option with short name "-$c".'); | 502 // Walk up to the parent command if possible. |
| 503 validate(parent != null, | |
| 504 'Could not find an option with short name "-$c".'); | |
| 505 return parent.parseAbbreviation(innermostCommand); | |
| 424 } else if (!first.isFlag) { | 506 } else if (!first.isFlag) { |
| 425 // The first character is a non-flag option, so the rest must be the | 507 // The first character is a non-flag option, so the rest must be the |
| 426 // value. | 508 // value. |
| 427 var value = '${abbrOpt[1].substring(1)}${abbrOpt[2]}'; | 509 var value = '${abbrOpt[1].substring(1)}${abbrOpt[2]}'; |
| 428 _setOption(results, first, value); | 510 setOption(results, first, value); |
| 429 } else { | 511 } else { |
| 430 // If we got some non-flag characters, then it must be a value, but | 512 // If we got some non-flag characters, then it must be a value, but |
| 431 // if we got here, it's a flag, which is wrong. | 513 // if we got here, it's a flag, which is wrong. |
| 432 _validate(abbrOpt[2] == '', | 514 validate(abbrOpt[2] == '', |
| 433 'Option "-$c" is a flag and cannot handle value ' | 515 'Option "-$c" is a flag and cannot handle value ' |
| 434 '"${abbrOpt[1].substring(1)}${abbrOpt[2]}".'); | 516 '"${abbrOpt[1].substring(1)}${abbrOpt[2]}".'); |
| 435 | 517 |
| 436 // Not an option, so all characters should be flags. | 518 // Not an option, so all characters should be flags. |
| 519 // We use "innermostCommand" here so that if a parent command parses the | |
| 520 // *first* letter, subcommands can still be found to parse the other | |
| 521 // letters. | |
| 437 for (var i = 0; i < abbrOpt[1].length; i++) { | 522 for (var i = 0; i < abbrOpt[1].length; i++) { |
| 438 var c = abbrOpt[1].substring(i, i + 1); | 523 var c = abbrOpt[1].substring(i, i + 1); |
| 439 var option = _findByAbbr(c); | 524 innermostCommand.parseShortFlag(c); |
| 440 _validate(option != null, | |
| 441 'Could not find an option with short name "-$c".'); | |
| 442 | |
| 443 // In a list of short options, only the first can be a non-flag. If | |
| 444 // we get here we've checked that already. | |
| 445 _validate(option.isFlag, | |
| 446 'Option "-$c" must be a flag to be in a collapsed "-".'); | |
| 447 | |
| 448 _setOption(results, option, true); | |
| 449 } | 525 } |
| 450 } | 526 } |
| 451 | 527 |
| 528 args.removeAt(0); | |
| 452 return true; | 529 return true; |
| 453 } | 530 } |
| 454 | 531 |
| 532 void parseShortFlag(String c) { | |
| 533 var option = parser._findByAbbr(c); | |
| 534 if (option == null) { | |
| 535 // Walk up to the parent command if possible. | |
| 536 validate(parent != null, | |
| 537 'Could not find an option with short name "-$c".'); | |
| 538 parent.parseShortFlag(c); | |
| 539 return; | |
| 540 } | |
| 541 | |
| 542 // In a list of short options, only the first can be a non-flag. If | |
| 543 // we get here we've checked that already. | |
| 544 validate(option.isFlag, | |
| 545 'Option "-$c" must be a flag to be in a collapsed "-".'); | |
| 546 | |
| 547 setOption(results, option, true); | |
| 548 } | |
| 549 | |
| 455 /** | 550 /** |
| 456 * Tries to parse the current argument as a long-form named option, which | 551 * Tries to parse the current argument as a long-form named option, which |
| 457 * may include a value like "--mode=release" or "--mode release". | 552 * may include a value like "--mode=release" or "--mode release". |
| 458 */ | 553 */ |
| 459 bool _parseLongOption(Map results) { | 554 bool parseLongOption() { |
| 460 var longOpt = _LONG_OPT.firstMatch(_args[_current]); | 555 var longOpt = _LONG_OPT.firstMatch(current); |
| 461 if (longOpt == null) return false; | 556 if (longOpt == null) return false; |
| 462 | 557 |
| 463 var name = longOpt[1]; | 558 var name = longOpt[1]; |
| 464 var option = _options[name]; | 559 var option = parser._options[name]; |
| 465 if (option != null) { | 560 if (option != null) { |
| 466 if (option.isFlag) { | 561 if (option.isFlag) { |
| 467 _validate(longOpt[3] == null, | 562 validate(longOpt[3] == null, |
| 468 'Flag option "$name" should not be given a value.'); | 563 'Flag option "$name" should not be given a value.'); |
| 469 | 564 |
| 470 _setOption(results, option, true); | 565 setOption(results, option, true); |
| 471 } else if (longOpt[3] != null) { | 566 } else if (longOpt[3] != null) { |
| 472 // We have a value like --foo=bar. | 567 // We have a value like --foo=bar. |
| 473 _setOption(results, option, longOpt[3]); | 568 setOption(results, option, longOpt[3]); |
| 474 } else { | 569 } else { |
| 475 // Option like --foo, so look for the value as the next arg. | 570 // Option like --foo, so look for the value as the next arg. |
| 476 _readNextArgAsValue(results, option); | 571 readNextArgAsValue(option); |
| 477 } | 572 } |
| 478 } else if (name.startsWith('no-')) { | 573 } else if (name.startsWith('no-')) { |
| 479 // See if it's a negated flag. | 574 // See if it's a negated flag. |
| 480 name = name.substring('no-'.length); | 575 name = name.substring('no-'.length); |
| 481 option = _options[name]; | 576 option = parser._options[name]; |
| 482 _validate(option != null, 'Could not find an option named "$name".'); | 577 if (option == null) { |
| 483 _validate(option.isFlag, 'Cannot negate non-flag option "$name".'); | 578 // Walk up to the parent command if possible. |
| 484 _validate(option.negatable, 'Cannot negate option "$name".'); | 579 validate(parent != null, 'Could not find an option named "$name".'); |
| 580 return parent.parseLongOption(); | |
| 581 } | |
| 485 | 582 |
| 486 _setOption(results, option, false); | 583 validate(option.isFlag, 'Cannot negate non-flag option "$name".'); |
| 584 validate(option.negatable, 'Cannot negate option "$name".'); | |
| 585 | |
| 586 setOption(results, option, false); | |
| 487 } else { | 587 } else { |
| 488 _validate(option != null, 'Could not find an option named "$name".'); | 588 // Walk up to the parent command if possible. |
| 589 validate(parent != null, 'Could not find an option named "$name".'); | |
| 590 return parent.parseLongOption(); | |
| 489 } | 591 } |
| 490 | 592 |
| 593 args.removeAt(0); | |
| 491 return true; | 594 return true; |
| 492 } | 595 } |
| 493 | 596 |
| 494 /** | 597 /** |
| 495 * Finds the option whose abbreviation is [abbr], or `null` if no option has | 598 * Called during parsing to validate the arguments. Throws a |
| 496 * that abbreviation. | 599 * [FormatException] if [condition] is `false`. |
| 497 */ | 600 */ |
| 498 _Option _findByAbbr(String abbr) { | 601 validate(bool condition, String message) { |
| 499 for (var option in _options.values) { | 602 if (!condition) throw new FormatException(message); |
| 500 if (option.abbreviation == abbr) return option; | 603 } |
| 604 | |
| 605 /** Validates and stores [value] as the value for [option]. */ | |
| 606 setOption(Map results, _Option option, value) { | |
| 607 // See if it's one of the allowed values. | |
| 608 if (option.allowed != null) { | |
| 609 validate(option.allowed.any((allow) => allow == value), | |
| 610 '"$value" is not an allowed value for option "${option.name}".'); | |
| 501 } | 611 } |
| 502 | 612 |
| 503 return null; | 613 if (option.allowMultiple) { |
| 504 } | 614 results[option.name].add(value); |
| 505 | 615 } else { |
| 506 /** | 616 results[option.name] = value; |
| 507 * Get the default value for an option. Useful after parsing to test | |
| 508 * if the user specified something other than the default. | |
| 509 */ | |
| 510 getDefault(String option) { | |
| 511 if (!_options.containsKey(option)) { | |
| 512 throw new ArgumentError('No option named $option'); | |
| 513 } | 617 } |
| 514 return _options[option].defaultValue; | |
| 515 } | 618 } |
| 516 } | 619 } |
| 517 | 620 |
| 518 /** | 621 /** |
| 519 * The results of parsing a series of command line arguments using | 622 * The results of parsing a series of command line arguments using |
| 520 * [ArgParser.parse()]. Includes the parsed options and any remaining unparsed | 623 * [ArgParser.parse()]. Includes the parsed options and any remaining unparsed |
| 521 * command line arguments. | 624 * command line arguments. |
| 522 */ | 625 */ |
| 523 class ArgResults { | 626 class ArgResults { |
| 524 final Map _options; | 627 final Map _options; |
| 525 | 628 |
| 526 /** | 629 /** |
| 630 * If these are the results for parsing a command's options, this will be | |
| 631 * the name of the command. For top-level results, this returns `null`. | |
| 632 */ | |
| 633 final String name; | |
| 634 | |
| 635 /** | |
| 636 * The command that was selected, or `null` if none was. This will contain | |
| 637 * the options that were selected for that command. | |
| 638 */ | |
| 639 final ArgResults command; | |
| 640 | |
| 641 /** | |
| 527 * The remaining command-line arguments that were not parsed as options or | 642 * The remaining command-line arguments that were not parsed as options or |
| 528 * flags. If `--` was used to separate the options from the remaining | 643 * flags. If `--` was used to separate the options from the remaining |
| 529 * arguments, it will not be included in this list. | 644 * arguments, it will not be included in this list. |
| 530 */ | 645 */ |
| 531 final List<String> rest; | 646 final List<String> rest; |
| 532 | 647 |
| 533 /** Creates a new [ArgResults]. */ | 648 /** Creates a new [ArgResults]. */ |
| 534 ArgResults(this._options, this.rest); | 649 ArgResults(this._options, this.name, this.command, this.rest); |
| 535 | 650 |
| 536 /** Gets the parsed command-line option named [name]. */ | 651 /** Gets the parsed command-line option named [name]. */ |
| 537 operator [](String name) { | 652 operator [](String name) { |
| 538 if (!_options.containsKey(name)) { | 653 if (!_options.containsKey(name)) { |
| 539 throw new ArgumentError( | 654 throw new ArgumentError( |
| 540 'Could not find an option named "$name".'); | 655 'Could not find an option named "$name".'); |
| 541 } | 656 } |
| 542 | 657 |
| 543 return _options[name]; | 658 return _options[name]; |
| 544 } | 659 } |
| (...skipping 231 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 776 allowedBuffer.add(allowed); | 891 allowedBuffer.add(allowed); |
| 777 if (allowed == option.defaultValue) { | 892 if (allowed == option.defaultValue) { |
| 778 allowedBuffer.add(' (default)'); | 893 allowedBuffer.add(' (default)'); |
| 779 } | 894 } |
| 780 first = false; | 895 first = false; |
| 781 } | 896 } |
| 782 allowedBuffer.add(']'); | 897 allowedBuffer.add(']'); |
| 783 return allowedBuffer.toString(); | 898 return allowedBuffer.toString(); |
| 784 } | 899 } |
| 785 } | 900 } |
| OLD | NEW |