index.js 24 KB

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