index.js 27 KB

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