You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 22KB

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