1var camelCase = require('camelcase') 2var decamelize = require('decamelize') 3var path = require('path') 4var tokenizeArgString = require('./lib/tokenize-arg-string') 5var util = require('util') 6 7function parse (args, opts) { 8 if (!opts) opts = {} 9 // allow a string argument to be passed in rather 10 // than an argv array. 11 args = tokenizeArgString(args) 12 13 // aliases might have transitive relationships, normalize this. 14 var aliases = combineAliases(opts.alias || {}) 15 var configuration = Object.assign({ 16 'short-option-groups': true, 17 'camel-case-expansion': true, 18 'dot-notation': true, 19 'parse-numbers': true, 20 'boolean-negation': true, 21 'negation-prefix': 'no-', 22 'duplicate-arguments-array': true, 23 'flatten-duplicate-arrays': true, 24 'populate--': false, 25 'combine-arrays': false, 26 'set-placeholder-key': false, 27 'halt-at-non-option': false, 28 'strip-aliased': false, 29 'strip-dashed': false, 30 'unknown-options-as-args': false 31 }, opts.configuration) 32 var defaults = opts.default || {} 33 var configObjects = opts.configObjects || [] 34 var envPrefix = opts.envPrefix 35 var notFlagsOption = configuration['populate--'] 36 var notFlagsArgv = notFlagsOption ? '--' : '_' 37 var newAliases = {} 38 // allow a i18n handler to be passed in, default to a fake one (util.format). 39 var __ = opts.__ || util.format 40 var error = null 41 var flags = { 42 aliases: {}, 43 arrays: {}, 44 bools: {}, 45 strings: {}, 46 numbers: {}, 47 counts: {}, 48 normalize: {}, 49 configs: {}, 50 nargs: {}, 51 coercions: {}, 52 keys: [] 53 } 54 var negative = /^-[0-9]+(\.[0-9]+)?/ 55 var negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)') 56 57 ;[].concat(opts.array).filter(Boolean).forEach(function (opt) { 58 var key = opt.key || opt 59 60 // assign to flags[bools|strings|numbers] 61 const assignment = Object.keys(opt).map(function (key) { 62 return ({ 63 boolean: 'bools', 64 string: 'strings', 65 number: 'numbers' 66 })[key] 67 }).filter(Boolean).pop() 68 69 // assign key to be coerced 70 if (assignment) { 71 flags[assignment][key] = true 72 } 73 74 flags.arrays[key] = true 75 flags.keys.push(key) 76 }) 77 78 ;[].concat(opts.boolean).filter(Boolean).forEach(function (key) { 79 flags.bools[key] = true 80 flags.keys.push(key) 81 }) 82 83 ;[].concat(opts.string).filter(Boolean).forEach(function (key) { 84 flags.strings[key] = true 85 flags.keys.push(key) 86 }) 87 88 ;[].concat(opts.number).filter(Boolean).forEach(function (key) { 89 flags.numbers[key] = true 90 flags.keys.push(key) 91 }) 92 93 ;[].concat(opts.count).filter(Boolean).forEach(function (key) { 94 flags.counts[key] = true 95 flags.keys.push(key) 96 }) 97 98 ;[].concat(opts.normalize).filter(Boolean).forEach(function (key) { 99 flags.normalize[key] = true 100 flags.keys.push(key) 101 }) 102 103 Object.keys(opts.narg || {}).forEach(function (k) { 104 flags.nargs[k] = opts.narg[k] 105 flags.keys.push(k) 106 }) 107 108 Object.keys(opts.coerce || {}).forEach(function (k) { 109 flags.coercions[k] = opts.coerce[k] 110 flags.keys.push(k) 111 }) 112 113 if (Array.isArray(opts.config) || typeof opts.config === 'string') { 114 ;[].concat(opts.config).filter(Boolean).forEach(function (key) { 115 flags.configs[key] = true 116 }) 117 } else { 118 Object.keys(opts.config || {}).forEach(function (k) { 119 flags.configs[k] = opts.config[k] 120 }) 121 } 122 123 // create a lookup table that takes into account all 124 // combinations of aliases: {f: ['foo'], foo: ['f']} 125 extendAliases(opts.key, aliases, opts.default, flags.arrays) 126 127 // apply default values to all aliases. 128 Object.keys(defaults).forEach(function (key) { 129 (flags.aliases[key] || []).forEach(function (alias) { 130 defaults[alias] = defaults[key] 131 }) 132 }) 133 134 var argv = { _: [] } 135 var notFlags = [] 136 137 for (var i = 0; i < args.length; i++) { 138 var arg = args[i] 139 var broken 140 var key 141 var letters 142 var m 143 var next 144 var value 145 146 if (isUnknownOptionAsArg(arg)) { 147 argv._.push(arg) 148 // -- separated by = 149 } else if (arg.match(/^--.+=/) || ( 150 !configuration['short-option-groups'] && arg.match(/^-.+=/) 151 )) { 152 // Using [\s\S] instead of . because js doesn't support the 153 // 'dotall' regex modifier. See: 154 // http://stackoverflow.com/a/1068308/13216 155 m = arg.match(/^--?([^=]+)=([\s\S]*)$/) 156 157 // nargs format = '--f=monkey washing cat' 158 if (checkAllAliases(m[1], flags.nargs)) { 159 args.splice(i + 1, 0, m[2]) 160 i = eatNargs(i, m[1], args) 161 // arrays format = '--f=a b c' 162 } else if (checkAllAliases(m[1], flags.arrays)) { 163 args.splice(i + 1, 0, m[2]) 164 i = eatArray(i, m[1], args) 165 } else { 166 setArg(m[1], m[2]) 167 } 168 } else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { 169 key = arg.match(negatedBoolean)[1] 170 setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false) 171 172 // -- separated by space. 173 } else if (arg.match(/^--.+/) || ( 174 !configuration['short-option-groups'] && arg.match(/^-[^-]+/) 175 )) { 176 key = arg.match(/^--?(.+)/)[1] 177 178 // nargs format = '--foo a b c' 179 // should be truthy even if: flags.nargs[key] === 0 180 if (checkAllAliases(key, flags.nargs) !== false) { 181 i = eatNargs(i, key, args) 182 // array format = '--foo a b c' 183 } else if (checkAllAliases(key, flags.arrays)) { 184 i = eatArray(i, key, args) 185 } else { 186 next = args[i + 1] 187 188 if (next !== undefined && (!next.match(/^-/) || 189 next.match(negative)) && 190 !checkAllAliases(key, flags.bools) && 191 !checkAllAliases(key, flags.counts)) { 192 setArg(key, next) 193 i++ 194 } else if (/^(true|false)$/.test(next)) { 195 setArg(key, next) 196 i++ 197 } else { 198 setArg(key, defaultValue(key)) 199 } 200 } 201 202 // dot-notation flag separated by '='. 203 } else if (arg.match(/^-.\..+=/)) { 204 m = arg.match(/^-([^=]+)=([\s\S]*)$/) 205 setArg(m[1], m[2]) 206 207 // dot-notation flag separated by space. 208 } else if (arg.match(/^-.\..+/)) { 209 next = args[i + 1] 210 key = arg.match(/^-(.\..+)/)[1] 211 212 if (next !== undefined && !next.match(/^-/) && 213 !checkAllAliases(key, flags.bools) && 214 !checkAllAliases(key, flags.counts)) { 215 setArg(key, next) 216 i++ 217 } else { 218 setArg(key, defaultValue(key)) 219 } 220 } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { 221 letters = arg.slice(1, -1).split('') 222 broken = false 223 224 for (var j = 0; j < letters.length; j++) { 225 next = arg.slice(j + 2) 226 227 if (letters[j + 1] && letters[j + 1] === '=') { 228 value = arg.slice(j + 3) 229 key = letters[j] 230 231 // nargs format = '-f=monkey washing cat' 232 if (checkAllAliases(key, flags.nargs)) { 233 args.splice(i + 1, 0, value) 234 i = eatNargs(i, key, args) 235 // array format = '-f=a b c' 236 } else if (checkAllAliases(key, flags.arrays)) { 237 args.splice(i + 1, 0, value) 238 i = eatArray(i, key, args) 239 } else { 240 setArg(key, value) 241 } 242 243 broken = true 244 break 245 } 246 247 if (next === '-') { 248 setArg(letters[j], next) 249 continue 250 } 251 252 // current letter is an alphabetic character and next value is a number 253 if (/[A-Za-z]/.test(letters[j]) && 254 /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { 255 setArg(letters[j], next) 256 broken = true 257 break 258 } 259 260 if (letters[j + 1] && letters[j + 1].match(/\W/)) { 261 setArg(letters[j], next) 262 broken = true 263 break 264 } else { 265 setArg(letters[j], defaultValue(letters[j])) 266 } 267 } 268 269 key = arg.slice(-1)[0] 270 271 if (!broken && key !== '-') { 272 // nargs format = '-f a b c' 273 // should be truthy even if: flags.nargs[key] === 0 274 if (checkAllAliases(key, flags.nargs) !== false) { 275 i = eatNargs(i, key, args) 276 // array format = '-f a b c' 277 } else if (checkAllAliases(key, flags.arrays)) { 278 i = eatArray(i, key, args) 279 } else { 280 next = args[i + 1] 281 282 if (next !== undefined && (!/^(-|--)[^-]/.test(next) || 283 next.match(negative)) && 284 !checkAllAliases(key, flags.bools) && 285 !checkAllAliases(key, flags.counts)) { 286 setArg(key, next) 287 i++ 288 } else if (/^(true|false)$/.test(next)) { 289 setArg(key, next) 290 i++ 291 } else { 292 setArg(key, defaultValue(key)) 293 } 294 } 295 } 296 } else if (arg === '--') { 297 notFlags = args.slice(i + 1) 298 break 299 } else if (configuration['halt-at-non-option']) { 300 notFlags = args.slice(i) 301 break 302 } else { 303 argv._.push(maybeCoerceNumber('_', arg)) 304 } 305 } 306 307 // order of precedence: 308 // 1. command line arg 309 // 2. value from env var 310 // 3. value from config file 311 // 4. value from config objects 312 // 5. configured default value 313 applyEnvVars(argv, true) // special case: check env vars that point to config file 314 applyEnvVars(argv, false) 315 setConfig(argv) 316 setConfigObjects() 317 applyDefaultsAndAliases(argv, flags.aliases, defaults) 318 applyCoercions(argv) 319 if (configuration['set-placeholder-key']) setPlaceholderKeys(argv) 320 321 // for any counts either not in args or without an explicit default, set to 0 322 Object.keys(flags.counts).forEach(function (key) { 323 if (!hasKey(argv, key.split('.'))) setArg(key, 0) 324 }) 325 326 // '--' defaults to undefined. 327 if (notFlagsOption && notFlags.length) argv[notFlagsArgv] = [] 328 notFlags.forEach(function (key) { 329 argv[notFlagsArgv].push(key) 330 }) 331 332 if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { 333 Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { 334 delete argv[key] 335 }) 336 } 337 338 if (configuration['strip-aliased']) { 339 // XXX Switch to [].concat(...Object.values(aliases)) once node.js 6 is dropped 340 ;[].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { 341 if (configuration['camel-case-expansion']) { 342 delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')] 343 } 344 345 delete argv[alias] 346 }) 347 } 348 349 // how many arguments should we consume, based 350 // on the nargs option? 351 function eatNargs (i, key, args) { 352 var ii 353 const toEat = checkAllAliases(key, flags.nargs) 354 355 if (toEat === 0) { 356 setArg(key, defaultValue(key)) 357 return i 358 } 359 360 // nargs will not consume flag arguments, e.g., -abc, --foo, 361 // and terminates when one is observed. 362 var available = 0 363 for (ii = i + 1; ii < args.length; ii++) { 364 if (!args[ii].match(/^-[^0-9]/) || isUnknownOptionAsArg(args[ii])) available++ 365 else break 366 } 367 368 if (available < toEat) error = Error(__('Not enough arguments following: %s', key)) 369 370 const consumed = Math.min(available, toEat) 371 for (ii = i + 1; ii < (consumed + i + 1); ii++) { 372 setArg(key, args[ii]) 373 } 374 375 return (i + consumed) 376 } 377 378 // if an option is an array, eat all non-hyphenated arguments 379 // following it... YUM! 380 // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] 381 function eatArray (i, key, args) { 382 let argsToSet = [] 383 let next = args[i + 1] 384 385 if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { 386 argsToSet.push(true) 387 } else if (isUndefined(next) || (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { 388 // for keys without value ==> argsToSet remains an empty [] 389 // set user default value, if available 390 if (defaults.hasOwnProperty(key)) { 391 argsToSet.push(defaults[key]) 392 } 393 } else { 394 for (var ii = i + 1; ii < args.length; ii++) { 395 next = args[ii] 396 if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) break 397 i = ii 398 argsToSet.push(processValue(key, next)) 399 } 400 } 401 402 setArg(key, argsToSet) 403 return i 404 } 405 406 function setArg (key, val) { 407 if (/-/.test(key) && configuration['camel-case-expansion']) { 408 var alias = key.split('.').map(function (prop) { 409 return camelCase(prop) 410 }).join('.') 411 addNewAlias(key, alias) 412 } 413 414 var value = processValue(key, val) 415 416 var splitKey = key.split('.') 417 setKey(argv, splitKey, value) 418 419 // handle populating aliases of the full key 420 if (flags.aliases[key] && flags.aliases[key].forEach) { 421 flags.aliases[key].forEach(function (x) { 422 x = x.split('.') 423 setKey(argv, x, value) 424 }) 425 } 426 427 // handle populating aliases of the first element of the dot-notation key 428 if (splitKey.length > 1 && configuration['dot-notation']) { 429 ;(flags.aliases[splitKey[0]] || []).forEach(function (x) { 430 x = x.split('.') 431 432 // expand alias with nested objects in key 433 var a = [].concat(splitKey) 434 a.shift() // nuke the old key. 435 x = x.concat(a) 436 437 setKey(argv, x, value) 438 }) 439 } 440 441 // Set normalize getter and setter when key is in 'normalize' but isn't an array 442 if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { 443 var keys = [key].concat(flags.aliases[key] || []) 444 keys.forEach(function (key) { 445 argv.__defineSetter__(key, function (v) { 446 val = path.normalize(v) 447 }) 448 449 argv.__defineGetter__(key, function () { 450 return typeof val === 'string' ? path.normalize(val) : val 451 }) 452 }) 453 } 454 } 455 456 function addNewAlias (key, alias) { 457 if (!(flags.aliases[key] && flags.aliases[key].length)) { 458 flags.aliases[key] = [alias] 459 newAliases[alias] = true 460 } 461 if (!(flags.aliases[alias] && flags.aliases[alias].length)) { 462 addNewAlias(alias, key) 463 } 464 } 465 466 function processValue (key, val) { 467 // strings may be quoted, clean this up as we assign values. 468 if (typeof val === 'string' && 469 (val[0] === "'" || val[0] === '"') && 470 val[val.length - 1] === val[0] 471 ) { 472 val = val.substring(1, val.length - 1) 473 } 474 475 // handle parsing boolean arguments --foo=true --bar false. 476 if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { 477 if (typeof val === 'string') val = val === 'true' 478 } 479 480 var value = Array.isArray(val) 481 ? val.map(function (v) { return maybeCoerceNumber(key, v) }) 482 : maybeCoerceNumber(key, val) 483 484 // increment a count given as arg (either no value or value parsed as boolean) 485 if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { 486 value = increment 487 } 488 489 // Set normalized value when key is in 'normalize' and in 'arrays' 490 if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { 491 if (Array.isArray(val)) value = val.map(path.normalize) 492 else value = path.normalize(val) 493 } 494 return value 495 } 496 497 function maybeCoerceNumber (key, value) { 498 if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { 499 const shouldCoerceNumber = isNumber(value) && configuration['parse-numbers'] && ( 500 Number.isSafeInteger(Math.floor(value)) 501 ) 502 if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) value = Number(value) 503 } 504 return value 505 } 506 507 // set args from config.json file, this should be 508 // applied last so that defaults can be applied. 509 function setConfig (argv) { 510 var configLookup = {} 511 512 // expand defaults/aliases, in-case any happen to reference 513 // the config.json file. 514 applyDefaultsAndAliases(configLookup, flags.aliases, defaults) 515 516 Object.keys(flags.configs).forEach(function (configKey) { 517 var configPath = argv[configKey] || configLookup[configKey] 518 if (configPath) { 519 try { 520 var config = null 521 var resolvedConfigPath = path.resolve(process.cwd(), configPath) 522 523 if (typeof flags.configs[configKey] === 'function') { 524 try { 525 config = flags.configs[configKey](resolvedConfigPath) 526 } catch (e) { 527 config = e 528 } 529 if (config instanceof Error) { 530 error = config 531 return 532 } 533 } else { 534 config = require(resolvedConfigPath) 535 } 536 537 setConfigObject(config) 538 } catch (ex) { 539 if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath)) 540 } 541 } 542 }) 543 } 544 545 // set args from config object. 546 // it recursively checks nested objects. 547 function setConfigObject (config, prev) { 548 Object.keys(config).forEach(function (key) { 549 var value = config[key] 550 var fullKey = prev ? prev + '.' + key : key 551 552 // if the value is an inner object and we have dot-notation 553 // enabled, treat inner objects in config the same as 554 // heavily nested dot notations (foo.bar.apple). 555 if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { 556 // if the value is an object but not an array, check nested object 557 setConfigObject(value, fullKey) 558 } else { 559 // setting arguments via CLI takes precedence over 560 // values within the config file. 561 if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { 562 setArg(fullKey, value) 563 } 564 } 565 }) 566 } 567 568 // set all config objects passed in opts 569 function setConfigObjects () { 570 if (typeof configObjects === 'undefined') return 571 configObjects.forEach(function (configObject) { 572 setConfigObject(configObject) 573 }) 574 } 575 576 function applyEnvVars (argv, configOnly) { 577 if (typeof envPrefix === 'undefined') return 578 579 var prefix = typeof envPrefix === 'string' ? envPrefix : '' 580 Object.keys(process.env).forEach(function (envVar) { 581 if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { 582 // get array of nested keys and convert them to camel case 583 var keys = envVar.split('__').map(function (key, i) { 584 if (i === 0) { 585 key = key.substring(prefix.length) 586 } 587 return camelCase(key) 588 }) 589 590 if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { 591 setArg(keys.join('.'), process.env[envVar]) 592 } 593 } 594 }) 595 } 596 597 function applyCoercions (argv) { 598 var coerce 599 var applied = {} 600 Object.keys(argv).forEach(function (key) { 601 if (!applied.hasOwnProperty(key)) { // If we haven't already coerced this option via one of its aliases 602 coerce = checkAllAliases(key, flags.coercions) 603 if (typeof coerce === 'function') { 604 try { 605 var value = maybeCoerceNumber(key, coerce(argv[key])) 606 ;([].concat(flags.aliases[key] || [], key)).forEach(ali => { 607 applied[ali] = argv[ali] = value 608 }) 609 } catch (err) { 610 error = err 611 } 612 } 613 } 614 }) 615 } 616 617 function setPlaceholderKeys (argv) { 618 flags.keys.forEach((key) => { 619 // don't set placeholder keys for dot notation options 'foo.bar'. 620 if (~key.indexOf('.')) return 621 if (typeof argv[key] === 'undefined') argv[key] = undefined 622 }) 623 return argv 624 } 625 626 function applyDefaultsAndAliases (obj, aliases, defaults) { 627 Object.keys(defaults).forEach(function (key) { 628 if (!hasKey(obj, key.split('.'))) { 629 setKey(obj, key.split('.'), defaults[key]) 630 631 ;(aliases[key] || []).forEach(function (x) { 632 if (hasKey(obj, x.split('.'))) return 633 setKey(obj, x.split('.'), defaults[key]) 634 }) 635 } 636 }) 637 } 638 639 function hasKey (obj, keys) { 640 var o = obj 641 642 if (!configuration['dot-notation']) keys = [keys.join('.')] 643 644 keys.slice(0, -1).forEach(function (key) { 645 o = (o[key] || {}) 646 }) 647 648 var key = keys[keys.length - 1] 649 650 if (typeof o !== 'object') return false 651 else return key in o 652 } 653 654 function setKey (obj, keys, value) { 655 var o = obj 656 657 if (!configuration['dot-notation']) keys = [keys.join('.')] 658 659 keys.slice(0, -1).forEach(function (key, index) { 660 // TODO(bcoe): in the next major version of yargs, switch to 661 // Object.create(null) for dot notation: 662 key = sanitizeKey(key) 663 664 if (typeof o === 'object' && o[key] === undefined) { 665 o[key] = {} 666 } 667 668 if (typeof o[key] !== 'object' || Array.isArray(o[key])) { 669 // ensure that o[key] is an array, and that the last item is an empty object. 670 if (Array.isArray(o[key])) { 671 o[key].push({}) 672 } else { 673 o[key] = [o[key], {}] 674 } 675 676 // we want to update the empty object at the end of the o[key] array, so set o to that object 677 o = o[key][o[key].length - 1] 678 } else { 679 o = o[key] 680 } 681 }) 682 683 // TODO(bcoe): in the next major version of yargs, switch to 684 // Object.create(null) for dot notation: 685 const key = sanitizeKey(keys[keys.length - 1]) 686 687 const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays) 688 const isValueArray = Array.isArray(value) 689 let duplicate = configuration['duplicate-arguments-array'] 690 691 // nargs has higher priority than duplicate 692 if (!duplicate && checkAllAliases(key, flags.nargs)) { 693 duplicate = true 694 if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { 695 o[key] = undefined 696 } 697 } 698 699 if (value === increment) { 700 o[key] = increment(o[key]) 701 } else if (Array.isArray(o[key])) { 702 if (duplicate && isTypeArray && isValueArray) { 703 o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]) 704 } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { 705 o[key] = value 706 } else { 707 o[key] = o[key].concat([value]) 708 } 709 } else if (o[key] === undefined && isTypeArray) { 710 o[key] = isValueArray ? value : [value] 711 } else if (duplicate && !(o[key] === undefined || checkAllAliases(key, flags.counts))) { 712 o[key] = [ o[key], value ] 713 } else { 714 o[key] = value 715 } 716 } 717 718 // extend the aliases list with inferred aliases. 719 function extendAliases (...args) { 720 args.forEach(function (obj) { 721 Object.keys(obj || {}).forEach(function (key) { 722 // short-circuit if we've already added a key 723 // to the aliases array, for example it might 724 // exist in both 'opts.default' and 'opts.key'. 725 if (flags.aliases[key]) return 726 727 flags.aliases[key] = [].concat(aliases[key] || []) 728 // For "--option-name", also set argv.optionName 729 flags.aliases[key].concat(key).forEach(function (x) { 730 if (/-/.test(x) && configuration['camel-case-expansion']) { 731 var c = camelCase(x) 732 if (c !== key && flags.aliases[key].indexOf(c) === -1) { 733 flags.aliases[key].push(c) 734 newAliases[c] = true 735 } 736 } 737 }) 738 // For "--optionName", also set argv['option-name'] 739 flags.aliases[key].concat(key).forEach(function (x) { 740 if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { 741 var c = decamelize(x, '-') 742 if (c !== key && flags.aliases[key].indexOf(c) === -1) { 743 flags.aliases[key].push(c) 744 newAliases[c] = true 745 } 746 } 747 }) 748 flags.aliases[key].forEach(function (x) { 749 flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { 750 return x !== y 751 })) 752 }) 753 }) 754 }) 755 } 756 757 // check if a flag is set for any of a key's aliases. 758 function checkAllAliases (key, flag) { 759 var isSet = false 760 var toCheck = [].concat(flags.aliases[key] || [], key) 761 762 toCheck.forEach(function (key) { 763 if (flag.hasOwnProperty(key)) isSet = flag[key] 764 }) 765 766 return isSet 767 } 768 769 function hasAnyFlag (key) { 770 // XXX Switch to [].concat(...Object.values(flags)) once node.js 6 is dropped 771 var toCheck = [].concat(...Object.keys(flags).map(k => flags[k])) 772 773 return toCheck.some(function (flag) { 774 return flag[key] 775 }) 776 } 777 778 function hasFlagsMatching (arg, ...patterns) { 779 var toCheck = [].concat(...patterns) 780 return toCheck.some(function (pattern) { 781 var match = arg.match(pattern) 782 return match && hasAnyFlag(match[1]) 783 }) 784 } 785 786 // based on a simplified version of the short flag group parsing logic 787 function hasAllShortFlags (arg) { 788 // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group 789 if (arg.match(negative) || !arg.match(/^-[^-]+/)) { return false } 790 var hasAllFlags = true 791 var letters = arg.slice(1).split('') 792 var next 793 for (var j = 0; j < letters.length; j++) { 794 next = arg.slice(j + 2) 795 796 if (!hasAnyFlag(letters[j])) { 797 hasAllFlags = false 798 break 799 } 800 801 if ((letters[j + 1] && letters[j + 1] === '=') || 802 next === '-' || 803 (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || 804 (letters[j + 1] && letters[j + 1].match(/\W/))) { 805 break 806 } 807 } 808 return hasAllFlags 809 } 810 811 function isUnknownOptionAsArg (arg) { 812 return configuration['unknown-options-as-args'] && isUnknownOption(arg) 813 } 814 815 function isUnknownOption (arg) { 816 // ignore negative numbers 817 if (arg.match(negative)) { return false } 818 // if this is a short option group and all of them are configured, it isn't unknown 819 if (hasAllShortFlags(arg)) { return false } 820 // e.g. '--count=2' 821 const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/ 822 // e.g. '-a' or '--arg' 823 const normalFlag = /^-+([^=]+?)$/ 824 // e.g. '-a-' 825 const flagEndingInHyphen = /^-+([^=]+?)-$/ 826 // e.g. '-abc123' 827 const flagEndingInDigits = /^-+([^=]+?)\d+$/ 828 // e.g. '-a/usr/local' 829 const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/ 830 // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method 831 return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters) 832 } 833 834 // make a best effor to pick a default value 835 // for an option based on name and type. 836 function defaultValue (key) { 837 if (!checkAllAliases(key, flags.bools) && 838 !checkAllAliases(key, flags.counts) && 839 `${key}` in defaults) { 840 return defaults[key] 841 } else { 842 return defaultForType(guessType(key)) 843 } 844 } 845 846 // return a default value, given the type of a flag., 847 // e.g., key of type 'string' will default to '', rather than 'true'. 848 function defaultForType (type) { 849 var def = { 850 boolean: true, 851 string: '', 852 number: undefined, 853 array: [] 854 } 855 856 return def[type] 857 } 858 859 // given a flag, enforce a default type. 860 function guessType (key) { 861 var type = 'boolean' 862 863 if (checkAllAliases(key, flags.strings)) type = 'string' 864 else if (checkAllAliases(key, flags.numbers)) type = 'number' 865 else if (checkAllAliases(key, flags.bools)) type = 'boolean' 866 else if (checkAllAliases(key, flags.arrays)) type = 'array' 867 868 return type 869 } 870 871 function isNumber (x) { 872 if (x === null || x === undefined) return false 873 // if loaded from config, may already be a number. 874 if (typeof x === 'number') return true 875 // hexadecimal. 876 if (/^0x[0-9a-f]+$/i.test(x)) return true 877 // don't treat 0123 as a number; as it drops the leading '0'. 878 if (x.length > 1 && x[0] === '0') return false 879 return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x) 880 } 881 882 function isUndefined (num) { 883 return num === undefined 884 } 885 886 return { 887 argv: argv, 888 error: error, 889 aliases: flags.aliases, 890 newAliases: newAliases, 891 configuration: configuration 892 } 893} 894 895// if any aliases reference each other, we should 896// merge them together. 897function combineAliases (aliases) { 898 var aliasArrays = [] 899 var change = true 900 var combined = {} 901 902 // turn alias lookup hash {key: ['alias1', 'alias2']} into 903 // a simple array ['key', 'alias1', 'alias2'] 904 Object.keys(aliases).forEach(function (key) { 905 aliasArrays.push( 906 [].concat(aliases[key], key) 907 ) 908 }) 909 910 // combine arrays until zero changes are 911 // made in an iteration. 912 while (change) { 913 change = false 914 for (var i = 0; i < aliasArrays.length; i++) { 915 for (var ii = i + 1; ii < aliasArrays.length; ii++) { 916 var intersect = aliasArrays[i].filter(function (v) { 917 return aliasArrays[ii].indexOf(v) !== -1 918 }) 919 920 if (intersect.length) { 921 aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]) 922 aliasArrays.splice(ii, 1) 923 change = true 924 break 925 } 926 } 927 } 928 } 929 930 // map arrays back to the hash-lookup (de-dupe while 931 // we're at it). 932 aliasArrays.forEach(function (aliasArray) { 933 aliasArray = aliasArray.filter(function (v, i, self) { 934 return self.indexOf(v) === i 935 }) 936 combined[aliasArray.pop()] = aliasArray 937 }) 938 939 return combined 940} 941 942// this function should only be called when a count is given as an arg 943// it is NOT called to set a default value 944// thus we can start the count at 1 instead of 0 945function increment (orig) { 946 return orig !== undefined ? orig + 1 : 1 947} 948 949function Parser (args, opts) { 950 var result = parse(args.slice(), opts) 951 952 return result.argv 953} 954 955// parse arguments and return detailed 956// meta information, aliases, etc. 957Parser.detailed = function (args, opts) { 958 return parse(args.slice(), opts) 959} 960 961// TODO(bcoe): in the next major version of yargs, switch to 962// Object.create(null) for dot notation: 963function sanitizeKey (key) { 964 if (key === '__proto__') return '___proto___' 965 return key 966} 967 968module.exports = Parser 969