yargs.js 32 KB

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