yargs.js 37 KB

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