index.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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 toEat = checkAllAliases(key, flags.nargs)
  268. if (args.length - (i + 1) < toEat) error = Error(__('Not enough arguments following: %s', key))
  269. for (var ii = i + 1; ii < (toEat + i + 1); ii++) {
  270. setArg(key, args[ii])
  271. }
  272. return (i + toEat)
  273. }
  274. // if an option is an array, eat all non-hyphenated arguments
  275. // following it... YUM!
  276. // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
  277. function eatArray (i, key, args) {
  278. var start = i + 1
  279. var argsToSet = []
  280. var multipleArrayFlag = i > 0
  281. for (var ii = i + 1; ii < args.length; ii++) {
  282. if (/^-/.test(args[ii]) && !negative.test(args[ii])) {
  283. if (ii === start) {
  284. setArg(key, defaultForType('array'))
  285. }
  286. multipleArrayFlag = true
  287. break
  288. }
  289. i = ii
  290. argsToSet.push(args[ii])
  291. }
  292. if (multipleArrayFlag) {
  293. setArg(key, argsToSet.map(function (arg) {
  294. return processValue(key, arg)
  295. }))
  296. } else {
  297. argsToSet.forEach(function (arg) {
  298. setArg(key, arg)
  299. })
  300. }
  301. return i
  302. }
  303. function setArg (key, val) {
  304. unsetDefaulted(key)
  305. if (/-/.test(key) && configuration['camel-case-expansion']) {
  306. addNewAlias(key, camelCase(key))
  307. }
  308. var value = processValue(key, val)
  309. var splitKey = key.split('.')
  310. setKey(argv, splitKey, value)
  311. // handle populating aliases of the full key
  312. if (flags.aliases[key]) {
  313. flags.aliases[key].forEach(function (x) {
  314. x = x.split('.')
  315. setKey(argv, x, value)
  316. })
  317. }
  318. // handle populating aliases of the first element of the dot-notation key
  319. if (splitKey.length > 1 && configuration['dot-notation']) {
  320. ;(flags.aliases[splitKey[0]] || []).forEach(function (x) {
  321. x = x.split('.')
  322. // expand alias with nested objects in key
  323. var a = [].concat(splitKey)
  324. a.shift() // nuke the old key.
  325. x = x.concat(a)
  326. setKey(argv, x, value)
  327. })
  328. }
  329. // Set normalize getter and setter when key is in 'normalize' but isn't an array
  330. if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
  331. var keys = [key].concat(flags.aliases[key] || [])
  332. keys.forEach(function (key) {
  333. argv.__defineSetter__(key, function (v) {
  334. val = path.normalize(v)
  335. })
  336. argv.__defineGetter__(key, function () {
  337. return typeof val === 'string' ? path.normalize(val) : val
  338. })
  339. })
  340. }
  341. }
  342. function addNewAlias (key, alias) {
  343. if (!(flags.aliases[key] && flags.aliases[key].length)) {
  344. flags.aliases[key] = [alias]
  345. newAliases[alias] = true
  346. }
  347. if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
  348. addNewAlias(alias, key)
  349. }
  350. }
  351. function processValue (key, val) {
  352. // handle parsing boolean arguments --foo=true --bar false.
  353. if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
  354. if (typeof val === 'string') val = val === 'true'
  355. }
  356. var value = maybeCoerceNumber(key, val)
  357. // increment a count given as arg (either no value or value parsed as boolean)
  358. if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
  359. value = increment
  360. }
  361. // Set normalized value when key is in 'normalize' and in 'arrays'
  362. if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
  363. if (Array.isArray(val)) value = val.map(path.normalize)
  364. else value = path.normalize(val)
  365. }
  366. return value
  367. }
  368. function maybeCoerceNumber (key, value) {
  369. if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.coercions)) {
  370. const shouldCoerceNumber = isNumber(value) && configuration['parse-numbers'] && (
  371. Number.isSafeInteger(Math.floor(value))
  372. )
  373. if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) value = Number(value)
  374. }
  375. return value
  376. }
  377. // set args from config.json file, this should be
  378. // applied last so that defaults can be applied.
  379. function setConfig (argv) {
  380. var configLookup = {}
  381. // expand defaults/aliases, in-case any happen to reference
  382. // the config.json file.
  383. applyDefaultsAndAliases(configLookup, flags.aliases, defaults)
  384. Object.keys(flags.configs).forEach(function (configKey) {
  385. var configPath = argv[configKey] || configLookup[configKey]
  386. if (configPath) {
  387. try {
  388. var config = null
  389. var resolvedConfigPath = path.resolve(process.cwd(), configPath)
  390. if (typeof flags.configs[configKey] === 'function') {
  391. try {
  392. config = flags.configs[configKey](resolvedConfigPath)
  393. } catch (e) {
  394. config = e
  395. }
  396. if (config instanceof Error) {
  397. error = config
  398. return
  399. }
  400. } else {
  401. config = require(resolvedConfigPath)
  402. }
  403. setConfigObject(config)
  404. } catch (ex) {
  405. if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath))
  406. }
  407. }
  408. })
  409. }
  410. // set args from config object.
  411. // it recursively checks nested objects.
  412. function setConfigObject (config, prev) {
  413. Object.keys(config).forEach(function (key) {
  414. var value = config[key]
  415. var fullKey = prev ? prev + '.' + key : key
  416. // if the value is an inner object and we have dot-notation
  417. // enabled, treat inner objects in config the same as
  418. // heavily nested dot notations (foo.bar.apple).
  419. if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
  420. // if the value is an object but not an array, check nested object
  421. setConfigObject(value, fullKey)
  422. } else {
  423. // setting arguments via CLI takes precedence over
  424. // values within the config file.
  425. if (!hasKey(argv, fullKey.split('.')) || (flags.defaulted[fullKey]) || (flags.arrays[fullKey] && configuration['combine-arrays'])) {
  426. setArg(fullKey, value)
  427. }
  428. }
  429. })
  430. }
  431. // set all config objects passed in opts
  432. function setConfigObjects () {
  433. if (typeof configObjects === 'undefined') return
  434. configObjects.forEach(function (configObject) {
  435. setConfigObject(configObject)
  436. })
  437. }
  438. function applyEnvVars (argv, configOnly) {
  439. if (typeof envPrefix === 'undefined') return
  440. var prefix = typeof envPrefix === 'string' ? envPrefix : ''
  441. Object.keys(process.env).forEach(function (envVar) {
  442. if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
  443. // get array of nested keys and convert them to camel case
  444. var keys = envVar.split('__').map(function (key, i) {
  445. if (i === 0) {
  446. key = key.substring(prefix.length)
  447. }
  448. return camelCase(key)
  449. })
  450. if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && (!hasKey(argv, keys) || flags.defaulted[keys.join('.')])) {
  451. setArg(keys.join('.'), process.env[envVar])
  452. }
  453. }
  454. })
  455. }
  456. function applyCoercions (argv) {
  457. var coerce
  458. var applied = {}
  459. Object.keys(argv).forEach(function (key) {
  460. if (!applied.hasOwnProperty(key)) { // If we haven't already coerced this option via one of its aliases
  461. coerce = checkAllAliases(key, flags.coercions)
  462. if (typeof coerce === 'function') {
  463. try {
  464. var value = coerce(argv[key])
  465. ;([].concat(flags.aliases[key] || [], key)).forEach(ali => {
  466. applied[ali] = argv[ali] = value
  467. })
  468. } catch (err) {
  469. error = err
  470. }
  471. }
  472. }
  473. })
  474. }
  475. function applyDefaultsAndAliases (obj, aliases, defaults) {
  476. Object.keys(defaults).forEach(function (key) {
  477. if (!hasKey(obj, key.split('.'))) {
  478. setKey(obj, key.split('.'), defaults[key])
  479. ;(aliases[key] || []).forEach(function (x) {
  480. if (hasKey(obj, x.split('.'))) return
  481. setKey(obj, x.split('.'), defaults[key])
  482. })
  483. }
  484. })
  485. }
  486. function hasKey (obj, keys) {
  487. var o = obj
  488. if (!configuration['dot-notation']) keys = [keys.join('.')]
  489. keys.slice(0, -1).forEach(function (key) {
  490. o = (o[key] || {})
  491. })
  492. var key = keys[keys.length - 1]
  493. if (typeof o !== 'object') return false
  494. else return key in o
  495. }
  496. function setKey (obj, keys, value) {
  497. var o = obj
  498. if (!configuration['dot-notation']) keys = [keys.join('.')]
  499. keys.slice(0, -1).forEach(function (key, index) {
  500. if (typeof o === 'object' && o[key] === undefined) {
  501. o[key] = {}
  502. }
  503. if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
  504. // ensure that o[key] is an array, and that the last item is an empty object.
  505. if (Array.isArray(o[key])) {
  506. o[key].push({})
  507. } else {
  508. o[key] = [o[key], {}]
  509. }
  510. // we want to update the empty object at the end of the o[key] array, so set o to that object
  511. o = o[key][o[key].length - 1]
  512. } else {
  513. o = o[key]
  514. }
  515. })
  516. var key = keys[keys.length - 1]
  517. var isTypeArray = checkAllAliases(keys.join('.'), flags.arrays)
  518. var isValueArray = Array.isArray(value)
  519. var duplicate = configuration['duplicate-arguments-array']
  520. if (value === increment) {
  521. o[key] = increment(o[key])
  522. } else if (Array.isArray(o[key])) {
  523. if (duplicate && isTypeArray && isValueArray) {
  524. o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : [o[key]].concat([value])
  525. } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
  526. o[key] = value
  527. } else {
  528. o[key] = o[key].concat([value])
  529. }
  530. } else if (o[key] === undefined && isTypeArray) {
  531. o[key] = isValueArray ? value : [value]
  532. } else if (duplicate && !(o[key] === undefined || checkAllAliases(key, flags.bools) || checkAllAliases(keys.join('.'), flags.bools) || checkAllAliases(key, flags.counts))) {
  533. o[key] = [ o[key], value ]
  534. } else {
  535. o[key] = value
  536. }
  537. }
  538. // extend the aliases list with inferred aliases.
  539. function extendAliases () {
  540. Array.prototype.slice.call(arguments).forEach(function (obj) {
  541. Object.keys(obj || {}).forEach(function (key) {
  542. // short-circuit if we've already added a key
  543. // to the aliases array, for example it might
  544. // exist in both 'opts.default' and 'opts.key'.
  545. if (flags.aliases[key]) return
  546. flags.aliases[key] = [].concat(aliases[key] || [])
  547. // For "--option-name", also set argv.optionName
  548. flags.aliases[key].concat(key).forEach(function (x) {
  549. if (/-/.test(x) && configuration['camel-case-expansion']) {
  550. var c = camelCase(x)
  551. if (c !== key && flags.aliases[key].indexOf(c) === -1) {
  552. flags.aliases[key].push(c)
  553. newAliases[c] = true
  554. }
  555. }
  556. })
  557. flags.aliases[key].forEach(function (x) {
  558. flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
  559. return x !== y
  560. }))
  561. })
  562. })
  563. })
  564. }
  565. // check if a flag is set for any of a key's aliases.
  566. function checkAllAliases (key, flag) {
  567. var isSet = false
  568. var toCheck = [].concat(flags.aliases[key] || [], key)
  569. toCheck.forEach(function (key) {
  570. if (flag[key]) isSet = flag[key]
  571. })
  572. return isSet
  573. }
  574. function setDefaulted (key) {
  575. [].concat(flags.aliases[key] || [], key).forEach(function (k) {
  576. flags.defaulted[k] = true
  577. })
  578. }
  579. function unsetDefaulted (key) {
  580. [].concat(flags.aliases[key] || [], key).forEach(function (k) {
  581. delete flags.defaulted[k]
  582. })
  583. }
  584. // return a default value, given the type of a flag.,
  585. // e.g., key of type 'string' will default to '', rather than 'true'.
  586. function defaultForType (type) {
  587. var def = {
  588. boolean: true,
  589. string: '',
  590. number: undefined,
  591. array: []
  592. }
  593. return def[type]
  594. }
  595. // given a flag, enforce a default type.
  596. function guessType (key, flags) {
  597. var type = 'boolean'
  598. if (checkAllAliases(key, flags.strings)) type = 'string'
  599. else if (checkAllAliases(key, flags.numbers)) type = 'number'
  600. else if (checkAllAliases(key, flags.arrays)) type = 'array'
  601. return type
  602. }
  603. function isNumber (x) {
  604. if (typeof x === 'number') return true
  605. if (/^0x[0-9a-f]+$/i.test(x)) return true
  606. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x)
  607. }
  608. function isUndefined (num) {
  609. return num === undefined
  610. }
  611. return {
  612. argv: argv,
  613. error: error,
  614. aliases: flags.aliases,
  615. newAliases: newAliases,
  616. configuration: configuration
  617. }
  618. }
  619. // if any aliases reference each other, we should
  620. // merge them together.
  621. function combineAliases (aliases) {
  622. var aliasArrays = []
  623. var change = true
  624. var combined = {}
  625. // turn alias lookup hash {key: ['alias1', 'alias2']} into
  626. // a simple array ['key', 'alias1', 'alias2']
  627. Object.keys(aliases).forEach(function (key) {
  628. aliasArrays.push(
  629. [].concat(aliases[key], key)
  630. )
  631. })
  632. // combine arrays until zero changes are
  633. // made in an iteration.
  634. while (change) {
  635. change = false
  636. for (var i = 0; i < aliasArrays.length; i++) {
  637. for (var ii = i + 1; ii < aliasArrays.length; ii++) {
  638. var intersect = aliasArrays[i].filter(function (v) {
  639. return aliasArrays[ii].indexOf(v) !== -1
  640. })
  641. if (intersect.length) {
  642. aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii])
  643. aliasArrays.splice(ii, 1)
  644. change = true
  645. break
  646. }
  647. }
  648. }
  649. }
  650. // map arrays back to the hash-lookup (de-dupe while
  651. // we're at it).
  652. aliasArrays.forEach(function (aliasArray) {
  653. aliasArray = aliasArray.filter(function (v, i, self) {
  654. return self.indexOf(v) === i
  655. })
  656. combined[aliasArray.pop()] = aliasArray
  657. })
  658. return combined
  659. }
  660. function assign (defaults, configuration) {
  661. var o = {}
  662. configuration = configuration || {}
  663. Object.keys(defaults).forEach(function (k) {
  664. o[k] = defaults[k]
  665. })
  666. Object.keys(configuration).forEach(function (k) {
  667. o[k] = configuration[k]
  668. })
  669. return o
  670. }
  671. // this function should only be called when a count is given as an arg
  672. // it is NOT called to set a default value
  673. // thus we can start the count at 1 instead of 0
  674. function increment (orig) {
  675. return orig !== undefined ? orig + 1 : 1
  676. }
  677. function Parser (args, opts) {
  678. var result = parse(args.slice(), opts)
  679. return result.argv
  680. }
  681. // parse arguments and return detailed
  682. // meta information, aliases, etc.
  683. Parser.detailed = function (args, opts) {
  684. return parse(args.slice(), opts)
  685. }
  686. module.exports = Parser