format: prettify entire project
This commit is contained in:
104
node_modules/yargs/build/lib/argsert.js
generated
vendored
104
node_modules/yargs/build/lib/argsert.js
generated
vendored
@ -2,61 +2,63 @@ import { YError } from './yerror.js';
|
||||
import { parseCommand } from './parse-command.js';
|
||||
const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
|
||||
export function argsert(arg1, arg2, arg3) {
|
||||
function parseArgs() {
|
||||
return typeof arg1 === 'object'
|
||||
? [{ demanded: [], optional: [] }, arg1, arg2]
|
||||
: [
|
||||
parseCommand(`cmd ${arg1}`),
|
||||
arg2,
|
||||
arg3,
|
||||
];
|
||||
function parseArgs() {
|
||||
return typeof arg1 === 'object' ?
|
||||
[{ demanded: [], optional: [] }, arg1, arg2]
|
||||
: [parseCommand(`cmd ${arg1}`), arg2, arg3];
|
||||
}
|
||||
try {
|
||||
let position = 0;
|
||||
const [parsed, callerArguments, _length] = parseArgs();
|
||||
const args = [].slice.call(callerArguments);
|
||||
while (args.length && args[args.length - 1] === undefined) args.pop();
|
||||
const length = _length || args.length;
|
||||
if (length < parsed.demanded.length) {
|
||||
throw new YError(
|
||||
`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`
|
||||
);
|
||||
}
|
||||
try {
|
||||
let position = 0;
|
||||
const [parsed, callerArguments, _length] = parseArgs();
|
||||
const args = [].slice.call(callerArguments);
|
||||
while (args.length && args[args.length - 1] === undefined)
|
||||
args.pop();
|
||||
const length = _length || args.length;
|
||||
if (length < parsed.demanded.length) {
|
||||
throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
|
||||
}
|
||||
const totalCommands = parsed.demanded.length + parsed.optional.length;
|
||||
if (length > totalCommands) {
|
||||
throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
|
||||
}
|
||||
parsed.demanded.forEach(demanded => {
|
||||
const arg = args.shift();
|
||||
const observedType = guessType(arg);
|
||||
const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*');
|
||||
if (matchingTypes.length === 0)
|
||||
argumentTypeError(observedType, demanded.cmd, position);
|
||||
position += 1;
|
||||
});
|
||||
parsed.optional.forEach(optional => {
|
||||
if (args.length === 0)
|
||||
return;
|
||||
const arg = args.shift();
|
||||
const observedType = guessType(arg);
|
||||
const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*');
|
||||
if (matchingTypes.length === 0)
|
||||
argumentTypeError(observedType, optional.cmd, position);
|
||||
position += 1;
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
console.warn(err.stack);
|
||||
const totalCommands = parsed.demanded.length + parsed.optional.length;
|
||||
if (length > totalCommands) {
|
||||
throw new YError(
|
||||
`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`
|
||||
);
|
||||
}
|
||||
parsed.demanded.forEach((demanded) => {
|
||||
const arg = args.shift();
|
||||
const observedType = guessType(arg);
|
||||
const matchingTypes = demanded.cmd.filter(
|
||||
(type) => type === observedType || type === '*'
|
||||
);
|
||||
if (matchingTypes.length === 0)
|
||||
argumentTypeError(observedType, demanded.cmd, position);
|
||||
position += 1;
|
||||
});
|
||||
parsed.optional.forEach((optional) => {
|
||||
if (args.length === 0) return;
|
||||
const arg = args.shift();
|
||||
const observedType = guessType(arg);
|
||||
const matchingTypes = optional.cmd.filter(
|
||||
(type) => type === observedType || type === '*'
|
||||
);
|
||||
if (matchingTypes.length === 0)
|
||||
argumentTypeError(observedType, optional.cmd, position);
|
||||
position += 1;
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn(err.stack);
|
||||
}
|
||||
}
|
||||
function guessType(arg) {
|
||||
if (Array.isArray(arg)) {
|
||||
return 'array';
|
||||
}
|
||||
else if (arg === null) {
|
||||
return 'null';
|
||||
}
|
||||
return typeof arg;
|
||||
if (Array.isArray(arg)) {
|
||||
return 'array';
|
||||
} else if (arg === null) {
|
||||
return 'null';
|
||||
}
|
||||
return typeof arg;
|
||||
}
|
||||
function argumentTypeError(observedType, allowedTypes, position) {
|
||||
throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`);
|
||||
throw new YError(
|
||||
`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`
|
||||
);
|
||||
}
|
||||
|
756
node_modules/yargs/build/lib/command.js
generated
vendored
756
node_modules/yargs/build/lib/command.js
generated
vendored
@ -1,382 +1,430 @@
|
||||
import { assertNotStrictEqual, } from './typings/common-types.js';
|
||||
import { assertNotStrictEqual } from './typings/common-types.js';
|
||||
import { isPromise } from './utils/is-promise.js';
|
||||
import { applyMiddleware, commandMiddlewareFactory, } from './middleware.js';
|
||||
import { applyMiddleware, commandMiddlewareFactory } from './middleware.js';
|
||||
import { parseCommand } from './parse-command.js';
|
||||
import { isYargsInstance, } from './yargs-factory.js';
|
||||
import { isYargsInstance } from './yargs-factory.js';
|
||||
import whichModule from './utils/which-module.js';
|
||||
const DEFAULT_MARKER = /(^\*)|(^\$0)/;
|
||||
export function command(yargs, usage, validation, globalMiddleware = [], shim) {
|
||||
const self = {};
|
||||
let handlers = {};
|
||||
let aliasMap = {};
|
||||
let defaultCommand;
|
||||
self.addHandler = function addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) {
|
||||
let aliases = [];
|
||||
const middlewares = commandMiddlewareFactory(commandMiddleware);
|
||||
handler = handler || (() => { });
|
||||
if (Array.isArray(cmd)) {
|
||||
if (isCommandAndAliases(cmd)) {
|
||||
[cmd, ...aliases] = cmd;
|
||||
}
|
||||
else {
|
||||
for (const command of cmd) {
|
||||
self.addHandler(command);
|
||||
}
|
||||
}
|
||||
const self = {};
|
||||
let handlers = {};
|
||||
let aliasMap = {};
|
||||
let defaultCommand;
|
||||
self.addHandler = function addHandler(
|
||||
cmd,
|
||||
description,
|
||||
builder,
|
||||
handler,
|
||||
commandMiddleware,
|
||||
deprecated
|
||||
) {
|
||||
let aliases = [];
|
||||
const middlewares = commandMiddlewareFactory(commandMiddleware);
|
||||
handler = handler || (() => {});
|
||||
if (Array.isArray(cmd)) {
|
||||
if (isCommandAndAliases(cmd)) {
|
||||
[cmd, ...aliases] = cmd;
|
||||
} else {
|
||||
for (const command of cmd) {
|
||||
self.addHandler(command);
|
||||
}
|
||||
else if (isCommandHandlerDefinition(cmd)) {
|
||||
let command = Array.isArray(cmd.command) || typeof cmd.command === 'string'
|
||||
? cmd.command
|
||||
: moduleName(cmd);
|
||||
if (cmd.aliases)
|
||||
command = [].concat(command).concat(cmd.aliases);
|
||||
self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
|
||||
return;
|
||||
}
|
||||
else if (isCommandBuilderDefinition(builder)) {
|
||||
self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
|
||||
return;
|
||||
}
|
||||
if (typeof cmd === 'string') {
|
||||
const parsedCommand = parseCommand(cmd);
|
||||
aliases = aliases.map(alias => parseCommand(alias).cmd);
|
||||
let isDefault = false;
|
||||
const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => {
|
||||
if (DEFAULT_MARKER.test(c)) {
|
||||
isDefault = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (parsedAliases.length === 0 && isDefault)
|
||||
parsedAliases.push('$0');
|
||||
if (isDefault) {
|
||||
parsedCommand.cmd = parsedAliases[0];
|
||||
aliases = parsedAliases.slice(1);
|
||||
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
|
||||
}
|
||||
aliases.forEach(alias => {
|
||||
aliasMap[alias] = parsedCommand.cmd;
|
||||
});
|
||||
if (description !== false) {
|
||||
usage.command(cmd, description, isDefault, aliases, deprecated);
|
||||
}
|
||||
handlers[parsedCommand.cmd] = {
|
||||
original: cmd,
|
||||
description,
|
||||
handler,
|
||||
builder: builder || {},
|
||||
middlewares,
|
||||
deprecated,
|
||||
demanded: parsedCommand.demanded,
|
||||
optional: parsedCommand.optional,
|
||||
};
|
||||
if (isDefault)
|
||||
defaultCommand = handlers[parsedCommand.cmd];
|
||||
}
|
||||
};
|
||||
self.addDirectory = function addDirectory(dir, context, req, callerFile, opts) {
|
||||
opts = opts || {};
|
||||
if (typeof opts.recurse !== 'boolean')
|
||||
opts.recurse = false;
|
||||
if (!Array.isArray(opts.extensions))
|
||||
opts.extensions = ['js'];
|
||||
const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o;
|
||||
opts.visit = function visit(obj, joined, filename) {
|
||||
const visited = parentVisit(obj, joined, filename);
|
||||
if (visited) {
|
||||
if (~context.files.indexOf(joined))
|
||||
return visited;
|
||||
context.files.push(joined);
|
||||
self.addHandler(visited);
|
||||
}
|
||||
return visited;
|
||||
};
|
||||
shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
|
||||
};
|
||||
function moduleName(obj) {
|
||||
const mod = whichModule(obj);
|
||||
if (!mod)
|
||||
throw new Error(`No command name given for module: ${shim.inspect(obj)}`);
|
||||
return commandFromFilename(mod.filename);
|
||||
}
|
||||
} else if (isCommandHandlerDefinition(cmd)) {
|
||||
let command =
|
||||
Array.isArray(cmd.command) || typeof cmd.command === 'string' ?
|
||||
cmd.command
|
||||
: moduleName(cmd);
|
||||
if (cmd.aliases) command = [].concat(command).concat(cmd.aliases);
|
||||
self.addHandler(
|
||||
command,
|
||||
extractDesc(cmd),
|
||||
cmd.builder,
|
||||
cmd.handler,
|
||||
cmd.middlewares,
|
||||
cmd.deprecated
|
||||
);
|
||||
return;
|
||||
} else if (isCommandBuilderDefinition(builder)) {
|
||||
self.addHandler(
|
||||
[cmd].concat(aliases),
|
||||
description,
|
||||
builder.builder,
|
||||
builder.handler,
|
||||
builder.middlewares,
|
||||
builder.deprecated
|
||||
);
|
||||
return;
|
||||
}
|
||||
function commandFromFilename(filename) {
|
||||
return shim.path.basename(filename, shim.path.extname(filename));
|
||||
if (typeof cmd === 'string') {
|
||||
const parsedCommand = parseCommand(cmd);
|
||||
aliases = aliases.map((alias) => parseCommand(alias).cmd);
|
||||
let isDefault = false;
|
||||
const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => {
|
||||
if (DEFAULT_MARKER.test(c)) {
|
||||
isDefault = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (parsedAliases.length === 0 && isDefault) parsedAliases.push('$0');
|
||||
if (isDefault) {
|
||||
parsedCommand.cmd = parsedAliases[0];
|
||||
aliases = parsedAliases.slice(1);
|
||||
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
|
||||
}
|
||||
aliases.forEach((alias) => {
|
||||
aliasMap[alias] = parsedCommand.cmd;
|
||||
});
|
||||
if (description !== false) {
|
||||
usage.command(cmd, description, isDefault, aliases, deprecated);
|
||||
}
|
||||
handlers[parsedCommand.cmd] = {
|
||||
original: cmd,
|
||||
description,
|
||||
handler,
|
||||
builder: builder || {},
|
||||
middlewares,
|
||||
deprecated,
|
||||
demanded: parsedCommand.demanded,
|
||||
optional: parsedCommand.optional,
|
||||
};
|
||||
if (isDefault) defaultCommand = handlers[parsedCommand.cmd];
|
||||
}
|
||||
function extractDesc({ describe, description, desc, }) {
|
||||
for (const test of [describe, description, desc]) {
|
||||
if (typeof test === 'string' || test === false)
|
||||
return test;
|
||||
assertNotStrictEqual(test, true, shim);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap));
|
||||
self.getCommandHandlers = () => handlers;
|
||||
self.hasDefaultCommand = () => !!defaultCommand;
|
||||
self.runCommand = function runCommand(command, yargs, parsed, commandIndex) {
|
||||
let aliases = parsed.aliases;
|
||||
const commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand;
|
||||
const currentContext = yargs.getContext();
|
||||
let numFiles = currentContext.files.length;
|
||||
const parentCommands = currentContext.commands.slice();
|
||||
let innerArgv = parsed.argv;
|
||||
let positionalMap = {};
|
||||
if (command) {
|
||||
currentContext.commands.push(command);
|
||||
currentContext.fullCommands.push(commandHandler.original);
|
||||
}
|
||||
const builder = commandHandler.builder;
|
||||
if (isCommandBuilderCallback(builder)) {
|
||||
const builderOutput = builder(yargs.reset(parsed.aliases));
|
||||
const innerYargs = isYargsInstance(builderOutput) ? builderOutput : yargs;
|
||||
if (shouldUpdateUsage(innerYargs)) {
|
||||
innerYargs
|
||||
.getUsageInstance()
|
||||
.usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
|
||||
}
|
||||
innerArgv = innerYargs._parseArgs(null, null, true, commandIndex);
|
||||
aliases = innerYargs.parsed.aliases;
|
||||
}
|
||||
else if (isCommandBuilderOptionDefinitions(builder)) {
|
||||
const innerYargs = yargs.reset(parsed.aliases);
|
||||
if (shouldUpdateUsage(innerYargs)) {
|
||||
innerYargs
|
||||
.getUsageInstance()
|
||||
.usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
|
||||
}
|
||||
Object.keys(commandHandler.builder).forEach(key => {
|
||||
innerYargs.option(key, builder[key]);
|
||||
});
|
||||
innerArgv = innerYargs._parseArgs(null, null, true, commandIndex);
|
||||
aliases = innerYargs.parsed.aliases;
|
||||
}
|
||||
if (!yargs._hasOutput()) {
|
||||
positionalMap = populatePositionals(commandHandler, innerArgv, currentContext);
|
||||
}
|
||||
const middlewares = globalMiddleware
|
||||
.slice(0)
|
||||
.concat(commandHandler.middlewares);
|
||||
applyMiddleware(innerArgv, yargs, middlewares, true);
|
||||
if (!yargs._hasOutput()) {
|
||||
yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error, !command);
|
||||
}
|
||||
if (commandHandler.handler && !yargs._hasOutput()) {
|
||||
yargs._setHasOutput();
|
||||
const populateDoubleDash = !!yargs.getOptions().configuration['populate--'];
|
||||
yargs._postProcess(innerArgv, populateDoubleDash);
|
||||
innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
|
||||
let handlerResult;
|
||||
if (isPromise(innerArgv)) {
|
||||
handlerResult = innerArgv.then(argv => commandHandler.handler(argv));
|
||||
}
|
||||
else {
|
||||
handlerResult = commandHandler.handler(innerArgv);
|
||||
}
|
||||
const handlerFinishCommand = yargs.getHandlerFinishCommand();
|
||||
if (isPromise(handlerResult)) {
|
||||
yargs.getUsageInstance().cacheHelpMessage();
|
||||
handlerResult
|
||||
.then(value => {
|
||||
if (handlerFinishCommand) {
|
||||
handlerFinishCommand(value);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
try {
|
||||
yargs.getUsageInstance().fail(null, error);
|
||||
}
|
||||
catch (err) {
|
||||
}
|
||||
})
|
||||
.then(() => {
|
||||
yargs.getUsageInstance().clearCachedHelpMessage();
|
||||
});
|
||||
}
|
||||
else {
|
||||
if (handlerFinishCommand) {
|
||||
handlerFinishCommand(handlerResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (command) {
|
||||
currentContext.commands.pop();
|
||||
currentContext.fullCommands.pop();
|
||||
}
|
||||
numFiles = currentContext.files.length - numFiles;
|
||||
if (numFiles > 0)
|
||||
currentContext.files.splice(numFiles * -1, numFiles);
|
||||
return innerArgv;
|
||||
};
|
||||
self.addDirectory = function addDirectory(
|
||||
dir,
|
||||
context,
|
||||
req,
|
||||
callerFile,
|
||||
opts
|
||||
) {
|
||||
opts = opts || {};
|
||||
if (typeof opts.recurse !== 'boolean') opts.recurse = false;
|
||||
if (!Array.isArray(opts.extensions)) opts.extensions = ['js'];
|
||||
const parentVisit =
|
||||
typeof opts.visit === 'function' ? opts.visit : (o) => o;
|
||||
opts.visit = function visit(obj, joined, filename) {
|
||||
const visited = parentVisit(obj, joined, filename);
|
||||
if (visited) {
|
||||
if (~context.files.indexOf(joined)) return visited;
|
||||
context.files.push(joined);
|
||||
self.addHandler(visited);
|
||||
}
|
||||
return visited;
|
||||
};
|
||||
function shouldUpdateUsage(yargs) {
|
||||
return (!yargs.getUsageInstance().getUsageDisabled() &&
|
||||
yargs.getUsageInstance().getUsage().length === 0);
|
||||
shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
|
||||
};
|
||||
function moduleName(obj) {
|
||||
const mod = whichModule(obj);
|
||||
if (!mod)
|
||||
throw new Error(`No command name given for module: ${shim.inspect(obj)}`);
|
||||
return commandFromFilename(mod.filename);
|
||||
}
|
||||
function commandFromFilename(filename) {
|
||||
return shim.path.basename(filename, shim.path.extname(filename));
|
||||
}
|
||||
function extractDesc({ describe, description, desc }) {
|
||||
for (const test of [describe, description, desc]) {
|
||||
if (typeof test === 'string' || test === false) return test;
|
||||
assertNotStrictEqual(test, true, shim);
|
||||
}
|
||||
function usageFromParentCommandsCommandHandler(parentCommands, 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(' ')}`;
|
||||
return false;
|
||||
}
|
||||
self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap));
|
||||
self.getCommandHandlers = () => handlers;
|
||||
self.hasDefaultCommand = () => !!defaultCommand;
|
||||
self.runCommand = function runCommand(command, yargs, parsed, commandIndex) {
|
||||
let aliases = parsed.aliases;
|
||||
const commandHandler =
|
||||
handlers[command] || handlers[aliasMap[command]] || defaultCommand;
|
||||
const currentContext = yargs.getContext();
|
||||
let numFiles = currentContext.files.length;
|
||||
const parentCommands = currentContext.commands.slice();
|
||||
let innerArgv = parsed.argv;
|
||||
let positionalMap = {};
|
||||
if (command) {
|
||||
currentContext.commands.push(command);
|
||||
currentContext.fullCommands.push(commandHandler.original);
|
||||
}
|
||||
self.runDefaultBuilderOn = function (yargs) {
|
||||
assertNotStrictEqual(defaultCommand, undefined, shim);
|
||||
if (shouldUpdateUsage(yargs)) {
|
||||
const commandString = DEFAULT_MARKER.test(defaultCommand.original)
|
||||
? defaultCommand.original
|
||||
: defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
|
||||
yargs.getUsageInstance().usage(commandString, defaultCommand.description);
|
||||
}
|
||||
const builder = defaultCommand.builder;
|
||||
if (isCommandBuilderCallback(builder)) {
|
||||
builder(yargs);
|
||||
}
|
||||
else if (!isCommandBuilderDefinition(builder)) {
|
||||
Object.keys(builder).forEach(key => {
|
||||
yargs.option(key, builder[key]);
|
||||
});
|
||||
}
|
||||
};
|
||||
function populatePositionals(commandHandler, argv, context) {
|
||||
argv._ = argv._.slice(context.commands.length);
|
||||
const demanded = commandHandler.demanded.slice(0);
|
||||
const optional = commandHandler.optional.slice(0);
|
||||
const positionalMap = {};
|
||||
validation.positionalCount(demanded.length, argv._.length);
|
||||
while (demanded.length) {
|
||||
const demand = demanded.shift();
|
||||
populatePositional(demand, argv, positionalMap);
|
||||
}
|
||||
while (optional.length) {
|
||||
const maybe = optional.shift();
|
||||
populatePositional(maybe, argv, positionalMap);
|
||||
}
|
||||
argv._ = context.commands.concat(argv._.map(a => '' + a));
|
||||
postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original));
|
||||
return positionalMap;
|
||||
const builder = commandHandler.builder;
|
||||
if (isCommandBuilderCallback(builder)) {
|
||||
const builderOutput = builder(yargs.reset(parsed.aliases));
|
||||
const innerYargs = isYargsInstance(builderOutput) ? builderOutput : yargs;
|
||||
if (shouldUpdateUsage(innerYargs)) {
|
||||
innerYargs
|
||||
.getUsageInstance()
|
||||
.usage(
|
||||
usageFromParentCommandsCommandHandler(
|
||||
parentCommands,
|
||||
commandHandler
|
||||
),
|
||||
commandHandler.description
|
||||
);
|
||||
}
|
||||
innerArgv = innerYargs._parseArgs(null, null, true, commandIndex);
|
||||
aliases = innerYargs.parsed.aliases;
|
||||
} else if (isCommandBuilderOptionDefinitions(builder)) {
|
||||
const innerYargs = yargs.reset(parsed.aliases);
|
||||
if (shouldUpdateUsage(innerYargs)) {
|
||||
innerYargs
|
||||
.getUsageInstance()
|
||||
.usage(
|
||||
usageFromParentCommandsCommandHandler(
|
||||
parentCommands,
|
||||
commandHandler
|
||||
),
|
||||
commandHandler.description
|
||||
);
|
||||
}
|
||||
Object.keys(commandHandler.builder).forEach((key) => {
|
||||
innerYargs.option(key, builder[key]);
|
||||
});
|
||||
innerArgv = innerYargs._parseArgs(null, null, true, commandIndex);
|
||||
aliases = innerYargs.parsed.aliases;
|
||||
}
|
||||
function populatePositional(positional, argv, positionalMap) {
|
||||
const cmd = positional.cmd[0];
|
||||
if (positional.variadic) {
|
||||
positionalMap[cmd] = argv._.splice(0).map(String);
|
||||
}
|
||||
else {
|
||||
if (argv._.length)
|
||||
positionalMap[cmd] = [String(argv._.shift())];
|
||||
}
|
||||
if (!yargs._hasOutput()) {
|
||||
positionalMap = populatePositionals(
|
||||
commandHandler,
|
||||
innerArgv,
|
||||
currentContext
|
||||
);
|
||||
}
|
||||
function postProcessPositionals(argv, positionalMap, parseOptions) {
|
||||
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 = {};
|
||||
const unparsed = [];
|
||||
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);
|
||||
});
|
||||
});
|
||||
if (!unparsed.length)
|
||||
return;
|
||||
const config = Object.assign({}, options.configuration, {
|
||||
'populate--': true,
|
||||
});
|
||||
const parsed = shim.Parser.detailed(unparsed, Object.assign({}, options, {
|
||||
configuration: config,
|
||||
}));
|
||||
if (parsed.error) {
|
||||
yargs.getUsageInstance().fail(parsed.error.message, parsed.error);
|
||||
}
|
||||
else {
|
||||
const positionalKeys = Object.keys(positionalMap);
|
||||
Object.keys(positionalMap).forEach(key => {
|
||||
positionalKeys.push(...parsed.aliases[key]);
|
||||
});
|
||||
Object.keys(parsed.argv).forEach(key => {
|
||||
if (positionalKeys.indexOf(key) !== -1) {
|
||||
if (!positionalMap[key])
|
||||
positionalMap[key] = parsed.argv[key];
|
||||
argv[key] = parsed.argv[key];
|
||||
}
|
||||
});
|
||||
}
|
||||
const middlewares = globalMiddleware
|
||||
.slice(0)
|
||||
.concat(commandHandler.middlewares);
|
||||
applyMiddleware(innerArgv, yargs, middlewares, true);
|
||||
if (!yargs._hasOutput()) {
|
||||
yargs._runValidation(
|
||||
innerArgv,
|
||||
aliases,
|
||||
positionalMap,
|
||||
yargs.parsed.error,
|
||||
!command
|
||||
);
|
||||
}
|
||||
self.cmdToParseOptions = function (cmdString) {
|
||||
const parseOptions = {
|
||||
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] = [];
|
||||
if (commandHandler.handler && !yargs._hasOutput()) {
|
||||
yargs._setHasOutput();
|
||||
const populateDoubleDash =
|
||||
!!yargs.getOptions().configuration['populate--'];
|
||||
yargs._postProcess(innerArgv, populateDoubleDash);
|
||||
innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
|
||||
let handlerResult;
|
||||
if (isPromise(innerArgv)) {
|
||||
handlerResult = innerArgv.then((argv) => commandHandler.handler(argv));
|
||||
} else {
|
||||
handlerResult = commandHandler.handler(innerArgv);
|
||||
}
|
||||
const handlerFinishCommand = yargs.getHandlerFinishCommand();
|
||||
if (isPromise(handlerResult)) {
|
||||
yargs.getUsageInstance().cacheHelpMessage();
|
||||
handlerResult
|
||||
.then((value) => {
|
||||
if (handlerFinishCommand) {
|
||||
handlerFinishCommand(value);
|
||||
}
|
||||
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;
|
||||
};
|
||||
self.reset = () => {
|
||||
handlers = {};
|
||||
aliasMap = {};
|
||||
defaultCommand = undefined;
|
||||
return self;
|
||||
};
|
||||
const frozens = [];
|
||||
self.freeze = () => {
|
||||
frozens.push({
|
||||
handlers,
|
||||
aliasMap,
|
||||
defaultCommand,
|
||||
});
|
||||
};
|
||||
self.unfreeze = () => {
|
||||
const frozen = frozens.pop();
|
||||
assertNotStrictEqual(frozen, undefined, shim);
|
||||
({ handlers, aliasMap, defaultCommand } = frozen);
|
||||
})
|
||||
.catch((error) => {
|
||||
try {
|
||||
yargs.getUsageInstance().fail(null, error);
|
||||
} catch (err) {}
|
||||
})
|
||||
.then(() => {
|
||||
yargs.getUsageInstance().clearCachedHelpMessage();
|
||||
});
|
||||
} else {
|
||||
if (handlerFinishCommand) {
|
||||
handlerFinishCommand(handlerResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (command) {
|
||||
currentContext.commands.pop();
|
||||
currentContext.fullCommands.pop();
|
||||
}
|
||||
numFiles = currentContext.files.length - numFiles;
|
||||
if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles);
|
||||
return innerArgv;
|
||||
};
|
||||
function shouldUpdateUsage(yargs) {
|
||||
return (
|
||||
!yargs.getUsageInstance().getUsageDisabled() &&
|
||||
yargs.getUsageInstance().getUsage().length === 0
|
||||
);
|
||||
}
|
||||
function usageFromParentCommandsCommandHandler(
|
||||
parentCommands,
|
||||
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(' ')}`;
|
||||
}
|
||||
self.runDefaultBuilderOn = function (yargs) {
|
||||
assertNotStrictEqual(defaultCommand, undefined, shim);
|
||||
if (shouldUpdateUsage(yargs)) {
|
||||
const commandString =
|
||||
DEFAULT_MARKER.test(defaultCommand.original) ?
|
||||
defaultCommand.original
|
||||
: defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
|
||||
yargs.getUsageInstance().usage(commandString, defaultCommand.description);
|
||||
}
|
||||
const builder = defaultCommand.builder;
|
||||
if (isCommandBuilderCallback(builder)) {
|
||||
builder(yargs);
|
||||
} else if (!isCommandBuilderDefinition(builder)) {
|
||||
Object.keys(builder).forEach((key) => {
|
||||
yargs.option(key, builder[key]);
|
||||
});
|
||||
}
|
||||
};
|
||||
function populatePositionals(commandHandler, argv, context) {
|
||||
argv._ = argv._.slice(context.commands.length);
|
||||
const demanded = commandHandler.demanded.slice(0);
|
||||
const optional = commandHandler.optional.slice(0);
|
||||
const positionalMap = {};
|
||||
validation.positionalCount(demanded.length, argv._.length);
|
||||
while (demanded.length) {
|
||||
const demand = demanded.shift();
|
||||
populatePositional(demand, argv, positionalMap);
|
||||
}
|
||||
while (optional.length) {
|
||||
const maybe = optional.shift();
|
||||
populatePositional(maybe, argv, positionalMap);
|
||||
}
|
||||
argv._ = context.commands.concat(argv._.map((a) => '' + a));
|
||||
postProcessPositionals(
|
||||
argv,
|
||||
positionalMap,
|
||||
self.cmdToParseOptions(commandHandler.original)
|
||||
);
|
||||
return positionalMap;
|
||||
}
|
||||
function populatePositional(positional, argv, positionalMap) {
|
||||
const cmd = positional.cmd[0];
|
||||
if (positional.variadic) {
|
||||
positionalMap[cmd] = argv._.splice(0).map(String);
|
||||
} else {
|
||||
if (argv._.length) positionalMap[cmd] = [String(argv._.shift())];
|
||||
}
|
||||
}
|
||||
function postProcessPositionals(argv, positionalMap, parseOptions) {
|
||||
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 = {};
|
||||
const unparsed = [];
|
||||
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);
|
||||
});
|
||||
});
|
||||
if (!unparsed.length) return;
|
||||
const config = Object.assign({}, options.configuration, {
|
||||
'populate--': true,
|
||||
});
|
||||
const parsed = shim.Parser.detailed(
|
||||
unparsed,
|
||||
Object.assign({}, options, {
|
||||
configuration: config,
|
||||
})
|
||||
);
|
||||
if (parsed.error) {
|
||||
yargs.getUsageInstance().fail(parsed.error.message, parsed.error);
|
||||
} else {
|
||||
const positionalKeys = Object.keys(positionalMap);
|
||||
Object.keys(positionalMap).forEach((key) => {
|
||||
positionalKeys.push(...parsed.aliases[key]);
|
||||
});
|
||||
Object.keys(parsed.argv).forEach((key) => {
|
||||
if (positionalKeys.indexOf(key) !== -1) {
|
||||
if (!positionalMap[key]) positionalMap[key] = parsed.argv[key];
|
||||
argv[key] = parsed.argv[key];
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
self.cmdToParseOptions = function (cmdString) {
|
||||
const parseOptions = {
|
||||
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;
|
||||
};
|
||||
self.reset = () => {
|
||||
handlers = {};
|
||||
aliasMap = {};
|
||||
defaultCommand = undefined;
|
||||
return self;
|
||||
};
|
||||
const frozens = [];
|
||||
self.freeze = () => {
|
||||
frozens.push({
|
||||
handlers,
|
||||
aliasMap,
|
||||
defaultCommand,
|
||||
});
|
||||
};
|
||||
self.unfreeze = () => {
|
||||
const frozen = frozens.pop();
|
||||
assertNotStrictEqual(frozen, undefined, shim);
|
||||
({ handlers, aliasMap, defaultCommand } = frozen);
|
||||
};
|
||||
return self;
|
||||
}
|
||||
export function isCommandBuilderDefinition(builder) {
|
||||
return (typeof builder === 'object' &&
|
||||
!!builder.builder &&
|
||||
typeof builder.handler === 'function');
|
||||
return (
|
||||
typeof builder === 'object' &&
|
||||
!!builder.builder &&
|
||||
typeof builder.handler === 'function'
|
||||
);
|
||||
}
|
||||
function isCommandAndAliases(cmd) {
|
||||
if (cmd.every(c => typeof c === 'string')) {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
if (cmd.every((c) => typeof c === 'string')) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
export function isCommandBuilderCallback(builder) {
|
||||
return typeof builder === 'function';
|
||||
return typeof builder === 'function';
|
||||
}
|
||||
function isCommandBuilderOptionDefinitions(builder) {
|
||||
return typeof builder === 'object';
|
||||
return typeof builder === 'object';
|
||||
}
|
||||
export function isCommandHandlerDefinition(cmd) {
|
||||
return typeof cmd === 'object' && !Array.isArray(cmd);
|
||||
return typeof cmd === 'object' && !Array.isArray(cmd);
|
||||
}
|
||||
|
239
node_modules/yargs/build/lib/completion.js
generated
vendored
239
node_modules/yargs/build/lib/completion.js
generated
vendored
@ -4,125 +4,132 @@ import * as templates from './completion-templates.js';
|
||||
import { isPromise } from './utils/is-promise.js';
|
||||
import { parseCommand } from './parse-command.js';
|
||||
export function completion(yargs, usage, command, shim) {
|
||||
const self = {
|
||||
completionKey: 'get-yargs-completions',
|
||||
};
|
||||
let aliases;
|
||||
self.setParsed = function setParsed(parsed) {
|
||||
aliases = parsed.aliases;
|
||||
};
|
||||
const zshShell = (shim.getEnv('SHELL') && shim.getEnv('SHELL').indexOf('zsh') !== -1) ||
|
||||
(shim.getEnv('ZSH_NAME') && shim.getEnv('ZSH_NAME').indexOf('zsh') !== -1);
|
||||
self.getCompletion = function getCompletion(args, done) {
|
||||
const completions = [];
|
||||
const current = args.length ? args[args.length - 1] : '';
|
||||
const argv = yargs.parse(args, true);
|
||||
const parentCommands = yargs.getContext().commands;
|
||||
function runCompletionFunction(argv) {
|
||||
assertNotStrictEqual(completionFunction, null, shim);
|
||||
if (isSyncCompletionFunction(completionFunction)) {
|
||||
const result = completionFunction(current, argv);
|
||||
if (isPromise(result)) {
|
||||
return result
|
||||
.then(list => {
|
||||
shim.process.nextTick(() => {
|
||||
done(list);
|
||||
});
|
||||
})
|
||||
.catch(err => {
|
||||
shim.process.nextTick(() => {
|
||||
throw err;
|
||||
});
|
||||
});
|
||||
}
|
||||
return done(result);
|
||||
}
|
||||
else {
|
||||
return completionFunction(current, argv, completions => {
|
||||
done(completions);
|
||||
});
|
||||
}
|
||||
}
|
||||
if (completionFunction) {
|
||||
return isPromise(argv)
|
||||
? argv.then(runCompletionFunction)
|
||||
: runCompletionFunction(argv);
|
||||
}
|
||||
const handlers = command.getCommandHandlers();
|
||||
for (let i = 0, ii = args.length; i < ii; ++i) {
|
||||
if (handlers[args[i]] && handlers[args[i]].builder) {
|
||||
const builder = handlers[args[i]].builder;
|
||||
if (isCommandBuilderCallback(builder)) {
|
||||
const y = yargs.reset();
|
||||
builder(y);
|
||||
return y.argv;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!current.match(/^-/) &&
|
||||
parentCommands[parentCommands.length - 1] !== current) {
|
||||
usage.getCommands().forEach(usageCommand => {
|
||||
const commandName = parseCommand(usageCommand[0]).cmd;
|
||||
if (args.indexOf(commandName) === -1) {
|
||||
if (!zshShell) {
|
||||
completions.push(commandName);
|
||||
}
|
||||
else {
|
||||
const desc = usageCommand[1] || '';
|
||||
completions.push(commandName.replace(/:/g, '\\:') + ':' + desc);
|
||||
}
|
||||
}
|
||||
const self = {
|
||||
completionKey: 'get-yargs-completions',
|
||||
};
|
||||
let aliases;
|
||||
self.setParsed = function setParsed(parsed) {
|
||||
aliases = parsed.aliases;
|
||||
};
|
||||
const zshShell =
|
||||
(shim.getEnv('SHELL') && shim.getEnv('SHELL').indexOf('zsh') !== -1) ||
|
||||
(shim.getEnv('ZSH_NAME') && shim.getEnv('ZSH_NAME').indexOf('zsh') !== -1);
|
||||
self.getCompletion = function getCompletion(args, done) {
|
||||
const completions = [];
|
||||
const current = args.length ? args[args.length - 1] : '';
|
||||
const argv = yargs.parse(args, true);
|
||||
const parentCommands = yargs.getContext().commands;
|
||||
function runCompletionFunction(argv) {
|
||||
assertNotStrictEqual(completionFunction, null, shim);
|
||||
if (isSyncCompletionFunction(completionFunction)) {
|
||||
const result = completionFunction(current, argv);
|
||||
if (isPromise(result)) {
|
||||
return result
|
||||
.then((list) => {
|
||||
shim.process.nextTick(() => {
|
||||
done(list);
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
shim.process.nextTick(() => {
|
||||
throw err;
|
||||
});
|
||||
});
|
||||
}
|
||||
if (current.match(/^-/) || (current === '' && completions.length === 0)) {
|
||||
const descs = usage.getDescriptions();
|
||||
const options = yargs.getOptions();
|
||||
Object.keys(options.key).forEach(key => {
|
||||
const negable = !!options.configuration['boolean-negation'] &&
|
||||
options.boolean.includes(key);
|
||||
let keyAndAliases = [key].concat(aliases[key] || []);
|
||||
if (negable)
|
||||
keyAndAliases = keyAndAliases.concat(keyAndAliases.map(key => `no-${key}`));
|
||||
function completeOptionKey(key) {
|
||||
const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1);
|
||||
if (notInArgs) {
|
||||
const startsByTwoDashes = (s) => /^--/.test(s);
|
||||
const isShortOption = (s) => /^[^0-9]$/.test(s);
|
||||
const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
|
||||
if (!zshShell) {
|
||||
completions.push(dashes + key);
|
||||
}
|
||||
else {
|
||||
const desc = descs[key] || '';
|
||||
completions.push(dashes +
|
||||
`${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
completeOptionKey(key);
|
||||
if (negable && !!options.default[key])
|
||||
completeOptionKey(`no-${key}`);
|
||||
});
|
||||
return done(result);
|
||||
} else {
|
||||
return completionFunction(current, argv, (completions) => {
|
||||
done(completions);
|
||||
});
|
||||
}
|
||||
}
|
||||
if (completionFunction) {
|
||||
return isPromise(argv) ?
|
||||
argv.then(runCompletionFunction)
|
||||
: runCompletionFunction(argv);
|
||||
}
|
||||
const handlers = command.getCommandHandlers();
|
||||
for (let i = 0, ii = args.length; i < ii; ++i) {
|
||||
if (handlers[args[i]] && handlers[args[i]].builder) {
|
||||
const builder = handlers[args[i]].builder;
|
||||
if (isCommandBuilderCallback(builder)) {
|
||||
const y = yargs.reset();
|
||||
builder(y);
|
||||
return y.argv;
|
||||
}
|
||||
done(completions);
|
||||
};
|
||||
self.generateCompletionScript = function generateCompletionScript($0, cmd) {
|
||||
let script = zshShell
|
||||
? templates.completionZshTemplate
|
||||
: templates.completionShTemplate;
|
||||
const name = shim.path.basename($0);
|
||||
if ($0.match(/\.js$/))
|
||||
$0 = `./${$0}`;
|
||||
script = script.replace(/{{app_name}}/g, name);
|
||||
script = script.replace(/{{completion_command}}/g, cmd);
|
||||
return script.replace(/{{app_path}}/g, $0);
|
||||
};
|
||||
let completionFunction = null;
|
||||
self.registerFunction = fn => {
|
||||
completionFunction = fn;
|
||||
};
|
||||
return self;
|
||||
}
|
||||
}
|
||||
if (
|
||||
!current.match(/^-/) &&
|
||||
parentCommands[parentCommands.length - 1] !== current
|
||||
) {
|
||||
usage.getCommands().forEach((usageCommand) => {
|
||||
const commandName = parseCommand(usageCommand[0]).cmd;
|
||||
if (args.indexOf(commandName) === -1) {
|
||||
if (!zshShell) {
|
||||
completions.push(commandName);
|
||||
} else {
|
||||
const desc = usageCommand[1] || '';
|
||||
completions.push(commandName.replace(/:/g, '\\:') + ':' + desc);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if (current.match(/^-/) || (current === '' && completions.length === 0)) {
|
||||
const descs = usage.getDescriptions();
|
||||
const options = yargs.getOptions();
|
||||
Object.keys(options.key).forEach((key) => {
|
||||
const negable =
|
||||
!!options.configuration['boolean-negation'] &&
|
||||
options.boolean.includes(key);
|
||||
let keyAndAliases = [key].concat(aliases[key] || []);
|
||||
if (negable)
|
||||
keyAndAliases = keyAndAliases.concat(
|
||||
keyAndAliases.map((key) => `no-${key}`)
|
||||
);
|
||||
function completeOptionKey(key) {
|
||||
const notInArgs = keyAndAliases.every(
|
||||
(val) => args.indexOf(`--${val}`) === -1
|
||||
);
|
||||
if (notInArgs) {
|
||||
const startsByTwoDashes = (s) => /^--/.test(s);
|
||||
const isShortOption = (s) => /^[^0-9]$/.test(s);
|
||||
const dashes =
|
||||
!startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
|
||||
if (!zshShell) {
|
||||
completions.push(dashes + key);
|
||||
} else {
|
||||
const desc = descs[key] || '';
|
||||
completions.push(
|
||||
dashes +
|
||||
`${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
completeOptionKey(key);
|
||||
if (negable && !!options.default[key]) completeOptionKey(`no-${key}`);
|
||||
});
|
||||
}
|
||||
done(completions);
|
||||
};
|
||||
self.generateCompletionScript = function generateCompletionScript($0, cmd) {
|
||||
let script =
|
||||
zshShell ?
|
||||
templates.completionZshTemplate
|
||||
: templates.completionShTemplate;
|
||||
const name = shim.path.basename($0);
|
||||
if ($0.match(/\.js$/)) $0 = `./${$0}`;
|
||||
script = script.replace(/{{app_name}}/g, name);
|
||||
script = script.replace(/{{completion_command}}/g, cmd);
|
||||
return script.replace(/{{app_path}}/g, $0);
|
||||
};
|
||||
let completionFunction = null;
|
||||
self.registerFunction = (fn) => {
|
||||
completionFunction = fn;
|
||||
};
|
||||
return self;
|
||||
}
|
||||
function isSyncCompletionFunction(completionFunction) {
|
||||
return completionFunction.length < 3;
|
||||
return completionFunction.length < 3;
|
||||
}
|
||||
|
91
node_modules/yargs/build/lib/middleware.js
generated
vendored
91
node_modules/yargs/build/lib/middleware.js
generated
vendored
@ -1,53 +1,56 @@
|
||||
import { argsert } from './argsert.js';
|
||||
import { isPromise } from './utils/is-promise.js';
|
||||
export function globalMiddlewareFactory(globalMiddleware, context) {
|
||||
return function (callback, applyBeforeValidation = false) {
|
||||
argsert('<array|function> [boolean]', [callback, applyBeforeValidation], 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');
|
||||
}
|
||||
callback[i].applyBeforeValidation = applyBeforeValidation;
|
||||
}
|
||||
Array.prototype.push.apply(globalMiddleware, callback);
|
||||
return function (callback, applyBeforeValidation = false) {
|
||||
argsert(
|
||||
'<array|function> [boolean]',
|
||||
[callback, applyBeforeValidation],
|
||||
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');
|
||||
}
|
||||
else if (typeof callback === 'function') {
|
||||
callback.applyBeforeValidation = applyBeforeValidation;
|
||||
globalMiddleware.push(callback);
|
||||
}
|
||||
return context;
|
||||
};
|
||||
callback[i].applyBeforeValidation = applyBeforeValidation;
|
||||
}
|
||||
Array.prototype.push.apply(globalMiddleware, callback);
|
||||
} else if (typeof callback === 'function') {
|
||||
callback.applyBeforeValidation = applyBeforeValidation;
|
||||
globalMiddleware.push(callback);
|
||||
}
|
||||
return context;
|
||||
};
|
||||
}
|
||||
export function commandMiddlewareFactory(commandMiddleware) {
|
||||
if (!commandMiddleware)
|
||||
return [];
|
||||
return commandMiddleware.map(middleware => {
|
||||
middleware.applyBeforeValidation = false;
|
||||
return middleware;
|
||||
});
|
||||
if (!commandMiddleware) return [];
|
||||
return commandMiddleware.map((middleware) => {
|
||||
middleware.applyBeforeValidation = false;
|
||||
return middleware;
|
||||
});
|
||||
}
|
||||
export function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
|
||||
const beforeValidationError = new Error('middleware cannot return a promise when applyBeforeValidation is true');
|
||||
return middlewares.reduce((acc, middleware) => {
|
||||
if (middleware.applyBeforeValidation !== beforeValidation) {
|
||||
return acc;
|
||||
}
|
||||
if (isPromise(acc)) {
|
||||
return acc
|
||||
.then(initialObj => Promise.all([
|
||||
initialObj,
|
||||
middleware(initialObj, yargs),
|
||||
]))
|
||||
.then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
|
||||
}
|
||||
else {
|
||||
const result = middleware(acc, yargs);
|
||||
if (beforeValidation && isPromise(result))
|
||||
throw beforeValidationError;
|
||||
return isPromise(result)
|
||||
? result.then(middlewareObj => Object.assign(acc, middlewareObj))
|
||||
: Object.assign(acc, result);
|
||||
}
|
||||
}, argv);
|
||||
const beforeValidationError = new Error(
|
||||
'middleware cannot return a promise when applyBeforeValidation is true'
|
||||
);
|
||||
return middlewares.reduce((acc, middleware) => {
|
||||
if (middleware.applyBeforeValidation !== beforeValidation) {
|
||||
return acc;
|
||||
}
|
||||
if (isPromise(acc)) {
|
||||
return acc
|
||||
.then((initialObj) =>
|
||||
Promise.all([initialObj, middleware(initialObj, yargs)])
|
||||
)
|
||||
.then(([initialObj, middlewareObj]) =>
|
||||
Object.assign(initialObj, middlewareObj)
|
||||
);
|
||||
} else {
|
||||
const result = middleware(acc, yargs);
|
||||
if (beforeValidation && isPromise(result)) throw beforeValidationError;
|
||||
return isPromise(result) ?
|
||||
result.then((middlewareObj) => Object.assign(acc, middlewareObj))
|
||||
: Object.assign(acc, result);
|
||||
}
|
||||
}, argv);
|
||||
}
|
||||
|
57
node_modules/yargs/build/lib/parse-command.js
generated
vendored
57
node_modules/yargs/build/lib/parse-command.js
generated
vendored
@ -1,32 +1,29 @@
|
||||
export function parseCommand(cmd) {
|
||||
const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ');
|
||||
const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
|
||||
const bregex = /\.*[\][<>]/g;
|
||||
const firstCommand = splitCommand.shift();
|
||||
if (!firstCommand)
|
||||
throw new Error(`No command found in: ${cmd}`);
|
||||
const parsedCommand = {
|
||||
cmd: firstCommand.replace(bregex, ''),
|
||||
demanded: [],
|
||||
optional: [],
|
||||
};
|
||||
splitCommand.forEach((cmd, i) => {
|
||||
let variadic = false;
|
||||
cmd = cmd.replace(/\s/g, '');
|
||||
if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1)
|
||||
variadic = true;
|
||||
if (/^\[/.test(cmd)) {
|
||||
parsedCommand.optional.push({
|
||||
cmd: cmd.replace(bregex, '').split('|'),
|
||||
variadic,
|
||||
});
|
||||
}
|
||||
else {
|
||||
parsedCommand.demanded.push({
|
||||
cmd: cmd.replace(bregex, '').split('|'),
|
||||
variadic,
|
||||
});
|
||||
}
|
||||
});
|
||||
return parsedCommand;
|
||||
const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ');
|
||||
const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
|
||||
const bregex = /\.*[\][<>]/g;
|
||||
const firstCommand = splitCommand.shift();
|
||||
if (!firstCommand) throw new Error(`No command found in: ${cmd}`);
|
||||
const parsedCommand = {
|
||||
cmd: firstCommand.replace(bregex, ''),
|
||||
demanded: [],
|
||||
optional: [],
|
||||
};
|
||||
splitCommand.forEach((cmd, i) => {
|
||||
let variadic = false;
|
||||
cmd = cmd.replace(/\s/g, '');
|
||||
if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) variadic = true;
|
||||
if (/^\[/.test(cmd)) {
|
||||
parsedCommand.optional.push({
|
||||
cmd: cmd.replace(bregex, '').split('|'),
|
||||
variadic,
|
||||
});
|
||||
} else {
|
||||
parsedCommand.demanded.push({
|
||||
cmd: cmd.replace(bregex, '').split('|'),
|
||||
variadic,
|
||||
});
|
||||
}
|
||||
});
|
||||
return parsedCommand;
|
||||
}
|
||||
|
6
node_modules/yargs/build/lib/typings/common-types.js
generated
vendored
6
node_modules/yargs/build/lib/typings/common-types.js
generated
vendored
@ -1,9 +1,9 @@
|
||||
export function assertNotStrictEqual(actual, expected, shim, message) {
|
||||
shim.assert.notStrictEqual(actual, expected, message);
|
||||
shim.assert.notStrictEqual(actual, expected, message);
|
||||
}
|
||||
export function assertSingleKey(actual, shim) {
|
||||
shim.assert.strictEqual(typeof actual, 'string');
|
||||
shim.assert.strictEqual(typeof actual, 'string');
|
||||
}
|
||||
export function objectKeys(object) {
|
||||
return Object.keys(object);
|
||||
return Object.keys(object);
|
||||
}
|
||||
|
1065
node_modules/yargs/build/lib/usage.js
generated
vendored
1065
node_modules/yargs/build/lib/usage.js
generated
vendored
File diff suppressed because it is too large
Load Diff
94
node_modules/yargs/build/lib/utils/apply-extends.js
generated
vendored
94
node_modules/yargs/build/lib/utils/apply-extends.js
generated
vendored
@ -2,58 +2,60 @@ import { YError } from '../yerror.js';
|
||||
let previouslyVisitedConfigs = [];
|
||||
let shim;
|
||||
export function applyExtends(config, cwd, mergeExtends, _shim) {
|
||||
shim = _shim;
|
||||
let defaultConfig = {};
|
||||
if (Object.prototype.hasOwnProperty.call(config, 'extends')) {
|
||||
if (typeof config.extends !== 'string')
|
||||
return defaultConfig;
|
||||
const isPath = /\.json|\..*rc$/.test(config.extends);
|
||||
let pathToDefault = null;
|
||||
if (!isPath) {
|
||||
try {
|
||||
pathToDefault = require.resolve(config.extends);
|
||||
}
|
||||
catch (_err) {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
else {
|
||||
pathToDefault = getPathToDefaultConfig(cwd, config.extends);
|
||||
}
|
||||
checkForCircularExtends(pathToDefault);
|
||||
previouslyVisitedConfigs.push(pathToDefault);
|
||||
defaultConfig = isPath
|
||||
? JSON.parse(shim.readFileSync(pathToDefault, 'utf8'))
|
||||
: require(config.extends);
|
||||
delete config.extends;
|
||||
defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim);
|
||||
shim = _shim;
|
||||
let defaultConfig = {};
|
||||
if (Object.prototype.hasOwnProperty.call(config, 'extends')) {
|
||||
if (typeof config.extends !== 'string') return defaultConfig;
|
||||
const isPath = /\.json|\..*rc$/.test(config.extends);
|
||||
let pathToDefault = null;
|
||||
if (!isPath) {
|
||||
try {
|
||||
pathToDefault = require.resolve(config.extends);
|
||||
} catch (_err) {
|
||||
return config;
|
||||
}
|
||||
} else {
|
||||
pathToDefault = getPathToDefaultConfig(cwd, config.extends);
|
||||
}
|
||||
previouslyVisitedConfigs = [];
|
||||
return mergeExtends
|
||||
? mergeDeep(defaultConfig, config)
|
||||
: Object.assign({}, defaultConfig, config);
|
||||
checkForCircularExtends(pathToDefault);
|
||||
previouslyVisitedConfigs.push(pathToDefault);
|
||||
defaultConfig =
|
||||
isPath ?
|
||||
JSON.parse(shim.readFileSync(pathToDefault, 'utf8'))
|
||||
: require(config.extends);
|
||||
delete config.extends;
|
||||
defaultConfig = applyExtends(
|
||||
defaultConfig,
|
||||
shim.path.dirname(pathToDefault),
|
||||
mergeExtends,
|
||||
shim
|
||||
);
|
||||
}
|
||||
previouslyVisitedConfigs = [];
|
||||
return mergeExtends ?
|
||||
mergeDeep(defaultConfig, config)
|
||||
: Object.assign({}, defaultConfig, config);
|
||||
}
|
||||
function checkForCircularExtends(cfgPath) {
|
||||
if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
|
||||
throw new YError(`Circular extended configurations: '${cfgPath}'.`);
|
||||
}
|
||||
if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
|
||||
throw new YError(`Circular extended configurations: '${cfgPath}'.`);
|
||||
}
|
||||
}
|
||||
function getPathToDefaultConfig(cwd, pathToExtend) {
|
||||
return shim.path.resolve(cwd, pathToExtend);
|
||||
return shim.path.resolve(cwd, pathToExtend);
|
||||
}
|
||||
function mergeDeep(config1, config2) {
|
||||
const target = {};
|
||||
function isObject(obj) {
|
||||
return obj && typeof obj === 'object' && !Array.isArray(obj);
|
||||
const target = {};
|
||||
function isObject(obj) {
|
||||
return obj && typeof obj === 'object' && !Array.isArray(obj);
|
||||
}
|
||||
Object.assign(target, config1);
|
||||
for (const key of Object.keys(config2)) {
|
||||
if (isObject(config2[key]) && isObject(target[key])) {
|
||||
target[key] = mergeDeep(config1[key], config2[key]);
|
||||
} else {
|
||||
target[key] = config2[key];
|
||||
}
|
||||
Object.assign(target, config1);
|
||||
for (const key of Object.keys(config2)) {
|
||||
if (isObject(config2[key]) && isObject(target[key])) {
|
||||
target[key] = mergeDeep(config1[key], config2[key]);
|
||||
}
|
||||
else {
|
||||
target[key] = config2[key];
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
8
node_modules/yargs/build/lib/utils/is-promise.js
generated
vendored
8
node_modules/yargs/build/lib/utils/is-promise.js
generated
vendored
@ -1,5 +1,7 @@
|
||||
export function isPromise(maybePromise) {
|
||||
return (!!maybePromise &&
|
||||
!!maybePromise.then &&
|
||||
typeof maybePromise.then === 'function');
|
||||
return (
|
||||
!!maybePromise &&
|
||||
!!maybePromise.then &&
|
||||
typeof maybePromise.then === 'function'
|
||||
);
|
||||
}
|
||||
|
46
node_modules/yargs/build/lib/utils/levenshtein.js
generated
vendored
46
node_modules/yargs/build/lib/utils/levenshtein.js
generated
vendored
@ -1,26 +1,26 @@
|
||||
export function levenshtein(a, b) {
|
||||
if (a.length === 0)
|
||||
return b.length;
|
||||
if (b.length === 0)
|
||||
return a.length;
|
||||
const matrix = [];
|
||||
let i;
|
||||
for (i = 0; i <= b.length; i++) {
|
||||
matrix[i] = [i];
|
||||
if (a.length === 0) return b.length;
|
||||
if (b.length === 0) return a.length;
|
||||
const matrix = [];
|
||||
let i;
|
||||
for (i = 0; i <= b.length; i++) {
|
||||
matrix[i] = [i];
|
||||
}
|
||||
let j;
|
||||
for (j = 0; j <= a.length; j++) {
|
||||
matrix[0][j] = j;
|
||||
}
|
||||
for (i = 1; i <= b.length; i++) {
|
||||
for (j = 1; j <= a.length; j++) {
|
||||
if (b.charAt(i - 1) === a.charAt(j - 1)) {
|
||||
matrix[i][j] = matrix[i - 1][j - 1];
|
||||
} else {
|
||||
matrix[i][j] = Math.min(
|
||||
matrix[i - 1][j - 1] + 1,
|
||||
Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1)
|
||||
);
|
||||
}
|
||||
}
|
||||
let j;
|
||||
for (j = 0; j <= a.length; j++) {
|
||||
matrix[0][j] = j;
|
||||
}
|
||||
for (i = 1; i <= b.length; i++) {
|
||||
for (j = 1; j <= a.length; j++) {
|
||||
if (b.charAt(i - 1) === a.charAt(j - 1)) {
|
||||
matrix[i][j] = matrix[i - 1][j - 1];
|
||||
}
|
||||
else {
|
||||
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
return matrix[b.length][a.length];
|
||||
}
|
||||
return matrix[b.length][a.length];
|
||||
}
|
||||
|
14
node_modules/yargs/build/lib/utils/obj-filter.js
generated
vendored
14
node_modules/yargs/build/lib/utils/obj-filter.js
generated
vendored
@ -1,10 +1,10 @@
|
||||
import { objectKeys } from '../typings/common-types.js';
|
||||
export function objFilter(original = {}, filter = () => true) {
|
||||
const obj = {};
|
||||
objectKeys(original).forEach(key => {
|
||||
if (filter(key, original[key])) {
|
||||
obj[key] = original[key];
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
const obj = {};
|
||||
objectKeys(original).forEach((key) => {
|
||||
if (filter(key, original[key])) {
|
||||
obj[key] = original[key];
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
}
|
||||
|
13
node_modules/yargs/build/lib/utils/process-argv.js
generated
vendored
13
node_modules/yargs/build/lib/utils/process-argv.js
generated
vendored
@ -1,17 +1,16 @@
|
||||
function getProcessArgvBinIndex() {
|
||||
if (isBundledElectronApp())
|
||||
return 0;
|
||||
return 1;
|
||||
if (isBundledElectronApp()) return 0;
|
||||
return 1;
|
||||
}
|
||||
function isBundledElectronApp() {
|
||||
return isElectronApp() && !process.defaultApp;
|
||||
return isElectronApp() && !process.defaultApp;
|
||||
}
|
||||
function isElectronApp() {
|
||||
return !!process.versions.electron;
|
||||
return !!process.versions.electron;
|
||||
}
|
||||
export function hideBin(argv) {
|
||||
return argv.slice(getProcessArgvBinIndex() + 1);
|
||||
return argv.slice(getProcessArgvBinIndex() + 1);
|
||||
}
|
||||
export function getProcessArgvBin() {
|
||||
return process.argv[getProcessArgvBinIndex()];
|
||||
return process.argv[getProcessArgvBinIndex()];
|
||||
}
|
||||
|
21
node_modules/yargs/build/lib/utils/set-blocking.js
generated
vendored
21
node_modules/yargs/build/lib/utils/set-blocking.js
generated
vendored
@ -1,12 +1,13 @@
|
||||
export default function setBlocking(blocking) {
|
||||
if (typeof process === 'undefined')
|
||||
return;
|
||||
[process.stdout, process.stderr].forEach(_stream => {
|
||||
const stream = _stream;
|
||||
if (stream._handle &&
|
||||
stream.isTTY &&
|
||||
typeof stream._handle.setBlocking === 'function') {
|
||||
stream._handle.setBlocking(blocking);
|
||||
}
|
||||
});
|
||||
if (typeof process === 'undefined') return;
|
||||
[process.stdout, process.stderr].forEach((_stream) => {
|
||||
const stream = _stream;
|
||||
if (
|
||||
stream._handle &&
|
||||
stream.isTTY &&
|
||||
typeof stream._handle.setBlocking === 'function'
|
||||
) {
|
||||
stream._handle.setBlocking(blocking);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
18
node_modules/yargs/build/lib/utils/which-module.js
generated
vendored
18
node_modules/yargs/build/lib/utils/which-module.js
generated
vendored
@ -1,10 +1,12 @@
|
||||
export default function whichModule(exported) {
|
||||
if (typeof require === 'undefined')
|
||||
return null;
|
||||
for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) {
|
||||
mod = require.cache[files[i]];
|
||||
if (mod.exports === exported)
|
||||
return mod;
|
||||
}
|
||||
return null;
|
||||
if (typeof require === 'undefined') return null;
|
||||
for (
|
||||
let i = 0, files = Object.keys(require.cache), mod;
|
||||
i < files.length;
|
||||
i++
|
||||
) {
|
||||
mod = require.cache[files[i]];
|
||||
if (mod.exports === exported) return mod;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
658
node_modules/yargs/build/lib/validation.js
generated
vendored
658
node_modules/yargs/build/lib/validation.js
generated
vendored
@ -1,308 +1,376 @@
|
||||
import { argsert } from './argsert.js';
|
||||
import { assertNotStrictEqual, } from './typings/common-types.js';
|
||||
import { assertNotStrictEqual } from './typings/common-types.js';
|
||||
import { levenshtein as distance } from './utils/levenshtein.js';
|
||||
import { objFilter } from './utils/obj-filter.js';
|
||||
const specialKeys = ['$0', '--', '_'];
|
||||
export function validation(yargs, usage, y18n, shim) {
|
||||
const __ = y18n.__;
|
||||
const __n = y18n.__n;
|
||||
const self = {};
|
||||
self.nonOptionCount = function nonOptionCount(argv) {
|
||||
const demandedCommands = yargs.getDemandedCommands();
|
||||
const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0);
|
||||
const _s = positionalCount - yargs.getContext().commands.length;
|
||||
if (demandedCommands._ &&
|
||||
(_s < demandedCommands._.min || _s > demandedCommands._.max)) {
|
||||
if (_s < demandedCommands._.min) {
|
||||
if (demandedCommands._.minMsg !== undefined) {
|
||||
usage.fail(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(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()));
|
||||
}
|
||||
}
|
||||
const __ = y18n.__;
|
||||
const __n = y18n.__n;
|
||||
const self = {};
|
||||
self.nonOptionCount = function nonOptionCount(argv) {
|
||||
const demandedCommands = yargs.getDemandedCommands();
|
||||
const positionalCount =
|
||||
argv._.length + (argv['--'] ? argv['--'].length : 0);
|
||||
const _s = positionalCount - yargs.getContext().commands.length;
|
||||
if (
|
||||
demandedCommands._ &&
|
||||
(_s < demandedCommands._.min || _s > demandedCommands._.max)
|
||||
) {
|
||||
if (_s < demandedCommands._.min) {
|
||||
if (demandedCommands._.minMsg !== undefined) {
|
||||
usage.fail(
|
||||
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()
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
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 + ''));
|
||||
} else if (_s > demandedCommands._.max) {
|
||||
if (demandedCommands._.maxMsg !== undefined) {
|
||||
usage.fail(
|
||||
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()
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
self.requiredArguments = function requiredArguments(argv) {
|
||||
const demandedOptions = yargs.getDemandedOptions();
|
||||
let missing = 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 = [];
|
||||
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));
|
||||
}
|
||||
};
|
||||
self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) {
|
||||
const commandKeys = yargs.getCommandInstance().getCommands();
|
||||
const unknown = [];
|
||||
const currentContext = yargs.getContext();
|
||||
Object.keys(argv).forEach(key => {
|
||||
if (specialKeys.indexOf(key) === -1 &&
|
||||
!Object.prototype.hasOwnProperty.call(positionalMap, key) &&
|
||||
!Object.prototype.hasOwnProperty.call(yargs._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.indexOf('' + key) === -1) {
|
||||
unknown.push('' + key);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (unknown.length > 0) {
|
||||
usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.join(', ')));
|
||||
}
|
||||
};
|
||||
self.unknownCommands = function unknownCommands(argv) {
|
||||
const commandKeys = yargs.getCommandInstance().getCommands();
|
||||
const unknown = [];
|
||||
const currentContext = yargs.getContext();
|
||||
if (currentContext.commands.length > 0 || commandKeys.length > 0) {
|
||||
argv._.slice(currentContext.commands.length).forEach(key => {
|
||||
if (commandKeys.indexOf('' + key) === -1) {
|
||||
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;
|
||||
}
|
||||
};
|
||||
self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) {
|
||||
if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
|
||||
return false;
|
||||
}
|
||||
const newAliases = yargs.parsed.newAliases;
|
||||
for (const a of [key, ...aliases[key]]) {
|
||||
if (!Object.prototype.hasOwnProperty.call(newAliases, a) ||
|
||||
!newAliases[key]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
self.limitedChoices = function limitedChoices(argv) {
|
||||
const options = yargs.getOptions();
|
||||
const invalid = {};
|
||||
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 => {
|
||||
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);
|
||||
};
|
||||
let checks = [];
|
||||
self.check = function check(f, global) {
|
||||
checks.push({
|
||||
func: f,
|
||||
global,
|
||||
});
|
||||
};
|
||||
self.customChecks = function customChecks(argv, aliases) {
|
||||
for (let i = 0, f; (f = checks[i]) !== undefined; i++) {
|
||||
const func = f.func;
|
||||
let result = null;
|
||||
try {
|
||||
result = func(argv, aliases);
|
||||
}
|
||||
catch (err) {
|
||||
usage.fail(err.message ? err.message : err, err);
|
||||
continue;
|
||||
}
|
||||
if (!result) {
|
||||
usage.fail(__('Argument check failed: %s', func.toString()));
|
||||
}
|
||||
else if (typeof result === 'string' || result instanceof Error) {
|
||||
usage.fail(result.toString(), result);
|
||||
}
|
||||
}
|
||||
};
|
||||
let implied = {};
|
||||
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, val) {
|
||||
const num = Number(val);
|
||||
val = isNaN(num) ? val : num;
|
||||
if (typeof val === 'number') {
|
||||
val = argv._.length >= val;
|
||||
}
|
||||
else if (val.match(/^--no-.+/)) {
|
||||
val = val.match(/^--no-(.+)/)[1];
|
||||
val = !argv[val];
|
||||
}
|
||||
else {
|
||||
val = argv[val];
|
||||
}
|
||||
return val;
|
||||
}
|
||||
}
|
||||
self.implications = function implications(argv) {
|
||||
const implyFail = [];
|
||||
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}`);
|
||||
}
|
||||
});
|
||||
};
|
||||
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 + ''
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
self.requiredArguments = function requiredArguments(argv) {
|
||||
const demandedOptions = yargs.getDemandedOptions();
|
||||
let missing = 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 = [];
|
||||
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
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
self.unknownArguments = function unknownArguments(
|
||||
argv,
|
||||
aliases,
|
||||
positionalMap,
|
||||
isDefaultCommand,
|
||||
checkPositionals = true
|
||||
) {
|
||||
const commandKeys = yargs.getCommandInstance().getCommands();
|
||||
const unknown = [];
|
||||
const currentContext = yargs.getContext();
|
||||
Object.keys(argv).forEach((key) => {
|
||||
if (
|
||||
specialKeys.indexOf(key) === -1 &&
|
||||
!Object.prototype.hasOwnProperty.call(positionalMap, key) &&
|
||||
!Object.prototype.hasOwnProperty.call(yargs._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.indexOf('' + key) === -1) {
|
||||
unknown.push('' + key);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (unknown.length > 0) {
|
||||
usage.fail(
|
||||
__n(
|
||||
'Unknown argument: %s',
|
||||
'Unknown arguments: %s',
|
||||
unknown.length,
|
||||
unknown.join(', ')
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
self.unknownCommands = function unknownCommands(argv) {
|
||||
const commandKeys = yargs.getCommandInstance().getCommands();
|
||||
const unknown = [];
|
||||
const currentContext = yargs.getContext();
|
||||
if (currentContext.commands.length > 0 || commandKeys.length > 0) {
|
||||
argv._.slice(currentContext.commands.length).forEach((key) => {
|
||||
if (commandKeys.indexOf('' + key) === -1) {
|
||||
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;
|
||||
}
|
||||
};
|
||||
self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(
|
||||
key,
|
||||
aliases
|
||||
) {
|
||||
if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
|
||||
return false;
|
||||
}
|
||||
const newAliases = yargs.parsed.newAliases;
|
||||
for (const a of [key, ...aliases[key]]) {
|
||||
if (
|
||||
!Object.prototype.hasOwnProperty.call(newAliases, a) ||
|
||||
!newAliases[key]
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
self.limitedChoices = function limitedChoices(argv) {
|
||||
const options = yargs.getOptions();
|
||||
const invalid = {};
|
||||
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) => {
|
||||
if (
|
||||
options.choices[key].indexOf(value) === -1 &&
|
||||
value !== undefined
|
||||
) {
|
||||
invalid[key] = (invalid[key] || []).concat(value);
|
||||
}
|
||||
});
|
||||
if (implyFail.length) {
|
||||
let msg = `${__('Implications failed:')}\n`;
|
||||
implyFail.forEach(value => {
|
||||
msg += value;
|
||||
});
|
||||
usage.fail(msg);
|
||||
}
|
||||
});
|
||||
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);
|
||||
};
|
||||
let checks = [];
|
||||
self.check = function check(f, global) {
|
||||
checks.push({
|
||||
func: f,
|
||||
global,
|
||||
});
|
||||
};
|
||||
self.customChecks = function customChecks(argv, aliases) {
|
||||
for (let i = 0, f; (f = checks[i]) !== undefined; i++) {
|
||||
const func = f.func;
|
||||
let result = null;
|
||||
try {
|
||||
result = func(argv, aliases);
|
||||
} catch (err) {
|
||||
usage.fail(err.message ? err.message : err, err);
|
||||
continue;
|
||||
}
|
||||
if (!result) {
|
||||
usage.fail(__('Argument check failed: %s', func.toString()));
|
||||
} else if (typeof result === 'string' || result instanceof Error) {
|
||||
usage.fail(result.toString(), result);
|
||||
}
|
||||
}
|
||||
};
|
||||
let implied = {};
|
||||
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, val) {
|
||||
const num = Number(val);
|
||||
val = isNaN(num) ? val : num;
|
||||
if (typeof val === 'number') {
|
||||
val = argv._.length >= val;
|
||||
} else if (val.match(/^--no-.+/)) {
|
||||
val = val.match(/^--no-(.+)/)[1];
|
||||
val = !argv[val];
|
||||
} else {
|
||||
val = argv[val];
|
||||
}
|
||||
return val;
|
||||
}
|
||||
self.implications = function implications(argv) {
|
||||
const implyFail = [];
|
||||
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}`);
|
||||
}
|
||||
};
|
||||
let conflicting = {};
|
||||
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 => {
|
||||
if (value && argv[key] !== undefined && argv[value] !== undefined) {
|
||||
usage.fail(__('Arguments %s and %s are mutually exclusive', key, value));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
if (implyFail.length) {
|
||||
let msg = `${__('Implications failed:')}\n`;
|
||||
implyFail.forEach((value) => {
|
||||
msg += value;
|
||||
});
|
||||
usage.fail(msg);
|
||||
}
|
||||
};
|
||||
let conflicting = {};
|
||||
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) => {
|
||||
if (value && argv[key] !== undefined && argv[value] !== undefined) {
|
||||
usage.fail(
|
||||
__('Arguments %s and %s are mutually exclusive', key, value)
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
|
||||
const threshold = 3;
|
||||
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]);
|
||||
checks = checks.filter(c => c.global);
|
||||
return self;
|
||||
};
|
||||
const frozens = [];
|
||||
self.freeze = function freeze() {
|
||||
frozens.push({
|
||||
implied,
|
||||
checks,
|
||||
conflicting,
|
||||
});
|
||||
};
|
||||
self.unfreeze = function unfreeze() {
|
||||
const frozen = frozens.pop();
|
||||
assertNotStrictEqual(frozen, undefined, shim);
|
||||
({ implied, checks, conflicting } = frozen);
|
||||
};
|
||||
}
|
||||
});
|
||||
};
|
||||
self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
|
||||
const threshold = 3;
|
||||
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]);
|
||||
checks = checks.filter((c) => c.global);
|
||||
return self;
|
||||
};
|
||||
const frozens = [];
|
||||
self.freeze = function freeze() {
|
||||
frozens.push({
|
||||
implied,
|
||||
checks,
|
||||
conflicting,
|
||||
});
|
||||
};
|
||||
self.unfreeze = function unfreeze() {
|
||||
const frozen = frozens.pop();
|
||||
assertNotStrictEqual(frozen, undefined, shim);
|
||||
({ implied, checks, conflicting } = frozen);
|
||||
};
|
||||
return self;
|
||||
}
|
||||
|
2334
node_modules/yargs/build/lib/yargs-factory.js
generated
vendored
2334
node_modules/yargs/build/lib/yargs-factory.js
generated
vendored
File diff suppressed because it is too large
Load Diff
10
node_modules/yargs/build/lib/yerror.js
generated
vendored
10
node_modules/yargs/build/lib/yerror.js
generated
vendored
@ -1,7 +1,7 @@
|
||||
export class YError extends Error {
|
||||
constructor(msg) {
|
||||
super(msg || 'yargs error');
|
||||
this.name = 'YError';
|
||||
Error.captureStackTrace(this, YError);
|
||||
}
|
||||
constructor(msg) {
|
||||
super(msg || 'yargs error');
|
||||
this.name = 'YError';
|
||||
Error.captureStackTrace(this, YError);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user