index.js 33 KB

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