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.

1190 lines
36 KiB

4 years ago
  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 middlewareFactory = 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 = middlewareFactory(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. self.showHelp = function (level) {
  652. argsert('[string|function]', [level], arguments.length)
  653. if (!self.parsed) self._parseArgs(processArgs) // run parser, if it has not already been executed.
  654. if (command.hasDefaultCommand()) {
  655. context.resets++ // override the restriction on top-level positoinals.
  656. command.runDefaultBuilderOn(self, true)
  657. }
  658. usage.showHelp(level)
  659. return self
  660. }
  661. let versionOpt = null
  662. self.version = function version (opt, msg, ver) {
  663. const defaultVersionOpt = 'version'
  664. argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length)
  665. // nuke the key previously configured
  666. // to return version #.
  667. if (versionOpt) {
  668. deleteFromParserHintObject(versionOpt)
  669. usage.version(undefined)
  670. versionOpt = null
  671. }
  672. if (arguments.length === 0) {
  673. ver = guessVersion()
  674. opt = defaultVersionOpt
  675. } else if (arguments.length === 1) {
  676. if (opt === false) { // disable default 'version' key.
  677. return self
  678. }
  679. ver = opt
  680. opt = defaultVersionOpt
  681. } else if (arguments.length === 2) {
  682. ver = msg
  683. msg = null
  684. }
  685. versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt
  686. msg = msg || usage.deferY18nLookup('Show version number')
  687. usage.version(ver || undefined)
  688. self.boolean(versionOpt)
  689. self.describe(versionOpt, msg)
  690. return self
  691. }
  692. function guessVersion () {
  693. const obj = pkgUp()
  694. return obj.version || 'unknown'
  695. }
  696. let helpOpt = null
  697. self.addHelpOpt = self.help = function addHelpOpt (opt, msg) {
  698. const defaultHelpOpt = 'help'
  699. argsert('[string|boolean] [string]', [opt, msg], arguments.length)
  700. // nuke the key previously configured
  701. // to return help.
  702. if (helpOpt) {
  703. deleteFromParserHintObject(helpOpt)
  704. helpOpt = null
  705. }
  706. if (arguments.length === 1) {
  707. if (opt === false) return self
  708. }
  709. // use arguments, fallback to defaults for opt and msg
  710. helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt
  711. self.boolean(helpOpt)
  712. self.describe(helpOpt, msg || usage.deferY18nLookup('Show help'))
  713. return self
  714. }
  715. const defaultShowHiddenOpt = 'show-hidden'
  716. options.showHiddenOpt = defaultShowHiddenOpt
  717. self.addShowHiddenOpt = self.showHidden = function addShowHiddenOpt (opt, msg) {
  718. argsert('[string|boolean] [string]', [opt, msg], arguments.length)
  719. if (arguments.length === 1) {
  720. if (opt === false) return self
  721. }
  722. const showHiddenOpt = typeof opt === 'string' ? opt : defaultShowHiddenOpt
  723. self.boolean(showHiddenOpt)
  724. self.describe(showHiddenOpt, msg || usage.deferY18nLookup('Show hidden options'))
  725. options.showHiddenOpt = showHiddenOpt
  726. return self
  727. }
  728. self.hide = function hide (key) {
  729. argsert('<string|object>', [key], arguments.length)
  730. options.hiddenOptions.push(key)
  731. return self
  732. }
  733. self.showHelpOnFail = function showHelpOnFail (enabled, message) {
  734. argsert('[boolean|string] [string]', [enabled, message], arguments.length)
  735. usage.showHelpOnFail(enabled, message)
  736. return self
  737. }
  738. var exitProcess = true
  739. self.exitProcess = function (enabled) {
  740. argsert('[boolean]', [enabled], arguments.length)
  741. if (typeof enabled !== 'boolean') {
  742. enabled = true
  743. }
  744. exitProcess = enabled
  745. return self
  746. }
  747. self.getExitProcess = () => exitProcess
  748. var completionCommand = null
  749. self.completion = function (cmd, desc, fn) {
  750. argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length)
  751. // a function to execute when generating
  752. // completions can be provided as the second
  753. // or third argument to completion.
  754. if (typeof desc === 'function') {
  755. fn = desc
  756. desc = null
  757. }
  758. // register the completion command.
  759. completionCommand = cmd || 'completion'
  760. if (!desc && desc !== false) {
  761. desc = 'generate bash completion script'
  762. }
  763. self.command(completionCommand, desc)
  764. // a function can be provided
  765. if (fn) completion.registerFunction(fn)
  766. return self
  767. }
  768. self.showCompletionScript = function ($0) {
  769. argsert('[string]', [$0], arguments.length)
  770. $0 = $0 || self.$0
  771. _logger.log(completion.generateCompletionScript($0, completionCommand))
  772. return self
  773. }
  774. self.getCompletion = function (args, done) {
  775. argsert('<array> <function>', [args, done], arguments.length)
  776. completion.getCompletion(args, done)
  777. }
  778. self.locale = function (locale) {
  779. argsert('[string]', [locale], arguments.length)
  780. if (arguments.length === 0) {
  781. guessLocale()
  782. return y18n.getLocale()
  783. }
  784. detectLocale = false
  785. y18n.setLocale(locale)
  786. return self
  787. }
  788. self.updateStrings = self.updateLocale = function (obj) {
  789. argsert('<object>', [obj], arguments.length)
  790. detectLocale = false
  791. y18n.updateLocale(obj)
  792. return self
  793. }
  794. let detectLocale = true
  795. self.detectLocale = function (detect) {
  796. argsert('<boolean>', [detect], arguments.length)
  797. detectLocale = detect
  798. return self
  799. }
  800. self.getDetectLocale = () => detectLocale
  801. var hasOutput = false
  802. var exitError = null
  803. // maybe exit, always capture
  804. // context about why we wanted to exit.
  805. self.exit = (code, err) => {
  806. hasOutput = true
  807. exitError = err
  808. if (exitProcess) process.exit(code)
  809. }
  810. // we use a custom logger that buffers output,
  811. // so that we can print to non-CLIs, e.g., chat-bots.
  812. const _logger = {
  813. log () {
  814. const args = []
  815. for (let i = 0; i < arguments.length; i++) args.push(arguments[i])
  816. if (!self._hasParseCallback()) console.log.apply(console, args)
  817. hasOutput = true
  818. if (output.length) output += '\n'
  819. output += args.join(' ')
  820. },
  821. error () {
  822. const args = []
  823. for (let i = 0; i < arguments.length; i++) args.push(arguments[i])
  824. if (!self._hasParseCallback()) console.error.apply(console, args)
  825. hasOutput = true
  826. if (output.length) output += '\n'
  827. output += args.join(' ')
  828. }
  829. }
  830. self._getLoggerInstance = () => _logger
  831. // has yargs output an error our help
  832. // message in the current execution context.
  833. self._hasOutput = () => hasOutput
  834. self._setHasOutput = () => {
  835. hasOutput = true
  836. }
  837. let recommendCommands
  838. self.recommendCommands = function (recommend) {
  839. argsert('[boolean]', [recommend], arguments.length)
  840. recommendCommands = typeof recommend === 'boolean' ? recommend : true
  841. return self
  842. }
  843. self.getUsageInstance = () => usage
  844. self.getValidationInstance = () => validation
  845. self.getCommandInstance = () => command
  846. self.terminalWidth = () => {
  847. argsert([], 0)
  848. return typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null
  849. }
  850. Object.defineProperty(self, 'argv', {
  851. get: () => self._parseArgs(processArgs),
  852. enumerable: true
  853. })
  854. self._parseArgs = function parseArgs (args, shortCircuit, _skipValidation, commandIndex) {
  855. let skipValidation = !!_skipValidation
  856. args = args || processArgs
  857. options.__ = y18n.__
  858. options.configuration = pkgUp()['yargs'] || {}
  859. const parsed = Parser.detailed(args, options)
  860. let argv = parsed.argv
  861. if (parseContext) argv = Object.assign({}, argv, parseContext)
  862. const aliases = parsed.aliases
  863. argv.$0 = self.$0
  864. self.parsed = parsed
  865. try {
  866. guessLocale() // guess locale lazily, so that it can be turned off in chain.
  867. // while building up the argv object, there
  868. // are two passes through the parser. If completion
  869. // is being performed short-circuit on the first pass.
  870. if (shortCircuit) {
  871. return argv
  872. }
  873. // if there's a handler associated with a
  874. // command defer processing to it.
  875. if (helpOpt) {
  876. // consider any multi-char helpOpt alias as a valid help command
  877. // unless all helpOpt aliases are single-char
  878. // note that parsed.aliases is a normalized bidirectional map :)
  879. const helpCmds = [helpOpt]
  880. .concat(aliases[helpOpt] || [])
  881. .filter(k => k.length > 1)
  882. // check if help should trigger and strip it from _.
  883. if (~helpCmds.indexOf(argv._[argv._.length - 1])) {
  884. argv._.pop()
  885. argv[helpOpt] = true
  886. }
  887. }
  888. const handlerKeys = command.getCommands()
  889. const requestCompletions = completion.completionKey in argv
  890. const skipRecommendation = argv[helpOpt] || requestCompletions
  891. const skipDefaultCommand = skipRecommendation && (handlerKeys.length > 1 || handlerKeys[0] !== '$0')
  892. if (argv._.length) {
  893. if (handlerKeys.length) {
  894. let firstUnknownCommand
  895. for (let i = (commandIndex || 0), cmd; argv._[i] !== undefined; i++) {
  896. cmd = String(argv._[i])
  897. if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
  898. // commands are executed using a recursive algorithm that executes
  899. // the deepest command first; we keep track of the position in the
  900. // argv._ array that is currently being executed.
  901. return command.runCommand(cmd, self, parsed, i + 1)
  902. } else if (!firstUnknownCommand && cmd !== completionCommand) {
  903. firstUnknownCommand = cmd
  904. break
  905. }
  906. }
  907. // run the default command, if defined
  908. if (command.hasDefaultCommand() && !skipDefaultCommand) {
  909. return command.runCommand(null, self, parsed)
  910. }
  911. // recommend a command if recommendCommands() has
  912. // been enabled, and no commands were found to execute
  913. if (recommendCommands && firstUnknownCommand && !skipRecommendation) {
  914. validation.recommendCommands(firstUnknownCommand, handlerKeys)
  915. }
  916. }
  917. // generate a completion script for adding to ~/.bashrc.
  918. if (completionCommand && ~argv._.indexOf(completionCommand) && !requestCompletions) {
  919. if (exitProcess) setBlocking(true)
  920. self.showCompletionScript()
  921. self.exit(0)
  922. }
  923. } else if (command.hasDefaultCommand() && !skipDefaultCommand) {
  924. return command.runCommand(null, self, parsed)
  925. }
  926. // we must run completions first, a user might
  927. // want to complete the --help or --version option.
  928. if (requestCompletions) {
  929. if (exitProcess) setBlocking(true)
  930. // we allow for asynchronous completions,
  931. // e.g., loading in a list of commands from an API.
  932. const completionArgs = args.slice(args.indexOf(`--${completion.completionKey}`) + 1)
  933. completion.getCompletion(completionArgs, (completions) => {
  934. ;(completions || []).forEach((completion) => {
  935. _logger.log(completion)
  936. })
  937. self.exit(0)
  938. })
  939. return argv
  940. }
  941. // Handle 'help' and 'version' options
  942. // if we haven't already output help!
  943. if (!hasOutput) {
  944. Object.keys(argv).forEach((key) => {
  945. if (key === helpOpt && argv[key]) {
  946. if (exitProcess) setBlocking(true)
  947. skipValidation = true
  948. self.showHelp('log')
  949. self.exit(0)
  950. } else if (key === versionOpt && argv[key]) {
  951. if (exitProcess) setBlocking(true)
  952. skipValidation = true
  953. usage.showVersion()
  954. self.exit(0)
  955. }
  956. })
  957. }
  958. // Check if any of the options to skip validation were provided
  959. if (!skipValidation && options.skipValidation.length > 0) {
  960. skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true)
  961. }
  962. // If the help or version options where used and exitProcess is false,
  963. // or if explicitly skipped, we won't run validations.
  964. if (!skipValidation) {
  965. if (parsed.error) throw new YError(parsed.error.message)
  966. // if we're executed via bash completion, don't
  967. // bother with validation.
  968. if (!requestCompletions) {
  969. self._runValidation(argv, aliases, {}, parsed.error)
  970. }
  971. }
  972. } catch (err) {
  973. if (err instanceof YError) usage.fail(err.message, err)
  974. else throw err
  975. }
  976. return argv
  977. }
  978. self._runValidation = function runValidation (argv, aliases, positionalMap, parseErrors) {
  979. if (parseErrors) throw new YError(parseErrors.message)
  980. validation.nonOptionCount(argv)
  981. validation.requiredArguments(argv)
  982. if (strict) validation.unknownArguments(argv, aliases, positionalMap)
  983. validation.customChecks(argv, aliases)
  984. validation.limitedChoices(argv)
  985. validation.implications(argv)
  986. validation.conflicting(argv)
  987. }
  988. function guessLocale () {
  989. if (!detectLocale) return
  990. try {
  991. const osLocale = require('os-locale')
  992. self.locale(osLocale.sync({ spawn: false }))
  993. } catch (err) {
  994. // if we explode looking up locale just noop
  995. // we'll keep using the default language 'en'.
  996. }
  997. }
  998. // an app should almost always have --version and --help,
  999. // if you *really* want to disable this use .help(false)/.version(false).
  1000. self.help()
  1001. self.version()
  1002. return self
  1003. }
  1004. // rebase an absolute path to a relative one with respect to a base directory
  1005. // exported for tests
  1006. exports.rebase = rebase
  1007. function rebase (base, dir) {
  1008. return path.relative(base, dir)
  1009. }