id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
2,800 | setParsed(parsed: DetailedArguments) {
this.aliases = parsed.aliases;
} | interface DetailedArguments extends ParserDetailedArguments {
argv: Arguments;
aliases: Dictionary<string[]>;
} |
2,801 | setParsed(parsed: DetailedArguments) {
this.aliases = parsed.aliases;
} | interface DetailedArguments {
/** An object representing the parsed value of `args` */
argv: Arguments;
/** Populated with an error object if an exception occurred during parsing. */
error: Error | null;
/** The inferred list of aliases built by combining lists in opts.alias. */
aliases: Dictionary<string[]>;
/** Any new aliases added via camel-case expansion. */
newAliases: Dictionary<boolean>;
/** Any new argument created by opts.default, no aliases included. */
defaulted: Dictionary<boolean>;
/** The configuration loaded from the yargs stanza in package.json. */
configuration: Configuration;
} |
2,802 | function completion(
yargs: YargsInstance,
usage: UsageInstance,
command: CommandInstance,
shim: PlatformShim
): CompletionInstance {
return new Completion(yargs, usage, command, shim);
} | class CommandInstance {
shim: PlatformShim;
requireCache: Set<string> = new Set();
handlers: Dictionary<CommandHandler> = {};
aliasMap: Dictionary<string> = {};
defaultCommand?: CommandHandler;
usage: UsageInstance;
globalMiddleware: GlobalMiddleware;
validation: ValidationInstance;
// Used to cache state from prior invocations of commands.
// This allows the parser to push and pop state when running
// a nested command:
frozens: FrozenCommandInstance[] = [];
constructor(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
this.shim = shim;
this.usage = usage;
this.globalMiddleware = globalMiddleware;
this.validation = validation;
}
addDirectory(
dir: string,
req: Function,
callerFile: string,
opts?: RequireDirectoryOptions
): void {
opts = opts || {};
// disable recursion to support nested directories of subcommands
if (typeof opts.recurse !== 'boolean') opts.recurse = false;
// exclude 'json', 'coffee' from require-directory defaults
if (!Array.isArray(opts.extensions)) opts.extensions = ['js'];
// allow consumer to define their own visitor function
const parentVisit =
typeof opts.visit === 'function' ? opts.visit : (o: any) => o;
// call addHandler via visitor function
opts.visit = (obj, joined, filename) => {
const visited = parentVisit(obj, joined, filename);
// allow consumer to skip modules with their own visitor
if (visited) {
// check for cyclic reference:
if (this.requireCache.has(joined)) return visited;
else this.requireCache.add(joined);
this.addHandler(visited);
}
return visited;
};
this.shim.requireDirectory({require: req, filename: callerFile}, dir, opts);
}
addHandler(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
commandMiddleware?: Middleware[],
deprecated?: boolean
): void {
let aliases: string[] = [];
const middlewares = commandMiddlewareFactory(commandMiddleware);
handler = handler || (() => {});
// If an array is provided that is all CommandHandlerDefinitions, add
// each handler individually:
if (Array.isArray(cmd)) {
if (isCommandAndAliases(cmd)) {
[cmd, ...aliases] = cmd;
} else {
for (const command of cmd) {
this.addHandler(command);
}
}
} else if (isCommandHandlerDefinition(cmd)) {
let command =
Array.isArray(cmd.command) || typeof cmd.command === 'string'
? cmd.command
: this.moduleName(cmd);
if (cmd.aliases)
command = ([] as string[]).concat(command).concat(cmd.aliases);
this.addHandler(
command,
this.extractDesc(cmd),
cmd.builder,
cmd.handler,
cmd.middlewares,
cmd.deprecated
);
return;
} else if (isCommandBuilderDefinition(builder)) {
// Allow a module to be provided as builder, rather than function:
this.addHandler(
[cmd].concat(aliases),
description,
builder.builder,
builder.handler,
builder.middlewares,
builder.deprecated
);
return;
}
// The 'cmd' provided was a string, we apply the command DSL:
// https://github.com/yargs/yargs/blob/main/docs/advanced.md#advanced-topics
if (typeof cmd === 'string') {
// parse positionals out of cmd string
const parsedCommand = parseCommand(cmd);
// remove positional args from aliases only
aliases = aliases.map(alias => parseCommand(alias).cmd);
// check for default and filter out '*'
let isDefault = false;
const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => {
if (DEFAULT_MARKER.test(c)) {
isDefault = true;
return false;
}
return true;
});
// standardize on $0 for default command.
if (parsedAliases.length === 0 && isDefault) parsedAliases.push('$0');
// shift cmd and aliases after filtering out '*'
if (isDefault) {
parsedCommand.cmd = parsedAliases[0];
aliases = parsedAliases.slice(1);
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
}
// populate aliasMap
aliases.forEach(alias => {
this.aliasMap[alias] = parsedCommand.cmd;
});
if (description !== false) {
this.usage.command(cmd, description, isDefault, aliases, deprecated);
}
this.handlers[parsedCommand.cmd] = {
original: cmd,
description,
handler,
builder: (builder as CommandBuilder) || {},
middlewares,
deprecated,
demanded: parsedCommand.demanded,
optional: parsedCommand.optional,
};
if (isDefault) this.defaultCommand = this.handlers[parsedCommand.cmd];
}
}
getCommandHandlers(): Dictionary<CommandHandler> {
return this.handlers;
}
getCommands(): string[] {
return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
}
hasDefaultCommand(): boolean {
return !!this.defaultCommand;
}
runCommand(
command: string | null,
yargs: YargsInstance,
parsed: DetailedArguments,
commandIndex: number,
helpOnly: boolean,
helpOrVersionSet: boolean
): Arguments | Promise<Arguments> {
const commandHandler =
this.handlers[command!] ||
this.handlers[this.aliasMap[command!]] ||
this.defaultCommand;
const currentContext = yargs.getInternalMethods().getContext();
const parentCommands = currentContext.commands.slice();
const isDefaultCommand = !command;
if (command) {
currentContext.commands.push(command);
currentContext.fullCommands.push(commandHandler.original);
}
const builderResult = this.applyBuilderUpdateUsageAndParse(
isDefaultCommand,
commandHandler,
yargs,
parsed.aliases,
parentCommands,
commandIndex,
helpOnly,
helpOrVersionSet
);
return isPromise(builderResult)
? builderResult.then(result =>
this.applyMiddlewareAndGetResult(
isDefaultCommand,
commandHandler,
result.innerArgv,
currentContext,
helpOnly,
result.aliases,
yargs
)
)
: this.applyMiddlewareAndGetResult(
isDefaultCommand,
commandHandler,
builderResult.innerArgv,
currentContext,
helpOnly,
builderResult.aliases,
yargs
);
}
private applyBuilderUpdateUsageAndParse(
isDefaultCommand: boolean,
commandHandler: CommandHandler,
yargs: YargsInstance,
aliases: Dictionary<string[]>,
parentCommands: string[],
commandIndex: number,
helpOnly: boolean,
helpOrVersionSet: boolean
):
| {aliases: Dictionary<string[]>; innerArgv: Arguments}
| Promise<{aliases: Dictionary<string[]>; innerArgv: Arguments}> {
const builder = commandHandler.builder;
let innerYargs: YargsInstance = yargs;
if (isCommandBuilderCallback(builder)) {
// A function can be provided, which builds
// up a yargs chain and possibly returns it.
const builderOutput = builder(
yargs.getInternalMethods().reset(aliases),
helpOrVersionSet
);
// Support the use-case of async builders:
if (isPromise(builderOutput)) {
return builderOutput.then(output => {
innerYargs = isYargsInstance(output) ? output : yargs;
return this.parseAndUpdateUsage(
isDefaultCommand,
commandHandler,
innerYargs,
parentCommands,
commandIndex,
helpOnly
);
});
}
} else if (isCommandBuilderOptionDefinitions(builder)) {
// as a short hand, an object can instead be provided, specifying
// the options that a command takes.
innerYargs = yargs.getInternalMethods().reset(aliases);
Object.keys(commandHandler.builder).forEach(key => {
innerYargs.option(key, builder[key]);
});
}
return this.parseAndUpdateUsage(
isDefaultCommand,
commandHandler,
innerYargs,
parentCommands,
commandIndex,
helpOnly
);
}
private parseAndUpdateUsage(
isDefaultCommand: boolean,
commandHandler: CommandHandler,
innerYargs: YargsInstance,
parentCommands: string[],
commandIndex: number,
helpOnly: boolean
):
| {aliases: Dictionary<string[]>; innerArgv: Arguments}
| Promise<{aliases: Dictionary<string[]>; innerArgv: Arguments}> {
// A null command indicates we are running the default command,
// if this is the case, we should show the root usage instructions
// rather than the usage instructions for the nested default command:
if (isDefaultCommand)
innerYargs.getInternalMethods().getUsageInstance().unfreeze(true);
if (this.shouldUpdateUsage(innerYargs)) {
innerYargs
.getInternalMethods()
.getUsageInstance()
.usage(
this.usageFromParentCommandsCommandHandler(
parentCommands,
commandHandler
),
commandHandler.description
);
}
const innerArgv = innerYargs
.getInternalMethods()
.runYargsParserAndExecuteCommands(
null,
undefined,
true,
commandIndex,
helpOnly
);
return isPromise(innerArgv)
? innerArgv.then(argv => ({
aliases: (innerYargs.parsed as DetailedArguments).aliases,
innerArgv: argv,
}))
: {
aliases: (innerYargs.parsed as DetailedArguments).aliases,
innerArgv: innerArgv,
};
}
private shouldUpdateUsage(yargs: YargsInstance) {
return (
!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() &&
yargs.getInternalMethods().getUsageInstance().getUsage().length === 0
);
}
private usageFromParentCommandsCommandHandler(
parentCommands: string[],
commandHandler: CommandHandler
) {
const c = DEFAULT_MARKER.test(commandHandler.original)
? commandHandler.original.replace(DEFAULT_MARKER, '').trim()
: commandHandler.original;
const pc = parentCommands.filter(c => {
return !DEFAULT_MARKER.test(c);
});
pc.push(c);
return `$0 ${pc.join(' ')}`;
}
private handleValidationAndGetResult(
isDefaultCommand: boolean,
commandHandler: CommandHandler,
innerArgv: Arguments | Promise<Arguments>,
currentContext: Context,
aliases: Dictionary<string[]>,
yargs: YargsInstance,
middlewares: Middleware[],
positionalMap: Dictionary<string[]>
) {
// we apply validation post-hoc, so that custom
// checks get passed populated positional arguments.
if (!yargs.getInternalMethods().getHasOutput()) {
const validation = yargs
.getInternalMethods()
.runValidation(
aliases,
positionalMap,
(yargs.parsed as DetailedArguments).error,
isDefaultCommand
);
innerArgv = maybeAsyncResult<Arguments>(innerArgv, result => {
validation(result);
return result;
});
}
if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) {
yargs.getInternalMethods().setHasOutput();
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
const populateDoubleDash =
!!yargs.getOptions().configuration['populate--'];
yargs
.getInternalMethods()
.postProcess(innerArgv, populateDoubleDash, false, false);
innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
innerArgv = maybeAsyncResult<Arguments>(innerArgv, result => {
const handlerResult = commandHandler.handler(result as Arguments);
return isPromise(handlerResult)
? handlerResult.then(() => result)
: result;
});
if (!isDefaultCommand) {
yargs.getInternalMethods().getUsageInstance().cacheHelpMessage();
}
if (
isPromise(innerArgv) &&
!yargs.getInternalMethods().hasParseCallback()
) {
innerArgv.catch(error => {
try {
yargs.getInternalMethods().getUsageInstance().fail(null, error);
} catch (_err) {
// If .fail(false) is not set, and no parse cb() has been
// registered, run usage's default fail method.
}
});
}
}
if (!isDefaultCommand) {
currentContext.commands.pop();
currentContext.fullCommands.pop();
}
return innerArgv;
}
private applyMiddlewareAndGetResult(
isDefaultCommand: boolean,
commandHandler: CommandHandler,
innerArgv: Arguments,
currentContext: Context,
helpOnly: boolean,
aliases: Dictionary<string[]>,
yargs: YargsInstance
): Arguments | Promise<Arguments> {
let positionalMap: Dictionary<string[]> = {};
// If showHelp() or getHelp() is being run, we should not
// execute middleware or handlers (these may perform expensive operations
// like creating a DB connection).
if (helpOnly) return innerArgv;
if (!yargs.getInternalMethods().getHasOutput()) {
positionalMap = this.populatePositionals(
commandHandler,
innerArgv as Arguments,
currentContext,
yargs
);
}
const middlewares = this.globalMiddleware
.getMiddleware()
.slice(0)
.concat(commandHandler.middlewares);
const maybePromiseArgv = applyMiddleware(
innerArgv,
yargs,
middlewares,
true
);
return isPromise(maybePromiseArgv)
? maybePromiseArgv.then(resolvedInnerArgv =>
this.handleValidationAndGetResult(
isDefaultCommand,
commandHandler,
resolvedInnerArgv,
currentContext,
aliases,
yargs,
middlewares,
positionalMap
)
)
: this.handleValidationAndGetResult(
isDefaultCommand,
commandHandler,
maybePromiseArgv,
currentContext,
aliases,
yargs,
middlewares,
positionalMap
);
}
// transcribe all positional arguments "command <foo> <bar> [apple]"
// onto argv.
private populatePositionals(
commandHandler: CommandHandler,
argv: Arguments,
context: Context,
yargs: YargsInstance
) {
argv._ = argv._.slice(context.commands.length); // nuke the current commands
const demanded = commandHandler.demanded.slice(0);
const optional = commandHandler.optional.slice(0);
const positionalMap: Dictionary<string[]> = {};
this.validation.positionalCount(demanded.length, argv._.length);
while (demanded.length) {
const demand = demanded.shift()!;
this.populatePositional(demand, argv, positionalMap);
}
while (optional.length) {
const maybe = optional.shift()!;
this.populatePositional(maybe, argv, positionalMap);
}
argv._ = context.commands.concat(argv._.map(a => '' + a));
this.postProcessPositionals(
argv,
positionalMap,
this.cmdToParseOptions(commandHandler.original),
yargs
);
return positionalMap;
}
private populatePositional(
positional: Positional,
argv: Arguments,
positionalMap: Dictionary<string[]>
) {
const cmd = positional.cmd[0];
if (positional.variadic) {
positionalMap[cmd] = argv._.splice(0).map(String);
} else {
if (argv._.length) positionalMap[cmd] = [String(argv._.shift())];
}
}
// Based on parsing variadic markers '...', demand syntax '<foo>', etc.,
// populate parser hints:
public cmdToParseOptions(cmdString: string): Positionals {
const parseOptions: Positionals = {
array: [],
default: {},
alias: {},
demand: {},
};
const parsed = parseCommand(cmdString);
parsed.demanded.forEach(d => {
const [cmd, ...aliases] = d.cmd;
if (d.variadic) {
parseOptions.array.push(cmd);
parseOptions.default[cmd] = [];
}
parseOptions.alias[cmd] = aliases;
parseOptions.demand[cmd] = true;
});
parsed.optional.forEach(o => {
const [cmd, ...aliases] = o.cmd;
if (o.variadic) {
parseOptions.array.push(cmd);
parseOptions.default[cmd] = [];
}
parseOptions.alias[cmd] = aliases;
});
return parseOptions;
}
// we run yargs-parser against the positional arguments
// applying the same parsing logic used for flags.
private postProcessPositionals(
argv: Arguments,
positionalMap: Dictionary<string[]>,
parseOptions: Positionals,
yargs: YargsInstance
) {
// combine the parsing hints we've inferred from the command
// string with explicitly configured parsing hints.
const options = Object.assign({}, yargs.getOptions());
options.default = Object.assign(parseOptions.default, options.default);
for (const key of Object.keys(parseOptions.alias)) {
options.alias[key] = (options.alias[key] || []).concat(
parseOptions.alias[key]
);
}
options.array = options.array.concat(parseOptions.array);
options.config = {}; // don't load config when processing positionals.
const unparsed: string[] = [];
Object.keys(positionalMap).forEach(key => {
positionalMap[key].map(value => {
if (options.configuration['unknown-options-as-args'])
options.key[key] = true;
unparsed.push(`--${key}`);
unparsed.push(value);
});
});
// short-circuit parse.
if (!unparsed.length) return;
const config: Configuration = Object.assign({}, options.configuration, {
'populate--': false,
});
const parsed = this.shim.Parser.detailed(
unparsed,
Object.assign({}, options, {
configuration: config,
})
);
if (parsed.error) {
yargs
.getInternalMethods()
.getUsageInstance()
.fail(parsed.error.message, parsed.error);
} else {
// only copy over positional keys (don't overwrite
// flag arguments that were already parsed).
const positionalKeys = Object.keys(positionalMap);
Object.keys(positionalMap).forEach(key => {
positionalKeys.push(...parsed.aliases[key]);
});
Object.keys(parsed.argv).forEach(key => {
if (positionalKeys.includes(key)) {
// any new aliases need to be placed in positionalMap, which
// is used for validation.
if (!positionalMap[key]) positionalMap[key] = parsed.argv[key];
// Addresses: https://github.com/yargs/yargs/issues/1637
// If both positionals/options provided,
// and no default or config values were set for that key,
// and if at least one is an array: don't overwrite, combine.
if (
!this.isInConfigs(yargs, key) &&
!this.isDefaulted(yargs, key) &&
Object.prototype.hasOwnProperty.call(argv, key) &&
Object.prototype.hasOwnProperty.call(parsed.argv, key) &&
(Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))
) {
argv[key] = ([] as string[]).concat(argv[key], parsed.argv[key]);
} else {
argv[key] = parsed.argv[key];
}
}
});
}
}
// Check defaults for key (and camel case version of key)
isDefaulted(yargs: YargsInstance, key: string): boolean {
const {default: defaults} = yargs.getOptions();
return (
Object.prototype.hasOwnProperty.call(defaults, key) ||
Object.prototype.hasOwnProperty.call(
defaults,
this.shim.Parser.camelCase(key)
)
);
}
// Check each config for key (and camel case version of key)
isInConfigs(yargs: YargsInstance, key: string): boolean {
const {configObjects} = yargs.getOptions();
return (
configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) ||
configObjects.some(c =>
Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key))
)
);
}
runDefaultBuilderOn(yargs: YargsInstance): unknown | Promise<unknown> {
if (!this.defaultCommand) return;
if (this.shouldUpdateUsage(yargs)) {
// build the root-level command string from the default string.
const commandString = DEFAULT_MARKER.test(this.defaultCommand.original)
? this.defaultCommand.original
: this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
yargs
.getInternalMethods()
.getUsageInstance()
.usage(commandString, this.defaultCommand.description);
}
const builder = this.defaultCommand.builder;
if (isCommandBuilderCallback(builder)) {
return builder(yargs, true);
} else if (!isCommandBuilderDefinition(builder)) {
Object.keys(builder).forEach(key => {
yargs.option(key, builder[key]);
});
}
return undefined;
}
// lookup module object from require()d command and derive name
// if module was not require()d and no name given, throw error
private moduleName(obj: CommandHandlerDefinition) {
const mod = whichModule(obj);
if (!mod)
throw new Error(
`No command name given for module: ${this.shim.inspect(obj)}`
);
return this.commandFromFilename(mod.filename);
}
private commandFromFilename(filename: string) {
return this.shim.path.basename(filename, this.shim.path.extname(filename));
}
private extractDesc({describe, description, desc}: CommandHandlerDefinition) {
for (const test of [describe, description, desc]) {
if (typeof test === 'string' || test === false) return test;
assertNotStrictEqual(test, true as const, this.shim);
}
return false;
}
// Push/pop the current command configuration:
freeze() {
this.frozens.push({
handlers: this.handlers,
aliasMap: this.aliasMap,
defaultCommand: this.defaultCommand,
});
}
unfreeze() {
const frozen = this.frozens.pop();
assertNotStrictEqual(frozen, undefined, this.shim);
({
handlers: this.handlers,
aliasMap: this.aliasMap,
defaultCommand: this.defaultCommand,
} = frozen);
}
// Revert to initial state:
reset(): CommandInstance {
this.handlers = {};
this.aliasMap = {};
this.defaultCommand = undefined;
this.requireCache = new Set();
return this;
}
} |
2,803 | function completion(
yargs: YargsInstance,
usage: UsageInstance,
command: CommandInstance,
shim: PlatformShim
): CompletionInstance {
return new Completion(yargs, usage, command, shim);
} | interface UsageInstance {
cacheHelpMessage(): void;
clearCachedHelpMessage(): void;
hasCachedHelpMessage(): boolean;
command(
cmd: string,
description: string | undefined,
isDefault: boolean,
aliases: string[],
deprecated?: boolean
): void;
deferY18nLookup(str: string): string;
describe(keys: string | string[] | Dictionary<string>, desc?: string): void;
epilog(msg: string): void;
example(cmd: string, description?: string): void;
fail(msg?: string | null, err?: YError | string): void;
failFn(f: FailureFunction | boolean): void;
freeze(): void;
functionDescription(fn: {name?: string}): string;
getCommands(): [string, string, boolean, string[], boolean][];
getDescriptions(): Dictionary<string | undefined>;
getPositionalGroupName(): string;
getUsage(): [string, string][];
getUsageDisabled(): boolean;
getWrap(): number | nil;
help(): string;
reset(localLookup: Dictionary<boolean>): UsageInstance;
showHelp(level?: 'error' | 'log' | ((message: string) => void)): void;
showHelpOnFail(enabled?: boolean | string, message?: string): UsageInstance;
showVersion(level?: 'error' | 'log' | ((message: string) => void)): void;
stringifiedValues(values?: any[], separator?: string): string;
unfreeze(defaultCommand?: boolean): void;
usage(msg: string | null, description?: string | false): UsageInstance;
version(ver: any): void;
wrap(cols: number | nil): void;
} |
2,804 | function completion(
yargs: YargsInstance,
usage: UsageInstance,
command: CommandInstance,
shim: PlatformShim
): CompletionInstance {
return new Completion(yargs, usage, command, shim);
} | interface PlatformShim {
cwd: Function;
format: Function;
normalize: Function;
require: Function;
resolve: Function;
env: Function;
} |
2,805 | function completion(
yargs: YargsInstance,
usage: UsageInstance,
command: CommandInstance,
shim: PlatformShim
): CompletionInstance {
return new Completion(yargs, usage, command, shim);
} | interface PlatformShim {
assert: {
notStrictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
strictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
};
findUp: (
startDir: string,
fn: (dir: string[], names: string[]) => string | undefined
) => string;
getCallerFile: () => string;
getEnv: (key: string) => string | undefined;
getProcessArgvBin: () => string;
inspect: (obj: object) => string;
mainFilename: string;
requireDirectory: Function;
stringWidth: (str: string) => number;
cliui: Function;
Parser: Parser;
path: {
basename: (p1: string, p2?: string) => string;
extname: (path: string) => string;
dirname: (path: string) => string;
relative: (p1: string, p2: string) => string;
resolve: (p1: string, p2: string) => string;
};
process: {
argv: () => string[];
cwd: () => string;
emitWarning: (warning: string | Error, type?: string) => void;
execPath: () => string;
exit: (code: number) => void;
nextTick: (cb: Function) => void;
stdColumns: number | null;
};
readFileSync: (path: string, encoding: string) => string;
require: RequireType;
y18n: Y18N;
} |
2,806 | function completion(
yargs: YargsInstance,
usage: UsageInstance,
command: CommandInstance,
shim: PlatformShim
): CompletionInstance {
return new Completion(yargs, usage, command, shim);
} | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,807 | (onCompleted?: CompletionCallback) => any | type CompletionCallback = (
err: Error | null,
completions: string[] | undefined
) => void; |
2,808 | function isSyncCompletionFunction(
completionFunction: CompletionFunction
): completionFunction is SyncCompletionFunction {
return completionFunction.length < 3;
} | type CompletionFunction =
| SyncCompletionFunction
| AsyncCompletionFunction
| FallbackCompletionFunction; |
2,809 | function isFallbackCompletionFunction(
completionFunction: CompletionFunction
): completionFunction is FallbackCompletionFunction {
return completionFunction.length > 3;
} | type CompletionFunction =
| SyncCompletionFunction
| AsyncCompletionFunction
| FallbackCompletionFunction; |
2,810 | constructor(yargs: YargsInstance) {
this.yargs = yargs;
} | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,811 | addCoerceMiddleware(
callback: MiddlewareCallback,
option: string
): YargsInstance {
const aliases = this.yargs.getAliases();
this.globalMiddleware = this.globalMiddleware.filter(m => {
const toCheck = [...(aliases[option] || []), option];
if (!m.option) return true;
else return !toCheck.includes(m.option);
});
(callback as Middleware).option = option;
return this.addMiddleware(callback, true, true, true);
} | interface MiddlewareCallback {
(argv: Arguments, yargs: YargsInstance):
| Partial<Arguments>
| Promise<Partial<Arguments>>;
} |
2,812 | (argv: Arguments, yargs: YargsInstance):
| Partial<Arguments>
| Promise<Partial<Arguments>> | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,813 | (argv: Arguments, yargs: YargsInstance):
| Partial<Arguments>
| Promise<Partial<Arguments>> | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,814 | (argv: Arguments, yargs: YargsInstance):
| Partial<Arguments>
| Promise<Partial<Arguments>> | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,815 | (argv: Arguments, yargs: YargsInstance):
| Partial<Arguments>
| Promise<Partial<Arguments>> | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,816 | function usage(yargs: YargsInstance, shim: PlatformShim) {
const __ = shim.y18n.__;
const self = {} as UsageInstance;
// methods for ouputting/building failure message.
const fails: (FailureFunction | boolean)[] = [];
self.failFn = function failFn(f) {
fails.push(f);
};
let failMessage: string | nil = null;
let globalFailMessage: string | nil = null;
let showHelpOnFail = true;
self.showHelpOnFail = function showHelpOnFailFn(
arg1: boolean | string = true,
arg2?: string
) {
const [enabled, message] =
typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2];
// If global context, set globalFailMessage
// Addresses: https://github.com/yargs/yargs/issues/2085
if (yargs.getInternalMethods().isGlobalContext()) {
globalFailMessage = message;
}
failMessage = message;
showHelpOnFail = enabled;
return self;
};
let failureOutput = false;
self.fail = function fail(msg, err) {
const logger = yargs.getInternalMethods().getLoggerInstance();
if (fails.length) {
for (let i = fails.length - 1; i >= 0; --i) {
const fail = fails[i];
if (isBoolean(fail)) {
if (err) throw err;
else if (msg) throw Error(msg);
} else {
fail(msg, err, self);
}
}
} else {
if (yargs.getExitProcess()) setBlocking(true);
// don't output failure message more than once
if (!failureOutput) {
failureOutput = true;
if (showHelpOnFail) {
yargs.showHelp('error');
logger.error();
}
if (msg || err) logger.error(msg || err);
const globalOrCommandFailMessage = failMessage || globalFailMessage;
if (globalOrCommandFailMessage) {
if (msg || err) logger.error('');
logger.error(globalOrCommandFailMessage);
}
}
err = err || new YError(msg);
if (yargs.getExitProcess()) {
return yargs.exit(1);
} else if (yargs.getInternalMethods().hasParseCallback()) {
return yargs.exit(1, err);
} else {
throw err;
}
}
};
// methods for ouputting/building help (usage) message.
let usages: [string, string][] = [];
let usageDisabled = false;
self.usage = (msg, description) => {
if (msg === null) {
usageDisabled = true;
usages = [];
return self;
}
usageDisabled = false;
usages.push([msg, description || '']);
return self;
};
self.getUsage = () => {
return usages;
};
self.getUsageDisabled = () => {
return usageDisabled;
};
self.getPositionalGroupName = () => {
return __('Positionals:');
};
let examples: [string, string][] = [];
self.example = (cmd, description) => {
examples.push([cmd, description || '']);
};
let commands: [string, string, boolean, string[], boolean][] = [];
self.command = function command(
cmd,
description,
isDefault,
aliases,
deprecated = false
) {
// the last default wins, so cancel out any previously set default
if (isDefault) {
commands = commands.map(cmdArray => {
cmdArray[2] = false;
return cmdArray;
});
}
commands.push([cmd, description || '', isDefault, aliases, deprecated]);
};
self.getCommands = () => commands;
let descriptions: Dictionary<string | undefined> = {};
self.describe = function describe(
keyOrKeys: string | string[] | Dictionary<string>,
desc?: string
) {
if (Array.isArray(keyOrKeys)) {
keyOrKeys.forEach(k => {
self.describe(k, desc);
});
} else if (typeof keyOrKeys === 'object') {
Object.keys(keyOrKeys).forEach(k => {
self.describe(k, keyOrKeys[k]);
});
} else {
descriptions[keyOrKeys] = desc;
}
};
self.getDescriptions = () => descriptions;
let epilogs: string[] = [];
self.epilog = msg => {
epilogs.push(msg);
};
let wrapSet = false;
let wrap: number | nil;
self.wrap = cols => {
wrapSet = true;
wrap = cols;
};
self.getWrap = () => {
if (shim.getEnv('YARGS_DISABLE_WRAP')) {
return null;
}
if (!wrapSet) {
wrap = windowWidth();
wrapSet = true;
}
return wrap;
};
const deferY18nLookupPrefix = '__yargsString__:';
self.deferY18nLookup = str => deferY18nLookupPrefix + str;
self.help = function help() {
if (cachedHelpMessage) return cachedHelpMessage;
normalizeAliases();
// handle old demanded API
const base$0 = yargs.customScriptName
? yargs.$0
: shim.path.basename(yargs.$0);
const demandedOptions = yargs.getDemandedOptions();
const demandedCommands = yargs.getDemandedCommands();
const deprecatedOptions = yargs.getDeprecatedOptions();
const groups = yargs.getGroups();
const options = yargs.getOptions();
let keys: string[] = [];
keys = keys.concat(Object.keys(descriptions));
keys = keys.concat(Object.keys(demandedOptions));
keys = keys.concat(Object.keys(demandedCommands));
keys = keys.concat(Object.keys(options.default));
keys = keys.filter(filterHiddenOptions);
keys = Object.keys(
keys.reduce((acc, key) => {
if (key !== '_') acc[key] = true;
return acc;
}, {} as Dictionary<boolean>)
);
const theWrap = self.getWrap();
const ui = shim.cliui({
width: theWrap,
wrap: !!theWrap,
});
// the usage string.
if (!usageDisabled) {
if (usages.length) {
// user-defined usage.
usages.forEach(usage => {
ui.div({text: `${usage[0].replace(/\$0/g, base$0)}`});
if (usage[1]) {
ui.div({text: `${usage[1]}`, padding: [1, 0, 0, 0]});
}
});
ui.div();
} else if (commands.length) {
let u = null;
// demonstrate how commands are used.
if (demandedCommands._) {
u = `${base$0} <${__('command')}>\n`;
} else {
u = `${base$0} [${__('command')}]\n`;
}
ui.div(`${u}`);
}
}
// your application's commands, i.e., non-option
// arguments populated in '_'.
//
// If there's only a single command, and it's the default command
// (represented by commands[0][2]) don't show command stanza:
//
// TODO(@bcoe): why isnt commands[0][2] an object with a named property?
if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) {
ui.div(__('Commands:'));
const context = yargs.getInternalMethods().getContext();
const parentCommands = context.commands.length
? `${context.commands.join(' ')} `
: '';
if (
yargs.getInternalMethods().getParserConfiguration()['sort-commands'] ===
true
) {
commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
}
const prefix = base$0 ? `${base$0} ` : '';
commands.forEach(command => {
const commandString = `${prefix}${parentCommands}${command[0].replace(
/^\$0 ?/,
''
)}`; // drop $0 from default commands.
ui.span(
{
text: commandString,
padding: [0, 2, 0, 2],
width:
maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4,
},
{text: command[1]}
);
const hints = [];
if (command[2]) hints.push(`[${__('default')}]`);
if (command[3] && command[3].length) {
hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`);
}
if (command[4]) {
if (typeof command[4] === 'string') {
hints.push(`[${__('deprecated: %s', command[4])}]`);
} else {
hints.push(`[${__('deprecated')}]`);
}
}
if (hints.length) {
ui.div({
text: hints.join(' '),
padding: [0, 0, 0, 2],
align: 'right',
});
} else {
ui.div();
}
});
ui.div();
}
// perform some cleanup on the keys array, making it
// only include top-level keys not their aliases.
const aliasKeys = (Object.keys(options.alias) || []).concat(
Object.keys((yargs.parsed as DetailedArguments).newAliases) || []
);
keys = keys.filter(
key =>
!(yargs.parsed as DetailedArguments).newAliases[key] &&
aliasKeys.every(
alias => (options.alias[alias] || []).indexOf(key) === -1
)
);
// populate 'Options:' group with any keys that have not
// explicitly had a group set.
const defaultGroup = __('Options:');
if (!groups[defaultGroup]) groups[defaultGroup] = [];
addUngroupedKeys(keys, options.alias, groups, defaultGroup);
const isLongSwitch = (sw: string | IndentedText) => /^--/.test(getText(sw));
// prepare 'Options:' tables display
const displayedGroups = Object.keys(groups)
.filter(groupName => groups[groupName].length > 0)
.map(groupName => {
// if we've grouped the key 'f', but 'f' aliases 'foobar',
// normalizedKeys should contain only 'foobar'.
const normalizedKeys: string[] = groups[groupName]
.filter(filterHiddenOptions)
.map(key => {
if (aliasKeys.includes(key)) return key;
for (
let i = 0, aliasKey;
(aliasKey = aliasKeys[i]) !== undefined;
i++
) {
if ((options.alias[aliasKey] || []).includes(key))
return aliasKey;
}
return key;
});
return {groupName, normalizedKeys};
})
.filter(({normalizedKeys}) => normalizedKeys.length > 0)
.map(({groupName, normalizedKeys}) => {
// actually generate the switches string --foo, -f, --bar.
const switches: Dictionary<string | IndentedText> =
normalizedKeys.reduce((acc, key) => {
acc[key] = [key]
.concat(options.alias[key] || [])
.map(sw => {
// for the special positional group don't
// add '--' or '-' prefix.
if (groupName === self.getPositionalGroupName()) return sw;
else {
return (
// matches yargs-parser logic in which single-digits
// aliases declared with a boolean type are now valid
(/^[0-9]$/.test(sw)
? options.boolean.includes(key)
? '-'
: '--'
: sw.length > 1
? '--'
: '-') + sw
);
}
})
// place short switches first (see #1403)
.sort((sw1, sw2) =>
isLongSwitch(sw1) === isLongSwitch(sw2)
? 0
: isLongSwitch(sw1)
? 1
: -1
)
.join(', ');
return acc;
}, {} as Dictionary<string>);
return {groupName, normalizedKeys, switches};
});
// if some options use short switches, indent long-switches only options (see #1403)
const shortSwitchesUsed = displayedGroups
.filter(({groupName}) => groupName !== self.getPositionalGroupName())
.some(
({normalizedKeys, switches}) =>
!normalizedKeys.every(key => isLongSwitch(switches[key]))
);
if (shortSwitchesUsed) {
displayedGroups
.filter(({groupName}) => groupName !== self.getPositionalGroupName())
.forEach(({normalizedKeys, switches}) => {
normalizedKeys.forEach(key => {
if (isLongSwitch(switches[key])) {
switches[key] = addIndentation(switches[key], '-x, '.length);
}
});
});
}
// display 'Options:' table along with any custom tables:
displayedGroups.forEach(({groupName, normalizedKeys, switches}) => {
ui.div(groupName);
normalizedKeys.forEach(key => {
const kswitch = switches[key];
let desc = descriptions[key] || '';
let type = null;
if (desc.includes(deferY18nLookupPrefix))
desc = __(desc.substring(deferY18nLookupPrefix.length));
if (options.boolean.includes(key)) type = `[${__('boolean')}]`;
if (options.count.includes(key)) type = `[${__('count')}]`;
if (options.string.includes(key)) type = `[${__('string')}]`;
if (options.normalize.includes(key)) type = `[${__('string')}]`;
if (options.array.includes(key)) type = `[${__('array')}]`;
if (options.number.includes(key)) type = `[${__('number')}]`;
const deprecatedExtra = (deprecated?: string | boolean) =>
typeof deprecated === 'string'
? `[${__('deprecated: %s', deprecated)}]`
: `[${__('deprecated')}]`;
const extra = [
key in deprecatedOptions
? deprecatedExtra(deprecatedOptions[key])
: null,
type,
key in demandedOptions ? `[${__('required')}]` : null,
options.choices && options.choices[key]
? `[${__('choices:')} ${self.stringifiedValues(
options.choices[key]
)}]`
: null,
defaultString(options.default[key], options.defaultDescription[key]),
]
.filter(Boolean)
.join(' ');
ui.span(
{
text: getText(kswitch),
padding: [0, 2, 0, 2 + getIndentation(kswitch)],
width: maxWidth(switches, theWrap) + 4,
},
desc
);
const shouldHideOptionExtras =
yargs.getInternalMethods().getUsageConfiguration()['hide-types'] ===
true;
if (extra && !shouldHideOptionExtras)
ui.div({text: extra, padding: [0, 0, 0, 2], align: 'right'});
else ui.div();
});
ui.div();
});
// describe some common use-cases for your application.
if (examples.length) {
ui.div(__('Examples:'));
examples.forEach(example => {
example[0] = example[0].replace(/\$0/g, base$0);
});
examples.forEach(example => {
if (example[1] === '') {
ui.div({
text: example[0],
padding: [0, 2, 0, 2],
});
} else {
ui.div(
{
text: example[0],
padding: [0, 2, 0, 2],
width: maxWidth(examples, theWrap) + 4,
},
{
text: example[1],
}
);
}
});
ui.div();
}
// the usage string.
if (epilogs.length > 0) {
const e = epilogs
.map(epilog => epilog.replace(/\$0/g, base$0))
.join('\n');
ui.div(`${e}\n`);
}
// Remove the trailing white spaces
return ui.toString().replace(/\s*$/, '');
};
// return the maximum width of a string
// in the left-hand column of a table.
function maxWidth(
table:
| [string | IndentedText, ...any[]][]
| Dictionary<string | IndentedText>,
theWrap?: number | null,
modifier?: string
) {
let width = 0;
// table might be of the form [leftColumn],
// or {key: leftColumn}
if (!Array.isArray(table)) {
table = Object.values(table).map<[string | IndentedText]>(v => [v]);
}
table.forEach(v => {
// column might be of the form "text"
// or { text: "text", indent: 4 }
width = Math.max(
shim.stringWidth(
modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])
) + getIndentation(v[0]),
width
);
});
// if we've enabled 'wrap' we should limit
// the max-width of the left-column.
if (theWrap)
width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
return width;
}
// make sure any options set for aliases,
// are copied to the keys being aliased.
function normalizeAliases() {
// handle old demanded API
const demandedOptions = yargs.getDemandedOptions();
const options = yargs.getOptions();
(Object.keys(options.alias) || []).forEach(key => {
options.alias[key].forEach(alias => {
// copy descriptions.
if (descriptions[alias]) self.describe(key, descriptions[alias]);
// copy demanded.
if (alias in demandedOptions)
yargs.demandOption(key, demandedOptions[alias]);
// type messages.
if (options.boolean.includes(alias)) yargs.boolean(key);
if (options.count.includes(alias)) yargs.count(key);
if (options.string.includes(alias)) yargs.string(key);
if (options.normalize.includes(alias)) yargs.normalize(key);
if (options.array.includes(alias)) yargs.array(key);
if (options.number.includes(alias)) yargs.number(key);
});
});
}
// if yargs is executing an async handler, we take a snapshot of the
// help message to display on failure:
let cachedHelpMessage: string | undefined;
self.cacheHelpMessage = function () {
cachedHelpMessage = this.help();
};
// however this snapshot must be cleared afterwards
// not to be be used by next calls to parse
self.clearCachedHelpMessage = function () {
cachedHelpMessage = undefined;
};
self.hasCachedHelpMessage = function () {
return !!cachedHelpMessage;
};
// given a set of keys, place any keys that are
// ungrouped under the 'Options:' grouping.
function addUngroupedKeys(
keys: string[],
aliases: Dictionary<string[]>,
groups: Dictionary<string[]>,
defaultGroup: string
) {
let groupedKeys = [] as string[];
let toCheck = null;
Object.keys(groups).forEach(group => {
groupedKeys = groupedKeys.concat(groups[group]);
});
keys.forEach(key => {
toCheck = [key].concat(aliases[key]);
if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
groups[defaultGroup].push(key);
}
});
return groupedKeys;
}
function filterHiddenOptions(key: string) {
return (
yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
(yargs.parsed as DetailedArguments).argv[yargs.getOptions().showHiddenOpt]
);
}
self.showHelp = (level: 'error' | 'log' | ((message: string) => void)) => {
const logger = yargs.getInternalMethods().getLoggerInstance();
if (!level) level = 'error';
const emit = typeof level === 'function' ? level : logger[level];
emit(self.help());
};
self.functionDescription = fn => {
const description = fn.name
? shim.Parser.decamelize(fn.name, '-')
: __('generated-value');
return ['(', description, ')'].join('');
};
self.stringifiedValues = function stringifiedValues(values, separator) {
let string = '';
const sep = separator || ', ';
const array = ([] as any[]).concat(values);
if (!values || !array.length) return string;
array.forEach(value => {
if (string.length) string += sep;
string += JSON.stringify(value);
});
return string;
};
// format the default-value-string displayed in
// the right-hand column.
function defaultString(value: any, defaultDescription?: string) {
let string = `[${__('default:')} `;
if (value === undefined && !defaultDescription) return null;
if (defaultDescription) {
string += defaultDescription;
} else {
switch (typeof value) {
case 'string':
string += `"${value}"`;
break;
case 'object':
string += JSON.stringify(value);
break;
default:
string += value;
}
}
return `${string}]`;
}
// guess the width of the console window, max-width 80.
function windowWidth() {
const maxWidth = 80;
// CI is not a TTY
/* c8 ignore next 2 */
if (shim.process.stdColumns) {
return Math.min(maxWidth, shim.process.stdColumns);
} else {
return maxWidth;
}
}
// logic for displaying application version.
let version: any = null;
self.version = ver => {
version = ver;
};
self.showVersion = level => {
const logger = yargs.getInternalMethods().getLoggerInstance();
if (!level) level = 'error';
const emit = typeof level === 'function' ? level : logger[level];
emit(version);
};
self.reset = function reset(localLookup) {
// do not reset wrap here
// do not reset fails here
failMessage = null;
failureOutput = false;
usages = [];
usageDisabled = false;
epilogs = [];
examples = [];
commands = [];
descriptions = objFilter(descriptions, k => !localLookup[k]);
return self;
};
const frozens = [] as FrozenUsageInstance[];
self.freeze = function freeze() {
frozens.push({
failMessage,
failureOutput,
usages,
usageDisabled,
epilogs,
examples,
commands,
descriptions,
});
};
self.unfreeze = function unfreeze(defaultCommand = false) {
const frozen = frozens.pop();
// In the case of running a defaultCommand, we reset
// usage early to ensure we receive the top level instructions.
// unfreezing again should just be a noop:
if (!frozen) return;
// Addresses: https://github.com/yargs/yargs/issues/2030
if (defaultCommand) {
descriptions = {...frozen.descriptions, ...descriptions};
commands = [...frozen.commands, ...commands];
usages = [...frozen.usages, ...usages];
examples = [...frozen.examples, ...examples];
epilogs = [...frozen.epilogs, ...epilogs];
} else {
({
failMessage,
failureOutput,
usages,
usageDisabled,
epilogs,
examples,
commands,
descriptions,
} = frozen);
}
};
return self;
} | interface PlatformShim {
cwd: Function;
format: Function;
normalize: Function;
require: Function;
resolve: Function;
env: Function;
} |
2,817 | function usage(yargs: YargsInstance, shim: PlatformShim) {
const __ = shim.y18n.__;
const self = {} as UsageInstance;
// methods for ouputting/building failure message.
const fails: (FailureFunction | boolean)[] = [];
self.failFn = function failFn(f) {
fails.push(f);
};
let failMessage: string | nil = null;
let globalFailMessage: string | nil = null;
let showHelpOnFail = true;
self.showHelpOnFail = function showHelpOnFailFn(
arg1: boolean | string = true,
arg2?: string
) {
const [enabled, message] =
typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2];
// If global context, set globalFailMessage
// Addresses: https://github.com/yargs/yargs/issues/2085
if (yargs.getInternalMethods().isGlobalContext()) {
globalFailMessage = message;
}
failMessage = message;
showHelpOnFail = enabled;
return self;
};
let failureOutput = false;
self.fail = function fail(msg, err) {
const logger = yargs.getInternalMethods().getLoggerInstance();
if (fails.length) {
for (let i = fails.length - 1; i >= 0; --i) {
const fail = fails[i];
if (isBoolean(fail)) {
if (err) throw err;
else if (msg) throw Error(msg);
} else {
fail(msg, err, self);
}
}
} else {
if (yargs.getExitProcess()) setBlocking(true);
// don't output failure message more than once
if (!failureOutput) {
failureOutput = true;
if (showHelpOnFail) {
yargs.showHelp('error');
logger.error();
}
if (msg || err) logger.error(msg || err);
const globalOrCommandFailMessage = failMessage || globalFailMessage;
if (globalOrCommandFailMessage) {
if (msg || err) logger.error('');
logger.error(globalOrCommandFailMessage);
}
}
err = err || new YError(msg);
if (yargs.getExitProcess()) {
return yargs.exit(1);
} else if (yargs.getInternalMethods().hasParseCallback()) {
return yargs.exit(1, err);
} else {
throw err;
}
}
};
// methods for ouputting/building help (usage) message.
let usages: [string, string][] = [];
let usageDisabled = false;
self.usage = (msg, description) => {
if (msg === null) {
usageDisabled = true;
usages = [];
return self;
}
usageDisabled = false;
usages.push([msg, description || '']);
return self;
};
self.getUsage = () => {
return usages;
};
self.getUsageDisabled = () => {
return usageDisabled;
};
self.getPositionalGroupName = () => {
return __('Positionals:');
};
let examples: [string, string][] = [];
self.example = (cmd, description) => {
examples.push([cmd, description || '']);
};
let commands: [string, string, boolean, string[], boolean][] = [];
self.command = function command(
cmd,
description,
isDefault,
aliases,
deprecated = false
) {
// the last default wins, so cancel out any previously set default
if (isDefault) {
commands = commands.map(cmdArray => {
cmdArray[2] = false;
return cmdArray;
});
}
commands.push([cmd, description || '', isDefault, aliases, deprecated]);
};
self.getCommands = () => commands;
let descriptions: Dictionary<string | undefined> = {};
self.describe = function describe(
keyOrKeys: string | string[] | Dictionary<string>,
desc?: string
) {
if (Array.isArray(keyOrKeys)) {
keyOrKeys.forEach(k => {
self.describe(k, desc);
});
} else if (typeof keyOrKeys === 'object') {
Object.keys(keyOrKeys).forEach(k => {
self.describe(k, keyOrKeys[k]);
});
} else {
descriptions[keyOrKeys] = desc;
}
};
self.getDescriptions = () => descriptions;
let epilogs: string[] = [];
self.epilog = msg => {
epilogs.push(msg);
};
let wrapSet = false;
let wrap: number | nil;
self.wrap = cols => {
wrapSet = true;
wrap = cols;
};
self.getWrap = () => {
if (shim.getEnv('YARGS_DISABLE_WRAP')) {
return null;
}
if (!wrapSet) {
wrap = windowWidth();
wrapSet = true;
}
return wrap;
};
const deferY18nLookupPrefix = '__yargsString__:';
self.deferY18nLookup = str => deferY18nLookupPrefix + str;
self.help = function help() {
if (cachedHelpMessage) return cachedHelpMessage;
normalizeAliases();
// handle old demanded API
const base$0 = yargs.customScriptName
? yargs.$0
: shim.path.basename(yargs.$0);
const demandedOptions = yargs.getDemandedOptions();
const demandedCommands = yargs.getDemandedCommands();
const deprecatedOptions = yargs.getDeprecatedOptions();
const groups = yargs.getGroups();
const options = yargs.getOptions();
let keys: string[] = [];
keys = keys.concat(Object.keys(descriptions));
keys = keys.concat(Object.keys(demandedOptions));
keys = keys.concat(Object.keys(demandedCommands));
keys = keys.concat(Object.keys(options.default));
keys = keys.filter(filterHiddenOptions);
keys = Object.keys(
keys.reduce((acc, key) => {
if (key !== '_') acc[key] = true;
return acc;
}, {} as Dictionary<boolean>)
);
const theWrap = self.getWrap();
const ui = shim.cliui({
width: theWrap,
wrap: !!theWrap,
});
// the usage string.
if (!usageDisabled) {
if (usages.length) {
// user-defined usage.
usages.forEach(usage => {
ui.div({text: `${usage[0].replace(/\$0/g, base$0)}`});
if (usage[1]) {
ui.div({text: `${usage[1]}`, padding: [1, 0, 0, 0]});
}
});
ui.div();
} else if (commands.length) {
let u = null;
// demonstrate how commands are used.
if (demandedCommands._) {
u = `${base$0} <${__('command')}>\n`;
} else {
u = `${base$0} [${__('command')}]\n`;
}
ui.div(`${u}`);
}
}
// your application's commands, i.e., non-option
// arguments populated in '_'.
//
// If there's only a single command, and it's the default command
// (represented by commands[0][2]) don't show command stanza:
//
// TODO(@bcoe): why isnt commands[0][2] an object with a named property?
if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) {
ui.div(__('Commands:'));
const context = yargs.getInternalMethods().getContext();
const parentCommands = context.commands.length
? `${context.commands.join(' ')} `
: '';
if (
yargs.getInternalMethods().getParserConfiguration()['sort-commands'] ===
true
) {
commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
}
const prefix = base$0 ? `${base$0} ` : '';
commands.forEach(command => {
const commandString = `${prefix}${parentCommands}${command[0].replace(
/^\$0 ?/,
''
)}`; // drop $0 from default commands.
ui.span(
{
text: commandString,
padding: [0, 2, 0, 2],
width:
maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4,
},
{text: command[1]}
);
const hints = [];
if (command[2]) hints.push(`[${__('default')}]`);
if (command[3] && command[3].length) {
hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`);
}
if (command[4]) {
if (typeof command[4] === 'string') {
hints.push(`[${__('deprecated: %s', command[4])}]`);
} else {
hints.push(`[${__('deprecated')}]`);
}
}
if (hints.length) {
ui.div({
text: hints.join(' '),
padding: [0, 0, 0, 2],
align: 'right',
});
} else {
ui.div();
}
});
ui.div();
}
// perform some cleanup on the keys array, making it
// only include top-level keys not their aliases.
const aliasKeys = (Object.keys(options.alias) || []).concat(
Object.keys((yargs.parsed as DetailedArguments).newAliases) || []
);
keys = keys.filter(
key =>
!(yargs.parsed as DetailedArguments).newAliases[key] &&
aliasKeys.every(
alias => (options.alias[alias] || []).indexOf(key) === -1
)
);
// populate 'Options:' group with any keys that have not
// explicitly had a group set.
const defaultGroup = __('Options:');
if (!groups[defaultGroup]) groups[defaultGroup] = [];
addUngroupedKeys(keys, options.alias, groups, defaultGroup);
const isLongSwitch = (sw: string | IndentedText) => /^--/.test(getText(sw));
// prepare 'Options:' tables display
const displayedGroups = Object.keys(groups)
.filter(groupName => groups[groupName].length > 0)
.map(groupName => {
// if we've grouped the key 'f', but 'f' aliases 'foobar',
// normalizedKeys should contain only 'foobar'.
const normalizedKeys: string[] = groups[groupName]
.filter(filterHiddenOptions)
.map(key => {
if (aliasKeys.includes(key)) return key;
for (
let i = 0, aliasKey;
(aliasKey = aliasKeys[i]) !== undefined;
i++
) {
if ((options.alias[aliasKey] || []).includes(key))
return aliasKey;
}
return key;
});
return {groupName, normalizedKeys};
})
.filter(({normalizedKeys}) => normalizedKeys.length > 0)
.map(({groupName, normalizedKeys}) => {
// actually generate the switches string --foo, -f, --bar.
const switches: Dictionary<string | IndentedText> =
normalizedKeys.reduce((acc, key) => {
acc[key] = [key]
.concat(options.alias[key] || [])
.map(sw => {
// for the special positional group don't
// add '--' or '-' prefix.
if (groupName === self.getPositionalGroupName()) return sw;
else {
return (
// matches yargs-parser logic in which single-digits
// aliases declared with a boolean type are now valid
(/^[0-9]$/.test(sw)
? options.boolean.includes(key)
? '-'
: '--'
: sw.length > 1
? '--'
: '-') + sw
);
}
})
// place short switches first (see #1403)
.sort((sw1, sw2) =>
isLongSwitch(sw1) === isLongSwitch(sw2)
? 0
: isLongSwitch(sw1)
? 1
: -1
)
.join(', ');
return acc;
}, {} as Dictionary<string>);
return {groupName, normalizedKeys, switches};
});
// if some options use short switches, indent long-switches only options (see #1403)
const shortSwitchesUsed = displayedGroups
.filter(({groupName}) => groupName !== self.getPositionalGroupName())
.some(
({normalizedKeys, switches}) =>
!normalizedKeys.every(key => isLongSwitch(switches[key]))
);
if (shortSwitchesUsed) {
displayedGroups
.filter(({groupName}) => groupName !== self.getPositionalGroupName())
.forEach(({normalizedKeys, switches}) => {
normalizedKeys.forEach(key => {
if (isLongSwitch(switches[key])) {
switches[key] = addIndentation(switches[key], '-x, '.length);
}
});
});
}
// display 'Options:' table along with any custom tables:
displayedGroups.forEach(({groupName, normalizedKeys, switches}) => {
ui.div(groupName);
normalizedKeys.forEach(key => {
const kswitch = switches[key];
let desc = descriptions[key] || '';
let type = null;
if (desc.includes(deferY18nLookupPrefix))
desc = __(desc.substring(deferY18nLookupPrefix.length));
if (options.boolean.includes(key)) type = `[${__('boolean')}]`;
if (options.count.includes(key)) type = `[${__('count')}]`;
if (options.string.includes(key)) type = `[${__('string')}]`;
if (options.normalize.includes(key)) type = `[${__('string')}]`;
if (options.array.includes(key)) type = `[${__('array')}]`;
if (options.number.includes(key)) type = `[${__('number')}]`;
const deprecatedExtra = (deprecated?: string | boolean) =>
typeof deprecated === 'string'
? `[${__('deprecated: %s', deprecated)}]`
: `[${__('deprecated')}]`;
const extra = [
key in deprecatedOptions
? deprecatedExtra(deprecatedOptions[key])
: null,
type,
key in demandedOptions ? `[${__('required')}]` : null,
options.choices && options.choices[key]
? `[${__('choices:')} ${self.stringifiedValues(
options.choices[key]
)}]`
: null,
defaultString(options.default[key], options.defaultDescription[key]),
]
.filter(Boolean)
.join(' ');
ui.span(
{
text: getText(kswitch),
padding: [0, 2, 0, 2 + getIndentation(kswitch)],
width: maxWidth(switches, theWrap) + 4,
},
desc
);
const shouldHideOptionExtras =
yargs.getInternalMethods().getUsageConfiguration()['hide-types'] ===
true;
if (extra && !shouldHideOptionExtras)
ui.div({text: extra, padding: [0, 0, 0, 2], align: 'right'});
else ui.div();
});
ui.div();
});
// describe some common use-cases for your application.
if (examples.length) {
ui.div(__('Examples:'));
examples.forEach(example => {
example[0] = example[0].replace(/\$0/g, base$0);
});
examples.forEach(example => {
if (example[1] === '') {
ui.div({
text: example[0],
padding: [0, 2, 0, 2],
});
} else {
ui.div(
{
text: example[0],
padding: [0, 2, 0, 2],
width: maxWidth(examples, theWrap) + 4,
},
{
text: example[1],
}
);
}
});
ui.div();
}
// the usage string.
if (epilogs.length > 0) {
const e = epilogs
.map(epilog => epilog.replace(/\$0/g, base$0))
.join('\n');
ui.div(`${e}\n`);
}
// Remove the trailing white spaces
return ui.toString().replace(/\s*$/, '');
};
// return the maximum width of a string
// in the left-hand column of a table.
function maxWidth(
table:
| [string | IndentedText, ...any[]][]
| Dictionary<string | IndentedText>,
theWrap?: number | null,
modifier?: string
) {
let width = 0;
// table might be of the form [leftColumn],
// or {key: leftColumn}
if (!Array.isArray(table)) {
table = Object.values(table).map<[string | IndentedText]>(v => [v]);
}
table.forEach(v => {
// column might be of the form "text"
// or { text: "text", indent: 4 }
width = Math.max(
shim.stringWidth(
modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])
) + getIndentation(v[0]),
width
);
});
// if we've enabled 'wrap' we should limit
// the max-width of the left-column.
if (theWrap)
width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
return width;
}
// make sure any options set for aliases,
// are copied to the keys being aliased.
function normalizeAliases() {
// handle old demanded API
const demandedOptions = yargs.getDemandedOptions();
const options = yargs.getOptions();
(Object.keys(options.alias) || []).forEach(key => {
options.alias[key].forEach(alias => {
// copy descriptions.
if (descriptions[alias]) self.describe(key, descriptions[alias]);
// copy demanded.
if (alias in demandedOptions)
yargs.demandOption(key, demandedOptions[alias]);
// type messages.
if (options.boolean.includes(alias)) yargs.boolean(key);
if (options.count.includes(alias)) yargs.count(key);
if (options.string.includes(alias)) yargs.string(key);
if (options.normalize.includes(alias)) yargs.normalize(key);
if (options.array.includes(alias)) yargs.array(key);
if (options.number.includes(alias)) yargs.number(key);
});
});
}
// if yargs is executing an async handler, we take a snapshot of the
// help message to display on failure:
let cachedHelpMessage: string | undefined;
self.cacheHelpMessage = function () {
cachedHelpMessage = this.help();
};
// however this snapshot must be cleared afterwards
// not to be be used by next calls to parse
self.clearCachedHelpMessage = function () {
cachedHelpMessage = undefined;
};
self.hasCachedHelpMessage = function () {
return !!cachedHelpMessage;
};
// given a set of keys, place any keys that are
// ungrouped under the 'Options:' grouping.
function addUngroupedKeys(
keys: string[],
aliases: Dictionary<string[]>,
groups: Dictionary<string[]>,
defaultGroup: string
) {
let groupedKeys = [] as string[];
let toCheck = null;
Object.keys(groups).forEach(group => {
groupedKeys = groupedKeys.concat(groups[group]);
});
keys.forEach(key => {
toCheck = [key].concat(aliases[key]);
if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
groups[defaultGroup].push(key);
}
});
return groupedKeys;
}
function filterHiddenOptions(key: string) {
return (
yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
(yargs.parsed as DetailedArguments).argv[yargs.getOptions().showHiddenOpt]
);
}
self.showHelp = (level: 'error' | 'log' | ((message: string) => void)) => {
const logger = yargs.getInternalMethods().getLoggerInstance();
if (!level) level = 'error';
const emit = typeof level === 'function' ? level : logger[level];
emit(self.help());
};
self.functionDescription = fn => {
const description = fn.name
? shim.Parser.decamelize(fn.name, '-')
: __('generated-value');
return ['(', description, ')'].join('');
};
self.stringifiedValues = function stringifiedValues(values, separator) {
let string = '';
const sep = separator || ', ';
const array = ([] as any[]).concat(values);
if (!values || !array.length) return string;
array.forEach(value => {
if (string.length) string += sep;
string += JSON.stringify(value);
});
return string;
};
// format the default-value-string displayed in
// the right-hand column.
function defaultString(value: any, defaultDescription?: string) {
let string = `[${__('default:')} `;
if (value === undefined && !defaultDescription) return null;
if (defaultDescription) {
string += defaultDescription;
} else {
switch (typeof value) {
case 'string':
string += `"${value}"`;
break;
case 'object':
string += JSON.stringify(value);
break;
default:
string += value;
}
}
return `${string}]`;
}
// guess the width of the console window, max-width 80.
function windowWidth() {
const maxWidth = 80;
// CI is not a TTY
/* c8 ignore next 2 */
if (shim.process.stdColumns) {
return Math.min(maxWidth, shim.process.stdColumns);
} else {
return maxWidth;
}
}
// logic for displaying application version.
let version: any = null;
self.version = ver => {
version = ver;
};
self.showVersion = level => {
const logger = yargs.getInternalMethods().getLoggerInstance();
if (!level) level = 'error';
const emit = typeof level === 'function' ? level : logger[level];
emit(version);
};
self.reset = function reset(localLookup) {
// do not reset wrap here
// do not reset fails here
failMessage = null;
failureOutput = false;
usages = [];
usageDisabled = false;
epilogs = [];
examples = [];
commands = [];
descriptions = objFilter(descriptions, k => !localLookup[k]);
return self;
};
const frozens = [] as FrozenUsageInstance[];
self.freeze = function freeze() {
frozens.push({
failMessage,
failureOutput,
usages,
usageDisabled,
epilogs,
examples,
commands,
descriptions,
});
};
self.unfreeze = function unfreeze(defaultCommand = false) {
const frozen = frozens.pop();
// In the case of running a defaultCommand, we reset
// usage early to ensure we receive the top level instructions.
// unfreezing again should just be a noop:
if (!frozen) return;
// Addresses: https://github.com/yargs/yargs/issues/2030
if (defaultCommand) {
descriptions = {...frozen.descriptions, ...descriptions};
commands = [...frozen.commands, ...commands];
usages = [...frozen.usages, ...usages];
examples = [...frozen.examples, ...examples];
epilogs = [...frozen.epilogs, ...epilogs];
} else {
({
failMessage,
failureOutput,
usages,
usageDisabled,
epilogs,
examples,
commands,
descriptions,
} = frozen);
}
};
return self;
} | interface PlatformShim {
assert: {
notStrictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
strictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
};
findUp: (
startDir: string,
fn: (dir: string[], names: string[]) => string | undefined
) => string;
getCallerFile: () => string;
getEnv: (key: string) => string | undefined;
getProcessArgvBin: () => string;
inspect: (obj: object) => string;
mainFilename: string;
requireDirectory: Function;
stringWidth: (str: string) => number;
cliui: Function;
Parser: Parser;
path: {
basename: (p1: string, p2?: string) => string;
extname: (path: string) => string;
dirname: (path: string) => string;
relative: (p1: string, p2: string) => string;
resolve: (p1: string, p2: string) => string;
};
process: {
argv: () => string[];
cwd: () => string;
emitWarning: (warning: string | Error, type?: string) => void;
execPath: () => string;
exit: (code: number) => void;
nextTick: (cb: Function) => void;
stdColumns: number | null;
};
readFileSync: (path: string, encoding: string) => string;
require: RequireType;
y18n: Y18N;
} |
2,818 | function usage(yargs: YargsInstance, shim: PlatformShim) {
const __ = shim.y18n.__;
const self = {} as UsageInstance;
// methods for ouputting/building failure message.
const fails: (FailureFunction | boolean)[] = [];
self.failFn = function failFn(f) {
fails.push(f);
};
let failMessage: string | nil = null;
let globalFailMessage: string | nil = null;
let showHelpOnFail = true;
self.showHelpOnFail = function showHelpOnFailFn(
arg1: boolean | string = true,
arg2?: string
) {
const [enabled, message] =
typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2];
// If global context, set globalFailMessage
// Addresses: https://github.com/yargs/yargs/issues/2085
if (yargs.getInternalMethods().isGlobalContext()) {
globalFailMessage = message;
}
failMessage = message;
showHelpOnFail = enabled;
return self;
};
let failureOutput = false;
self.fail = function fail(msg, err) {
const logger = yargs.getInternalMethods().getLoggerInstance();
if (fails.length) {
for (let i = fails.length - 1; i >= 0; --i) {
const fail = fails[i];
if (isBoolean(fail)) {
if (err) throw err;
else if (msg) throw Error(msg);
} else {
fail(msg, err, self);
}
}
} else {
if (yargs.getExitProcess()) setBlocking(true);
// don't output failure message more than once
if (!failureOutput) {
failureOutput = true;
if (showHelpOnFail) {
yargs.showHelp('error');
logger.error();
}
if (msg || err) logger.error(msg || err);
const globalOrCommandFailMessage = failMessage || globalFailMessage;
if (globalOrCommandFailMessage) {
if (msg || err) logger.error('');
logger.error(globalOrCommandFailMessage);
}
}
err = err || new YError(msg);
if (yargs.getExitProcess()) {
return yargs.exit(1);
} else if (yargs.getInternalMethods().hasParseCallback()) {
return yargs.exit(1, err);
} else {
throw err;
}
}
};
// methods for ouputting/building help (usage) message.
let usages: [string, string][] = [];
let usageDisabled = false;
self.usage = (msg, description) => {
if (msg === null) {
usageDisabled = true;
usages = [];
return self;
}
usageDisabled = false;
usages.push([msg, description || '']);
return self;
};
self.getUsage = () => {
return usages;
};
self.getUsageDisabled = () => {
return usageDisabled;
};
self.getPositionalGroupName = () => {
return __('Positionals:');
};
let examples: [string, string][] = [];
self.example = (cmd, description) => {
examples.push([cmd, description || '']);
};
let commands: [string, string, boolean, string[], boolean][] = [];
self.command = function command(
cmd,
description,
isDefault,
aliases,
deprecated = false
) {
// the last default wins, so cancel out any previously set default
if (isDefault) {
commands = commands.map(cmdArray => {
cmdArray[2] = false;
return cmdArray;
});
}
commands.push([cmd, description || '', isDefault, aliases, deprecated]);
};
self.getCommands = () => commands;
let descriptions: Dictionary<string | undefined> = {};
self.describe = function describe(
keyOrKeys: string | string[] | Dictionary<string>,
desc?: string
) {
if (Array.isArray(keyOrKeys)) {
keyOrKeys.forEach(k => {
self.describe(k, desc);
});
} else if (typeof keyOrKeys === 'object') {
Object.keys(keyOrKeys).forEach(k => {
self.describe(k, keyOrKeys[k]);
});
} else {
descriptions[keyOrKeys] = desc;
}
};
self.getDescriptions = () => descriptions;
let epilogs: string[] = [];
self.epilog = msg => {
epilogs.push(msg);
};
let wrapSet = false;
let wrap: number | nil;
self.wrap = cols => {
wrapSet = true;
wrap = cols;
};
self.getWrap = () => {
if (shim.getEnv('YARGS_DISABLE_WRAP')) {
return null;
}
if (!wrapSet) {
wrap = windowWidth();
wrapSet = true;
}
return wrap;
};
const deferY18nLookupPrefix = '__yargsString__:';
self.deferY18nLookup = str => deferY18nLookupPrefix + str;
self.help = function help() {
if (cachedHelpMessage) return cachedHelpMessage;
normalizeAliases();
// handle old demanded API
const base$0 = yargs.customScriptName
? yargs.$0
: shim.path.basename(yargs.$0);
const demandedOptions = yargs.getDemandedOptions();
const demandedCommands = yargs.getDemandedCommands();
const deprecatedOptions = yargs.getDeprecatedOptions();
const groups = yargs.getGroups();
const options = yargs.getOptions();
let keys: string[] = [];
keys = keys.concat(Object.keys(descriptions));
keys = keys.concat(Object.keys(demandedOptions));
keys = keys.concat(Object.keys(demandedCommands));
keys = keys.concat(Object.keys(options.default));
keys = keys.filter(filterHiddenOptions);
keys = Object.keys(
keys.reduce((acc, key) => {
if (key !== '_') acc[key] = true;
return acc;
}, {} as Dictionary<boolean>)
);
const theWrap = self.getWrap();
const ui = shim.cliui({
width: theWrap,
wrap: !!theWrap,
});
// the usage string.
if (!usageDisabled) {
if (usages.length) {
// user-defined usage.
usages.forEach(usage => {
ui.div({text: `${usage[0].replace(/\$0/g, base$0)}`});
if (usage[1]) {
ui.div({text: `${usage[1]}`, padding: [1, 0, 0, 0]});
}
});
ui.div();
} else if (commands.length) {
let u = null;
// demonstrate how commands are used.
if (demandedCommands._) {
u = `${base$0} <${__('command')}>\n`;
} else {
u = `${base$0} [${__('command')}]\n`;
}
ui.div(`${u}`);
}
}
// your application's commands, i.e., non-option
// arguments populated in '_'.
//
// If there's only a single command, and it's the default command
// (represented by commands[0][2]) don't show command stanza:
//
// TODO(@bcoe): why isnt commands[0][2] an object with a named property?
if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) {
ui.div(__('Commands:'));
const context = yargs.getInternalMethods().getContext();
const parentCommands = context.commands.length
? `${context.commands.join(' ')} `
: '';
if (
yargs.getInternalMethods().getParserConfiguration()['sort-commands'] ===
true
) {
commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
}
const prefix = base$0 ? `${base$0} ` : '';
commands.forEach(command => {
const commandString = `${prefix}${parentCommands}${command[0].replace(
/^\$0 ?/,
''
)}`; // drop $0 from default commands.
ui.span(
{
text: commandString,
padding: [0, 2, 0, 2],
width:
maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4,
},
{text: command[1]}
);
const hints = [];
if (command[2]) hints.push(`[${__('default')}]`);
if (command[3] && command[3].length) {
hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`);
}
if (command[4]) {
if (typeof command[4] === 'string') {
hints.push(`[${__('deprecated: %s', command[4])}]`);
} else {
hints.push(`[${__('deprecated')}]`);
}
}
if (hints.length) {
ui.div({
text: hints.join(' '),
padding: [0, 0, 0, 2],
align: 'right',
});
} else {
ui.div();
}
});
ui.div();
}
// perform some cleanup on the keys array, making it
// only include top-level keys not their aliases.
const aliasKeys = (Object.keys(options.alias) || []).concat(
Object.keys((yargs.parsed as DetailedArguments).newAliases) || []
);
keys = keys.filter(
key =>
!(yargs.parsed as DetailedArguments).newAliases[key] &&
aliasKeys.every(
alias => (options.alias[alias] || []).indexOf(key) === -1
)
);
// populate 'Options:' group with any keys that have not
// explicitly had a group set.
const defaultGroup = __('Options:');
if (!groups[defaultGroup]) groups[defaultGroup] = [];
addUngroupedKeys(keys, options.alias, groups, defaultGroup);
const isLongSwitch = (sw: string | IndentedText) => /^--/.test(getText(sw));
// prepare 'Options:' tables display
const displayedGroups = Object.keys(groups)
.filter(groupName => groups[groupName].length > 0)
.map(groupName => {
// if we've grouped the key 'f', but 'f' aliases 'foobar',
// normalizedKeys should contain only 'foobar'.
const normalizedKeys: string[] = groups[groupName]
.filter(filterHiddenOptions)
.map(key => {
if (aliasKeys.includes(key)) return key;
for (
let i = 0, aliasKey;
(aliasKey = aliasKeys[i]) !== undefined;
i++
) {
if ((options.alias[aliasKey] || []).includes(key))
return aliasKey;
}
return key;
});
return {groupName, normalizedKeys};
})
.filter(({normalizedKeys}) => normalizedKeys.length > 0)
.map(({groupName, normalizedKeys}) => {
// actually generate the switches string --foo, -f, --bar.
const switches: Dictionary<string | IndentedText> =
normalizedKeys.reduce((acc, key) => {
acc[key] = [key]
.concat(options.alias[key] || [])
.map(sw => {
// for the special positional group don't
// add '--' or '-' prefix.
if (groupName === self.getPositionalGroupName()) return sw;
else {
return (
// matches yargs-parser logic in which single-digits
// aliases declared with a boolean type are now valid
(/^[0-9]$/.test(sw)
? options.boolean.includes(key)
? '-'
: '--'
: sw.length > 1
? '--'
: '-') + sw
);
}
})
// place short switches first (see #1403)
.sort((sw1, sw2) =>
isLongSwitch(sw1) === isLongSwitch(sw2)
? 0
: isLongSwitch(sw1)
? 1
: -1
)
.join(', ');
return acc;
}, {} as Dictionary<string>);
return {groupName, normalizedKeys, switches};
});
// if some options use short switches, indent long-switches only options (see #1403)
const shortSwitchesUsed = displayedGroups
.filter(({groupName}) => groupName !== self.getPositionalGroupName())
.some(
({normalizedKeys, switches}) =>
!normalizedKeys.every(key => isLongSwitch(switches[key]))
);
if (shortSwitchesUsed) {
displayedGroups
.filter(({groupName}) => groupName !== self.getPositionalGroupName())
.forEach(({normalizedKeys, switches}) => {
normalizedKeys.forEach(key => {
if (isLongSwitch(switches[key])) {
switches[key] = addIndentation(switches[key], '-x, '.length);
}
});
});
}
// display 'Options:' table along with any custom tables:
displayedGroups.forEach(({groupName, normalizedKeys, switches}) => {
ui.div(groupName);
normalizedKeys.forEach(key => {
const kswitch = switches[key];
let desc = descriptions[key] || '';
let type = null;
if (desc.includes(deferY18nLookupPrefix))
desc = __(desc.substring(deferY18nLookupPrefix.length));
if (options.boolean.includes(key)) type = `[${__('boolean')}]`;
if (options.count.includes(key)) type = `[${__('count')}]`;
if (options.string.includes(key)) type = `[${__('string')}]`;
if (options.normalize.includes(key)) type = `[${__('string')}]`;
if (options.array.includes(key)) type = `[${__('array')}]`;
if (options.number.includes(key)) type = `[${__('number')}]`;
const deprecatedExtra = (deprecated?: string | boolean) =>
typeof deprecated === 'string'
? `[${__('deprecated: %s', deprecated)}]`
: `[${__('deprecated')}]`;
const extra = [
key in deprecatedOptions
? deprecatedExtra(deprecatedOptions[key])
: null,
type,
key in demandedOptions ? `[${__('required')}]` : null,
options.choices && options.choices[key]
? `[${__('choices:')} ${self.stringifiedValues(
options.choices[key]
)}]`
: null,
defaultString(options.default[key], options.defaultDescription[key]),
]
.filter(Boolean)
.join(' ');
ui.span(
{
text: getText(kswitch),
padding: [0, 2, 0, 2 + getIndentation(kswitch)],
width: maxWidth(switches, theWrap) + 4,
},
desc
);
const shouldHideOptionExtras =
yargs.getInternalMethods().getUsageConfiguration()['hide-types'] ===
true;
if (extra && !shouldHideOptionExtras)
ui.div({text: extra, padding: [0, 0, 0, 2], align: 'right'});
else ui.div();
});
ui.div();
});
// describe some common use-cases for your application.
if (examples.length) {
ui.div(__('Examples:'));
examples.forEach(example => {
example[0] = example[0].replace(/\$0/g, base$0);
});
examples.forEach(example => {
if (example[1] === '') {
ui.div({
text: example[0],
padding: [0, 2, 0, 2],
});
} else {
ui.div(
{
text: example[0],
padding: [0, 2, 0, 2],
width: maxWidth(examples, theWrap) + 4,
},
{
text: example[1],
}
);
}
});
ui.div();
}
// the usage string.
if (epilogs.length > 0) {
const e = epilogs
.map(epilog => epilog.replace(/\$0/g, base$0))
.join('\n');
ui.div(`${e}\n`);
}
// Remove the trailing white spaces
return ui.toString().replace(/\s*$/, '');
};
// return the maximum width of a string
// in the left-hand column of a table.
function maxWidth(
table:
| [string | IndentedText, ...any[]][]
| Dictionary<string | IndentedText>,
theWrap?: number | null,
modifier?: string
) {
let width = 0;
// table might be of the form [leftColumn],
// or {key: leftColumn}
if (!Array.isArray(table)) {
table = Object.values(table).map<[string | IndentedText]>(v => [v]);
}
table.forEach(v => {
// column might be of the form "text"
// or { text: "text", indent: 4 }
width = Math.max(
shim.stringWidth(
modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])
) + getIndentation(v[0]),
width
);
});
// if we've enabled 'wrap' we should limit
// the max-width of the left-column.
if (theWrap)
width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
return width;
}
// make sure any options set for aliases,
// are copied to the keys being aliased.
function normalizeAliases() {
// handle old demanded API
const demandedOptions = yargs.getDemandedOptions();
const options = yargs.getOptions();
(Object.keys(options.alias) || []).forEach(key => {
options.alias[key].forEach(alias => {
// copy descriptions.
if (descriptions[alias]) self.describe(key, descriptions[alias]);
// copy demanded.
if (alias in demandedOptions)
yargs.demandOption(key, demandedOptions[alias]);
// type messages.
if (options.boolean.includes(alias)) yargs.boolean(key);
if (options.count.includes(alias)) yargs.count(key);
if (options.string.includes(alias)) yargs.string(key);
if (options.normalize.includes(alias)) yargs.normalize(key);
if (options.array.includes(alias)) yargs.array(key);
if (options.number.includes(alias)) yargs.number(key);
});
});
}
// if yargs is executing an async handler, we take a snapshot of the
// help message to display on failure:
let cachedHelpMessage: string | undefined;
self.cacheHelpMessage = function () {
cachedHelpMessage = this.help();
};
// however this snapshot must be cleared afterwards
// not to be be used by next calls to parse
self.clearCachedHelpMessage = function () {
cachedHelpMessage = undefined;
};
self.hasCachedHelpMessage = function () {
return !!cachedHelpMessage;
};
// given a set of keys, place any keys that are
// ungrouped under the 'Options:' grouping.
function addUngroupedKeys(
keys: string[],
aliases: Dictionary<string[]>,
groups: Dictionary<string[]>,
defaultGroup: string
) {
let groupedKeys = [] as string[];
let toCheck = null;
Object.keys(groups).forEach(group => {
groupedKeys = groupedKeys.concat(groups[group]);
});
keys.forEach(key => {
toCheck = [key].concat(aliases[key]);
if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
groups[defaultGroup].push(key);
}
});
return groupedKeys;
}
function filterHiddenOptions(key: string) {
return (
yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
(yargs.parsed as DetailedArguments).argv[yargs.getOptions().showHiddenOpt]
);
}
self.showHelp = (level: 'error' | 'log' | ((message: string) => void)) => {
const logger = yargs.getInternalMethods().getLoggerInstance();
if (!level) level = 'error';
const emit = typeof level === 'function' ? level : logger[level];
emit(self.help());
};
self.functionDescription = fn => {
const description = fn.name
? shim.Parser.decamelize(fn.name, '-')
: __('generated-value');
return ['(', description, ')'].join('');
};
self.stringifiedValues = function stringifiedValues(values, separator) {
let string = '';
const sep = separator || ', ';
const array = ([] as any[]).concat(values);
if (!values || !array.length) return string;
array.forEach(value => {
if (string.length) string += sep;
string += JSON.stringify(value);
});
return string;
};
// format the default-value-string displayed in
// the right-hand column.
function defaultString(value: any, defaultDescription?: string) {
let string = `[${__('default:')} `;
if (value === undefined && !defaultDescription) return null;
if (defaultDescription) {
string += defaultDescription;
} else {
switch (typeof value) {
case 'string':
string += `"${value}"`;
break;
case 'object':
string += JSON.stringify(value);
break;
default:
string += value;
}
}
return `${string}]`;
}
// guess the width of the console window, max-width 80.
function windowWidth() {
const maxWidth = 80;
// CI is not a TTY
/* c8 ignore next 2 */
if (shim.process.stdColumns) {
return Math.min(maxWidth, shim.process.stdColumns);
} else {
return maxWidth;
}
}
// logic for displaying application version.
let version: any = null;
self.version = ver => {
version = ver;
};
self.showVersion = level => {
const logger = yargs.getInternalMethods().getLoggerInstance();
if (!level) level = 'error';
const emit = typeof level === 'function' ? level : logger[level];
emit(version);
};
self.reset = function reset(localLookup) {
// do not reset wrap here
// do not reset fails here
failMessage = null;
failureOutput = false;
usages = [];
usageDisabled = false;
epilogs = [];
examples = [];
commands = [];
descriptions = objFilter(descriptions, k => !localLookup[k]);
return self;
};
const frozens = [] as FrozenUsageInstance[];
self.freeze = function freeze() {
frozens.push({
failMessage,
failureOutput,
usages,
usageDisabled,
epilogs,
examples,
commands,
descriptions,
});
};
self.unfreeze = function unfreeze(defaultCommand = false) {
const frozen = frozens.pop();
// In the case of running a defaultCommand, we reset
// usage early to ensure we receive the top level instructions.
// unfreezing again should just be a noop:
if (!frozen) return;
// Addresses: https://github.com/yargs/yargs/issues/2030
if (defaultCommand) {
descriptions = {...frozen.descriptions, ...descriptions};
commands = [...frozen.commands, ...commands];
usages = [...frozen.usages, ...usages];
examples = [...frozen.examples, ...examples];
epilogs = [...frozen.epilogs, ...epilogs];
} else {
({
failMessage,
failureOutput,
usages,
usageDisabled,
epilogs,
examples,
commands,
descriptions,
} = frozen);
}
};
return self;
} | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,819 | constructor(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
this.shim = shim;
this.usage = usage;
this.globalMiddleware = globalMiddleware;
this.validation = validation;
} | class GlobalMiddleware {
globalMiddleware: Middleware[] = [];
yargs: YargsInstance;
frozens: Array<Middleware[]> = [];
constructor(yargs: YargsInstance) {
this.yargs = yargs;
}
addMiddleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation: boolean,
global = true,
mutates = false
): YargsInstance {
argsert(
'<array|function> [boolean] [boolean] [boolean]',
[callback, applyBeforeValidation, global],
arguments.length
);
if (Array.isArray(callback)) {
for (let i = 0; i < callback.length; i++) {
if (typeof callback[i] !== 'function') {
throw Error('middleware must be a function');
}
const m = callback[i] as Middleware;
m.applyBeforeValidation = applyBeforeValidation;
m.global = global;
}
Array.prototype.push.apply(
this.globalMiddleware,
callback as Middleware[]
);
} else if (typeof callback === 'function') {
const m = callback as Middleware;
m.applyBeforeValidation = applyBeforeValidation;
m.global = global;
m.mutates = mutates;
this.globalMiddleware.push(callback as Middleware);
}
return this.yargs;
}
// For "coerce" middleware, only one middleware instance can be registered
// per option:
addCoerceMiddleware(
callback: MiddlewareCallback,
option: string
): YargsInstance {
const aliases = this.yargs.getAliases();
this.globalMiddleware = this.globalMiddleware.filter(m => {
const toCheck = [...(aliases[option] || []), option];
if (!m.option) return true;
else return !toCheck.includes(m.option);
});
(callback as Middleware).option = option;
return this.addMiddleware(callback, true, true, true);
}
getMiddleware() {
return this.globalMiddleware;
}
freeze() {
this.frozens.push([...this.globalMiddleware]);
}
unfreeze() {
const frozen = this.frozens.pop();
if (frozen !== undefined) this.globalMiddleware = frozen;
}
reset() {
this.globalMiddleware = this.globalMiddleware.filter(m => m.global);
}
} |
2,820 | constructor(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
this.shim = shim;
this.usage = usage;
this.globalMiddleware = globalMiddleware;
this.validation = validation;
} | interface ValidationInstance {
conflicting(argv: Arguments): void;
conflicts(
key: string | Dictionary<string | string[]>,
value?: string | string[]
): void;
freeze(): void;
getConflicting(): Dictionary<(string | undefined)[]>;
getImplied(): Dictionary<KeyOrPos[]>;
implications(argv: Arguments): void;
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): void;
isValidAndSomeAliasIsNotNew(
key: string,
aliases: DetailedArguments['aliases']
): boolean;
limitedChoices(argv: Arguments): void;
nonOptionCount(argv: Arguments): void;
positionalCount(required: number, observed: number): void;
recommendCommands(cmd: string, potentialCommands: string[]): void;
requiredArguments(
argv: Arguments,
demandedOptions: Dictionary<string | undefined>
): void;
reset(localLookup: Dictionary): ValidationInstance;
unfreeze(): void;
unknownArguments(
argv: Arguments,
aliases: DetailedArguments['aliases'],
positionalMap: Dictionary,
isDefaultCommand: boolean,
checkPositionals?: boolean
): void;
unknownCommands(argv: Arguments): boolean;
} |
2,821 | constructor(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
this.shim = shim;
this.usage = usage;
this.globalMiddleware = globalMiddleware;
this.validation = validation;
} | interface UsageInstance {
cacheHelpMessage(): void;
clearCachedHelpMessage(): void;
hasCachedHelpMessage(): boolean;
command(
cmd: string,
description: string | undefined,
isDefault: boolean,
aliases: string[],
deprecated?: boolean
): void;
deferY18nLookup(str: string): string;
describe(keys: string | string[] | Dictionary<string>, desc?: string): void;
epilog(msg: string): void;
example(cmd: string, description?: string): void;
fail(msg?: string | null, err?: YError | string): void;
failFn(f: FailureFunction | boolean): void;
freeze(): void;
functionDescription(fn: {name?: string}): string;
getCommands(): [string, string, boolean, string[], boolean][];
getDescriptions(): Dictionary<string | undefined>;
getPositionalGroupName(): string;
getUsage(): [string, string][];
getUsageDisabled(): boolean;
getWrap(): number | nil;
help(): string;
reset(localLookup: Dictionary<boolean>): UsageInstance;
showHelp(level?: 'error' | 'log' | ((message: string) => void)): void;
showHelpOnFail(enabled?: boolean | string, message?: string): UsageInstance;
showVersion(level?: 'error' | 'log' | ((message: string) => void)): void;
stringifiedValues(values?: any[], separator?: string): string;
unfreeze(defaultCommand?: boolean): void;
usage(msg: string | null, description?: string | false): UsageInstance;
version(ver: any): void;
wrap(cols: number | nil): void;
} |
2,822 | constructor(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
this.shim = shim;
this.usage = usage;
this.globalMiddleware = globalMiddleware;
this.validation = validation;
} | interface PlatformShim {
cwd: Function;
format: Function;
normalize: Function;
require: Function;
resolve: Function;
env: Function;
} |
2,823 | constructor(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
this.shim = shim;
this.usage = usage;
this.globalMiddleware = globalMiddleware;
this.validation = validation;
} | interface PlatformShim {
assert: {
notStrictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
strictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
};
findUp: (
startDir: string,
fn: (dir: string[], names: string[]) => string | undefined
) => string;
getCallerFile: () => string;
getEnv: (key: string) => string | undefined;
getProcessArgvBin: () => string;
inspect: (obj: object) => string;
mainFilename: string;
requireDirectory: Function;
stringWidth: (str: string) => number;
cliui: Function;
Parser: Parser;
path: {
basename: (p1: string, p2?: string) => string;
extname: (path: string) => string;
dirname: (path: string) => string;
relative: (p1: string, p2: string) => string;
resolve: (p1: string, p2: string) => string;
};
process: {
argv: () => string[];
cwd: () => string;
emitWarning: (warning: string | Error, type?: string) => void;
execPath: () => string;
exit: (code: number) => void;
nextTick: (cb: Function) => void;
stdColumns: number | null;
};
readFileSync: (path: string, encoding: string) => string;
require: RequireType;
y18n: Y18N;
} |
2,824 | private shouldUpdateUsage(yargs: YargsInstance) {
return (
!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() &&
yargs.getInternalMethods().getUsageInstance().getUsage().length === 0
);
} | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,825 | private populatePositionals(
commandHandler: CommandHandler,
argv: Arguments,
context: Context,
yargs: YargsInstance
) {
argv._ = argv._.slice(context.commands.length); // nuke the current commands
const demanded = commandHandler.demanded.slice(0);
const optional = commandHandler.optional.slice(0);
const positionalMap: Dictionary<string[]> = {};
this.validation.positionalCount(demanded.length, argv._.length);
while (demanded.length) {
const demand = demanded.shift()!;
this.populatePositional(demand, argv, positionalMap);
}
while (optional.length) {
const maybe = optional.shift()!;
this.populatePositional(maybe, argv, positionalMap);
}
argv._ = context.commands.concat(argv._.map(a => '' + a));
this.postProcessPositionals(
argv,
positionalMap,
this.cmdToParseOptions(commandHandler.original),
yargs
);
return positionalMap;
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,826 | private populatePositionals(
commandHandler: CommandHandler,
argv: Arguments,
context: Context,
yargs: YargsInstance
) {
argv._ = argv._.slice(context.commands.length); // nuke the current commands
const demanded = commandHandler.demanded.slice(0);
const optional = commandHandler.optional.slice(0);
const positionalMap: Dictionary<string[]> = {};
this.validation.positionalCount(demanded.length, argv._.length);
while (demanded.length) {
const demand = demanded.shift()!;
this.populatePositional(demand, argv, positionalMap);
}
while (optional.length) {
const maybe = optional.shift()!;
this.populatePositional(maybe, argv, positionalMap);
}
argv._ = context.commands.concat(argv._.map(a => '' + a));
this.postProcessPositionals(
argv,
positionalMap,
this.cmdToParseOptions(commandHandler.original),
yargs
);
return positionalMap;
} | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,827 | private populatePositionals(
commandHandler: CommandHandler,
argv: Arguments,
context: Context,
yargs: YargsInstance
) {
argv._ = argv._.slice(context.commands.length); // nuke the current commands
const demanded = commandHandler.demanded.slice(0);
const optional = commandHandler.optional.slice(0);
const positionalMap: Dictionary<string[]> = {};
this.validation.positionalCount(demanded.length, argv._.length);
while (demanded.length) {
const demand = demanded.shift()!;
this.populatePositional(demand, argv, positionalMap);
}
while (optional.length) {
const maybe = optional.shift()!;
this.populatePositional(maybe, argv, positionalMap);
}
argv._ = context.commands.concat(argv._.map(a => '' + a));
this.postProcessPositionals(
argv,
positionalMap,
this.cmdToParseOptions(commandHandler.original),
yargs
);
return positionalMap;
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,828 | private populatePositionals(
commandHandler: CommandHandler,
argv: Arguments,
context: Context,
yargs: YargsInstance
) {
argv._ = argv._.slice(context.commands.length); // nuke the current commands
const demanded = commandHandler.demanded.slice(0);
const optional = commandHandler.optional.slice(0);
const positionalMap: Dictionary<string[]> = {};
this.validation.positionalCount(demanded.length, argv._.length);
while (demanded.length) {
const demand = demanded.shift()!;
this.populatePositional(demand, argv, positionalMap);
}
while (optional.length) {
const maybe = optional.shift()!;
this.populatePositional(maybe, argv, positionalMap);
}
argv._ = context.commands.concat(argv._.map(a => '' + a));
this.postProcessPositionals(
argv,
positionalMap,
this.cmdToParseOptions(commandHandler.original),
yargs
);
return positionalMap;
} | interface CommandHandler {
builder: CommandBuilder;
demanded: Positional[];
deprecated?: boolean;
description?: string | false;
handler: CommandHandlerCallback;
middlewares: Middleware[];
optional: Positional[];
original: string;
} |
2,829 | private populatePositionals(
commandHandler: CommandHandler,
argv: Arguments,
context: Context,
yargs: YargsInstance
) {
argv._ = argv._.slice(context.commands.length); // nuke the current commands
const demanded = commandHandler.demanded.slice(0);
const optional = commandHandler.optional.slice(0);
const positionalMap: Dictionary<string[]> = {};
this.validation.positionalCount(demanded.length, argv._.length);
while (demanded.length) {
const demand = demanded.shift()!;
this.populatePositional(demand, argv, positionalMap);
}
while (optional.length) {
const maybe = optional.shift()!;
this.populatePositional(maybe, argv, positionalMap);
}
argv._ = context.commands.concat(argv._.map(a => '' + a));
this.postProcessPositionals(
argv,
positionalMap,
this.cmdToParseOptions(commandHandler.original),
yargs
);
return positionalMap;
} | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,830 | private populatePositionals(
commandHandler: CommandHandler,
argv: Arguments,
context: Context,
yargs: YargsInstance
) {
argv._ = argv._.slice(context.commands.length); // nuke the current commands
const demanded = commandHandler.demanded.slice(0);
const optional = commandHandler.optional.slice(0);
const positionalMap: Dictionary<string[]> = {};
this.validation.positionalCount(demanded.length, argv._.length);
while (demanded.length) {
const demand = demanded.shift()!;
this.populatePositional(demand, argv, positionalMap);
}
while (optional.length) {
const maybe = optional.shift()!;
this.populatePositional(maybe, argv, positionalMap);
}
argv._ = context.commands.concat(argv._.map(a => '' + a));
this.postProcessPositionals(
argv,
positionalMap,
this.cmdToParseOptions(commandHandler.original),
yargs
);
return positionalMap;
} | interface Context {
commands: string[];
fullCommands: string[];
} |
2,831 | private populatePositional(
positional: Positional,
argv: Arguments,
positionalMap: Dictionary<string[]>
) {
const cmd = positional.cmd[0];
if (positional.variadic) {
positionalMap[cmd] = argv._.splice(0).map(String);
} else {
if (argv._.length) positionalMap[cmd] = [String(argv._.shift())];
}
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,832 | private populatePositional(
positional: Positional,
argv: Arguments,
positionalMap: Dictionary<string[]>
) {
const cmd = positional.cmd[0];
if (positional.variadic) {
positionalMap[cmd] = argv._.splice(0).map(String);
} else {
if (argv._.length) positionalMap[cmd] = [String(argv._.shift())];
}
} | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,833 | private populatePositional(
positional: Positional,
argv: Arguments,
positionalMap: Dictionary<string[]>
) {
const cmd = positional.cmd[0];
if (positional.variadic) {
positionalMap[cmd] = argv._.splice(0).map(String);
} else {
if (argv._.length) positionalMap[cmd] = [String(argv._.shift())];
}
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,834 | private populatePositional(
positional: Positional,
argv: Arguments,
positionalMap: Dictionary<string[]>
) {
const cmd = positional.cmd[0];
if (positional.variadic) {
positionalMap[cmd] = argv._.splice(0).map(String);
} else {
if (argv._.length) positionalMap[cmd] = [String(argv._.shift())];
}
} | interface Positional {
cmd: NotEmptyArray<string>;
variadic: boolean;
} |
2,835 | private postProcessPositionals(
argv: Arguments,
positionalMap: Dictionary<string[]>,
parseOptions: Positionals,
yargs: YargsInstance
) {
// combine the parsing hints we've inferred from the command
// string with explicitly configured parsing hints.
const options = Object.assign({}, yargs.getOptions());
options.default = Object.assign(parseOptions.default, options.default);
for (const key of Object.keys(parseOptions.alias)) {
options.alias[key] = (options.alias[key] || []).concat(
parseOptions.alias[key]
);
}
options.array = options.array.concat(parseOptions.array);
options.config = {}; // don't load config when processing positionals.
const unparsed: string[] = [];
Object.keys(positionalMap).forEach(key => {
positionalMap[key].map(value => {
if (options.configuration['unknown-options-as-args'])
options.key[key] = true;
unparsed.push(`--${key}`);
unparsed.push(value);
});
});
// short-circuit parse.
if (!unparsed.length) return;
const config: Configuration = Object.assign({}, options.configuration, {
'populate--': false,
});
const parsed = this.shim.Parser.detailed(
unparsed,
Object.assign({}, options, {
configuration: config,
})
);
if (parsed.error) {
yargs
.getInternalMethods()
.getUsageInstance()
.fail(parsed.error.message, parsed.error);
} else {
// only copy over positional keys (don't overwrite
// flag arguments that were already parsed).
const positionalKeys = Object.keys(positionalMap);
Object.keys(positionalMap).forEach(key => {
positionalKeys.push(...parsed.aliases[key]);
});
Object.keys(parsed.argv).forEach(key => {
if (positionalKeys.includes(key)) {
// any new aliases need to be placed in positionalMap, which
// is used for validation.
if (!positionalMap[key]) positionalMap[key] = parsed.argv[key];
// Addresses: https://github.com/yargs/yargs/issues/1637
// If both positionals/options provided,
// and no default or config values were set for that key,
// and if at least one is an array: don't overwrite, combine.
if (
!this.isInConfigs(yargs, key) &&
!this.isDefaulted(yargs, key) &&
Object.prototype.hasOwnProperty.call(argv, key) &&
Object.prototype.hasOwnProperty.call(parsed.argv, key) &&
(Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))
) {
argv[key] = ([] as string[]).concat(argv[key], parsed.argv[key]);
} else {
argv[key] = parsed.argv[key];
}
}
});
}
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,836 | private postProcessPositionals(
argv: Arguments,
positionalMap: Dictionary<string[]>,
parseOptions: Positionals,
yargs: YargsInstance
) {
// combine the parsing hints we've inferred from the command
// string with explicitly configured parsing hints.
const options = Object.assign({}, yargs.getOptions());
options.default = Object.assign(parseOptions.default, options.default);
for (const key of Object.keys(parseOptions.alias)) {
options.alias[key] = (options.alias[key] || []).concat(
parseOptions.alias[key]
);
}
options.array = options.array.concat(parseOptions.array);
options.config = {}; // don't load config when processing positionals.
const unparsed: string[] = [];
Object.keys(positionalMap).forEach(key => {
positionalMap[key].map(value => {
if (options.configuration['unknown-options-as-args'])
options.key[key] = true;
unparsed.push(`--${key}`);
unparsed.push(value);
});
});
// short-circuit parse.
if (!unparsed.length) return;
const config: Configuration = Object.assign({}, options.configuration, {
'populate--': false,
});
const parsed = this.shim.Parser.detailed(
unparsed,
Object.assign({}, options, {
configuration: config,
})
);
if (parsed.error) {
yargs
.getInternalMethods()
.getUsageInstance()
.fail(parsed.error.message, parsed.error);
} else {
// only copy over positional keys (don't overwrite
// flag arguments that were already parsed).
const positionalKeys = Object.keys(positionalMap);
Object.keys(positionalMap).forEach(key => {
positionalKeys.push(...parsed.aliases[key]);
});
Object.keys(parsed.argv).forEach(key => {
if (positionalKeys.includes(key)) {
// any new aliases need to be placed in positionalMap, which
// is used for validation.
if (!positionalMap[key]) positionalMap[key] = parsed.argv[key];
// Addresses: https://github.com/yargs/yargs/issues/1637
// If both positionals/options provided,
// and no default or config values were set for that key,
// and if at least one is an array: don't overwrite, combine.
if (
!this.isInConfigs(yargs, key) &&
!this.isDefaulted(yargs, key) &&
Object.prototype.hasOwnProperty.call(argv, key) &&
Object.prototype.hasOwnProperty.call(parsed.argv, key) &&
(Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))
) {
argv[key] = ([] as string[]).concat(argv[key], parsed.argv[key]);
} else {
argv[key] = parsed.argv[key];
}
}
});
}
} | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,837 | private postProcessPositionals(
argv: Arguments,
positionalMap: Dictionary<string[]>,
parseOptions: Positionals,
yargs: YargsInstance
) {
// combine the parsing hints we've inferred from the command
// string with explicitly configured parsing hints.
const options = Object.assign({}, yargs.getOptions());
options.default = Object.assign(parseOptions.default, options.default);
for (const key of Object.keys(parseOptions.alias)) {
options.alias[key] = (options.alias[key] || []).concat(
parseOptions.alias[key]
);
}
options.array = options.array.concat(parseOptions.array);
options.config = {}; // don't load config when processing positionals.
const unparsed: string[] = [];
Object.keys(positionalMap).forEach(key => {
positionalMap[key].map(value => {
if (options.configuration['unknown-options-as-args'])
options.key[key] = true;
unparsed.push(`--${key}`);
unparsed.push(value);
});
});
// short-circuit parse.
if (!unparsed.length) return;
const config: Configuration = Object.assign({}, options.configuration, {
'populate--': false,
});
const parsed = this.shim.Parser.detailed(
unparsed,
Object.assign({}, options, {
configuration: config,
})
);
if (parsed.error) {
yargs
.getInternalMethods()
.getUsageInstance()
.fail(parsed.error.message, parsed.error);
} else {
// only copy over positional keys (don't overwrite
// flag arguments that were already parsed).
const positionalKeys = Object.keys(positionalMap);
Object.keys(positionalMap).forEach(key => {
positionalKeys.push(...parsed.aliases[key]);
});
Object.keys(parsed.argv).forEach(key => {
if (positionalKeys.includes(key)) {
// any new aliases need to be placed in positionalMap, which
// is used for validation.
if (!positionalMap[key]) positionalMap[key] = parsed.argv[key];
// Addresses: https://github.com/yargs/yargs/issues/1637
// If both positionals/options provided,
// and no default or config values were set for that key,
// and if at least one is an array: don't overwrite, combine.
if (
!this.isInConfigs(yargs, key) &&
!this.isDefaulted(yargs, key) &&
Object.prototype.hasOwnProperty.call(argv, key) &&
Object.prototype.hasOwnProperty.call(parsed.argv, key) &&
(Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))
) {
argv[key] = ([] as string[]).concat(argv[key], parsed.argv[key]);
} else {
argv[key] = parsed.argv[key];
}
}
});
}
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,838 | private postProcessPositionals(
argv: Arguments,
positionalMap: Dictionary<string[]>,
parseOptions: Positionals,
yargs: YargsInstance
) {
// combine the parsing hints we've inferred from the command
// string with explicitly configured parsing hints.
const options = Object.assign({}, yargs.getOptions());
options.default = Object.assign(parseOptions.default, options.default);
for (const key of Object.keys(parseOptions.alias)) {
options.alias[key] = (options.alias[key] || []).concat(
parseOptions.alias[key]
);
}
options.array = options.array.concat(parseOptions.array);
options.config = {}; // don't load config when processing positionals.
const unparsed: string[] = [];
Object.keys(positionalMap).forEach(key => {
positionalMap[key].map(value => {
if (options.configuration['unknown-options-as-args'])
options.key[key] = true;
unparsed.push(`--${key}`);
unparsed.push(value);
});
});
// short-circuit parse.
if (!unparsed.length) return;
const config: Configuration = Object.assign({}, options.configuration, {
'populate--': false,
});
const parsed = this.shim.Parser.detailed(
unparsed,
Object.assign({}, options, {
configuration: config,
})
);
if (parsed.error) {
yargs
.getInternalMethods()
.getUsageInstance()
.fail(parsed.error.message, parsed.error);
} else {
// only copy over positional keys (don't overwrite
// flag arguments that were already parsed).
const positionalKeys = Object.keys(positionalMap);
Object.keys(positionalMap).forEach(key => {
positionalKeys.push(...parsed.aliases[key]);
});
Object.keys(parsed.argv).forEach(key => {
if (positionalKeys.includes(key)) {
// any new aliases need to be placed in positionalMap, which
// is used for validation.
if (!positionalMap[key]) positionalMap[key] = parsed.argv[key];
// Addresses: https://github.com/yargs/yargs/issues/1637
// If both positionals/options provided,
// and no default or config values were set for that key,
// and if at least one is an array: don't overwrite, combine.
if (
!this.isInConfigs(yargs, key) &&
!this.isDefaulted(yargs, key) &&
Object.prototype.hasOwnProperty.call(argv, key) &&
Object.prototype.hasOwnProperty.call(parsed.argv, key) &&
(Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))
) {
argv[key] = ([] as string[]).concat(argv[key], parsed.argv[key]);
} else {
argv[key] = parsed.argv[key];
}
}
});
}
} | interface Positionals extends Pick<Options, 'alias' | 'array' | 'default'> {
demand: Dictionary<boolean>;
} |
2,839 | private postProcessPositionals(
argv: Arguments,
positionalMap: Dictionary<string[]>,
parseOptions: Positionals,
yargs: YargsInstance
) {
// combine the parsing hints we've inferred from the command
// string with explicitly configured parsing hints.
const options = Object.assign({}, yargs.getOptions());
options.default = Object.assign(parseOptions.default, options.default);
for (const key of Object.keys(parseOptions.alias)) {
options.alias[key] = (options.alias[key] || []).concat(
parseOptions.alias[key]
);
}
options.array = options.array.concat(parseOptions.array);
options.config = {}; // don't load config when processing positionals.
const unparsed: string[] = [];
Object.keys(positionalMap).forEach(key => {
positionalMap[key].map(value => {
if (options.configuration['unknown-options-as-args'])
options.key[key] = true;
unparsed.push(`--${key}`);
unparsed.push(value);
});
});
// short-circuit parse.
if (!unparsed.length) return;
const config: Configuration = Object.assign({}, options.configuration, {
'populate--': false,
});
const parsed = this.shim.Parser.detailed(
unparsed,
Object.assign({}, options, {
configuration: config,
})
);
if (parsed.error) {
yargs
.getInternalMethods()
.getUsageInstance()
.fail(parsed.error.message, parsed.error);
} else {
// only copy over positional keys (don't overwrite
// flag arguments that were already parsed).
const positionalKeys = Object.keys(positionalMap);
Object.keys(positionalMap).forEach(key => {
positionalKeys.push(...parsed.aliases[key]);
});
Object.keys(parsed.argv).forEach(key => {
if (positionalKeys.includes(key)) {
// any new aliases need to be placed in positionalMap, which
// is used for validation.
if (!positionalMap[key]) positionalMap[key] = parsed.argv[key];
// Addresses: https://github.com/yargs/yargs/issues/1637
// If both positionals/options provided,
// and no default or config values were set for that key,
// and if at least one is an array: don't overwrite, combine.
if (
!this.isInConfigs(yargs, key) &&
!this.isDefaulted(yargs, key) &&
Object.prototype.hasOwnProperty.call(argv, key) &&
Object.prototype.hasOwnProperty.call(parsed.argv, key) &&
(Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))
) {
argv[key] = ([] as string[]).concat(argv[key], parsed.argv[key]);
} else {
argv[key] = parsed.argv[key];
}
}
});
}
} | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,840 | isDefaulted(yargs: YargsInstance, key: string): boolean {
const {default: defaults} = yargs.getOptions();
return (
Object.prototype.hasOwnProperty.call(defaults, key) ||
Object.prototype.hasOwnProperty.call(
defaults,
this.shim.Parser.camelCase(key)
)
);
} | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,841 | isInConfigs(yargs: YargsInstance, key: string): boolean {
const {configObjects} = yargs.getOptions();
return (
configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) ||
configObjects.some(c =>
Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key))
)
);
} | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,842 | runDefaultBuilderOn(yargs: YargsInstance): unknown | Promise<unknown> {
if (!this.defaultCommand) return;
if (this.shouldUpdateUsage(yargs)) {
// build the root-level command string from the default string.
const commandString = DEFAULT_MARKER.test(this.defaultCommand.original)
? this.defaultCommand.original
: this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
yargs
.getInternalMethods()
.getUsageInstance()
.usage(commandString, this.defaultCommand.description);
}
const builder = this.defaultCommand.builder;
if (isCommandBuilderCallback(builder)) {
return builder(yargs, true);
} else if (!isCommandBuilderDefinition(builder)) {
Object.keys(builder).forEach(key => {
yargs.option(key, builder[key]);
});
}
return undefined;
} | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,843 | private moduleName(obj: CommandHandlerDefinition) {
const mod = whichModule(obj);
if (!mod)
throw new Error(
`No command name given for module: ${this.shim.inspect(obj)}`
);
return this.commandFromFilename(mod.filename);
} | interface CommandHandlerDefinition
extends Partial<
Pick<
CommandHandler,
'deprecated' | 'description' | 'handler' | 'middlewares'
>
> {
aliases?: string[];
builder?: CommandBuilder | CommandBuilderDefinition;
command?: string | string[];
desc?: CommandHandler['description'];
describe?: CommandHandler['description'];
} |
2,844 | private extractDesc({describe, description, desc}: CommandHandlerDefinition) {
for (const test of [describe, description, desc]) {
if (typeof test === 'string' || test === false) return test;
assertNotStrictEqual(test, true as const, this.shim);
}
return false;
} | interface CommandHandlerDefinition
extends Partial<
Pick<
CommandHandler,
'deprecated' | 'description' | 'handler' | 'middlewares'
>
> {
aliases?: string[];
builder?: CommandBuilder | CommandBuilderDefinition;
command?: string | string[];
desc?: CommandHandler['description'];
describe?: CommandHandler['description'];
} |
2,845 | function command(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
return new CommandInstance(usage, validation, globalMiddleware, shim);
} | class GlobalMiddleware {
globalMiddleware: Middleware[] = [];
yargs: YargsInstance;
frozens: Array<Middleware[]> = [];
constructor(yargs: YargsInstance) {
this.yargs = yargs;
}
addMiddleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation: boolean,
global = true,
mutates = false
): YargsInstance {
argsert(
'<array|function> [boolean] [boolean] [boolean]',
[callback, applyBeforeValidation, global],
arguments.length
);
if (Array.isArray(callback)) {
for (let i = 0; i < callback.length; i++) {
if (typeof callback[i] !== 'function') {
throw Error('middleware must be a function');
}
const m = callback[i] as Middleware;
m.applyBeforeValidation = applyBeforeValidation;
m.global = global;
}
Array.prototype.push.apply(
this.globalMiddleware,
callback as Middleware[]
);
} else if (typeof callback === 'function') {
const m = callback as Middleware;
m.applyBeforeValidation = applyBeforeValidation;
m.global = global;
m.mutates = mutates;
this.globalMiddleware.push(callback as Middleware);
}
return this.yargs;
}
// For "coerce" middleware, only one middleware instance can be registered
// per option:
addCoerceMiddleware(
callback: MiddlewareCallback,
option: string
): YargsInstance {
const aliases = this.yargs.getAliases();
this.globalMiddleware = this.globalMiddleware.filter(m => {
const toCheck = [...(aliases[option] || []), option];
if (!m.option) return true;
else return !toCheck.includes(m.option);
});
(callback as Middleware).option = option;
return this.addMiddleware(callback, true, true, true);
}
getMiddleware() {
return this.globalMiddleware;
}
freeze() {
this.frozens.push([...this.globalMiddleware]);
}
unfreeze() {
const frozen = this.frozens.pop();
if (frozen !== undefined) this.globalMiddleware = frozen;
}
reset() {
this.globalMiddleware = this.globalMiddleware.filter(m => m.global);
}
} |
2,846 | function command(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
return new CommandInstance(usage, validation, globalMiddleware, shim);
} | interface ValidationInstance {
conflicting(argv: Arguments): void;
conflicts(
key: string | Dictionary<string | string[]>,
value?: string | string[]
): void;
freeze(): void;
getConflicting(): Dictionary<(string | undefined)[]>;
getImplied(): Dictionary<KeyOrPos[]>;
implications(argv: Arguments): void;
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): void;
isValidAndSomeAliasIsNotNew(
key: string,
aliases: DetailedArguments['aliases']
): boolean;
limitedChoices(argv: Arguments): void;
nonOptionCount(argv: Arguments): void;
positionalCount(required: number, observed: number): void;
recommendCommands(cmd: string, potentialCommands: string[]): void;
requiredArguments(
argv: Arguments,
demandedOptions: Dictionary<string | undefined>
): void;
reset(localLookup: Dictionary): ValidationInstance;
unfreeze(): void;
unknownArguments(
argv: Arguments,
aliases: DetailedArguments['aliases'],
positionalMap: Dictionary,
isDefaultCommand: boolean,
checkPositionals?: boolean
): void;
unknownCommands(argv: Arguments): boolean;
} |
2,847 | function command(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
return new CommandInstance(usage, validation, globalMiddleware, shim);
} | interface UsageInstance {
cacheHelpMessage(): void;
clearCachedHelpMessage(): void;
hasCachedHelpMessage(): boolean;
command(
cmd: string,
description: string | undefined,
isDefault: boolean,
aliases: string[],
deprecated?: boolean
): void;
deferY18nLookup(str: string): string;
describe(keys: string | string[] | Dictionary<string>, desc?: string): void;
epilog(msg: string): void;
example(cmd: string, description?: string): void;
fail(msg?: string | null, err?: YError | string): void;
failFn(f: FailureFunction | boolean): void;
freeze(): void;
functionDescription(fn: {name?: string}): string;
getCommands(): [string, string, boolean, string[], boolean][];
getDescriptions(): Dictionary<string | undefined>;
getPositionalGroupName(): string;
getUsage(): [string, string][];
getUsageDisabled(): boolean;
getWrap(): number | nil;
help(): string;
reset(localLookup: Dictionary<boolean>): UsageInstance;
showHelp(level?: 'error' | 'log' | ((message: string) => void)): void;
showHelpOnFail(enabled?: boolean | string, message?: string): UsageInstance;
showVersion(level?: 'error' | 'log' | ((message: string) => void)): void;
stringifiedValues(values?: any[], separator?: string): string;
unfreeze(defaultCommand?: boolean): void;
usage(msg: string | null, description?: string | false): UsageInstance;
version(ver: any): void;
wrap(cols: number | nil): void;
} |
2,848 | function command(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
return new CommandInstance(usage, validation, globalMiddleware, shim);
} | interface PlatformShim {
cwd: Function;
format: Function;
normalize: Function;
require: Function;
resolve: Function;
env: Function;
} |
2,849 | function command(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
return new CommandInstance(usage, validation, globalMiddleware, shim);
} | interface PlatformShim {
assert: {
notStrictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
strictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
};
findUp: (
startDir: string,
fn: (dir: string[], names: string[]) => string | undefined
) => string;
getCallerFile: () => string;
getEnv: (key: string) => string | undefined;
getProcessArgvBin: () => string;
inspect: (obj: object) => string;
mainFilename: string;
requireDirectory: Function;
stringWidth: (str: string) => number;
cliui: Function;
Parser: Parser;
path: {
basename: (p1: string, p2?: string) => string;
extname: (path: string) => string;
dirname: (path: string) => string;
relative: (p1: string, p2: string) => string;
resolve: (p1: string, p2: string) => string;
};
process: {
argv: () => string[];
cwd: () => string;
emitWarning: (warning: string | Error, type?: string) => void;
execPath: () => string;
exit: (code: number) => void;
nextTick: (cb: Function) => void;
stdColumns: number | null;
};
readFileSync: (path: string, encoding: string) => string;
require: RequireType;
y18n: Y18N;
} |
2,850 | (argv: Arguments): any | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,851 | (argv: Arguments): any | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,852 | (argv: Arguments): any | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,853 | (y: YargsInstance, helpOrVersionSet: boolean): YargsInstance | void | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,854 | function isCommandBuilderCallback(
builder: CommandBuilder
): builder is CommandBuilderCallback {
return typeof builder === 'function';
} | type CommandBuilder =
| CommandBuilderCallback
| Dictionary<OptionDefinition>; |
2,855 | function isCommandBuilderOptionDefinitions(
builder: CommandBuilder
): builder is Dictionary<OptionDefinition> {
return typeof builder === 'object';
} | type CommandBuilder =
| CommandBuilderCallback
| Dictionary<OptionDefinition>; |
2,856 | function validation(
yargs: YargsInstance,
usage: UsageInstance,
shim: PlatformShim
) {
const __ = shim.y18n.__;
const __n = shim.y18n.__n;
const self = {} as ValidationInstance;
// validate appropriate # of non-option
// arguments were provided, i.e., '_'.
self.nonOptionCount = function nonOptionCount(argv) {
const demandedCommands = yargs.getDemandedCommands();
// don't count currently executing commands
const positionalCount =
argv._.length + (argv['--'] ? argv['--'].length : 0);
const _s =
positionalCount - yargs.getInternalMethods().getContext().commands.length;
if (
demandedCommands._ &&
(_s < demandedCommands._.min || _s > demandedCommands._.max)
) {
if (_s < demandedCommands._.min) {
if (demandedCommands._.minMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.minMsg
? demandedCommands._.minMsg
.replace(/\$0/g, _s.toString())
.replace(/\$1/, demandedCommands._.min.toString())
: null
);
} else {
usage.fail(
__n(
'Not enough non-option arguments: got %s, need at least %s',
'Not enough non-option arguments: got %s, need at least %s',
_s,
_s.toString(),
demandedCommands._.min.toString()
)
);
}
} else if (_s > demandedCommands._.max) {
if (demandedCommands._.maxMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.maxMsg
? demandedCommands._.maxMsg
.replace(/\$0/g, _s.toString())
.replace(/\$1/, demandedCommands._.max.toString())
: null
);
} else {
usage.fail(
__n(
'Too many non-option arguments: got %s, maximum of %s',
'Too many non-option arguments: got %s, maximum of %s',
_s,
_s.toString(),
demandedCommands._.max.toString()
)
);
}
}
}
};
// validate the appropriate # of <required>
// positional arguments were provided:
self.positionalCount = function positionalCount(required, observed) {
if (observed < required) {
usage.fail(
__n(
'Not enough non-option arguments: got %s, need at least %s',
'Not enough non-option arguments: got %s, need at least %s',
observed,
observed + '',
required + ''
)
);
}
};
// make sure all the required arguments are present.
self.requiredArguments = function requiredArguments(
argv,
demandedOptions: Dictionary<string | undefined>
) {
let missing: Dictionary<string | undefined> | null = null;
for (const key of Object.keys(demandedOptions)) {
if (
!Object.prototype.hasOwnProperty.call(argv, key) ||
typeof argv[key] === 'undefined'
) {
missing = missing || {};
missing[key] = demandedOptions[key];
}
}
if (missing) {
const customMsgs: string[] = [];
for (const key of Object.keys(missing)) {
const msg = missing[key];
if (msg && customMsgs.indexOf(msg) < 0) {
customMsgs.push(msg);
}
}
const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
usage.fail(
__n(
'Missing required argument: %s',
'Missing required arguments: %s',
Object.keys(missing).length,
Object.keys(missing).join(', ') + customMsg
)
);
}
};
// check for unknown arguments (strict-mode).
self.unknownArguments = function unknownArguments(
argv,
aliases,
positionalMap,
isDefaultCommand,
checkPositionals = true
) {
const commandKeys = yargs
.getInternalMethods()
.getCommandInstance()
.getCommands();
const unknown: string[] = [];
const currentContext = yargs.getInternalMethods().getContext();
Object.keys(argv).forEach(key => {
if (
!specialKeys.includes(key) &&
!Object.prototype.hasOwnProperty.call(positionalMap, key) &&
!Object.prototype.hasOwnProperty.call(
yargs.getInternalMethods().getParseContext(),
key
) &&
!self.isValidAndSomeAliasIsNotNew(key, aliases)
) {
unknown.push(key);
}
});
if (
checkPositionals &&
(currentContext.commands.length > 0 ||
commandKeys.length > 0 ||
isDefaultCommand)
) {
argv._.slice(currentContext.commands.length).forEach(key => {
if (!commandKeys.includes('' + key)) {
unknown.push('' + key);
}
});
}
// https://github.com/yargs/yargs/issues/1861
if (checkPositionals) {
// Check for non-option args that are not in currentContext.commands
// Take into account expected args from commands and yargs.demand(number)
const demandedCommands = yargs.getDemandedCommands();
const maxNonOptDemanded = demandedCommands._?.max || 0;
const expected = currentContext.commands.length + maxNonOptDemanded;
if (expected < argv._.length) {
argv._.slice(expected).forEach(key => {
key = String(key);
if (
!currentContext.commands.includes(key) &&
!unknown.includes(key)
) {
unknown.push(key);
}
});
}
}
if (unknown.length) {
usage.fail(
__n(
'Unknown argument: %s',
'Unknown arguments: %s',
unknown.length,
unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', ')
)
);
}
};
self.unknownCommands = function unknownCommands(argv) {
const commandKeys = yargs
.getInternalMethods()
.getCommandInstance()
.getCommands();
const unknown: string[] = [];
const currentContext = yargs.getInternalMethods().getContext();
if (currentContext.commands.length > 0 || commandKeys.length > 0) {
argv._.slice(currentContext.commands.length).forEach(key => {
if (!commandKeys.includes('' + key)) {
unknown.push('' + key);
}
});
}
if (unknown.length > 0) {
usage.fail(
__n(
'Unknown command: %s',
'Unknown commands: %s',
unknown.length,
unknown.join(', ')
)
);
return true;
} else {
return false;
}
};
// check for a key that is not an alias, or for which every alias is new,
// implying that it was invented by the parser, e.g., during camelization
self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(
key,
aliases
) {
if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
return false;
}
const newAliases = (yargs.parsed as DetailedArguments).newAliases;
return [key, ...aliases[key]].some(
a =>
!Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]
);
};
// validate arguments limited to enumerated choices
self.limitedChoices = function limitedChoices(argv) {
const options = yargs.getOptions();
const invalid: Dictionary<any[]> = {};
if (!Object.keys(options.choices).length) return;
Object.keys(argv).forEach(key => {
if (
specialKeys.indexOf(key) === -1 &&
Object.prototype.hasOwnProperty.call(options.choices, key)
) {
[].concat(argv[key]).forEach(value => {
// TODO case-insensitive configurability
if (
options.choices[key].indexOf(value) === -1 &&
value !== undefined
) {
invalid[key] = (invalid[key] || []).concat(value);
}
});
}
});
const invalidKeys = Object.keys(invalid);
if (!invalidKeys.length) return;
let msg = __('Invalid values:');
invalidKeys.forEach(key => {
msg += `\n ${__(
'Argument: %s, Given: %s, Choices: %s',
key,
usage.stringifiedValues(invalid[key]),
usage.stringifiedValues(options.choices[key])
)}`;
});
usage.fail(msg);
};
// check implications, argument foo implies => argument bar.
let implied: Dictionary<KeyOrPos[]> = {};
self.implies = function implies(key, value) {
argsert(
'<string|object> [array|number|string]',
[key, value],
arguments.length
);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
self.implies(k, key[k]);
});
} else {
yargs.global(key);
if (!implied[key]) {
implied[key] = [];
}
if (Array.isArray(value)) {
value.forEach(i => self.implies(key, i));
} else {
assertNotStrictEqual(value, undefined, shim);
implied[key].push(value);
}
}
};
self.getImplied = function getImplied() {
return implied;
};
function keyExists(argv: Arguments, val: any): any {
// convert string '1' to number 1
const num = Number(val);
val = isNaN(num) ? val : num;
if (typeof val === 'number') {
// check length of argv._
val = argv._.length >= val;
} else if (val.match(/^--no-.+/)) {
// check if key/value doesn't exist
val = val.match(/^--no-(.+)/)[1];
val = !Object.prototype.hasOwnProperty.call(argv, val);
} else {
// check if key/value exists
val = Object.prototype.hasOwnProperty.call(argv, val);
}
return val;
}
self.implications = function implications(argv) {
const implyFail: string[] = [];
Object.keys(implied).forEach(key => {
const origKey = key;
(implied[key] || []).forEach(value => {
let key = origKey;
const origValue = value;
key = keyExists(argv, key);
value = keyExists(argv, value);
if (key && !value) {
implyFail.push(` ${origKey} -> ${origValue}`);
}
});
});
if (implyFail.length) {
let msg = `${__('Implications failed:')}\n`;
implyFail.forEach(value => {
msg += value;
});
usage.fail(msg);
}
};
let conflicting: Dictionary<(string | undefined)[]> = {};
self.conflicts = function conflicts(key, value) {
argsert('<string|object> [array|string]', [key, value], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
self.conflicts(k, key[k]);
});
} else {
yargs.global(key);
if (!conflicting[key]) {
conflicting[key] = [];
}
if (Array.isArray(value)) {
value.forEach(i => self.conflicts(key, i));
} else {
conflicting[key].push(value);
}
}
};
self.getConflicting = () => conflicting;
self.conflicting = function conflictingFn(argv) {
Object.keys(argv).forEach(key => {
if (conflicting[key]) {
conflicting[key].forEach(value => {
// we default keys to 'undefined' that have been configured, we should not
// apply conflicting check unless they are a value other than 'undefined'.
if (value && argv[key] !== undefined && argv[value] !== undefined) {
usage.fail(
__('Arguments %s and %s are mutually exclusive', key, value)
);
}
});
}
});
// When strip-dashed is true, match conflicts (kebab) with argv (camel)
// Addresses: https://github.com/yargs/yargs/issues/1952
if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) {
Object.keys(conflicting).forEach(key => {
conflicting[key].forEach(value => {
if (
value &&
argv[shim.Parser.camelCase(key)] !== undefined &&
argv[shim.Parser.camelCase(value)] !== undefined
) {
usage.fail(
__('Arguments %s and %s are mutually exclusive', key, value)
);
}
});
});
}
};
self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
const threshold = 3; // if it takes more than three edits, let's move on.
potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
let recommended = null;
let bestDistance = Infinity;
for (
let i = 0, candidate;
(candidate = potentialCommands[i]) !== undefined;
i++
) {
const d = distance(cmd, candidate);
if (d <= threshold && d < bestDistance) {
bestDistance = d;
recommended = candidate;
}
}
if (recommended) usage.fail(__('Did you mean %s?', recommended));
};
self.reset = function reset(localLookup) {
implied = objFilter(implied, k => !localLookup[k]);
conflicting = objFilter(conflicting, k => !localLookup[k]);
return self;
};
const frozens: FrozenValidationInstance[] = [];
self.freeze = function freeze() {
frozens.push({
implied,
conflicting,
});
};
self.unfreeze = function unfreeze() {
const frozen = frozens.pop();
assertNotStrictEqual(frozen, undefined, shim);
({implied, conflicting} = frozen);
};
return self;
} | interface UsageInstance {
cacheHelpMessage(): void;
clearCachedHelpMessage(): void;
hasCachedHelpMessage(): boolean;
command(
cmd: string,
description: string | undefined,
isDefault: boolean,
aliases: string[],
deprecated?: boolean
): void;
deferY18nLookup(str: string): string;
describe(keys: string | string[] | Dictionary<string>, desc?: string): void;
epilog(msg: string): void;
example(cmd: string, description?: string): void;
fail(msg?: string | null, err?: YError | string): void;
failFn(f: FailureFunction | boolean): void;
freeze(): void;
functionDescription(fn: {name?: string}): string;
getCommands(): [string, string, boolean, string[], boolean][];
getDescriptions(): Dictionary<string | undefined>;
getPositionalGroupName(): string;
getUsage(): [string, string][];
getUsageDisabled(): boolean;
getWrap(): number | nil;
help(): string;
reset(localLookup: Dictionary<boolean>): UsageInstance;
showHelp(level?: 'error' | 'log' | ((message: string) => void)): void;
showHelpOnFail(enabled?: boolean | string, message?: string): UsageInstance;
showVersion(level?: 'error' | 'log' | ((message: string) => void)): void;
stringifiedValues(values?: any[], separator?: string): string;
unfreeze(defaultCommand?: boolean): void;
usage(msg: string | null, description?: string | false): UsageInstance;
version(ver: any): void;
wrap(cols: number | nil): void;
} |
2,857 | function validation(
yargs: YargsInstance,
usage: UsageInstance,
shim: PlatformShim
) {
const __ = shim.y18n.__;
const __n = shim.y18n.__n;
const self = {} as ValidationInstance;
// validate appropriate # of non-option
// arguments were provided, i.e., '_'.
self.nonOptionCount = function nonOptionCount(argv) {
const demandedCommands = yargs.getDemandedCommands();
// don't count currently executing commands
const positionalCount =
argv._.length + (argv['--'] ? argv['--'].length : 0);
const _s =
positionalCount - yargs.getInternalMethods().getContext().commands.length;
if (
demandedCommands._ &&
(_s < demandedCommands._.min || _s > demandedCommands._.max)
) {
if (_s < demandedCommands._.min) {
if (demandedCommands._.minMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.minMsg
? demandedCommands._.minMsg
.replace(/\$0/g, _s.toString())
.replace(/\$1/, demandedCommands._.min.toString())
: null
);
} else {
usage.fail(
__n(
'Not enough non-option arguments: got %s, need at least %s',
'Not enough non-option arguments: got %s, need at least %s',
_s,
_s.toString(),
demandedCommands._.min.toString()
)
);
}
} else if (_s > demandedCommands._.max) {
if (demandedCommands._.maxMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.maxMsg
? demandedCommands._.maxMsg
.replace(/\$0/g, _s.toString())
.replace(/\$1/, demandedCommands._.max.toString())
: null
);
} else {
usage.fail(
__n(
'Too many non-option arguments: got %s, maximum of %s',
'Too many non-option arguments: got %s, maximum of %s',
_s,
_s.toString(),
demandedCommands._.max.toString()
)
);
}
}
}
};
// validate the appropriate # of <required>
// positional arguments were provided:
self.positionalCount = function positionalCount(required, observed) {
if (observed < required) {
usage.fail(
__n(
'Not enough non-option arguments: got %s, need at least %s',
'Not enough non-option arguments: got %s, need at least %s',
observed,
observed + '',
required + ''
)
);
}
};
// make sure all the required arguments are present.
self.requiredArguments = function requiredArguments(
argv,
demandedOptions: Dictionary<string | undefined>
) {
let missing: Dictionary<string | undefined> | null = null;
for (const key of Object.keys(demandedOptions)) {
if (
!Object.prototype.hasOwnProperty.call(argv, key) ||
typeof argv[key] === 'undefined'
) {
missing = missing || {};
missing[key] = demandedOptions[key];
}
}
if (missing) {
const customMsgs: string[] = [];
for (const key of Object.keys(missing)) {
const msg = missing[key];
if (msg && customMsgs.indexOf(msg) < 0) {
customMsgs.push(msg);
}
}
const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
usage.fail(
__n(
'Missing required argument: %s',
'Missing required arguments: %s',
Object.keys(missing).length,
Object.keys(missing).join(', ') + customMsg
)
);
}
};
// check for unknown arguments (strict-mode).
self.unknownArguments = function unknownArguments(
argv,
aliases,
positionalMap,
isDefaultCommand,
checkPositionals = true
) {
const commandKeys = yargs
.getInternalMethods()
.getCommandInstance()
.getCommands();
const unknown: string[] = [];
const currentContext = yargs.getInternalMethods().getContext();
Object.keys(argv).forEach(key => {
if (
!specialKeys.includes(key) &&
!Object.prototype.hasOwnProperty.call(positionalMap, key) &&
!Object.prototype.hasOwnProperty.call(
yargs.getInternalMethods().getParseContext(),
key
) &&
!self.isValidAndSomeAliasIsNotNew(key, aliases)
) {
unknown.push(key);
}
});
if (
checkPositionals &&
(currentContext.commands.length > 0 ||
commandKeys.length > 0 ||
isDefaultCommand)
) {
argv._.slice(currentContext.commands.length).forEach(key => {
if (!commandKeys.includes('' + key)) {
unknown.push('' + key);
}
});
}
// https://github.com/yargs/yargs/issues/1861
if (checkPositionals) {
// Check for non-option args that are not in currentContext.commands
// Take into account expected args from commands and yargs.demand(number)
const demandedCommands = yargs.getDemandedCommands();
const maxNonOptDemanded = demandedCommands._?.max || 0;
const expected = currentContext.commands.length + maxNonOptDemanded;
if (expected < argv._.length) {
argv._.slice(expected).forEach(key => {
key = String(key);
if (
!currentContext.commands.includes(key) &&
!unknown.includes(key)
) {
unknown.push(key);
}
});
}
}
if (unknown.length) {
usage.fail(
__n(
'Unknown argument: %s',
'Unknown arguments: %s',
unknown.length,
unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', ')
)
);
}
};
self.unknownCommands = function unknownCommands(argv) {
const commandKeys = yargs
.getInternalMethods()
.getCommandInstance()
.getCommands();
const unknown: string[] = [];
const currentContext = yargs.getInternalMethods().getContext();
if (currentContext.commands.length > 0 || commandKeys.length > 0) {
argv._.slice(currentContext.commands.length).forEach(key => {
if (!commandKeys.includes('' + key)) {
unknown.push('' + key);
}
});
}
if (unknown.length > 0) {
usage.fail(
__n(
'Unknown command: %s',
'Unknown commands: %s',
unknown.length,
unknown.join(', ')
)
);
return true;
} else {
return false;
}
};
// check for a key that is not an alias, or for which every alias is new,
// implying that it was invented by the parser, e.g., during camelization
self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(
key,
aliases
) {
if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
return false;
}
const newAliases = (yargs.parsed as DetailedArguments).newAliases;
return [key, ...aliases[key]].some(
a =>
!Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]
);
};
// validate arguments limited to enumerated choices
self.limitedChoices = function limitedChoices(argv) {
const options = yargs.getOptions();
const invalid: Dictionary<any[]> = {};
if (!Object.keys(options.choices).length) return;
Object.keys(argv).forEach(key => {
if (
specialKeys.indexOf(key) === -1 &&
Object.prototype.hasOwnProperty.call(options.choices, key)
) {
[].concat(argv[key]).forEach(value => {
// TODO case-insensitive configurability
if (
options.choices[key].indexOf(value) === -1 &&
value !== undefined
) {
invalid[key] = (invalid[key] || []).concat(value);
}
});
}
});
const invalidKeys = Object.keys(invalid);
if (!invalidKeys.length) return;
let msg = __('Invalid values:');
invalidKeys.forEach(key => {
msg += `\n ${__(
'Argument: %s, Given: %s, Choices: %s',
key,
usage.stringifiedValues(invalid[key]),
usage.stringifiedValues(options.choices[key])
)}`;
});
usage.fail(msg);
};
// check implications, argument foo implies => argument bar.
let implied: Dictionary<KeyOrPos[]> = {};
self.implies = function implies(key, value) {
argsert(
'<string|object> [array|number|string]',
[key, value],
arguments.length
);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
self.implies(k, key[k]);
});
} else {
yargs.global(key);
if (!implied[key]) {
implied[key] = [];
}
if (Array.isArray(value)) {
value.forEach(i => self.implies(key, i));
} else {
assertNotStrictEqual(value, undefined, shim);
implied[key].push(value);
}
}
};
self.getImplied = function getImplied() {
return implied;
};
function keyExists(argv: Arguments, val: any): any {
// convert string '1' to number 1
const num = Number(val);
val = isNaN(num) ? val : num;
if (typeof val === 'number') {
// check length of argv._
val = argv._.length >= val;
} else if (val.match(/^--no-.+/)) {
// check if key/value doesn't exist
val = val.match(/^--no-(.+)/)[1];
val = !Object.prototype.hasOwnProperty.call(argv, val);
} else {
// check if key/value exists
val = Object.prototype.hasOwnProperty.call(argv, val);
}
return val;
}
self.implications = function implications(argv) {
const implyFail: string[] = [];
Object.keys(implied).forEach(key => {
const origKey = key;
(implied[key] || []).forEach(value => {
let key = origKey;
const origValue = value;
key = keyExists(argv, key);
value = keyExists(argv, value);
if (key && !value) {
implyFail.push(` ${origKey} -> ${origValue}`);
}
});
});
if (implyFail.length) {
let msg = `${__('Implications failed:')}\n`;
implyFail.forEach(value => {
msg += value;
});
usage.fail(msg);
}
};
let conflicting: Dictionary<(string | undefined)[]> = {};
self.conflicts = function conflicts(key, value) {
argsert('<string|object> [array|string]', [key, value], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
self.conflicts(k, key[k]);
});
} else {
yargs.global(key);
if (!conflicting[key]) {
conflicting[key] = [];
}
if (Array.isArray(value)) {
value.forEach(i => self.conflicts(key, i));
} else {
conflicting[key].push(value);
}
}
};
self.getConflicting = () => conflicting;
self.conflicting = function conflictingFn(argv) {
Object.keys(argv).forEach(key => {
if (conflicting[key]) {
conflicting[key].forEach(value => {
// we default keys to 'undefined' that have been configured, we should not
// apply conflicting check unless they are a value other than 'undefined'.
if (value && argv[key] !== undefined && argv[value] !== undefined) {
usage.fail(
__('Arguments %s and %s are mutually exclusive', key, value)
);
}
});
}
});
// When strip-dashed is true, match conflicts (kebab) with argv (camel)
// Addresses: https://github.com/yargs/yargs/issues/1952
if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) {
Object.keys(conflicting).forEach(key => {
conflicting[key].forEach(value => {
if (
value &&
argv[shim.Parser.camelCase(key)] !== undefined &&
argv[shim.Parser.camelCase(value)] !== undefined
) {
usage.fail(
__('Arguments %s and %s are mutually exclusive', key, value)
);
}
});
});
}
};
self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
const threshold = 3; // if it takes more than three edits, let's move on.
potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
let recommended = null;
let bestDistance = Infinity;
for (
let i = 0, candidate;
(candidate = potentialCommands[i]) !== undefined;
i++
) {
const d = distance(cmd, candidate);
if (d <= threshold && d < bestDistance) {
bestDistance = d;
recommended = candidate;
}
}
if (recommended) usage.fail(__('Did you mean %s?', recommended));
};
self.reset = function reset(localLookup) {
implied = objFilter(implied, k => !localLookup[k]);
conflicting = objFilter(conflicting, k => !localLookup[k]);
return self;
};
const frozens: FrozenValidationInstance[] = [];
self.freeze = function freeze() {
frozens.push({
implied,
conflicting,
});
};
self.unfreeze = function unfreeze() {
const frozen = frozens.pop();
assertNotStrictEqual(frozen, undefined, shim);
({implied, conflicting} = frozen);
};
return self;
} | interface PlatformShim {
cwd: Function;
format: Function;
normalize: Function;
require: Function;
resolve: Function;
env: Function;
} |
2,858 | function validation(
yargs: YargsInstance,
usage: UsageInstance,
shim: PlatformShim
) {
const __ = shim.y18n.__;
const __n = shim.y18n.__n;
const self = {} as ValidationInstance;
// validate appropriate # of non-option
// arguments were provided, i.e., '_'.
self.nonOptionCount = function nonOptionCount(argv) {
const demandedCommands = yargs.getDemandedCommands();
// don't count currently executing commands
const positionalCount =
argv._.length + (argv['--'] ? argv['--'].length : 0);
const _s =
positionalCount - yargs.getInternalMethods().getContext().commands.length;
if (
demandedCommands._ &&
(_s < demandedCommands._.min || _s > demandedCommands._.max)
) {
if (_s < demandedCommands._.min) {
if (demandedCommands._.minMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.minMsg
? demandedCommands._.minMsg
.replace(/\$0/g, _s.toString())
.replace(/\$1/, demandedCommands._.min.toString())
: null
);
} else {
usage.fail(
__n(
'Not enough non-option arguments: got %s, need at least %s',
'Not enough non-option arguments: got %s, need at least %s',
_s,
_s.toString(),
demandedCommands._.min.toString()
)
);
}
} else if (_s > demandedCommands._.max) {
if (demandedCommands._.maxMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.maxMsg
? demandedCommands._.maxMsg
.replace(/\$0/g, _s.toString())
.replace(/\$1/, demandedCommands._.max.toString())
: null
);
} else {
usage.fail(
__n(
'Too many non-option arguments: got %s, maximum of %s',
'Too many non-option arguments: got %s, maximum of %s',
_s,
_s.toString(),
demandedCommands._.max.toString()
)
);
}
}
}
};
// validate the appropriate # of <required>
// positional arguments were provided:
self.positionalCount = function positionalCount(required, observed) {
if (observed < required) {
usage.fail(
__n(
'Not enough non-option arguments: got %s, need at least %s',
'Not enough non-option arguments: got %s, need at least %s',
observed,
observed + '',
required + ''
)
);
}
};
// make sure all the required arguments are present.
self.requiredArguments = function requiredArguments(
argv,
demandedOptions: Dictionary<string | undefined>
) {
let missing: Dictionary<string | undefined> | null = null;
for (const key of Object.keys(demandedOptions)) {
if (
!Object.prototype.hasOwnProperty.call(argv, key) ||
typeof argv[key] === 'undefined'
) {
missing = missing || {};
missing[key] = demandedOptions[key];
}
}
if (missing) {
const customMsgs: string[] = [];
for (const key of Object.keys(missing)) {
const msg = missing[key];
if (msg && customMsgs.indexOf(msg) < 0) {
customMsgs.push(msg);
}
}
const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
usage.fail(
__n(
'Missing required argument: %s',
'Missing required arguments: %s',
Object.keys(missing).length,
Object.keys(missing).join(', ') + customMsg
)
);
}
};
// check for unknown arguments (strict-mode).
self.unknownArguments = function unknownArguments(
argv,
aliases,
positionalMap,
isDefaultCommand,
checkPositionals = true
) {
const commandKeys = yargs
.getInternalMethods()
.getCommandInstance()
.getCommands();
const unknown: string[] = [];
const currentContext = yargs.getInternalMethods().getContext();
Object.keys(argv).forEach(key => {
if (
!specialKeys.includes(key) &&
!Object.prototype.hasOwnProperty.call(positionalMap, key) &&
!Object.prototype.hasOwnProperty.call(
yargs.getInternalMethods().getParseContext(),
key
) &&
!self.isValidAndSomeAliasIsNotNew(key, aliases)
) {
unknown.push(key);
}
});
if (
checkPositionals &&
(currentContext.commands.length > 0 ||
commandKeys.length > 0 ||
isDefaultCommand)
) {
argv._.slice(currentContext.commands.length).forEach(key => {
if (!commandKeys.includes('' + key)) {
unknown.push('' + key);
}
});
}
// https://github.com/yargs/yargs/issues/1861
if (checkPositionals) {
// Check for non-option args that are not in currentContext.commands
// Take into account expected args from commands and yargs.demand(number)
const demandedCommands = yargs.getDemandedCommands();
const maxNonOptDemanded = demandedCommands._?.max || 0;
const expected = currentContext.commands.length + maxNonOptDemanded;
if (expected < argv._.length) {
argv._.slice(expected).forEach(key => {
key = String(key);
if (
!currentContext.commands.includes(key) &&
!unknown.includes(key)
) {
unknown.push(key);
}
});
}
}
if (unknown.length) {
usage.fail(
__n(
'Unknown argument: %s',
'Unknown arguments: %s',
unknown.length,
unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', ')
)
);
}
};
self.unknownCommands = function unknownCommands(argv) {
const commandKeys = yargs
.getInternalMethods()
.getCommandInstance()
.getCommands();
const unknown: string[] = [];
const currentContext = yargs.getInternalMethods().getContext();
if (currentContext.commands.length > 0 || commandKeys.length > 0) {
argv._.slice(currentContext.commands.length).forEach(key => {
if (!commandKeys.includes('' + key)) {
unknown.push('' + key);
}
});
}
if (unknown.length > 0) {
usage.fail(
__n(
'Unknown command: %s',
'Unknown commands: %s',
unknown.length,
unknown.join(', ')
)
);
return true;
} else {
return false;
}
};
// check for a key that is not an alias, or for which every alias is new,
// implying that it was invented by the parser, e.g., during camelization
self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(
key,
aliases
) {
if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
return false;
}
const newAliases = (yargs.parsed as DetailedArguments).newAliases;
return [key, ...aliases[key]].some(
a =>
!Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]
);
};
// validate arguments limited to enumerated choices
self.limitedChoices = function limitedChoices(argv) {
const options = yargs.getOptions();
const invalid: Dictionary<any[]> = {};
if (!Object.keys(options.choices).length) return;
Object.keys(argv).forEach(key => {
if (
specialKeys.indexOf(key) === -1 &&
Object.prototype.hasOwnProperty.call(options.choices, key)
) {
[].concat(argv[key]).forEach(value => {
// TODO case-insensitive configurability
if (
options.choices[key].indexOf(value) === -1 &&
value !== undefined
) {
invalid[key] = (invalid[key] || []).concat(value);
}
});
}
});
const invalidKeys = Object.keys(invalid);
if (!invalidKeys.length) return;
let msg = __('Invalid values:');
invalidKeys.forEach(key => {
msg += `\n ${__(
'Argument: %s, Given: %s, Choices: %s',
key,
usage.stringifiedValues(invalid[key]),
usage.stringifiedValues(options.choices[key])
)}`;
});
usage.fail(msg);
};
// check implications, argument foo implies => argument bar.
let implied: Dictionary<KeyOrPos[]> = {};
self.implies = function implies(key, value) {
argsert(
'<string|object> [array|number|string]',
[key, value],
arguments.length
);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
self.implies(k, key[k]);
});
} else {
yargs.global(key);
if (!implied[key]) {
implied[key] = [];
}
if (Array.isArray(value)) {
value.forEach(i => self.implies(key, i));
} else {
assertNotStrictEqual(value, undefined, shim);
implied[key].push(value);
}
}
};
self.getImplied = function getImplied() {
return implied;
};
function keyExists(argv: Arguments, val: any): any {
// convert string '1' to number 1
const num = Number(val);
val = isNaN(num) ? val : num;
if (typeof val === 'number') {
// check length of argv._
val = argv._.length >= val;
} else if (val.match(/^--no-.+/)) {
// check if key/value doesn't exist
val = val.match(/^--no-(.+)/)[1];
val = !Object.prototype.hasOwnProperty.call(argv, val);
} else {
// check if key/value exists
val = Object.prototype.hasOwnProperty.call(argv, val);
}
return val;
}
self.implications = function implications(argv) {
const implyFail: string[] = [];
Object.keys(implied).forEach(key => {
const origKey = key;
(implied[key] || []).forEach(value => {
let key = origKey;
const origValue = value;
key = keyExists(argv, key);
value = keyExists(argv, value);
if (key && !value) {
implyFail.push(` ${origKey} -> ${origValue}`);
}
});
});
if (implyFail.length) {
let msg = `${__('Implications failed:')}\n`;
implyFail.forEach(value => {
msg += value;
});
usage.fail(msg);
}
};
let conflicting: Dictionary<(string | undefined)[]> = {};
self.conflicts = function conflicts(key, value) {
argsert('<string|object> [array|string]', [key, value], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
self.conflicts(k, key[k]);
});
} else {
yargs.global(key);
if (!conflicting[key]) {
conflicting[key] = [];
}
if (Array.isArray(value)) {
value.forEach(i => self.conflicts(key, i));
} else {
conflicting[key].push(value);
}
}
};
self.getConflicting = () => conflicting;
self.conflicting = function conflictingFn(argv) {
Object.keys(argv).forEach(key => {
if (conflicting[key]) {
conflicting[key].forEach(value => {
// we default keys to 'undefined' that have been configured, we should not
// apply conflicting check unless they are a value other than 'undefined'.
if (value && argv[key] !== undefined && argv[value] !== undefined) {
usage.fail(
__('Arguments %s and %s are mutually exclusive', key, value)
);
}
});
}
});
// When strip-dashed is true, match conflicts (kebab) with argv (camel)
// Addresses: https://github.com/yargs/yargs/issues/1952
if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) {
Object.keys(conflicting).forEach(key => {
conflicting[key].forEach(value => {
if (
value &&
argv[shim.Parser.camelCase(key)] !== undefined &&
argv[shim.Parser.camelCase(value)] !== undefined
) {
usage.fail(
__('Arguments %s and %s are mutually exclusive', key, value)
);
}
});
});
}
};
self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
const threshold = 3; // if it takes more than three edits, let's move on.
potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
let recommended = null;
let bestDistance = Infinity;
for (
let i = 0, candidate;
(candidate = potentialCommands[i]) !== undefined;
i++
) {
const d = distance(cmd, candidate);
if (d <= threshold && d < bestDistance) {
bestDistance = d;
recommended = candidate;
}
}
if (recommended) usage.fail(__('Did you mean %s?', recommended));
};
self.reset = function reset(localLookup) {
implied = objFilter(implied, k => !localLookup[k]);
conflicting = objFilter(conflicting, k => !localLookup[k]);
return self;
};
const frozens: FrozenValidationInstance[] = [];
self.freeze = function freeze() {
frozens.push({
implied,
conflicting,
});
};
self.unfreeze = function unfreeze() {
const frozen = frozens.pop();
assertNotStrictEqual(frozen, undefined, shim);
({implied, conflicting} = frozen);
};
return self;
} | interface PlatformShim {
assert: {
notStrictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
strictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
};
findUp: (
startDir: string,
fn: (dir: string[], names: string[]) => string | undefined
) => string;
getCallerFile: () => string;
getEnv: (key: string) => string | undefined;
getProcessArgvBin: () => string;
inspect: (obj: object) => string;
mainFilename: string;
requireDirectory: Function;
stringWidth: (str: string) => number;
cliui: Function;
Parser: Parser;
path: {
basename: (p1: string, p2?: string) => string;
extname: (path: string) => string;
dirname: (path: string) => string;
relative: (p1: string, p2: string) => string;
resolve: (p1: string, p2: string) => string;
};
process: {
argv: () => string[];
cwd: () => string;
emitWarning: (warning: string | Error, type?: string) => void;
execPath: () => string;
exit: (code: number) => void;
nextTick: (cb: Function) => void;
stdColumns: number | null;
};
readFileSync: (path: string, encoding: string) => string;
require: RequireType;
y18n: Y18N;
} |
2,859 | function validation(
yargs: YargsInstance,
usage: UsageInstance,
shim: PlatformShim
) {
const __ = shim.y18n.__;
const __n = shim.y18n.__n;
const self = {} as ValidationInstance;
// validate appropriate # of non-option
// arguments were provided, i.e., '_'.
self.nonOptionCount = function nonOptionCount(argv) {
const demandedCommands = yargs.getDemandedCommands();
// don't count currently executing commands
const positionalCount =
argv._.length + (argv['--'] ? argv['--'].length : 0);
const _s =
positionalCount - yargs.getInternalMethods().getContext().commands.length;
if (
demandedCommands._ &&
(_s < demandedCommands._.min || _s > demandedCommands._.max)
) {
if (_s < demandedCommands._.min) {
if (demandedCommands._.minMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.minMsg
? demandedCommands._.minMsg
.replace(/\$0/g, _s.toString())
.replace(/\$1/, demandedCommands._.min.toString())
: null
);
} else {
usage.fail(
__n(
'Not enough non-option arguments: got %s, need at least %s',
'Not enough non-option arguments: got %s, need at least %s',
_s,
_s.toString(),
demandedCommands._.min.toString()
)
);
}
} else if (_s > demandedCommands._.max) {
if (demandedCommands._.maxMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.maxMsg
? demandedCommands._.maxMsg
.replace(/\$0/g, _s.toString())
.replace(/\$1/, demandedCommands._.max.toString())
: null
);
} else {
usage.fail(
__n(
'Too many non-option arguments: got %s, maximum of %s',
'Too many non-option arguments: got %s, maximum of %s',
_s,
_s.toString(),
demandedCommands._.max.toString()
)
);
}
}
}
};
// validate the appropriate # of <required>
// positional arguments were provided:
self.positionalCount = function positionalCount(required, observed) {
if (observed < required) {
usage.fail(
__n(
'Not enough non-option arguments: got %s, need at least %s',
'Not enough non-option arguments: got %s, need at least %s',
observed,
observed + '',
required + ''
)
);
}
};
// make sure all the required arguments are present.
self.requiredArguments = function requiredArguments(
argv,
demandedOptions: Dictionary<string | undefined>
) {
let missing: Dictionary<string | undefined> | null = null;
for (const key of Object.keys(demandedOptions)) {
if (
!Object.prototype.hasOwnProperty.call(argv, key) ||
typeof argv[key] === 'undefined'
) {
missing = missing || {};
missing[key] = demandedOptions[key];
}
}
if (missing) {
const customMsgs: string[] = [];
for (const key of Object.keys(missing)) {
const msg = missing[key];
if (msg && customMsgs.indexOf(msg) < 0) {
customMsgs.push(msg);
}
}
const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
usage.fail(
__n(
'Missing required argument: %s',
'Missing required arguments: %s',
Object.keys(missing).length,
Object.keys(missing).join(', ') + customMsg
)
);
}
};
// check for unknown arguments (strict-mode).
self.unknownArguments = function unknownArguments(
argv,
aliases,
positionalMap,
isDefaultCommand,
checkPositionals = true
) {
const commandKeys = yargs
.getInternalMethods()
.getCommandInstance()
.getCommands();
const unknown: string[] = [];
const currentContext = yargs.getInternalMethods().getContext();
Object.keys(argv).forEach(key => {
if (
!specialKeys.includes(key) &&
!Object.prototype.hasOwnProperty.call(positionalMap, key) &&
!Object.prototype.hasOwnProperty.call(
yargs.getInternalMethods().getParseContext(),
key
) &&
!self.isValidAndSomeAliasIsNotNew(key, aliases)
) {
unknown.push(key);
}
});
if (
checkPositionals &&
(currentContext.commands.length > 0 ||
commandKeys.length > 0 ||
isDefaultCommand)
) {
argv._.slice(currentContext.commands.length).forEach(key => {
if (!commandKeys.includes('' + key)) {
unknown.push('' + key);
}
});
}
// https://github.com/yargs/yargs/issues/1861
if (checkPositionals) {
// Check for non-option args that are not in currentContext.commands
// Take into account expected args from commands and yargs.demand(number)
const demandedCommands = yargs.getDemandedCommands();
const maxNonOptDemanded = demandedCommands._?.max || 0;
const expected = currentContext.commands.length + maxNonOptDemanded;
if (expected < argv._.length) {
argv._.slice(expected).forEach(key => {
key = String(key);
if (
!currentContext.commands.includes(key) &&
!unknown.includes(key)
) {
unknown.push(key);
}
});
}
}
if (unknown.length) {
usage.fail(
__n(
'Unknown argument: %s',
'Unknown arguments: %s',
unknown.length,
unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', ')
)
);
}
};
self.unknownCommands = function unknownCommands(argv) {
const commandKeys = yargs
.getInternalMethods()
.getCommandInstance()
.getCommands();
const unknown: string[] = [];
const currentContext = yargs.getInternalMethods().getContext();
if (currentContext.commands.length > 0 || commandKeys.length > 0) {
argv._.slice(currentContext.commands.length).forEach(key => {
if (!commandKeys.includes('' + key)) {
unknown.push('' + key);
}
});
}
if (unknown.length > 0) {
usage.fail(
__n(
'Unknown command: %s',
'Unknown commands: %s',
unknown.length,
unknown.join(', ')
)
);
return true;
} else {
return false;
}
};
// check for a key that is not an alias, or for which every alias is new,
// implying that it was invented by the parser, e.g., during camelization
self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(
key,
aliases
) {
if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
return false;
}
const newAliases = (yargs.parsed as DetailedArguments).newAliases;
return [key, ...aliases[key]].some(
a =>
!Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]
);
};
// validate arguments limited to enumerated choices
self.limitedChoices = function limitedChoices(argv) {
const options = yargs.getOptions();
const invalid: Dictionary<any[]> = {};
if (!Object.keys(options.choices).length) return;
Object.keys(argv).forEach(key => {
if (
specialKeys.indexOf(key) === -1 &&
Object.prototype.hasOwnProperty.call(options.choices, key)
) {
[].concat(argv[key]).forEach(value => {
// TODO case-insensitive configurability
if (
options.choices[key].indexOf(value) === -1 &&
value !== undefined
) {
invalid[key] = (invalid[key] || []).concat(value);
}
});
}
});
const invalidKeys = Object.keys(invalid);
if (!invalidKeys.length) return;
let msg = __('Invalid values:');
invalidKeys.forEach(key => {
msg += `\n ${__(
'Argument: %s, Given: %s, Choices: %s',
key,
usage.stringifiedValues(invalid[key]),
usage.stringifiedValues(options.choices[key])
)}`;
});
usage.fail(msg);
};
// check implications, argument foo implies => argument bar.
let implied: Dictionary<KeyOrPos[]> = {};
self.implies = function implies(key, value) {
argsert(
'<string|object> [array|number|string]',
[key, value],
arguments.length
);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
self.implies(k, key[k]);
});
} else {
yargs.global(key);
if (!implied[key]) {
implied[key] = [];
}
if (Array.isArray(value)) {
value.forEach(i => self.implies(key, i));
} else {
assertNotStrictEqual(value, undefined, shim);
implied[key].push(value);
}
}
};
self.getImplied = function getImplied() {
return implied;
};
function keyExists(argv: Arguments, val: any): any {
// convert string '1' to number 1
const num = Number(val);
val = isNaN(num) ? val : num;
if (typeof val === 'number') {
// check length of argv._
val = argv._.length >= val;
} else if (val.match(/^--no-.+/)) {
// check if key/value doesn't exist
val = val.match(/^--no-(.+)/)[1];
val = !Object.prototype.hasOwnProperty.call(argv, val);
} else {
// check if key/value exists
val = Object.prototype.hasOwnProperty.call(argv, val);
}
return val;
}
self.implications = function implications(argv) {
const implyFail: string[] = [];
Object.keys(implied).forEach(key => {
const origKey = key;
(implied[key] || []).forEach(value => {
let key = origKey;
const origValue = value;
key = keyExists(argv, key);
value = keyExists(argv, value);
if (key && !value) {
implyFail.push(` ${origKey} -> ${origValue}`);
}
});
});
if (implyFail.length) {
let msg = `${__('Implications failed:')}\n`;
implyFail.forEach(value => {
msg += value;
});
usage.fail(msg);
}
};
let conflicting: Dictionary<(string | undefined)[]> = {};
self.conflicts = function conflicts(key, value) {
argsert('<string|object> [array|string]', [key, value], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
self.conflicts(k, key[k]);
});
} else {
yargs.global(key);
if (!conflicting[key]) {
conflicting[key] = [];
}
if (Array.isArray(value)) {
value.forEach(i => self.conflicts(key, i));
} else {
conflicting[key].push(value);
}
}
};
self.getConflicting = () => conflicting;
self.conflicting = function conflictingFn(argv) {
Object.keys(argv).forEach(key => {
if (conflicting[key]) {
conflicting[key].forEach(value => {
// we default keys to 'undefined' that have been configured, we should not
// apply conflicting check unless they are a value other than 'undefined'.
if (value && argv[key] !== undefined && argv[value] !== undefined) {
usage.fail(
__('Arguments %s and %s are mutually exclusive', key, value)
);
}
});
}
});
// When strip-dashed is true, match conflicts (kebab) with argv (camel)
// Addresses: https://github.com/yargs/yargs/issues/1952
if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) {
Object.keys(conflicting).forEach(key => {
conflicting[key].forEach(value => {
if (
value &&
argv[shim.Parser.camelCase(key)] !== undefined &&
argv[shim.Parser.camelCase(value)] !== undefined
) {
usage.fail(
__('Arguments %s and %s are mutually exclusive', key, value)
);
}
});
});
}
};
self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
const threshold = 3; // if it takes more than three edits, let's move on.
potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
let recommended = null;
let bestDistance = Infinity;
for (
let i = 0, candidate;
(candidate = potentialCommands[i]) !== undefined;
i++
) {
const d = distance(cmd, candidate);
if (d <= threshold && d < bestDistance) {
bestDistance = d;
recommended = candidate;
}
}
if (recommended) usage.fail(__('Did you mean %s?', recommended));
};
self.reset = function reset(localLookup) {
implied = objFilter(implied, k => !localLookup[k]);
conflicting = objFilter(conflicting, k => !localLookup[k]);
return self;
};
const frozens: FrozenValidationInstance[] = [];
self.freeze = function freeze() {
frozens.push({
implied,
conflicting,
});
};
self.unfreeze = function unfreeze() {
const frozen = frozens.pop();
assertNotStrictEqual(frozen, undefined, shim);
({implied, conflicting} = frozen);
};
return self;
} | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [function]',
[keys, value],
arguments.length
);
if (Array.isArray(keys)) {
if (!value) {
throw new YError('coerce callback must be provided');
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === 'object') {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError('coerce callback must be provided');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
argv[keys] = result;
const stripAliased = yargs
.getInternalMethods()
.getParserConfiguration()['strip-aliased'];
if (aliases[keys] && stripAliased !== true) {
for (const alias of aliases[keys]) {
argv[alias] = result;
}
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
argsert(
'[number] [number|string] [string|null|undefined] [string|null|undefined]',
[min, max, minMsg, maxMsg],
arguments.length
);
if (typeof max !== 'number') {
minMsg = max;
max = Infinity;
}
this.global('_', false);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
} else {
if (typeof msg === 'string') {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === 'undefined') {
this.demandOption(keys);
}
}
return this;
}
demandOption(
keys: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [object]', [key, opt], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
this.options(k, key[k]);
});
} else {
if (typeof opt !== 'object') {
opt = {};
}
this[kTrackManuallySetKeys](key);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) {
this[kEmitWarning](
[
'"version" is a reserved word.',
'Please do one of the following:',
'- Disable version with `yargs.version(false)` if using "version" as an option',
'- Use the built-in `yargs.version` method instead (if applicable)',
'- Use a different option key',
'https://yargs.js.org/docs/#api-reference-version',
].join('\n'),
undefined,
'versionWarning' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
if (opt.alias) this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
// A required option can be specified via "demand: true".
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(
key,
typeof opt.demandOption === 'string' ? opt.demandOption : undefined
);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ('default' in opt) {
this.default(key, opt.default);
}
if (opt.implies !== undefined) {
this.implies(key, opt.implies);
}
if (opt.nargs !== undefined) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === 'boolean') {
this.boolean(key);
if (opt.alias) this.boolean(opt.alias);
}
if (opt.array || opt.type === 'array') {
this.array(key);
if (opt.alias) this.array(opt.alias);
}
if (opt.number || opt.type === 'number') {
this.number(key);
if (opt.alias) this.number(opt.alias);
}
if (opt.string || opt.type === 'string') {
this.string(key);
if (opt.alias) this.string(opt.alias);
}
if (opt.count || opt.type === 'count') {
this.count(key);
}
if (typeof opt.global === 'boolean') {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.getDescriptions();
if (
!Object.prototype.hasOwnProperty.call(descriptions, key) ||
typeof desc === 'string'
) {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(
'.parseSync() must not be used with asynchronous builders, handlers, or middleware'
);
}
return maybePromise;
}
parserConfiguration(config: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.cmdToParseOptions(fullCommand)
: {
array: [],
alias: {},
default: {},
demand: {},
};
objectKeys(parseOptions).forEach(pk => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1) opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key];
}
});
this.group(key, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
if ((msg || '').match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(
'.usage() description must start with $0 if being used as alias for .command()'
);
}
} else {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands:
this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this),
};
}
[kGetCommandInstance](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
if (calledFromCommand) return argv;
if (isPromise(argv)) return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers =
this[kGetParserConfiguration]()['parse-positional-numbers'] ||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
cmd = String(argv._[i]);
if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,860 | function keyExists(argv: Arguments, val: any): any {
// convert string '1' to number 1
const num = Number(val);
val = isNaN(num) ? val : num;
if (typeof val === 'number') {
// check length of argv._
val = argv._.length >= val;
} else if (val.match(/^--no-.+/)) {
// check if key/value doesn't exist
val = val.match(/^--no-(.+)/)[1];
val = !Object.prototype.hasOwnProperty.call(argv, val);
} else {
// check if key/value exists
val = Object.prototype.hasOwnProperty.call(argv, val);
}
return val;
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,861 | function keyExists(argv: Arguments, val: any): any {
// convert string '1' to number 1
const num = Number(val);
val = isNaN(num) ? val : num;
if (typeof val === 'number') {
// check length of argv._
val = argv._.length >= val;
} else if (val.match(/^--no-.+/)) {
// check if key/value doesn't exist
val = val.match(/^--no-(.+)/)[1];
val = !Object.prototype.hasOwnProperty.call(argv, val);
} else {
// check if key/value exists
val = Object.prototype.hasOwnProperty.call(argv, val);
}
return val;
} | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,862 | function keyExists(argv: Arguments, val: any): any {
// convert string '1' to number 1
const num = Number(val);
val = isNaN(num) ? val : num;
if (typeof val === 'number') {
// check length of argv._
val = argv._.length >= val;
} else if (val.match(/^--no-.+/)) {
// check if key/value doesn't exist
val = val.match(/^--no-(.+)/)[1];
val = !Object.prototype.hasOwnProperty.call(argv, val);
} else {
// check if key/value exists
val = Object.prototype.hasOwnProperty.call(argv, val);
}
return val;
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,863 | conflicting(argv: Arguments): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,864 | conflicting(argv: Arguments): void | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,865 | conflicting(argv: Arguments): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,866 | implications(argv: Arguments): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,867 | implications(argv: Arguments): void | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,868 | implications(argv: Arguments): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,869 | limitedChoices(argv: Arguments): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,870 | limitedChoices(argv: Arguments): void | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,871 | limitedChoices(argv: Arguments): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,872 | nonOptionCount(argv: Arguments): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,873 | nonOptionCount(argv: Arguments): void | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,874 | nonOptionCount(argv: Arguments): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,875 | requiredArguments(
argv: Arguments,
demandedOptions: Dictionary<string | undefined>
): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,876 | requiredArguments(
argv: Arguments,
demandedOptions: Dictionary<string | undefined>
): void | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,877 | requiredArguments(
argv: Arguments,
demandedOptions: Dictionary<string | undefined>
): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,878 | reset(localLookup: Dictionary): ValidationInstance | type Dictionary<T = any> = {[key: string]: T}; |
2,879 | unknownArguments(
argv: Arguments,
aliases: DetailedArguments['aliases'],
positionalMap: Dictionary,
isDefaultCommand: boolean,
checkPositionals?: boolean
): void | type Dictionary<T = any> = {[key: string]: T}; |
2,880 | unknownArguments(
argv: Arguments,
aliases: DetailedArguments['aliases'],
positionalMap: Dictionary,
isDefaultCommand: boolean,
checkPositionals?: boolean
): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,881 | unknownArguments(
argv: Arguments,
aliases: DetailedArguments['aliases'],
positionalMap: Dictionary,
isDefaultCommand: boolean,
checkPositionals?: boolean
): void | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,882 | unknownArguments(
argv: Arguments,
aliases: DetailedArguments['aliases'],
positionalMap: Dictionary,
isDefaultCommand: boolean,
checkPositionals?: boolean
): void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,883 | unknownCommands(argv: Arguments): boolean | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,884 | unknownCommands(argv: Arguments): boolean | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,885 | unknownCommands(argv: Arguments): boolean | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,886 | function YargsFactory(_shim: PlatformShim) {
return (
processArgs: string | string[] = [],
cwd = _shim.process.cwd(),
parentRequire?: RequireType
): YargsInstance => {
const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim);
// Legacy yargs.argv interface, it's recommended that you use .parse().
Object.defineProperty(yargs, 'argv', {
get: () => {
return yargs.parse();
},
enumerable: true,
});
// an app should almost always have --version and --help,
// if you *really* want to disable this use .help(false)/.version(false).
yargs.help();
yargs.version();
return yargs;
};
} | interface PlatformShim {
cwd: Function;
format: Function;
normalize: Function;
require: Function;
resolve: Function;
env: Function;
} |
2,887 | function YargsFactory(_shim: PlatformShim) {
return (
processArgs: string | string[] = [],
cwd = _shim.process.cwd(),
parentRequire?: RequireType
): YargsInstance => {
const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim);
// Legacy yargs.argv interface, it's recommended that you use .parse().
Object.defineProperty(yargs, 'argv', {
get: () => {
return yargs.parse();
},
enumerable: true,
});
// an app should almost always have --version and --help,
// if you *really* want to disable this use .help(false)/.version(false).
yargs.help();
yargs.version();
return yargs;
};
} | interface PlatformShim {
assert: {
notStrictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
strictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
};
findUp: (
startDir: string,
fn: (dir: string[], names: string[]) => string | undefined
) => string;
getCallerFile: () => string;
getEnv: (key: string) => string | undefined;
getProcessArgvBin: () => string;
inspect: (obj: object) => string;
mainFilename: string;
requireDirectory: Function;
stringWidth: (str: string) => number;
cliui: Function;
Parser: Parser;
path: {
basename: (p1: string, p2?: string) => string;
extname: (path: string) => string;
dirname: (path: string) => string;
relative: (p1: string, p2: string) => string;
resolve: (p1: string, p2: string) => string;
};
process: {
argv: () => string[];
cwd: () => string;
emitWarning: (warning: string | Error, type?: string) => void;
execPath: () => string;
exit: (code: number) => void;
nextTick: (cb: Function) => void;
stdColumns: number | null;
};
readFileSync: (path: string, encoding: string) => string;
require: RequireType;
y18n: Y18N;
} |
2,888 | reset(aliases?: Aliases): YargsInstance | interface Aliases {
[key: string]: Array<string>;
} |
2,889 | (argv: Arguments) => void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,890 | (argv: Arguments) => void | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,891 | (argv: Arguments) => void | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,892 | (argv: Arguments, options: Options) => any | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,893 | (argv: Arguments, options: Options) => any | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,894 | (argv: Arguments, options: Options) => any | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,895 | (argv: Arguments, options: Options) => any | interface Options extends ParserOptions {
__: (format: any, ...param: any[]) => string;
alias: Dictionary<string[]>;
array: string[];
boolean: string[];
choices: Dictionary<string[]>;
config: Dictionary<ConfigCallback | boolean>;
configObjects: Dictionary[];
configuration: Configuration;
count: string[];
defaultDescription: Dictionary<string | undefined>;
demandedCommands: Dictionary<{
min: number;
max: number;
minMsg?: string | null;
maxMsg?: string | null;
}>;
demandedOptions: Dictionary<string | undefined>;
deprecatedOptions: Dictionary<string | boolean | undefined>;
hiddenOptions: string[];
/** Manually set keys */
key: Dictionary<boolean | string>;
local: string[];
normalize: string[];
number: string[];
showHiddenOpt: string;
skipValidation: string[];
string: string[];
} |
2,896 | (argv: Arguments, options: Options) => any | interface Options {
/** An object representing the set of aliases for a key: `{ alias: { foo: ['f']} }`. */
alias: Dictionary<string | string[]>;
/**
* Indicate that keys should be parsed as an array: `{ array: ['foo', 'bar'] }`.
* Indicate that keys should be parsed as an array and coerced to booleans / numbers:
* { array: [ { key: 'foo', boolean: true }, {key: 'bar', number: true} ] }`.
*/
array: ArrayOption | ArrayOption[];
/** Arguments should be parsed as booleans: `{ boolean: ['x', 'y'] }`. */
boolean: string | string[];
/** Indicate a key that represents a path to a configuration file (this file will be loaded and parsed). */
config: string | string[] | Dictionary<boolean | ConfigCallback>;
/** configuration objects to parse, their properties will be set as arguments */
configObjects: Dictionary<any>[];
/** Provide configuration options to the yargs-parser. */
configuration: Partial<Configuration>;
/**
* Provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error), e.g.
* `{ coerce: { foo: function (arg) { return modifiedArg } } }`.
*/
coerce: Dictionary<CoerceCallback>;
/** Indicate a key that should be used as a counter, e.g., `-vvv = {v: 3}`. */
count: string | string[];
/** Provide default values for keys: `{ default: { x: 33, y: 'hello world!' } }`. */
default: Dictionary<any>;
/** Environment variables (`process.env`) with the prefix provided should be parsed. */
envPrefix?: string;
/** Specify that a key requires n arguments: `{ narg: {x: 2} }`. */
narg: Dictionary<number>;
/** `path.normalize()` will be applied to values set to this key. */
normalize: string | string[];
/** Keys should be treated as strings (even if they resemble a number `-x 33`). */
string: string | string[];
/** Keys should be treated as numbers. */
number: string | string[];
/** i18n handler, defaults to util.format */
__: (format: any, ...param: any[]) => string;
/** alias lookup table defaults */
key: Dictionary<any>;
} |
2,897 | (
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,898 | (
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
} | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,899 | (
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.