index.js 24 KB

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