2 const argsert = require('./lib/argsert')
3 const fs = require('fs')
4 const Command = require('./lib/command')
5 const Completion = require('./lib/completion')
6 const Parser = require('yargs-parser')
7 const path = require('path')
8 const Usage = require('./lib/usage')
9 const Validation = require('./lib/validation')
10 const Y18n = require('y18n')
11 const objFilter = require('./lib/obj-filter')
12 const setBlocking = require('set-blocking')
13 const applyExtends = require('./lib/apply-extends')
14 const YError = require('./lib/yerror')
16 exports = module.exports = Yargs
17 function Yargs (processArgs, cwd, parentRequire) {
18 processArgs = processArgs || [] // handle calling yargs().
25 let preservedGroups = {}
30 directory: path.resolve(__dirname, './locales'),
34 if (!cwd) cwd = process.cwd()
36 self.$0 = process.argv
39 // ignore the node bin, specify this in your
40 // bin file with #!/usr/bin/env node
41 if (i === 0 && /\b(node|iojs)(\.exe)?$/.test(x)) return
42 const b = rebase(cwd, x)
43 return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x
47 if (process.env._ !== undefined && process.argv[1] === process.env._) {
48 self.$0 = process.env._.replace(
49 `${path.dirname(process.execPath)}/`, ''
53 // use context object to keep track of resets, subcommand execution, etc
54 // submodules should modify and check the state of context as necessary
55 const context = { resets: -1, commands: [], fullCommands: [], files: [] }
56 self.getContext = () => context
58 // puts yargs back into an initial state. any keys
59 // that have been set to "global" will not be reset
62 self.resetOptions = self.reset = function resetOptions (aliases) {
64 aliases = aliases || {}
65 options = options || {}
66 // put yargs back into an initial state, this
67 // logic is used to build a nested command
70 tmpOptions.local = options.local ? options.local : []
71 tmpOptions.configObjects = options.configObjects ? options.configObjects : []
73 // if a key has been explicitly set as local,
74 // we should reset it before passing options to command.
75 const localLookup = {}
76 tmpOptions.local.forEach((l) => {
78 ;(aliases[l] || []).forEach((a) => {
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) {
91 // groups can now be reset
94 const arrayOptions = [
95 'array', 'boolean', 'string', 'skipValidation',
96 'count', 'normalize', 'number'
99 const objectOptions = [
100 'narg', 'key', 'alias', 'default', 'defaultDescription',
101 'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce'
104 arrayOptions.forEach((k) => {
105 tmpOptions[k] = (options[k] || []).filter(k => !localLookup[k])
108 objectOptions.forEach((k) => {
109 tmpOptions[k] = objFilter(options[k], (k, v) => !localLookup[k])
112 tmpOptions.envPrefix = options.envPrefix
115 // if this is the first time being executed, create
116 // instances of all our helpers -- otherwise just reset.
117 usage = usage ? usage.reset(localLookup) : Usage(self, y18n)
118 validation = validation ? validation.reset(localLookup) : Validation(self, usage, y18n)
119 command = command ? command.reset() : Command(self, usage, validation)
120 if (!completion) completion = Completion(self, usage, command)
122 completionCommand = null
132 // temporary hack: allow "freezing" of reset-able state for parse(msg, cb)
136 frozen.options = options
137 frozen.configObjects = options.configObjects.slice(0)
138 frozen.exitProcess = exitProcess
139 frozen.groups = groups
143 frozen.strict = strict
144 frozen.completionCommand = completionCommand
145 frozen.output = output
146 frozen.exitError = exitError
147 frozen.hasOutput = hasOutput
148 frozen.parsed = self.parsed
150 function unfreeze () {
151 options = frozen.options
152 options.configObjects = frozen.configObjects
153 exitProcess = frozen.exitProcess
154 groups = frozen.groups
155 output = frozen.output
156 exitError = frozen.exitError
157 hasOutput = frozen.hasOutput
158 self.parsed = frozen.parsed
160 validation.unfreeze()
162 strict = frozen.strict
163 completionCommand = frozen.completionCommand
169 self.boolean = function (keys) {
170 argsert('<array|string>', [keys], arguments.length)
171 populateParserHintArray('boolean', keys)
175 self.array = function (keys) {
176 argsert('<array|string>', [keys], arguments.length)
177 populateParserHintArray('array', keys)
181 self.number = function (keys) {
182 argsert('<array|string>', [keys], arguments.length)
183 populateParserHintArray('number', keys)
187 self.normalize = function (keys) {
188 argsert('<array|string>', [keys], arguments.length)
189 populateParserHintArray('normalize', keys)
193 self.count = function (keys) {
194 argsert('<array|string>', [keys], arguments.length)
195 populateParserHintArray('count', keys)
199 self.string = function (keys) {
200 argsert('<array|string>', [keys], arguments.length)
201 populateParserHintArray('string', keys)
205 self.requiresArg = function (keys) {
206 argsert('<array|string>', [keys], arguments.length)
207 populateParserHintObject(self.nargs, false, 'narg', keys, 1)
211 self.skipValidation = function (keys) {
212 argsert('<array|string>', [keys], arguments.length)
213 populateParserHintArray('skipValidation', keys)
217 function populateParserHintArray (type, keys, value) {
218 keys = [].concat(keys)
219 keys.forEach((key) => {
220 options[type].push(key)
224 self.nargs = function (key, value) {
225 argsert('<string|object|array> [number]', [key, value], arguments.length)
226 populateParserHintObject(self.nargs, false, 'narg', key, value)
230 self.choices = function (key, value) {
231 argsert('<object|string|array> [string|array]', [key, value], arguments.length)
232 populateParserHintObject(self.choices, true, 'choices', key, value)
236 self.alias = function (key, value) {
237 argsert('<object|string|array> [string|array]', [key, value], arguments.length)
238 populateParserHintObject(self.alias, true, 'alias', key, value)
242 // TODO: actually deprecate self.defaults.
243 self.default = self.defaults = function (key, value, defaultDescription) {
244 argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length)
245 if (defaultDescription) options.defaultDescription[key] = defaultDescription
246 if (typeof value === 'function') {
247 if (!options.defaultDescription[key]) options.defaultDescription[key] = usage.functionDescription(value)
250 populateParserHintObject(self.default, false, 'default', key, value)
254 self.describe = function (key, desc) {
255 argsert('<object|string|array> [string]', [key, desc], arguments.length)
256 populateParserHintObject(self.describe, false, 'key', key, true)
257 usage.describe(key, desc)
261 self.demandOption = function (keys, msg) {
262 argsert('<object|string|array> [string]', [keys, msg], arguments.length)
263 populateParserHintObject(self.demandOption, false, 'demandedOptions', keys, msg)
267 self.coerce = function (keys, value) {
268 argsert('<object|string|array> [function]', [keys, value], arguments.length)
269 populateParserHintObject(self.coerce, false, 'coerce', keys, value)
273 function populateParserHintObject (builder, isArray, type, key, value) {
274 if (Array.isArray(key)) {
275 // an array of keys with one value ['x', 'y', 'z'], function parse () {}
281 } else if (typeof key === 'object') {
282 // an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
283 Object.keys(key).forEach((k) => {
287 // a single key value pair 'x', parse() {}
289 options[type][key] = (options[type][key] || []).concat(value)
291 options[type][key] = value
296 function deleteFromParserHintObject (optionKey) {
297 // delete from all parsing hints:
298 // boolean, array, key, alias, etc.
299 Object.keys(options).forEach((hintKey) => {
300 const hint = options[hintKey]
301 if (Array.isArray(hint)) {
302 if (~hint.indexOf(optionKey)) hint.splice(hint.indexOf(optionKey), 1)
303 } else if (typeof hint === 'object') {
304 delete hint[optionKey]
307 // now delete the description from usage.js.
308 delete usage.getDescriptions()[optionKey]
311 self.config = function config (key, msg, parseFn) {
312 argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length)
313 // allow a config object to be provided directly.
314 if (typeof key === 'object') {
315 key = applyExtends(key, cwd)
316 options.configObjects = (options.configObjects || []).concat(key)
320 // allow for a custom parsing function.
321 if (typeof msg === 'function') {
326 key = key || 'config'
327 self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file'))
328 ;(Array.isArray(key) ? key : [key]).forEach((k) => {
329 options.config[k] = parseFn || true
335 self.example = function (cmd, description) {
336 argsert('<string> [string]', [cmd, description], arguments.length)
337 usage.example(cmd, description)
341 self.command = function (cmd, description, builder, handler, middlewares) {
342 argsert('<string|array|object> [string|boolean] [function|object] [function] [array]', [cmd, description, builder, handler, middlewares], arguments.length)
343 command.addHandler(cmd, description, builder, handler, middlewares)
347 self.commandDir = function (dir, opts) {
348 argsert('<string> [object]', [dir, opts], arguments.length)
349 const req = parentRequire || require
350 command.addDirectory(dir, self.getContext(), req, require('get-caller-file')(), opts)
354 // TODO: deprecate self.demand in favor of
355 // .demandCommand() .demandOption().
356 self.demand = self.required = self.require = function demand (keys, max, msg) {
357 // you can optionally provide a 'max' key,
358 // which will raise an exception if too many '_'
359 // options are provided.
360 if (Array.isArray(max)) {
361 max.forEach((key) => {
362 self.demandOption(key, msg)
365 } else if (typeof max !== 'number') {
370 if (typeof keys === 'number') {
371 self.demandCommand(keys, max, msg, msg)
372 } else if (Array.isArray(keys)) {
373 keys.forEach((key) => {
374 self.demandOption(key, msg)
377 if (typeof msg === 'string') {
378 self.demandOption(keys, msg)
379 } else if (msg === true || typeof msg === 'undefined') {
380 self.demandOption(keys)
387 self.demandCommand = function demandCommand (min, max, minMsg, maxMsg) {
388 argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length)
390 if (typeof min === 'undefined') min = 1
392 if (typeof max !== 'number') {
397 self.global('_', false)
399 options.demandedCommands._ = {
409 self.getDemandedOptions = () => {
411 return options.demandedOptions
414 self.getDemandedCommands = () => {
416 return options.demandedCommands
419 self.implies = function (key, value) {
420 argsert('<string|object> [number|string|array]', [key, value], arguments.length)
421 validation.implies(key, value)
425 self.conflicts = function (key1, key2) {
426 argsert('<string|object> [string|array]', [key1, key2], arguments.length)
427 validation.conflicts(key1, key2)
431 self.usage = function (msg, description, builder, handler) {
432 argsert('<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length)
434 if (description !== undefined) {
435 // .usage() can be used as an alias for defining
436 // a default command.
437 if ((msg || '').match(/^\$0( |$)/)) {
438 return self.command(msg, description, builder, handler)
440 throw new YError('.usage() description must start with $0 if being used as alias for .command()')
448 self.epilogue = self.epilog = function (msg) {
449 argsert('<string>', [msg], arguments.length)
454 self.fail = function (f) {
455 argsert('<function>', [f], arguments.length)
460 self.check = function (f, _global) {
461 argsert('<function> [boolean]', [f, _global], arguments.length)
462 validation.check(f, _global !== false)
466 self.global = function global (globals, global) {
467 argsert('<string|array> [boolean]', [globals, global], arguments.length)
468 globals = [].concat(globals)
469 if (global !== false) {
470 options.local = options.local.filter(l => globals.indexOf(l) === -1)
472 globals.forEach((g) => {
473 if (options.local.indexOf(g) === -1) options.local.push(g)
479 self.pkgConf = function pkgConf (key, rootPath) {
480 argsert('<string> [string]', [key, rootPath], arguments.length)
482 // prefer cwd to require-main-filename in this method
483 // since we're looking for e.g. "nyc" config in nyc consumer
484 // rather than "yargs" config in nyc (where nyc is the main filename)
485 const obj = pkgUp(rootPath || cwd)
487 // If an object exists in the key, add it to options.configObjects
488 if (obj[key] && typeof obj[key] === 'object') {
489 conf = applyExtends(obj[key], rootPath || cwd)
490 options.configObjects = (options.configObjects || []).concat(conf)
497 function pkgUp (rootPath) {
498 const npath = rootPath || '*'
499 if (pkgs[npath]) return pkgs[npath]
500 const findUp = require('find-up')
504 let startDir = rootPath || require('require-main-filename')(parentRequire || require)
506 // When called in an environment that lacks require.main.filename, such as a jest test runner,
507 // startDir is already process.cwd(), and should not be shortened.
508 // Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
509 if (!rootPath && path.extname(startDir)) {
510 startDir = path.dirname(startDir)
513 const pkgJsonPath = findUp.sync('package.json', {
516 obj = JSON.parse(fs.readFileSync(pkgJsonPath))
519 pkgs[npath] = obj || {}
524 let parseContext = null
525 self.parse = function parse (args, shortCircuit, _parseFn) {
526 argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length)
527 if (typeof args === 'undefined') args = processArgs
529 // a context object can optionally be provided, this allows
530 // additional information to be passed to a command handler.
531 if (typeof shortCircuit === 'object') {
532 parseContext = shortCircuit
533 shortCircuit = _parseFn
536 // by providing a function as a second argument to
537 // parse you can capture output that would otherwise
538 // default to printing to stdout/stderr.
539 if (typeof shortCircuit === 'function') {
540 parseFn = shortCircuit
543 // completion short-circuits the parsing process,
544 // skipping validation, etc.
545 if (!shortCircuit) processArgs = args
548 if (parseFn) exitProcess = false
550 const parsed = self._parseArgs(args, shortCircuit)
551 if (parseFn) parseFn(exitError, parsed, output)
557 self._getParseContext = () => parseContext || {}
559 self._hasParseCallback = () => !!parseFn
561 self.option = self.options = function option (key, opt) {
562 argsert('<string|object> [object]', [key, opt], arguments.length)
563 if (typeof key === 'object') {
564 Object.keys(key).forEach((k) => {
565 self.options(k, key[k])
568 if (typeof opt !== 'object') {
572 options.key[key] = true // track manually set keys.
574 if (opt.alias) self.alias(key, opt.alias)
576 const demand = opt.demand || opt.required || opt.require
578 // deprecated, use 'demandOption' instead
580 self.demand(key, demand)
583 if (opt.demandOption) {
584 self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined)
587 if ('conflicts' in opt) {
588 self.conflicts(key, opt.conflicts)
591 if ('default' in opt) {
592 self.default(key, opt.default)
595 if ('implies' in opt) {
596 self.implies(key, opt.implies)
599 if ('nargs' in opt) {
600 self.nargs(key, opt.nargs)
604 self.config(key, opt.configParser)
611 if ('choices' in opt) {
612 self.choices(key, opt.choices)
615 if ('coerce' in opt) {
616 self.coerce(key, opt.coerce)
619 if ('group' in opt) {
620 self.group(key, opt.group)
623 if (opt.boolean || opt.type === 'boolean') {
625 if (opt.alias) self.boolean(opt.alias)
628 if (opt.array || opt.type === 'array') {
630 if (opt.alias) self.array(opt.alias)
633 if (opt.number || opt.type === 'number') {
635 if (opt.alias) self.number(opt.alias)
638 if (opt.string || opt.type === 'string') {
640 if (opt.alias) self.string(opt.alias)
643 if (opt.count || opt.type === 'count') {
647 if (typeof opt.global === 'boolean') {
648 self.global(key, opt.global)
651 if (opt.defaultDescription) {
652 options.defaultDescription[key] = opt.defaultDescription
655 if (opt.skipValidation) {
656 self.skipValidation(key)
659 const desc = opt.describe || opt.description || opt.desc
661 self.describe(key, desc)
664 if (opt.requiresArg) {
665 self.requiresArg(key)
671 self.getOptions = () => options
673 self.positional = function (key, opts) {
674 argsert('<string> <object>', [key, opts], arguments.length)
675 if (context.resets === 0) {
676 throw new YError(".positional() can only be called in a command's builder function")
679 // .positional() only supports a subset of the configuration
680 // options availble to .option().
681 const supportedOpts = ['default', 'implies', 'normalize',
682 'choices', 'conflicts', 'coerce', 'type', 'describe',
683 'desc', 'description', 'alias']
684 opts = objFilter(opts, (k, v) => {
685 let accept = supportedOpts.indexOf(k) !== -1
686 // type can be one of string|number|boolean.
687 if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1) accept = false
691 // copy over any settings that can be inferred from the command string.
692 const fullCommand = context.fullCommands[context.fullCommands.length - 1]
693 const parseOptions = fullCommand ? command.cmdToParseOptions(fullCommand) : {
699 Object.keys(parseOptions).forEach((pk) => {
700 if (Array.isArray(parseOptions[pk])) {
701 if (parseOptions[pk].indexOf(key) !== -1) opts[pk] = true
703 if (parseOptions[pk][key] && !(pk in opts)) opts[pk] = parseOptions[pk][key]
706 self.group(key, usage.getPositionalGroupName())
707 return self.option(key, opts)
710 self.group = function group (opts, groupName) {
711 argsert('<string|array> <string>', [opts, groupName], arguments.length)
712 const existing = preservedGroups[groupName] || groups[groupName]
713 if (preservedGroups[groupName]) {
714 // we now only need to track this group name in groups.
715 delete preservedGroups[groupName]
719 groups[groupName] = (existing || []).concat(opts).filter((key) => {
720 if (seen[key]) return false
721 return (seen[key] = true)
725 // combine explicit and preserved groups. explicit groups should be first
726 self.getGroups = () => Object.assign({}, groups, preservedGroups)
728 // as long as options.envPrefix is not undefined,
729 // parser will apply env vars matching prefix to argv
730 self.env = function (prefix) {
731 argsert('[string|boolean]', [prefix], arguments.length)
732 if (prefix === false) options.envPrefix = undefined
733 else options.envPrefix = prefix || ''
737 self.wrap = function (cols) {
738 argsert('<number|null|undefined>', [cols], arguments.length)
744 self.strict = function (enabled) {
745 argsert('[boolean]', [enabled], arguments.length)
746 strict = enabled !== false
749 self.getStrict = () => strict
751 self.showHelp = function (level) {
752 argsert('[string|function]', [level], arguments.length)
753 if (!self.parsed) self._parseArgs(processArgs) // run parser, if it has not already been executed.
754 if (command.hasDefaultCommand()) {
755 context.resets++ // override the restriction on top-level positoinals.
756 command.runDefaultBuilderOn(self, true)
758 usage.showHelp(level)
762 let versionOpt = null
763 self.version = function version (opt, msg, ver) {
764 const defaultVersionOpt = 'version'
765 argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length)
767 // nuke the key previously configured
768 // to return version #.
770 deleteFromParserHintObject(versionOpt)
771 usage.version(undefined)
775 if (arguments.length === 0) {
777 opt = defaultVersionOpt
778 } else if (arguments.length === 1) {
779 if (opt === false) { // disable default 'version' key.
783 opt = defaultVersionOpt
784 } else if (arguments.length === 2) {
789 versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt
790 msg = msg || usage.deferY18nLookup('Show version number')
792 usage.version(ver || undefined)
793 self.boolean(versionOpt)
794 self.describe(versionOpt, msg)
798 function guessVersion () {
801 return obj.version || 'unknown'
805 self.addHelpOpt = self.help = function addHelpOpt (opt, msg) {
806 const defaultHelpOpt = 'help'
807 argsert('[string|boolean] [string]', [opt, msg], arguments.length)
809 // nuke the key previously configured
812 deleteFromParserHintObject(helpOpt)
816 if (arguments.length === 1) {
817 if (opt === false) return self
820 // use arguments, fallback to defaults for opt and msg
821 helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt
822 self.boolean(helpOpt)
823 self.describe(helpOpt, msg || usage.deferY18nLookup('Show help'))
827 self.showHelpOnFail = function showHelpOnFail (enabled, message) {
828 argsert('[boolean|string] [string]', [enabled, message], arguments.length)
829 usage.showHelpOnFail(enabled, message)
833 var exitProcess = true
834 self.exitProcess = function (enabled) {
835 argsert('[boolean]', [enabled], arguments.length)
836 if (typeof enabled !== 'boolean') {
839 exitProcess = enabled
842 self.getExitProcess = () => exitProcess
844 var completionCommand = null
845 self.completion = function (cmd, desc, fn) {
846 argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length)
848 // a function to execute when generating
849 // completions can be provided as the second
850 // or third argument to completion.
851 if (typeof desc === 'function') {
856 // register the completion command.
857 completionCommand = cmd || 'completion'
858 if (!desc && desc !== false) {
859 desc = 'generate bash completion script'
861 self.command(completionCommand, desc)
863 // a function can be provided
864 if (fn) completion.registerFunction(fn)
869 self.showCompletionScript = function ($0) {
870 argsert('[string]', [$0], arguments.length)
872 _logger.log(completion.generateCompletionScript($0, completionCommand))
876 self.getCompletion = function (args, done) {
877 argsert('<array> <function>', [args, done], arguments.length)
878 completion.getCompletion(args, done)
881 self.locale = function (locale) {
882 argsert('[string]', [locale], arguments.length)
883 if (arguments.length === 0) {
885 return y18n.getLocale()
888 y18n.setLocale(locale)
892 self.updateStrings = self.updateLocale = function (obj) {
893 argsert('<object>', [obj], arguments.length)
895 y18n.updateLocale(obj)
899 let detectLocale = true
900 self.detectLocale = function (detect) {
901 argsert('<boolean>', [detect], arguments.length)
902 detectLocale = detect
905 self.getDetectLocale = () => detectLocale
907 var hasOutput = false
909 // maybe exit, always capture
910 // context about why we wanted to exit.
911 self.exit = (code, err) => {
914 if (exitProcess) process.exit(code)
917 // we use a custom logger that buffers output,
918 // so that we can print to non-CLIs, e.g., chat-bots.
922 for (let i = 0; i < arguments.length; i++) args.push(arguments[i])
923 if (!self._hasParseCallback()) console.log.apply(console, args)
925 if (output.length) output += '\n'
926 output += args.join(' ')
930 for (let i = 0; i < arguments.length; i++) args.push(arguments[i])
931 if (!self._hasParseCallback()) console.error.apply(console, args)
933 if (output.length) output += '\n'
934 output += args.join(' ')
937 self._getLoggerInstance = () => _logger
938 // has yargs output an error our help
939 // message in the current execution context.
940 self._hasOutput = () => hasOutput
942 self._setHasOutput = () => {
946 let recommendCommands
947 self.recommendCommands = function (recommend) {
948 argsert('[boolean]', [recommend], arguments.length)
949 recommendCommands = typeof recommend === 'boolean' ? recommend : true
953 self.getUsageInstance = () => usage
955 self.getValidationInstance = () => validation
957 self.getCommandInstance = () => command
959 self.terminalWidth = () => {
961 return typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null
964 Object.defineProperty(self, 'argv', {
965 get: () => self._parseArgs(processArgs),
969 self._parseArgs = function parseArgs (args, shortCircuit, _skipValidation, commandIndex) {
970 let skipValidation = !!_skipValidation
971 args = args || processArgs
974 options.configuration = pkgUp()['yargs'] || {}
976 const parsed = Parser.detailed(args, options)
977 let argv = parsed.argv
978 if (parseContext) argv = Object.assign({}, argv, parseContext)
979 const aliases = parsed.aliases
985 guessLocale() // guess locale lazily, so that it can be turned off in chain.
987 // while building up the argv object, there
988 // are two passes through the parser. If completion
989 // is being performed short-circuit on the first pass.
994 // if there's a handler associated with a
995 // command defer processing to it.
997 // consider any multi-char helpOpt alias as a valid help command
998 // unless all helpOpt aliases are single-char
999 // note that parsed.aliases is a normalized bidirectional map :)
1000 const helpCmds = [helpOpt]
1001 .concat(aliases[helpOpt] || [])
1002 .filter(k => k.length > 1)
1003 // check if help should trigger and strip it from _.
1004 if (~helpCmds.indexOf(argv._[argv._.length - 1])) {
1006 argv[helpOpt] = true
1009 const handlerKeys = command.getCommands()
1010 const skipDefaultCommand = argv[helpOpt] && (handlerKeys.length > 1 || handlerKeys[0] !== '$0')
1012 if (argv._.length) {
1013 if (handlerKeys.length) {
1014 let firstUnknownCommand
1015 for (let i = (commandIndex || 0), cmd; argv._[i] !== undefined; i++) {
1016 cmd = String(argv._[i])
1017 if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
1018 setPlaceholderKeys(argv)
1019 // commands are executed using a recursive algorithm that executes
1020 // the deepest command first; we keep track of the position in the
1021 // argv._ array that is currently being executed.
1022 return command.runCommand(cmd, self, parsed, i + 1)
1023 } else if (!firstUnknownCommand && cmd !== completionCommand) {
1024 firstUnknownCommand = cmd
1029 // run the default command, if defined
1030 if (command.hasDefaultCommand() && !skipDefaultCommand) {
1031 setPlaceholderKeys(argv)
1032 return command.runCommand(null, self, parsed)
1035 // recommend a command if recommendCommands() has
1036 // been enabled, and no commands were found to execute
1037 if (recommendCommands && firstUnknownCommand && !argv[helpOpt]) {
1038 validation.recommendCommands(firstUnknownCommand, handlerKeys)
1042 // generate a completion script for adding to ~/.bashrc.
1043 if (completionCommand && ~argv._.indexOf(completionCommand) && !argv[completion.completionKey]) {
1044 if (exitProcess) setBlocking(true)
1045 self.showCompletionScript()
1048 } else if (command.hasDefaultCommand() && !skipDefaultCommand) {
1049 setPlaceholderKeys(argv)
1050 return command.runCommand(null, self, parsed)
1053 // we must run completions first, a user might
1054 // want to complete the --help or --version option.
1055 if (completion.completionKey in argv) {
1056 if (exitProcess) setBlocking(true)
1058 // we allow for asynchronous completions,
1059 // e.g., loading in a list of commands from an API.
1060 const completionArgs = args.slice(args.indexOf(`--${completion.completionKey}`) + 1)
1061 completion.getCompletion(completionArgs, (completions) => {
1062 ;(completions || []).forEach((completion) => {
1063 _logger.log(completion)
1068 return setPlaceholderKeys(argv)
1071 // Handle 'help' and 'version' options
1072 // if we haven't already output help!
1074 Object.keys(argv).forEach((key) => {
1075 if (key === helpOpt && argv[key]) {
1076 if (exitProcess) setBlocking(true)
1078 skipValidation = true
1079 self.showHelp('log')
1081 } else if (key === versionOpt && argv[key]) {
1082 if (exitProcess) setBlocking(true)
1084 skipValidation = true
1091 // Check if any of the options to skip validation were provided
1092 if (!skipValidation && options.skipValidation.length > 0) {
1093 skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true)
1096 // If the help or version options where used and exitProcess is false,
1097 // or if explicitly skipped, we won't run validations.
1098 if (!skipValidation) {
1099 if (parsed.error) throw new YError(parsed.error.message)
1101 // if we're executed via bash completion, don't
1102 // bother with validation.
1103 if (!argv[completion.completionKey]) {
1104 self._runValidation(argv, aliases, {}, parsed.error)
1108 if (err instanceof YError) usage.fail(err.message, err)
1112 return setPlaceholderKeys(argv)
1115 self._runValidation = function runValidation (argv, aliases, positionalMap, parseErrors) {
1116 if (parseErrors) throw new YError(parseErrors.message)
1117 validation.nonOptionCount(argv)
1118 validation.requiredArguments(argv)
1119 if (strict) validation.unknownArguments(argv, aliases, positionalMap)
1120 validation.customChecks(argv, aliases)
1121 validation.limitedChoices(argv)
1122 validation.implications(argv)
1123 validation.conflicting(argv)
1126 function guessLocale () {
1127 if (!detectLocale) return
1130 const osLocale = require('os-locale')
1131 self.locale(osLocale.sync({ spawn: false }))
1133 // if we explode looking up locale just noop
1134 // we'll keep using the default language 'en'.
1138 function setPlaceholderKeys (argv) {
1139 Object.keys(options.key).forEach((key) => {
1140 // don't set placeholder keys for dot
1141 // notation options 'foo.bar'.
1142 if (~key.indexOf('.')) return
1143 if (typeof argv[key] === 'undefined') argv[key] = undefined
1148 // an app should almost always have --version and --help,
1149 // if you *really* want to disable this use .help(false)/.version(false).
1156 // rebase an absolute path to a relative one with respect to a base directory
1157 // exported for tests
1158 exports.rebase = rebase
1159 function rebase (base, dir) {
1160 return path.relative(base, dir)