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