yargs.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. 'use strict'
  2. const argsert = require('./lib/argsert')
  3. const fs = require('fs')
  4. const Command = require('./lib/command')
  5. const Completion = require('./lib/completion')
  6. const Parser = require('yargs-parser')
  7. const path = require('path')
  8. const Usage = require('./lib/usage')
  9. const Validation = require('./lib/validation')
  10. const Y18n = require('y18n')
  11. const objFilter = require('./lib/obj-filter')
  12. const setBlocking = require('set-blocking')
  13. const applyExtends = require('./lib/apply-extends')
  14. const YError = require('./lib/yerror')
  15. exports = module.exports = Yargs
  16. function Yargs (processArgs, cwd, parentRequire) {
  17. processArgs = processArgs || [] // handle calling yargs().
  18. const self = {}
  19. let command = null
  20. let completion = null
  21. let groups = {}
  22. let output = ''
  23. let preservedGroups = {}
  24. let usage = null
  25. let validation = null
  26. const y18n = Y18n({
  27. directory: path.resolve(__dirname, './locales'),
  28. updateFiles: false
  29. })
  30. if (!cwd) cwd = process.cwd()
  31. self.$0 = process.argv
  32. .slice(0, 2)
  33. .map((x, i) => {
  34. // ignore the node bin, specify this in your
  35. // bin file with #!/usr/bin/env node
  36. if (i === 0 && /\b(node|iojs)(\.exe)?$/.test(x)) return
  37. const b = rebase(cwd, x)
  38. return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x
  39. })
  40. .join(' ').trim()
  41. if (process.env._ !== undefined && process.argv[1] === process.env._) {
  42. self.$0 = process.env._.replace(
  43. `${path.dirname(process.execPath)}/`, ''
  44. )
  45. }
  46. // use context object to keep track of resets, subcommand execution, etc
  47. // submodules should modify and check the state of context as necessary
  48. const context = { resets: -1, commands: [], fullCommands: [], files: [] }
  49. self.getContext = () => context
  50. // puts yargs back into an initial state. any keys
  51. // that have been set to "global" will not be reset
  52. // by this action.
  53. let options
  54. self.resetOptions = self.reset = function resetOptions (aliases) {
  55. context.resets++
  56. aliases = aliases || {}
  57. options = options || {}
  58. // put yargs back into an initial state, this
  59. // logic is used to build a nested command
  60. // hierarchy.
  61. const tmpOptions = {}
  62. tmpOptions.local = options.local ? options.local : []
  63. tmpOptions.configObjects = options.configObjects ? options.configObjects : []
  64. // if a key has been explicitly set as local,
  65. // we should reset it before passing options to command.
  66. const localLookup = {}
  67. tmpOptions.local.forEach((l) => {
  68. localLookup[l] = true
  69. ;(aliases[l] || []).forEach((a) => {
  70. localLookup[a] = true
  71. })
  72. })
  73. // preserve all groups not set to local.
  74. preservedGroups = Object.keys(groups).reduce((acc, groupName) => {
  75. const keys = groups[groupName].filter(key => !(key in localLookup))
  76. if (keys.length > 0) {
  77. acc[groupName] = keys
  78. }
  79. return acc
  80. }, {})
  81. // groups can now be reset
  82. groups = {}
  83. const arrayOptions = [
  84. 'array', 'boolean', 'string', 'skipValidation',
  85. 'count', 'normalize', 'number',
  86. 'hiddenOptions'
  87. ]
  88. const objectOptions = [
  89. 'narg', 'key', 'alias', 'default', 'defaultDescription',
  90. 'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce'
  91. ]
  92. arrayOptions.forEach((k) => {
  93. tmpOptions[k] = (options[k] || []).filter(k => !localLookup[k])
  94. })
  95. objectOptions.forEach((k) => {
  96. tmpOptions[k] = objFilter(options[k], (k, v) => !localLookup[k])
  97. })
  98. tmpOptions.envPrefix = options.envPrefix
  99. options = tmpOptions
  100. // if this is the first time being executed, create
  101. // instances of all our helpers -- otherwise just reset.
  102. usage = usage ? usage.reset(localLookup) : Usage(self, y18n)
  103. validation = validation ? validation.reset(localLookup) : Validation(self, usage, y18n)
  104. command = command ? command.reset() : Command(self, usage, validation)
  105. if (!completion) completion = Completion(self, usage, command)
  106. completionCommand = null
  107. output = ''
  108. exitError = null
  109. hasOutput = false
  110. self.parsed = false
  111. return self
  112. }
  113. self.resetOptions()
  114. // temporary hack: allow "freezing" of reset-able state for parse(msg, cb)
  115. let frozen
  116. function freeze () {
  117. frozen = {}
  118. frozen.options = options
  119. frozen.configObjects = options.configObjects.slice(0)
  120. frozen.exitProcess = exitProcess
  121. frozen.groups = groups
  122. usage.freeze()
  123. validation.freeze()
  124. command.freeze()
  125. frozen.strict = strict
  126. frozen.completionCommand = completionCommand
  127. frozen.output = output
  128. frozen.exitError = exitError
  129. frozen.hasOutput = hasOutput
  130. frozen.parsed = self.parsed
  131. }
  132. function unfreeze () {
  133. options = frozen.options
  134. options.configObjects = frozen.configObjects
  135. exitProcess = frozen.exitProcess
  136. groups = frozen.groups
  137. output = frozen.output
  138. exitError = frozen.exitError
  139. hasOutput = frozen.hasOutput
  140. self.parsed = frozen.parsed
  141. usage.unfreeze()
  142. validation.unfreeze()
  143. command.unfreeze()
  144. strict = frozen.strict
  145. completionCommand = frozen.completionCommand
  146. parseFn = null
  147. parseContext = null
  148. frozen = undefined
  149. }
  150. self.boolean = function (keys) {
  151. argsert('<array|string>', [keys], arguments.length)
  152. populateParserHintArray('boolean', keys)
  153. return self
  154. }
  155. self.array = function (keys) {
  156. argsert('<array|string>', [keys], arguments.length)
  157. populateParserHintArray('array', keys)
  158. return self
  159. }
  160. self.number = function (keys) {
  161. argsert('<array|string>', [keys], arguments.length)
  162. populateParserHintArray('number', keys)
  163. return self
  164. }
  165. self.normalize = function (keys) {
  166. argsert('<array|string>', [keys], arguments.length)
  167. populateParserHintArray('normalize', keys)
  168. return self
  169. }
  170. self.count = function (keys) {
  171. argsert('<array|string>', [keys], arguments.length)
  172. populateParserHintArray('count', keys)
  173. return self
  174. }
  175. self.string = function (keys) {
  176. argsert('<array|string>', [keys], arguments.length)
  177. populateParserHintArray('string', keys)
  178. return self
  179. }
  180. self.requiresArg = function (keys) {
  181. argsert('<array|string>', [keys], arguments.length)
  182. populateParserHintObject(self.nargs, false, 'narg', keys, 1)
  183. return self
  184. }
  185. self.skipValidation = function (keys) {
  186. argsert('<array|string>', [keys], arguments.length)
  187. populateParserHintArray('skipValidation', keys)
  188. return self
  189. }
  190. function populateParserHintArray (type, keys, value) {
  191. keys = [].concat(keys)
  192. keys.forEach((key) => {
  193. options[type].push(key)
  194. })
  195. }
  196. self.nargs = function (key, value) {
  197. argsert('<string|object|array> [number]', [key, value], arguments.length)
  198. populateParserHintObject(self.nargs, false, 'narg', key, value)
  199. return self
  200. }
  201. self.choices = function (key, value) {
  202. argsert('<object|string|array> [string|array]', [key, value], arguments.length)
  203. populateParserHintObject(self.choices, true, 'choices', key, value)
  204. return self
  205. }
  206. self.alias = function (key, value) {
  207. argsert('<object|string|array> [string|array]', [key, value], arguments.length)
  208. populateParserHintObject(self.alias, true, 'alias', key, value)
  209. return self
  210. }
  211. // TODO: actually deprecate self.defaults.
  212. self.default = self.defaults = function (key, value, defaultDescription) {
  213. argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length)
  214. if (defaultDescription) options.defaultDescription[key] = defaultDescription
  215. if (typeof value === 'function') {
  216. if (!options.defaultDescription[key]) options.defaultDescription[key] = usage.functionDescription(value)
  217. value = value.call()
  218. }
  219. populateParserHintObject(self.default, false, 'default', key, value)
  220. return self
  221. }
  222. self.describe = function (key, desc) {
  223. argsert('<object|string|array> [string]', [key, desc], arguments.length)
  224. populateParserHintObject(self.describe, false, 'key', key, true)
  225. usage.describe(key, desc)
  226. return self
  227. }
  228. self.demandOption = function (keys, msg) {
  229. argsert('<object|string|array> [string]', [keys, msg], arguments.length)
  230. populateParserHintObject(self.demandOption, false, 'demandedOptions', keys, msg)
  231. return self
  232. }
  233. self.coerce = function (keys, value) {
  234. argsert('<object|string|array> [function]', [keys, value], arguments.length)
  235. populateParserHintObject(self.coerce, false, 'coerce', keys, value)
  236. return self
  237. }
  238. function populateParserHintObject (builder, isArray, type, key, value) {
  239. if (Array.isArray(key)) {
  240. // an array of keys with one value ['x', 'y', 'z'], function parse () {}
  241. const temp = {}
  242. key.forEach((k) => {
  243. temp[k] = value
  244. })
  245. builder(temp)
  246. } else if (typeof key === 'object') {
  247. // an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
  248. Object.keys(key).forEach((k) => {
  249. builder(k, key[k])
  250. })
  251. } else {
  252. // a single key value pair 'x', parse() {}
  253. if (isArray) {
  254. options[type][key] = (options[type][key] || []).concat(value)
  255. } else {
  256. options[type][key] = value
  257. }
  258. }
  259. }
  260. function deleteFromParserHintObject (optionKey) {
  261. // delete from all parsing hints:
  262. // boolean, array, key, alias, etc.
  263. Object.keys(options).forEach((hintKey) => {
  264. const hint = options[hintKey]
  265. if (Array.isArray(hint)) {
  266. if (~hint.indexOf(optionKey)) hint.splice(hint.indexOf(optionKey), 1)
  267. } else if (typeof hint === 'object') {
  268. delete hint[optionKey]
  269. }
  270. })
  271. // now delete the description from usage.js.
  272. delete usage.getDescriptions()[optionKey]
  273. }
  274. self.config = function config (key, msg, parseFn) {
  275. argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length)
  276. // allow a config object to be provided directly.
  277. if (typeof key === 'object') {
  278. key = applyExtends(key, cwd)
  279. options.configObjects = (options.configObjects || []).concat(key)
  280. return self
  281. }
  282. // allow for a custom parsing function.
  283. if (typeof msg === 'function') {
  284. parseFn = msg
  285. msg = null
  286. }
  287. key = key || 'config'
  288. self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file'))
  289. ;(Array.isArray(key) ? key : [key]).forEach((k) => {
  290. options.config[k] = parseFn || true
  291. })
  292. return self
  293. }
  294. self.example = function (cmd, description) {
  295. argsert('<string> [string]', [cmd, description], arguments.length)
  296. usage.example(cmd, description)
  297. return self
  298. }
  299. self.command = function (cmd, description, builder, handler, middlewares) {
  300. argsert('<string|array|object> [string|boolean] [function|object] [function] [array]', [cmd, description, builder, handler, middlewares], arguments.length)
  301. command.addHandler(cmd, description, builder, handler, middlewares)
  302. return self
  303. }
  304. self.commandDir = function (dir, opts) {
  305. argsert('<string> [object]', [dir, opts], arguments.length)
  306. const req = parentRequire || require
  307. command.addDirectory(dir, self.getContext(), req, require('get-caller-file')(), opts)
  308. return self
  309. }
  310. // TODO: deprecate self.demand in favor of
  311. // .demandCommand() .demandOption().
  312. self.demand = self.required = self.require = function demand (keys, max, msg) {
  313. // you can optionally provide a 'max' key,
  314. // which will raise an exception if too many '_'
  315. // options are provided.
  316. if (Array.isArray(max)) {
  317. max.forEach((key) => {
  318. self.demandOption(key, msg)
  319. })
  320. max = Infinity
  321. } else if (typeof max !== 'number') {
  322. msg = max
  323. max = Infinity
  324. }
  325. if (typeof keys === 'number') {
  326. self.demandCommand(keys, max, msg, msg)
  327. } else if (Array.isArray(keys)) {
  328. keys.forEach((key) => {
  329. self.demandOption(key, msg)
  330. })
  331. } else {
  332. if (typeof msg === 'string') {
  333. self.demandOption(keys, msg)
  334. } else if (msg === true || typeof msg === 'undefined') {
  335. self.demandOption(keys)
  336. }
  337. }
  338. return self
  339. }
  340. self.demandCommand = function demandCommand (min, max, minMsg, maxMsg) {
  341. argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length)
  342. if (typeof min === 'undefined') min = 1
  343. if (typeof max !== 'number') {
  344. minMsg = max
  345. max = Infinity
  346. }
  347. self.global('_', false)
  348. options.demandedCommands._ = {
  349. min,
  350. max,
  351. minMsg,
  352. maxMsg
  353. }
  354. return self
  355. }
  356. self.getDemandedOptions = () => {
  357. argsert([], 0)
  358. return options.demandedOptions
  359. }
  360. self.getDemandedCommands = () => {
  361. argsert([], 0)
  362. return options.demandedCommands
  363. }
  364. self.implies = function (key, value) {
  365. argsert('<string|object> [number|string|array]', [key, value], arguments.length)
  366. validation.implies(key, value)
  367. return self
  368. }
  369. self.conflicts = function (key1, key2) {
  370. argsert('<string|object> [string|array]', [key1, key2], arguments.length)
  371. validation.conflicts(key1, key2)
  372. return self
  373. }
  374. self.usage = function (msg, description, builder, handler) {
  375. argsert('<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length)
  376. if (description !== undefined) {
  377. // .usage() can be used as an alias for defining
  378. // a default command.
  379. if ((msg || '').match(/^\$0( |$)/)) {
  380. return self.command(msg, description, builder, handler)
  381. } else {
  382. throw new YError('.usage() description must start with $0 if being used as alias for .command()')
  383. }
  384. } else {
  385. usage.usage(msg)
  386. return self
  387. }
  388. }
  389. self.epilogue = self.epilog = function (msg) {
  390. argsert('<string>', [msg], arguments.length)
  391. usage.epilog(msg)
  392. return self
  393. }
  394. self.fail = function (f) {
  395. argsert('<function>', [f], arguments.length)
  396. usage.failFn(f)
  397. return self
  398. }
  399. self.check = function (f, _global) {
  400. argsert('<function> [boolean]', [f, _global], arguments.length)
  401. validation.check(f, _global !== false)
  402. return self
  403. }
  404. self.global = function global (globals, global) {
  405. argsert('<string|array> [boolean]', [globals, global], arguments.length)
  406. globals = [].concat(globals)
  407. if (global !== false) {
  408. options.local = options.local.filter(l => globals.indexOf(l) === -1)
  409. } else {
  410. globals.forEach((g) => {
  411. if (options.local.indexOf(g) === -1) options.local.push(g)
  412. })
  413. }
  414. return self
  415. }
  416. self.pkgConf = function pkgConf (key, rootPath) {
  417. argsert('<string> [string]', [key, rootPath], arguments.length)
  418. let conf = null
  419. // prefer cwd to require-main-filename in this method
  420. // since we're looking for e.g. "nyc" config in nyc consumer
  421. // rather than "yargs" config in nyc (where nyc is the main filename)
  422. const obj = pkgUp(rootPath || cwd)
  423. // If an object exists in the key, add it to options.configObjects
  424. if (obj[key] && typeof obj[key] === 'object') {
  425. conf = applyExtends(obj[key], rootPath || cwd)
  426. options.configObjects = (options.configObjects || []).concat(conf)
  427. }
  428. return self
  429. }
  430. const pkgs = {}
  431. function pkgUp (rootPath) {
  432. const npath = rootPath || '*'
  433. if (pkgs[npath]) return pkgs[npath]
  434. const findUp = require('find-up')
  435. let obj = {}
  436. try {
  437. let startDir = rootPath || require('require-main-filename')(parentRequire || require)
  438. // When called in an environment that lacks require.main.filename, such as a jest test runner,
  439. // startDir is already process.cwd(), and should not be shortened.
  440. // Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
  441. if (!rootPath && path.extname(startDir)) {
  442. startDir = path.dirname(startDir)
  443. }
  444. const pkgJsonPath = findUp.sync('package.json', {
  445. cwd: startDir
  446. })
  447. obj = JSON.parse(fs.readFileSync(pkgJsonPath))
  448. } catch (noop) {}
  449. pkgs[npath] = obj || {}
  450. return pkgs[npath]
  451. }
  452. let parseFn = null
  453. let parseContext = null
  454. self.parse = function parse (args, shortCircuit, _parseFn) {
  455. argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length)
  456. if (typeof args === 'undefined') args = processArgs
  457. // a context object can optionally be provided, this allows
  458. // additional information to be passed to a command handler.
  459. if (typeof shortCircuit === 'object') {
  460. parseContext = shortCircuit
  461. shortCircuit = _parseFn
  462. }
  463. // by providing a function as a second argument to
  464. // parse you can capture output that would otherwise
  465. // default to printing to stdout/stderr.
  466. if (typeof shortCircuit === 'function') {
  467. parseFn = shortCircuit
  468. shortCircuit = null
  469. }
  470. // completion short-circuits the parsing process,
  471. // skipping validation, etc.
  472. if (!shortCircuit) processArgs = args
  473. freeze()
  474. if (parseFn) exitProcess = false
  475. const parsed = self._parseArgs(args, shortCircuit)
  476. if (parseFn) parseFn(exitError, parsed, output)
  477. unfreeze()
  478. return parsed
  479. }
  480. self._getParseContext = () => parseContext || {}
  481. self._hasParseCallback = () => !!parseFn
  482. self.option = self.options = function option (key, opt) {
  483. argsert('<string|object> [object]', [key, opt], arguments.length)
  484. if (typeof key === 'object') {
  485. Object.keys(key).forEach((k) => {
  486. self.options(k, key[k])
  487. })
  488. } else {
  489. if (typeof opt !== 'object') {
  490. opt = {}
  491. }
  492. options.key[key] = true // track manually set keys.
  493. if (opt.alias) self.alias(key, opt.alias)
  494. const demand = opt.demand || opt.required || opt.require
  495. // deprecated, use 'demandOption' instead
  496. if (demand) {
  497. self.demand(key, demand)
  498. }
  499. if (opt.demandOption) {
  500. self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined)
  501. }
  502. if ('conflicts' in opt) {
  503. self.conflicts(key, opt.conflicts)
  504. }
  505. if ('default' in opt) {
  506. self.default(key, opt.default)
  507. }
  508. if ('implies' in opt) {
  509. self.implies(key, opt.implies)
  510. }
  511. if ('nargs' in opt) {
  512. self.nargs(key, opt.nargs)
  513. }
  514. if (opt.config) {
  515. self.config(key, opt.configParser)
  516. }
  517. if (opt.normalize) {
  518. self.normalize(key)
  519. }
  520. if ('choices' in opt) {
  521. self.choices(key, opt.choices)
  522. }
  523. if ('coerce' in opt) {
  524. self.coerce(key, opt.coerce)
  525. }
  526. if ('group' in opt) {
  527. self.group(key, opt.group)
  528. }
  529. if (opt.boolean || opt.type === 'boolean') {
  530. self.boolean(key)
  531. if (opt.alias) self.boolean(opt.alias)
  532. }
  533. if (opt.array || opt.type === 'array') {
  534. self.array(key)
  535. if (opt.alias) self.array(opt.alias)
  536. }
  537. if (opt.number || opt.type === 'number') {
  538. self.number(key)
  539. if (opt.alias) self.number(opt.alias)
  540. }
  541. if (opt.string || opt.type === 'string') {
  542. self.string(key)
  543. if (opt.alias) self.string(opt.alias)
  544. }
  545. if (opt.count || opt.type === 'count') {
  546. self.count(key)
  547. }
  548. if (typeof opt.global === 'boolean') {
  549. self.global(key, opt.global)
  550. }
  551. if (opt.defaultDescription) {
  552. options.defaultDescription[key] = opt.defaultDescription
  553. }
  554. if (opt.skipValidation) {
  555. self.skipValidation(key)
  556. }
  557. const desc = opt.describe || opt.description || opt.desc
  558. self.describe(key, desc)
  559. if (opt.hidden) {
  560. self.hide(key)
  561. }
  562. if (opt.requiresArg) {
  563. self.requiresArg(key)
  564. }
  565. }
  566. return self
  567. }
  568. self.getOptions = () => options
  569. self.positional = function (key, opts) {
  570. argsert('<string> <object>', [key, opts], arguments.length)
  571. if (context.resets === 0) {
  572. throw new YError(".positional() can only be called in a command's builder function")
  573. }
  574. // .positional() only supports a subset of the configuration
  575. // options availble to .option().
  576. const supportedOpts = ['default', 'implies', 'normalize',
  577. 'choices', 'conflicts', 'coerce', 'type', 'describe',
  578. 'desc', 'description', 'alias']
  579. opts = objFilter(opts, (k, v) => {
  580. let accept = supportedOpts.indexOf(k) !== -1
  581. // type can be one of string|number|boolean.
  582. if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1) accept = false
  583. return accept
  584. })
  585. // copy over any settings that can be inferred from the command string.
  586. const fullCommand = context.fullCommands[context.fullCommands.length - 1]
  587. const parseOptions = fullCommand ? command.cmdToParseOptions(fullCommand) : {
  588. array: [],
  589. alias: {},
  590. default: {},
  591. demand: {}
  592. }
  593. Object.keys(parseOptions).forEach((pk) => {
  594. if (Array.isArray(parseOptions[pk])) {
  595. if (parseOptions[pk].indexOf(key) !== -1) opts[pk] = true
  596. } else {
  597. if (parseOptions[pk][key] && !(pk in opts)) opts[pk] = parseOptions[pk][key]
  598. }
  599. })
  600. self.group(key, usage.getPositionalGroupName())
  601. return self.option(key, opts)
  602. }
  603. self.group = function group (opts, groupName) {
  604. argsert('<string|array> <string>', [opts, groupName], arguments.length)
  605. const existing = preservedGroups[groupName] || groups[groupName]
  606. if (preservedGroups[groupName]) {
  607. // we now only need to track this group name in groups.
  608. delete preservedGroups[groupName]
  609. }
  610. const seen = {}
  611. groups[groupName] = (existing || []).concat(opts).filter((key) => {
  612. if (seen[key]) return false
  613. return (seen[key] = true)
  614. })
  615. return self
  616. }
  617. // combine explicit and preserved groups. explicit groups should be first
  618. self.getGroups = () => Object.assign({}, groups, preservedGroups)
  619. // as long as options.envPrefix is not undefined,
  620. // parser will apply env vars matching prefix to argv
  621. self.env = function (prefix) {
  622. argsert('[string|boolean]', [prefix], arguments.length)
  623. if (prefix === false) options.envPrefix = undefined
  624. else options.envPrefix = prefix || ''
  625. return self
  626. }
  627. self.wrap = function (cols) {
  628. argsert('<number|null|undefined>', [cols], arguments.length)
  629. usage.wrap(cols)
  630. return self
  631. }
  632. let strict = false
  633. self.strict = function (enabled) {
  634. argsert('[boolean]', [enabled], arguments.length)
  635. strict = enabled !== false
  636. return self
  637. }
  638. self.getStrict = () => strict
  639. self.showHelp = function (level) {
  640. argsert('[string|function]', [level], arguments.length)
  641. if (!self.parsed) self._parseArgs(processArgs) // run parser, if it has not already been executed.
  642. if (command.hasDefaultCommand()) {
  643. context.resets++ // override the restriction on top-level positoinals.
  644. command.runDefaultBuilderOn(self, true)
  645. }
  646. usage.showHelp(level)
  647. return self
  648. }
  649. let versionOpt = null
  650. self.version = function version (opt, msg, ver) {
  651. const defaultVersionOpt = 'version'
  652. argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length)
  653. // nuke the key previously configured
  654. // to return version #.
  655. if (versionOpt) {
  656. deleteFromParserHintObject(versionOpt)
  657. usage.version(undefined)
  658. versionOpt = null
  659. }
  660. if (arguments.length === 0) {
  661. ver = guessVersion()
  662. opt = defaultVersionOpt
  663. } else if (arguments.length === 1) {
  664. if (opt === false) { // disable default 'version' key.
  665. return self
  666. }
  667. ver = opt
  668. opt = defaultVersionOpt
  669. } else if (arguments.length === 2) {
  670. ver = msg
  671. msg = null
  672. }
  673. versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt
  674. msg = msg || usage.deferY18nLookup('Show version number')
  675. usage.version(ver || undefined)
  676. self.boolean(versionOpt)
  677. self.describe(versionOpt, msg)
  678. return self
  679. }
  680. function guessVersion () {
  681. const obj = pkgUp()
  682. return obj.version || 'unknown'
  683. }
  684. let helpOpt = null
  685. self.addHelpOpt = self.help = function addHelpOpt (opt, msg) {
  686. const defaultHelpOpt = 'help'
  687. argsert('[string|boolean] [string]', [opt, msg], arguments.length)
  688. // nuke the key previously configured
  689. // to return help.
  690. if (helpOpt) {
  691. deleteFromParserHintObject(helpOpt)
  692. helpOpt = null
  693. }
  694. if (arguments.length === 1) {
  695. if (opt === false) return self
  696. }
  697. // use arguments, fallback to defaults for opt and msg
  698. helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt
  699. self.boolean(helpOpt)
  700. self.describe(helpOpt, msg || usage.deferY18nLookup('Show help'))
  701. return self
  702. }
  703. const defaultShowHiddenOpt = 'show-hidden'
  704. options.showHiddenOpt = defaultShowHiddenOpt
  705. self.addShowHiddenOpt = self.showHidden = function addShowHiddenOpt (opt, msg) {
  706. argsert('[string|boolean] [string]', [opt, msg], arguments.length)
  707. if (arguments.length === 1) {
  708. if (opt === false) return self
  709. }
  710. const showHiddenOpt = typeof opt === 'string' ? opt : defaultShowHiddenOpt
  711. self.boolean(showHiddenOpt)
  712. self.describe(showHiddenOpt, msg || usage.deferY18nLookup('Show hidden options'))
  713. options.showHiddenOpt = showHiddenOpt
  714. return self
  715. }
  716. self.hide = function hide (key) {
  717. argsert('<string|object>', [key], arguments.length)
  718. options.hiddenOptions.push(key)
  719. return self
  720. }
  721. self.showHelpOnFail = function showHelpOnFail (enabled, message) {
  722. argsert('[boolean|string] [string]', [enabled, message], arguments.length)
  723. usage.showHelpOnFail(enabled, message)
  724. return self
  725. }
  726. var exitProcess = true
  727. self.exitProcess = function (enabled) {
  728. argsert('[boolean]', [enabled], arguments.length)
  729. if (typeof enabled !== 'boolean') {
  730. enabled = true
  731. }
  732. exitProcess = enabled
  733. return self
  734. }
  735. self.getExitProcess = () => exitProcess
  736. var completionCommand = null
  737. self.completion = function (cmd, desc, fn) {
  738. argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length)
  739. // a function to execute when generating
  740. // completions can be provided as the second
  741. // or third argument to completion.
  742. if (typeof desc === 'function') {
  743. fn = desc
  744. desc = null
  745. }
  746. // register the completion command.
  747. completionCommand = cmd || 'completion'
  748. if (!desc && desc !== false) {
  749. desc = 'generate bash completion script'
  750. }
  751. self.command(completionCommand, desc)
  752. // a function can be provided
  753. if (fn) completion.registerFunction(fn)
  754. return self
  755. }
  756. self.showCompletionScript = function ($0) {
  757. argsert('[string]', [$0], arguments.length)
  758. $0 = $0 || self.$0
  759. _logger.log(completion.generateCompletionScript($0, completionCommand))
  760. return self
  761. }
  762. self.getCompletion = function (args, done) {
  763. argsert('<array> <function>', [args, done], arguments.length)
  764. completion.getCompletion(args, done)
  765. }
  766. self.locale = function (locale) {
  767. argsert('[string]', [locale], arguments.length)
  768. if (arguments.length === 0) {
  769. guessLocale()
  770. return y18n.getLocale()
  771. }
  772. detectLocale = false
  773. y18n.setLocale(locale)
  774. return self
  775. }
  776. self.updateStrings = self.updateLocale = function (obj) {
  777. argsert('<object>', [obj], arguments.length)
  778. detectLocale = false
  779. y18n.updateLocale(obj)
  780. return self
  781. }
  782. let detectLocale = true
  783. self.detectLocale = function (detect) {
  784. argsert('<boolean>', [detect], arguments.length)
  785. detectLocale = detect
  786. return self
  787. }
  788. self.getDetectLocale = () => detectLocale
  789. var hasOutput = false
  790. var exitError = null
  791. // maybe exit, always capture
  792. // context about why we wanted to exit.
  793. self.exit = (code, err) => {
  794. hasOutput = true
  795. exitError = err
  796. if (exitProcess) process.exit(code)
  797. }
  798. // we use a custom logger that buffers output,
  799. // so that we can print to non-CLIs, e.g., chat-bots.
  800. const _logger = {
  801. log () {
  802. const args = []
  803. for (let i = 0; i < arguments.length; i++) args.push(arguments[i])
  804. if (!self._hasParseCallback()) console.log.apply(console, args)
  805. hasOutput = true
  806. if (output.length) output += '\n'
  807. output += args.join(' ')
  808. },
  809. error () {
  810. const args = []
  811. for (let i = 0; i < arguments.length; i++) args.push(arguments[i])
  812. if (!self._hasParseCallback()) console.error.apply(console, args)
  813. hasOutput = true
  814. if (output.length) output += '\n'
  815. output += args.join(' ')
  816. }
  817. }
  818. self._getLoggerInstance = () => _logger
  819. // has yargs output an error our help
  820. // message in the current execution context.
  821. self._hasOutput = () => hasOutput
  822. self._setHasOutput = () => {
  823. hasOutput = true
  824. }
  825. let recommendCommands
  826. self.recommendCommands = function (recommend) {
  827. argsert('[boolean]', [recommend], arguments.length)
  828. recommendCommands = typeof recommend === 'boolean' ? recommend : true
  829. return self
  830. }
  831. self.getUsageInstance = () => usage
  832. self.getValidationInstance = () => validation
  833. self.getCommandInstance = () => command
  834. self.terminalWidth = () => {
  835. argsert([], 0)
  836. return typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null
  837. }
  838. Object.defineProperty(self, 'argv', {
  839. get: () => self._parseArgs(processArgs),
  840. enumerable: true
  841. })
  842. self._parseArgs = function parseArgs (args, shortCircuit, _skipValidation, commandIndex) {
  843. let skipValidation = !!_skipValidation
  844. args = args || processArgs
  845. options.__ = y18n.__
  846. options.configuration = pkgUp()['yargs'] || {}
  847. const parsed = Parser.detailed(args, options)
  848. let argv = parsed.argv
  849. if (parseContext) argv = Object.assign({}, argv, parseContext)
  850. const aliases = parsed.aliases
  851. argv.$0 = self.$0
  852. self.parsed = parsed
  853. try {
  854. guessLocale() // guess locale lazily, so that it can be turned off in chain.
  855. // while building up the argv object, there
  856. // are two passes through the parser. If completion
  857. // is being performed short-circuit on the first pass.
  858. if (shortCircuit) {
  859. return argv
  860. }
  861. // if there's a handler associated with a
  862. // command defer processing to it.
  863. if (helpOpt) {
  864. // consider any multi-char helpOpt alias as a valid help command
  865. // unless all helpOpt aliases are single-char
  866. // note that parsed.aliases is a normalized bidirectional map :)
  867. const helpCmds = [helpOpt]
  868. .concat(aliases[helpOpt] || [])
  869. .filter(k => k.length > 1)
  870. // check if help should trigger and strip it from _.
  871. if (~helpCmds.indexOf(argv._[argv._.length - 1])) {
  872. argv._.pop()
  873. argv[helpOpt] = true
  874. }
  875. }
  876. const handlerKeys = command.getCommands()
  877. const skipDefaultCommand = argv[helpOpt] && (handlerKeys.length > 1 || handlerKeys[0] !== '$0')
  878. if (argv._.length) {
  879. if (handlerKeys.length) {
  880. let firstUnknownCommand
  881. for (let i = (commandIndex || 0), cmd; argv._[i] !== undefined; i++) {
  882. cmd = String(argv._[i])
  883. if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
  884. setPlaceholderKeys(argv)
  885. // commands are executed using a recursive algorithm that executes
  886. // the deepest command first; we keep track of the position in the
  887. // argv._ array that is currently being executed.
  888. return command.runCommand(cmd, self, parsed, i + 1)
  889. } else if (!firstUnknownCommand && cmd !== completionCommand) {
  890. firstUnknownCommand = cmd
  891. break
  892. }
  893. }
  894. // run the default command, if defined
  895. if (command.hasDefaultCommand() && !skipDefaultCommand) {
  896. setPlaceholderKeys(argv)
  897. return command.runCommand(null, self, parsed)
  898. }
  899. // recommend a command if recommendCommands() has
  900. // been enabled, and no commands were found to execute
  901. if (recommendCommands && firstUnknownCommand && !argv[helpOpt]) {
  902. validation.recommendCommands(firstUnknownCommand, handlerKeys)
  903. }
  904. }
  905. // generate a completion script for adding to ~/.bashrc.
  906. if (completionCommand && ~argv._.indexOf(completionCommand) && !argv[completion.completionKey]) {
  907. if (exitProcess) setBlocking(true)
  908. self.showCompletionScript()
  909. self.exit(0)
  910. }
  911. } else if (command.hasDefaultCommand() && !skipDefaultCommand) {
  912. setPlaceholderKeys(argv)
  913. return command.runCommand(null, self, parsed)
  914. }
  915. // we must run completions first, a user might
  916. // want to complete the --help or --version option.
  917. if (completion.completionKey in argv) {
  918. if (exitProcess) setBlocking(true)
  919. // we allow for asynchronous completions,
  920. // e.g., loading in a list of commands from an API.
  921. const completionArgs = args.slice(args.indexOf(`--${completion.completionKey}`) + 1)
  922. completion.getCompletion(completionArgs, (completions) => {
  923. ;(completions || []).forEach((completion) => {
  924. _logger.log(completion)
  925. })
  926. self.exit(0)
  927. })
  928. return setPlaceholderKeys(argv)
  929. }
  930. // Handle 'help' and 'version' options
  931. // if we haven't already output help!
  932. if (!hasOutput) {
  933. Object.keys(argv).forEach((key) => {
  934. if (key === helpOpt && argv[key]) {
  935. if (exitProcess) setBlocking(true)
  936. skipValidation = true
  937. self.showHelp('log')
  938. self.exit(0)
  939. } else if (key === versionOpt && argv[key]) {
  940. if (exitProcess) setBlocking(true)
  941. skipValidation = true
  942. usage.showVersion()
  943. self.exit(0)
  944. }
  945. })
  946. }
  947. // Check if any of the options to skip validation were provided
  948. if (!skipValidation && options.skipValidation.length > 0) {
  949. skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true)
  950. }
  951. // If the help or version options where used and exitProcess is false,
  952. // or if explicitly skipped, we won't run validations.
  953. if (!skipValidation) {
  954. if (parsed.error) throw new YError(parsed.error.message)
  955. // if we're executed via bash completion, don't
  956. // bother with validation.
  957. if (!argv[completion.completionKey]) {
  958. self._runValidation(argv, aliases, {}, parsed.error)
  959. }
  960. }
  961. } catch (err) {
  962. if (err instanceof YError) usage.fail(err.message, err)
  963. else throw err
  964. }
  965. return setPlaceholderKeys(argv)
  966. }
  967. self._runValidation = function runValidation (argv, aliases, positionalMap, parseErrors) {
  968. if (parseErrors) throw new YError(parseErrors.message)
  969. validation.nonOptionCount(argv)
  970. validation.requiredArguments(argv)
  971. if (strict) validation.unknownArguments(argv, aliases, positionalMap)
  972. validation.customChecks(argv, aliases)
  973. validation.limitedChoices(argv)
  974. validation.implications(argv)
  975. validation.conflicting(argv)
  976. }
  977. function guessLocale () {
  978. if (!detectLocale) return
  979. try {
  980. const osLocale = require('os-locale')
  981. self.locale(osLocale.sync({ spawn: false }))
  982. } catch (err) {
  983. // if we explode looking up locale just noop
  984. // we'll keep using the default language 'en'.
  985. }
  986. }
  987. function setPlaceholderKeys (argv) {
  988. Object.keys(options.key).forEach((key) => {
  989. // don't set placeholder keys for dot
  990. // notation options 'foo.bar'.
  991. if (~key.indexOf('.')) return
  992. if (typeof argv[key] === 'undefined') argv[key] = undefined
  993. })
  994. return argv
  995. }
  996. // an app should almost always have --version and --help,
  997. // if you *really* want to disable this use .help(false)/.version(false).
  998. self.help()
  999. self.version()
  1000. return self
  1001. }
  1002. // rebase an absolute path to a relative one with respect to a base directory
  1003. // exported for tests
  1004. exports.rebase = rebase
  1005. function rebase (base, dir) {
  1006. return path.relative(base, dir)
  1007. }