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

yargs.js 36KB

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