index.js 24 KB

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