index.js 22 KB

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