index.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. var camelCase = require('camelcase')
  2. var decamelize = require('decamelize')
  3. var path = require('path')
  4. var tokenizeArgString = require('./lib/tokenize-arg-string')
  5. var util = require('util')
  6. function parse (args, opts) {
  7. if (!opts) opts = {}
  8. // allow a string argument to be passed in rather
  9. // than an argv array.
  10. args = tokenizeArgString(args)
  11. // aliases might have transitive relationships, normalize this.
  12. var aliases = combineAliases(opts.alias || {})
  13. var configuration = assign({
  14. 'short-option-groups': true,
  15. 'camel-case-expansion': true,
  16. 'dot-notation': true,
  17. 'parse-numbers': true,
  18. 'boolean-negation': true,
  19. 'negation-prefix': 'no-',
  20. 'duplicate-arguments-array': true,
  21. 'flatten-duplicate-arrays': true,
  22. 'populate--': false,
  23. 'combine-arrays': false,
  24. 'set-placeholder-key': false,
  25. 'halt-at-non-option': false
  26. }, opts.configuration)
  27. var defaults = opts.default || {}
  28. var configObjects = opts.configObjects || []
  29. var envPrefix = opts.envPrefix
  30. var notFlagsOption = configuration['populate--']
  31. var notFlagsArgv = notFlagsOption ? '--' : '_'
  32. var newAliases = {}
  33. // allow a i18n handler to be passed in, default to a fake one (util.format).
  34. var __ = opts.__ || function (str) {
  35. return util.format.apply(util, Array.prototype.slice.call(arguments))
  36. }
  37. var error = null
  38. var flags = {
  39. aliases: {},
  40. arrays: {},
  41. bools: {},
  42. strings: {},
  43. numbers: {},
  44. counts: {},
  45. normalize: {},
  46. configs: {},
  47. defaulted: {},
  48. nargs: {},
  49. coercions: {},
  50. keys: []
  51. }
  52. var negative = /^-[0-9]+(\.[0-9]+)?/
  53. var negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)')
  54. ;[].concat(opts.array).filter(Boolean).forEach(function (opt) {
  55. var key = opt.key || opt
  56. // assign to flags[bools|strings|numbers]
  57. const assignment = Object.keys(opt).map(function (key) {
  58. return ({
  59. boolean: 'bools',
  60. string: 'strings',
  61. number: 'numbers'
  62. })[key]
  63. }).filter(Boolean).pop()
  64. // assign key to be coerced
  65. if (assignment) {
  66. flags[assignment][key] = true
  67. }
  68. flags.arrays[key] = true
  69. flags.keys.push(key)
  70. })
  71. ;[].concat(opts.boolean).filter(Boolean).forEach(function (key) {
  72. flags.bools[key] = true
  73. flags.keys.push(key)
  74. })
  75. ;[].concat(opts.string).filter(Boolean).forEach(function (key) {
  76. flags.strings[key] = true
  77. flags.keys.push(key)
  78. })
  79. ;[].concat(opts.number).filter(Boolean).forEach(function (key) {
  80. flags.numbers[key] = true
  81. flags.keys.push(key)
  82. })
  83. ;[].concat(opts.count).filter(Boolean).forEach(function (key) {
  84. flags.counts[key] = true
  85. flags.keys.push(key)
  86. })
  87. ;[].concat(opts.normalize).filter(Boolean).forEach(function (key) {
  88. flags.normalize[key] = true
  89. flags.keys.push(key)
  90. })
  91. Object.keys(opts.narg || {}).forEach(function (k) {
  92. flags.nargs[k] = opts.narg[k]
  93. flags.keys.push(k)
  94. })
  95. Object.keys(opts.coerce || {}).forEach(function (k) {
  96. flags.coercions[k] = opts.coerce[k]
  97. flags.keys.push(k)
  98. })
  99. if (Array.isArray(opts.config) || typeof opts.config === 'string') {
  100. ;[].concat(opts.config).filter(Boolean).forEach(function (key) {
  101. flags.configs[key] = true
  102. })
  103. } else {
  104. Object.keys(opts.config || {}).forEach(function (k) {
  105. flags.configs[k] = opts.config[k]
  106. })
  107. }
  108. // create a lookup table that takes into account all
  109. // combinations of aliases: {f: ['foo'], foo: ['f']}
  110. extendAliases(opts.key, aliases, opts.default, flags.arrays)
  111. // apply default values to all aliases.
  112. Object.keys(defaults).forEach(function (key) {
  113. (flags.aliases[key] || []).forEach(function (alias) {
  114. defaults[alias] = defaults[key]
  115. })
  116. })
  117. var argv = { _: [] }
  118. Object.keys(flags.bools).forEach(function (key) {
  119. if (Object.prototype.hasOwnProperty.call(defaults, key)) {
  120. setArg(key, defaults[key])
  121. setDefaulted(key)
  122. }
  123. })
  124. var notFlags = []
  125. for (var i = 0; i < args.length; i++) {
  126. var arg = args[i]
  127. var broken
  128. var key
  129. var letters
  130. var m
  131. var next
  132. var value
  133. // -- separated by =
  134. if (arg.match(/^--.+=/) || (
  135. !configuration['short-option-groups'] && arg.match(/^-.+=/)
  136. )) {
  137. // Using [\s\S] instead of . because js doesn't support the
  138. // 'dotall' regex modifier. See:
  139. // http://stackoverflow.com/a/1068308/13216
  140. m = arg.match(/^--?([^=]+)=([\s\S]*)$/)
  141. // nargs format = '--f=monkey washing cat'
  142. if (checkAllAliases(m[1], flags.nargs)) {
  143. args.splice(i + 1, 0, m[2])
  144. i = eatNargs(i, m[1], args)
  145. // arrays format = '--f=a b c'
  146. } else if (checkAllAliases(m[1], flags.arrays) && args.length > i + 1) {
  147. args.splice(i + 1, 0, m[2])
  148. i = eatArray(i, m[1], args)
  149. } else {
  150. setArg(m[1], m[2])
  151. }
  152. } else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
  153. key = arg.match(negatedBoolean)[1]
  154. setArg(key, false)
  155. // -- seperated by space.
  156. } else if (arg.match(/^--.+/) || (
  157. !configuration['short-option-groups'] && arg.match(/^-.+/)
  158. )) {
  159. key = arg.match(/^--?(.+)/)[1]
  160. // nargs format = '--foo a b c'
  161. if (checkAllAliases(key, flags.nargs)) {
  162. i = eatNargs(i, key, args)
  163. // array format = '--foo a b c'
  164. } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
  165. i = eatArray(i, key, args)
  166. } else {
  167. next = args[i + 1]
  168. if (next !== undefined && (!next.match(/^-/) ||
  169. next.match(negative)) &&
  170. !checkAllAliases(key, flags.bools) &&
  171. !checkAllAliases(key, flags.counts)) {
  172. setArg(key, next)
  173. i++
  174. } else if (/^(true|false)$/.test(next)) {
  175. setArg(key, next)
  176. i++
  177. } else {
  178. setArg(key, defaultForType(guessType(key, flags)))
  179. }
  180. }
  181. // dot-notation flag seperated by '='.
  182. } else if (arg.match(/^-.\..+=/)) {
  183. m = arg.match(/^-([^=]+)=([\s\S]*)$/)
  184. setArg(m[1], m[2])
  185. // dot-notation flag seperated by space.
  186. } else if (arg.match(/^-.\..+/)) {
  187. next = args[i + 1]
  188. key = arg.match(/^-(.\..+)/)[1]
  189. if (next !== undefined && !next.match(/^-/) &&
  190. !checkAllAliases(key, flags.bools) &&
  191. !checkAllAliases(key, flags.counts)) {
  192. setArg(key, next)
  193. i++
  194. } else {
  195. setArg(key, defaultForType(guessType(key, flags)))
  196. }
  197. } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
  198. letters = arg.slice(1, -1).split('')
  199. broken = false
  200. for (var j = 0; j < letters.length; j++) {
  201. next = arg.slice(j + 2)
  202. if (letters[j + 1] && letters[j + 1] === '=') {
  203. value = arg.slice(j + 3)
  204. key = letters[j]
  205. // nargs format = '-f=monkey washing cat'
  206. if (checkAllAliases(key, flags.nargs)) {
  207. args.splice(i + 1, 0, value)
  208. i = eatNargs(i, key, args)
  209. // array format = '-f=a b c'
  210. } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
  211. args.splice(i + 1, 0, value)
  212. i = eatArray(i, key, args)
  213. } else {
  214. setArg(key, value)
  215. }
  216. broken = true
  217. break
  218. }
  219. if (next === '-') {
  220. setArg(letters[j], next)
  221. continue
  222. }
  223. // current letter is an alphabetic character and next value is a number
  224. if (/[A-Za-z]/.test(letters[j]) &&
  225. /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
  226. setArg(letters[j], next)
  227. broken = true
  228. break
  229. }
  230. if (letters[j + 1] && letters[j + 1].match(/\W/)) {
  231. setArg(letters[j], next)
  232. broken = true
  233. break
  234. } else {
  235. setArg(letters[j], defaultForType(guessType(letters[j], flags)))
  236. }
  237. }
  238. key = arg.slice(-1)[0]
  239. if (!broken && key !== '-') {
  240. // nargs format = '-f a b c'
  241. if (checkAllAliases(key, flags.nargs)) {
  242. i = eatNargs(i, key, args)
  243. // array format = '-f a b c'
  244. } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
  245. i = eatArray(i, key, args)
  246. } else {
  247. next = args[i + 1]
  248. if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
  249. next.match(negative)) &&
  250. !checkAllAliases(key, flags.bools) &&
  251. !checkAllAliases(key, flags.counts)) {
  252. setArg(key, next)
  253. i++
  254. } else if (/^(true|false)$/.test(next)) {
  255. setArg(key, next)
  256. i++
  257. } else {
  258. setArg(key, defaultForType(guessType(key, flags)))
  259. }
  260. }
  261. }
  262. } else if (arg === '--') {
  263. notFlags = args.slice(i + 1)
  264. break
  265. } else if (configuration['halt-at-non-option']) {
  266. notFlags = args.slice(i)
  267. break
  268. } else {
  269. argv._.push(maybeCoerceNumber('_', arg))
  270. }
  271. }
  272. // order of precedence:
  273. // 1. command line arg
  274. // 2. value from env var
  275. // 3. value from config file
  276. // 4. value from config objects
  277. // 5. configured default value
  278. applyEnvVars(argv, true) // special case: check env vars that point to config file
  279. applyEnvVars(argv, false)
  280. setConfig(argv)
  281. setConfigObjects()
  282. applyDefaultsAndAliases(argv, flags.aliases, defaults)
  283. applyCoercions(argv)
  284. if (configuration['set-placeholder-key']) setPlaceholderKeys(argv)
  285. // for any counts either not in args or without an explicit default, set to 0
  286. Object.keys(flags.counts).forEach(function (key) {
  287. if (!hasKey(argv, key.split('.'))) setArg(key, 0)
  288. })
  289. // '--' defaults to undefined.
  290. if (notFlagsOption && notFlags.length) argv[notFlagsArgv] = []
  291. notFlags.forEach(function (key) {
  292. argv[notFlagsArgv].push(key)
  293. })
  294. // how many arguments should we consume, based
  295. // on the nargs option?
  296. function eatNargs (i, key, args) {
  297. var ii
  298. const toEat = checkAllAliases(key, flags.nargs)
  299. // nargs will not consume flag arguments, e.g., -abc, --foo,
  300. // and terminates when one is observed.
  301. var available = 0
  302. for (ii = i + 1; ii < args.length; ii++) {
  303. if (!args[ii].match(/^-[^0-9]/)) available++
  304. else break
  305. }
  306. if (available < toEat) error = Error(__('Not enough arguments following: %s', key))
  307. const consumed = Math.min(available, toEat)
  308. for (ii = i + 1; ii < (consumed + i + 1); ii++) {
  309. setArg(key, args[ii])
  310. }
  311. return (i + consumed)
  312. }
  313. // if an option is an array, eat all non-hyphenated arguments
  314. // following it... YUM!
  315. // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
  316. function eatArray (i, key, args) {
  317. var start = i + 1
  318. var argsToSet = []
  319. var multipleArrayFlag = i > 0
  320. for (var ii = i + 1; ii < args.length; ii++) {
  321. if (/^-/.test(args[ii]) && !negative.test(args[ii])) {
  322. if (ii === start) {
  323. setArg(key, defaultForType('array'))
  324. }
  325. multipleArrayFlag = true
  326. break
  327. }
  328. i = ii
  329. argsToSet.push(args[ii])
  330. }
  331. if (multipleArrayFlag) {
  332. setArg(key, argsToSet.map(function (arg) {
  333. return processValue(key, arg)
  334. }))
  335. } else {
  336. argsToSet.forEach(function (arg) {
  337. setArg(key, arg)
  338. })
  339. }
  340. return i
  341. }
  342. function setArg (key, val) {
  343. unsetDefaulted(key)
  344. if (/-/.test(key) && configuration['camel-case-expansion']) {
  345. var alias = key.split('.').map(function (prop) {
  346. return camelCase(prop)
  347. }).join('.')
  348. addNewAlias(key, alias)
  349. }
  350. var value = processValue(key, val)
  351. var splitKey = key.split('.')
  352. setKey(argv, splitKey, value)
  353. // handle populating aliases of the full key
  354. if (flags.aliases[key]) {
  355. flags.aliases[key].forEach(function (x) {
  356. x = x.split('.')
  357. setKey(argv, x, value)
  358. })
  359. }
  360. // handle populating aliases of the first element of the dot-notation key
  361. if (splitKey.length > 1 && configuration['dot-notation']) {
  362. ;(flags.aliases[splitKey[0]] || []).forEach(function (x) {
  363. x = x.split('.')
  364. // expand alias with nested objects in key
  365. var a = [].concat(splitKey)
  366. a.shift() // nuke the old key.
  367. x = x.concat(a)
  368. setKey(argv, x, value)
  369. })
  370. }
  371. // Set normalize getter and setter when key is in 'normalize' but isn't an array
  372. if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
  373. var keys = [key].concat(flags.aliases[key] || [])
  374. keys.forEach(function (key) {
  375. argv.__defineSetter__(key, function (v) {
  376. val = path.normalize(v)
  377. })
  378. argv.__defineGetter__(key, function () {
  379. return typeof val === 'string' ? path.normalize(val) : val
  380. })
  381. })
  382. }
  383. }
  384. function addNewAlias (key, alias) {
  385. if (!(flags.aliases[key] && flags.aliases[key].length)) {
  386. flags.aliases[key] = [alias]
  387. newAliases[alias] = true
  388. }
  389. if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
  390. addNewAlias(alias, key)
  391. }
  392. }
  393. function processValue (key, val) {
  394. // handle parsing boolean arguments --foo=true --bar false.
  395. if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
  396. if (typeof val === 'string') val = val === 'true'
  397. }
  398. var value = maybeCoerceNumber(key, val)
  399. // increment a count given as arg (either no value or value parsed as boolean)
  400. if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
  401. value = increment
  402. }
  403. // Set normalized value when key is in 'normalize' and in 'arrays'
  404. if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
  405. if (Array.isArray(val)) value = val.map(path.normalize)
  406. else value = path.normalize(val)
  407. }
  408. return value
  409. }
  410. function maybeCoerceNumber (key, value) {
  411. if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.coercions)) {
  412. const shouldCoerceNumber = isNumber(value) && configuration['parse-numbers'] && (
  413. Number.isSafeInteger(Math.floor(value))
  414. )
  415. if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) value = Number(value)
  416. }
  417. return value
  418. }
  419. // set args from config.json file, this should be
  420. // applied last so that defaults can be applied.
  421. function setConfig (argv) {
  422. var configLookup = {}
  423. // expand defaults/aliases, in-case any happen to reference
  424. // the config.json file.
  425. applyDefaultsAndAliases(configLookup, flags.aliases, defaults)
  426. Object.keys(flags.configs).forEach(function (configKey) {
  427. var configPath = argv[configKey] || configLookup[configKey]
  428. if (configPath) {
  429. try {
  430. var config = null
  431. var resolvedConfigPath = path.resolve(process.cwd(), configPath)
  432. if (typeof flags.configs[configKey] === 'function') {
  433. try {
  434. config = flags.configs[configKey](resolvedConfigPath)
  435. } catch (e) {
  436. config = e
  437. }
  438. if (config instanceof Error) {
  439. error = config
  440. return
  441. }
  442. } else {
  443. config = require(resolvedConfigPath)
  444. }
  445. setConfigObject(config)
  446. } catch (ex) {
  447. if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath))
  448. }
  449. }
  450. })
  451. }
  452. // set args from config object.
  453. // it recursively checks nested objects.
  454. function setConfigObject (config, prev) {
  455. Object.keys(config).forEach(function (key) {
  456. var value = config[key]
  457. var fullKey = prev ? prev + '.' + key : key
  458. // if the value is an inner object and we have dot-notation
  459. // enabled, treat inner objects in config the same as
  460. // heavily nested dot notations (foo.bar.apple).
  461. if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
  462. // if the value is an object but not an array, check nested object
  463. setConfigObject(value, fullKey)
  464. } else {
  465. // setting arguments via CLI takes precedence over
  466. // values within the config file.
  467. if (!hasKey(argv, fullKey.split('.')) || (flags.defaulted[fullKey]) || (flags.arrays[fullKey] && configuration['combine-arrays'])) {
  468. setArg(fullKey, value)
  469. }
  470. }
  471. })
  472. }
  473. // set all config objects passed in opts
  474. function setConfigObjects () {
  475. if (typeof configObjects === 'undefined') return
  476. configObjects.forEach(function (configObject) {
  477. setConfigObject(configObject)
  478. })
  479. }
  480. function applyEnvVars (argv, configOnly) {
  481. if (typeof envPrefix === 'undefined') return
  482. var prefix = typeof envPrefix === 'string' ? envPrefix : ''
  483. Object.keys(process.env).forEach(function (envVar) {
  484. if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
  485. // get array of nested keys and convert them to camel case
  486. var keys = envVar.split('__').map(function (key, i) {
  487. if (i === 0) {
  488. key = key.substring(prefix.length)
  489. }
  490. return camelCase(key)
  491. })
  492. if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && (!hasKey(argv, keys) || flags.defaulted[keys.join('.')])) {
  493. setArg(keys.join('.'), process.env[envVar])
  494. }
  495. }
  496. })
  497. }
  498. function applyCoercions (argv) {
  499. var coerce
  500. var applied = {}
  501. Object.keys(argv).forEach(function (key) {
  502. if (!applied.hasOwnProperty(key)) { // If we haven't already coerced this option via one of its aliases
  503. coerce = checkAllAliases(key, flags.coercions)
  504. if (typeof coerce === 'function') {
  505. try {
  506. var value = coerce(argv[key])
  507. ;([].concat(flags.aliases[key] || [], key)).forEach(ali => {
  508. applied[ali] = argv[ali] = value
  509. })
  510. } catch (err) {
  511. error = err
  512. }
  513. }
  514. }
  515. })
  516. }
  517. function setPlaceholderKeys (argv) {
  518. flags.keys.forEach((key) => {
  519. // don't set placeholder keys for dot notation options 'foo.bar'.
  520. if (~key.indexOf('.')) return
  521. if (typeof argv[key] === 'undefined') argv[key] = undefined
  522. })
  523. return argv
  524. }
  525. function applyDefaultsAndAliases (obj, aliases, defaults) {
  526. Object.keys(defaults).forEach(function (key) {
  527. if (!hasKey(obj, key.split('.'))) {
  528. setKey(obj, key.split('.'), defaults[key])
  529. ;(aliases[key] || []).forEach(function (x) {
  530. if (hasKey(obj, x.split('.'))) return
  531. setKey(obj, x.split('.'), defaults[key])
  532. })
  533. }
  534. })
  535. }
  536. function hasKey (obj, keys) {
  537. var o = obj
  538. if (!configuration['dot-notation']) keys = [keys.join('.')]
  539. keys.slice(0, -1).forEach(function (key) {
  540. o = (o[key] || {})
  541. })
  542. var key = keys[keys.length - 1]
  543. if (typeof o !== 'object') return false
  544. else return key in o
  545. }
  546. function setKey (obj, keys, value) {
  547. var o = obj
  548. if (!configuration['dot-notation']) keys = [keys.join('.')]
  549. keys.slice(0, -1).forEach(function (key, index) {
  550. if (typeof o === 'object' && o[key] === undefined) {
  551. o[key] = {}
  552. }
  553. if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
  554. // ensure that o[key] is an array, and that the last item is an empty object.
  555. if (Array.isArray(o[key])) {
  556. o[key].push({})
  557. } else {
  558. o[key] = [o[key], {}]
  559. }
  560. // we want to update the empty object at the end of the o[key] array, so set o to that object
  561. o = o[key][o[key].length - 1]
  562. } else {
  563. o = o[key]
  564. }
  565. })
  566. var key = keys[keys.length - 1]
  567. var isTypeArray = checkAllAliases(keys.join('.'), flags.arrays)
  568. var isValueArray = Array.isArray(value)
  569. var duplicate = configuration['duplicate-arguments-array']
  570. if (value === increment) {
  571. o[key] = increment(o[key])
  572. } else if (Array.isArray(o[key])) {
  573. if (duplicate && isTypeArray && isValueArray) {
  574. o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value])
  575. } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
  576. o[key] = value
  577. } else {
  578. o[key] = o[key].concat([value])
  579. }
  580. } else if (o[key] === undefined && isTypeArray) {
  581. o[key] = isValueArray ? value : [value]
  582. } else if (duplicate && !(o[key] === undefined || checkAllAliases(key, flags.bools) || checkAllAliases(keys.join('.'), flags.bools) || checkAllAliases(key, flags.counts))) {
  583. o[key] = [ o[key], value ]
  584. } else {
  585. o[key] = value
  586. }
  587. }
  588. // extend the aliases list with inferred aliases.
  589. function extendAliases () {
  590. Array.prototype.slice.call(arguments).forEach(function (obj) {
  591. Object.keys(obj || {}).forEach(function (key) {
  592. // short-circuit if we've already added a key
  593. // to the aliases array, for example it might
  594. // exist in both 'opts.default' and 'opts.key'.
  595. if (flags.aliases[key]) return
  596. flags.aliases[key] = [].concat(aliases[key] || [])
  597. // For "--option-name", also set argv.optionName
  598. flags.aliases[key].concat(key).forEach(function (x) {
  599. if (/-/.test(x) && configuration['camel-case-expansion']) {
  600. var c = camelCase(x)
  601. if (c !== key && flags.aliases[key].indexOf(c) === -1) {
  602. flags.aliases[key].push(c)
  603. newAliases[c] = true
  604. }
  605. }
  606. })
  607. // For "--optionName", also set argv['option-name']
  608. flags.aliases[key].concat(key).forEach(function (x) {
  609. if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
  610. var c = decamelize(x, '-')
  611. if (c !== key && flags.aliases[key].indexOf(c) === -1) {
  612. flags.aliases[key].push(c)
  613. newAliases[c] = true
  614. }
  615. }
  616. })
  617. flags.aliases[key].forEach(function (x) {
  618. flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
  619. return x !== y
  620. }))
  621. })
  622. })
  623. })
  624. }
  625. // check if a flag is set for any of a key's aliases.
  626. function checkAllAliases (key, flag) {
  627. var isSet = false
  628. var toCheck = [].concat(flags.aliases[key] || [], key)
  629. toCheck.forEach(function (key) {
  630. if (flag[key]) isSet = flag[key]
  631. })
  632. return isSet
  633. }
  634. function setDefaulted (key) {
  635. [].concat(flags.aliases[key] || [], key).forEach(function (k) {
  636. flags.defaulted[k] = true
  637. })
  638. }
  639. function unsetDefaulted (key) {
  640. [].concat(flags.aliases[key] || [], key).forEach(function (k) {
  641. delete flags.defaulted[k]
  642. })
  643. }
  644. // return a default value, given the type of a flag.,
  645. // e.g., key of type 'string' will default to '', rather than 'true'.
  646. function defaultForType (type) {
  647. var def = {
  648. boolean: true,
  649. string: '',
  650. number: undefined,
  651. array: []
  652. }
  653. return def[type]
  654. }
  655. // given a flag, enforce a default type.
  656. function guessType (key, flags) {
  657. var type = 'boolean'
  658. if (checkAllAliases(key, flags.strings)) type = 'string'
  659. else if (checkAllAliases(key, flags.numbers)) type = 'number'
  660. else if (checkAllAliases(key, flags.arrays)) type = 'array'
  661. return type
  662. }
  663. function isNumber (x) {
  664. if (typeof x === 'number') return true
  665. if (/^0x[0-9a-f]+$/i.test(x)) return true
  666. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x)
  667. }
  668. function isUndefined (num) {
  669. return num === undefined
  670. }
  671. return {
  672. argv: argv,
  673. error: error,
  674. aliases: flags.aliases,
  675. newAliases: newAliases,
  676. configuration: configuration
  677. }
  678. }
  679. // if any aliases reference each other, we should
  680. // merge them together.
  681. function combineAliases (aliases) {
  682. var aliasArrays = []
  683. var change = true
  684. var combined = {}
  685. // turn alias lookup hash {key: ['alias1', 'alias2']} into
  686. // a simple array ['key', 'alias1', 'alias2']
  687. Object.keys(aliases).forEach(function (key) {
  688. aliasArrays.push(
  689. [].concat(aliases[key], key)
  690. )
  691. })
  692. // combine arrays until zero changes are
  693. // made in an iteration.
  694. while (change) {
  695. change = false
  696. for (var i = 0; i < aliasArrays.length; i++) {
  697. for (var ii = i + 1; ii < aliasArrays.length; ii++) {
  698. var intersect = aliasArrays[i].filter(function (v) {
  699. return aliasArrays[ii].indexOf(v) !== -1
  700. })
  701. if (intersect.length) {
  702. aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii])
  703. aliasArrays.splice(ii, 1)
  704. change = true
  705. break
  706. }
  707. }
  708. }
  709. }
  710. // map arrays back to the hash-lookup (de-dupe while
  711. // we're at it).
  712. aliasArrays.forEach(function (aliasArray) {
  713. aliasArray = aliasArray.filter(function (v, i, self) {
  714. return self.indexOf(v) === i
  715. })
  716. combined[aliasArray.pop()] = aliasArray
  717. })
  718. return combined
  719. }
  720. function assign (defaults, configuration) {
  721. var o = {}
  722. configuration = configuration || {}
  723. Object.keys(defaults).forEach(function (k) {
  724. o[k] = defaults[k]
  725. })
  726. Object.keys(configuration).forEach(function (k) {
  727. o[k] = configuration[k]
  728. })
  729. return o
  730. }
  731. // this function should only be called when a count is given as an arg
  732. // it is NOT called to set a default value
  733. // thus we can start the count at 1 instead of 0
  734. function increment (orig) {
  735. return orig !== undefined ? orig + 1 : 1
  736. }
  737. function Parser (args, opts) {
  738. var result = parse(args.slice(), opts)
  739. return result.argv
  740. }
  741. // parse arguments and return detailed
  742. // meta information, aliases, etc.
  743. Parser.detailed = function (args, opts) {
  744. return parse(args.slice(), opts)
  745. }
  746. module.exports = Parser