You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2921 lines
105 KiB
2921 lines
105 KiB
3 weeks ago
|
'use strict';
|
||
|
|
||
|
var assert = require('assert');
|
||
|
|
||
|
class YError extends Error {
|
||
|
constructor(msg) {
|
||
|
super(msg || 'yargs error');
|
||
|
this.name = 'YError';
|
||
|
Error.captureStackTrace(this, YError);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
let previouslyVisitedConfigs = [];
|
||
|
let shim;
|
||
|
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);
|
||
|
}
|
||
|
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}'.`);
|
||
|
}
|
||
|
}
|
||
|
function getPathToDefaultConfig(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);
|
||
|
}
|
||
|
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;
|
||
|
}
|
||
|
|
||
|
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 positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
|
||
|
function argsert(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}.`);
|
||
|
}
|
||
|
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;
|
||
|
}
|
||
|
function argumentTypeError(observedType, allowedTypes, position) {
|
||
|
throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`);
|
||
|
}
|
||
|
|
||
|
function isPromise(maybePromise) {
|
||
|
return (!!maybePromise &&
|
||
|
!!maybePromise.then &&
|
||
|
typeof maybePromise.then === 'function');
|
||
|
}
|
||
|
|
||
|
function assertNotStrictEqual(actual, expected, shim, message) {
|
||
|
shim.assert.notStrictEqual(actual, expected, message);
|
||
|
}
|
||
|
function assertSingleKey(actual, shim) {
|
||
|
shim.assert.strictEqual(typeof actual, 'string');
|
||
|
}
|
||
|
function objectKeys(object) {
|
||
|
return Object.keys(object);
|
||
|
}
|
||
|
|
||
|
function objFilter(original = {}, filter = () => true) {
|
||
|
const obj = {};
|
||
|
objectKeys(original).forEach(key => {
|
||
|
if (filter(key, original[key])) {
|
||
|
obj[key] = original[key];
|
||
|
}
|
||
|
});
|
||
|
return obj;
|
||
|
}
|
||
|
|
||
|
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);
|
||
|
}
|
||
|
else if (typeof callback === 'function') {
|
||
|
callback.applyBeforeValidation = applyBeforeValidation;
|
||
|
globalMiddleware.push(callback);
|
||
|
}
|
||
|
return context;
|
||
|
};
|
||
|
}
|
||
|
function commandMiddlewareFactory(commandMiddleware) {
|
||
|
if (!commandMiddleware)
|
||
|
return [];
|
||
|
return commandMiddleware.map(middleware => {
|
||
|
middleware.applyBeforeValidation = false;
|
||
|
return middleware;
|
||
|
});
|
||
|
}
|
||
|
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);
|
||
|
}
|
||
|
|
||
|
function getProcessArgvBinIndex() {
|
||
|
if (isBundledElectronApp())
|
||
|
return 0;
|
||
|
return 1;
|
||
|
}
|
||
|
function isBundledElectronApp() {
|
||
|
return isElectronApp() && !process.defaultApp;
|
||
|
}
|
||
|
function isElectronApp() {
|
||
|
return !!process.versions.electron;
|
||
|
}
|
||
|
function hideBin(argv) {
|
||
|
return argv.slice(getProcessArgvBinIndex() + 1);
|
||
|
}
|
||
|
function getProcessArgvBin() {
|
||
|
return process.argv[getProcessArgvBinIndex()];
|
||
|
}
|
||
|
|
||
|
var processArgv = /*#__PURE__*/Object.freeze({
|
||
|
__proto__: null,
|
||
|
hideBin: hideBin,
|
||
|
getProcessArgvBin: getProcessArgvBin
|
||
|
});
|
||
|
|
||
|
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;
|
||
|
}
|
||
|
|
||
|
const DEFAULT_MARKER = /(^\*)|(^\$0)/;
|
||
|
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);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
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);
|
||
|
}
|
||
|
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);
|
||
|
}
|
||
|
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;
|
||
|
};
|
||
|
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;
|
||
|
}
|
||
|
function isCommandBuilderDefinition(builder) {
|
||
|
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;
|
||
|
}
|
||
|
}
|
||
|
function isCommandBuilderCallback(builder) {
|
||
|
return typeof builder === 'function';
|
||
|
}
|
||
|
function isCommandBuilderOptionDefinitions(builder) {
|
||
|
return typeof builder === 'object';
|
||
|
}
|
||
|
function isCommandHandlerDefinition(cmd) {
|
||
|
return typeof cmd === 'object' && !Array.isArray(cmd);
|
||
|
}
|
||
|
|
||
|
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);
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
function usage(yargs, y18n, shim) {
|
||
|
const __ = y18n.__;
|
||
|
const self = {};
|
||
|
const fails = [];
|
||
|
self.failFn = function failFn(f) {
|
||
|
fails.push(f);
|
||
|
};
|
||
|
let failMessage = null;
|
||
|
let showHelpOnFail = true;
|
||
|
self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) {
|
||
|
function parseFunctionArgs() {
|
||
|
return typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2];
|
||
|
}
|
||
|
const [enabled, message] = parseFunctionArgs();
|
||
|
failMessage = message;
|
||
|
showHelpOnFail = enabled;
|
||
|
return self;
|
||
|
};
|
||
|
let failureOutput = false;
|
||
|
self.fail = function fail(msg, err) {
|
||
|
const logger = yargs._getLoggerInstance();
|
||
|
if (fails.length) {
|
||
|
for (let i = fails.length - 1; i >= 0; --i) {
|
||
|
fails[i](msg, err, self);
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
if (yargs.getExitProcess())
|
||
|
setBlocking(true);
|
||
|
if (!failureOutput) {
|
||
|
failureOutput = true;
|
||
|
if (showHelpOnFail) {
|
||
|
yargs.showHelp('error');
|
||
|
logger.error();
|
||
|
}
|
||
|
if (msg || err)
|
||
|
logger.error(msg || err);
|
||
|
if (failMessage) {
|
||
|
if (msg || err)
|
||
|
logger.error('');
|
||
|
logger.error(failMessage);
|
||
|
}
|
||
|
}
|
||
|
err = err || new YError(msg);
|
||
|
if (yargs.getExitProcess()) {
|
||
|
return yargs.exit(1);
|
||
|
}
|
||
|
else if (yargs._hasParseCallback()) {
|
||
|
return yargs.exit(1, err);
|
||
|
}
|
||
|
else {
|
||
|
throw err;
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
let usages = [];
|
||
|
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 = [];
|
||
|
self.example = (cmd, description) => {
|
||
|
examples.push([cmd, description || '']);
|
||
|
};
|
||
|
let commands = [];
|
||
|
self.command = function command(cmd, description, isDefault, aliases, deprecated = false) {
|
||
|
if (isDefault) {
|
||
|
commands = commands.map(cmdArray => {
|
||
|
cmdArray[2] = false;
|
||
|
return cmdArray;
|
||
|
});
|
||
|
}
|
||
|
commands.push([cmd, description || '', isDefault, aliases, deprecated]);
|
||
|
};
|
||
|
self.getCommands = () => commands;
|
||
|
let descriptions = {};
|
||
|
self.describe = function describe(keyOrKeys, desc) {
|
||
|
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 = [];
|
||
|
self.epilog = msg => {
|
||
|
epilogs.push(msg);
|
||
|
};
|
||
|
let wrapSet = false;
|
||
|
let wrap;
|
||
|
self.wrap = cols => {
|
||
|
wrapSet = true;
|
||
|
wrap = cols;
|
||
|
};
|
||
|
function getWrap() {
|
||
|
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();
|
||
|
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 = [];
|
||
|
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;
|
||
|
}, {}));
|
||
|
const theWrap = getWrap();
|
||
|
const ui = shim.cliui({
|
||
|
width: theWrap,
|
||
|
wrap: !!theWrap,
|
||
|
});
|
||
|
if (!usageDisabled) {
|
||
|
if (usages.length) {
|
||
|
usages.forEach(usage => {
|
||
|
ui.div(`${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;
|
||
|
if (demandedCommands._) {
|
||
|
u = `${base$0} <${__('command')}>\n`;
|
||
|
}
|
||
|
else {
|
||
|
u = `${base$0} [${__('command')}]\n`;
|
||
|
}
|
||
|
ui.div(`${u}`);
|
||
|
}
|
||
|
}
|
||
|
if (commands.length) {
|
||
|
ui.div(__('Commands:'));
|
||
|
const context = yargs.getContext();
|
||
|
const parentCommands = context.commands.length
|
||
|
? `${context.commands.join(' ')} `
|
||
|
: '';
|
||
|
if (yargs.getParserConfiguration()['sort-commands'] === true) {
|
||
|
commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
|
||
|
}
|
||
|
commands.forEach(command => {
|
||
|
const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}`;
|
||
|
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();
|
||
|
}
|
||
|
const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
|
||
|
keys = keys.filter(key => !yargs.parsed.newAliases[key] &&
|
||
|
aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1));
|
||
|
const defaultGroup = __('Options:');
|
||
|
if (!groups[defaultGroup])
|
||
|
groups[defaultGroup] = [];
|
||
|
addUngroupedKeys(keys, options.alias, groups, defaultGroup);
|
||
|
const isLongSwitch = (sw) => /^--/.test(getText(sw));
|
||
|
const displayedGroups = Object.keys(groups)
|
||
|
.filter(groupName => groups[groupName].length > 0)
|
||
|
.map(groupName => {
|
||
|
const normalizedKeys = groups[groupName]
|
||
|
.filter(filterHiddenOptions)
|
||
|
.map(key => {
|
||
|
if (~aliasKeys.indexOf(key))
|
||
|
return key;
|
||
|
for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
|
||
|
if (~(options.alias[aliasKey] || []).indexOf(key))
|
||
|
return aliasKey;
|
||
|
}
|
||
|
return key;
|
||
|
});
|
||
|
return { groupName, normalizedKeys };
|
||
|
})
|
||
|
.filter(({ normalizedKeys }) => normalizedKeys.length > 0)
|
||
|
.map(({ groupName, normalizedKeys }) => {
|
||
|
const switches = normalizedKeys.reduce((acc, key) => {
|
||
|
acc[key] = [key]
|
||
|
.concat(options.alias[key] || [])
|
||
|
.map(sw => {
|
||
|
if (groupName === self.getPositionalGroupName())
|
||
|
return sw;
|
||
|
else {
|
||
|
return ((/^[0-9]$/.test(sw)
|
||
|
? ~options.boolean.indexOf(key)
|
||
|
? '-'
|
||
|
: '--'
|
||
|
: sw.length > 1
|
||
|
? '--'
|
||
|
: '-') + sw);
|
||
|
}
|
||
|
})
|
||
|
.sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2)
|
||
|
? 0
|
||
|
: isLongSwitch(sw1)
|
||
|
? 1
|
||
|
: -1)
|
||
|
.join(', ');
|
||
|
return acc;
|
||
|
}, {});
|
||
|
return { groupName, normalizedKeys, switches };
|
||
|
});
|
||
|
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);
|
||
|
}
|
||
|
});
|
||
|
});
|
||
|
}
|
||
|
displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
|
||
|
ui.div(groupName);
|
||
|
normalizedKeys.forEach(key => {
|
||
|
const kswitch = switches[key];
|
||
|
let desc = descriptions[key] || '';
|
||
|
let type = null;
|
||
|
if (~desc.lastIndexOf(deferY18nLookupPrefix))
|
||
|
desc = __(desc.substring(deferY18nLookupPrefix.length));
|
||
|
if (~options.boolean.indexOf(key))
|
||
|
type = `[${__('boolean')}]`;
|
||
|
if (~options.count.indexOf(key))
|
||
|
type = `[${__('count')}]`;
|
||
|
if (~options.string.indexOf(key))
|
||
|
type = `[${__('string')}]`;
|
||
|
if (~options.normalize.indexOf(key))
|
||
|
type = `[${__('string')}]`;
|
||
|
if (~options.array.indexOf(key))
|
||
|
type = `[${__('array')}]`;
|
||
|
if (~options.number.indexOf(key))
|
||
|
type = `[${__('number')}]`;
|
||
|
const deprecatedExtra = (deprecated) => 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);
|
||
|
if (extra)
|
||
|
ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' });
|
||
|
else
|
||
|
ui.div();
|
||
|
});
|
||
|
ui.div();
|
||
|
});
|
||
|
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();
|
||
|
}
|
||
|
if (epilogs.length > 0) {
|
||
|
const e = epilogs
|
||
|
.map(epilog => epilog.replace(/\$0/g, base$0))
|
||
|
.join('\n');
|
||
|
ui.div(`${e}\n`);
|
||
|
}
|
||
|
return ui.toString().replace(/\s*$/, '');
|
||
|
};
|
||
|
function maxWidth(table, theWrap, modifier) {
|
||
|
let width = 0;
|
||
|
if (!Array.isArray(table)) {
|
||
|
table = Object.values(table).map(v => [v]);
|
||
|
}
|
||
|
table.forEach(v => {
|
||
|
width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
|
||
|
});
|
||
|
if (theWrap)
|
||
|
width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
|
||
|
return width;
|
||
|
}
|
||
|
function normalizeAliases() {
|
||
|
const demandedOptions = yargs.getDemandedOptions();
|
||
|
const options = yargs.getOptions();
|
||
|
(Object.keys(options.alias) || []).forEach(key => {
|
||
|
options.alias[key].forEach(alias => {
|
||
|
if (descriptions[alias])
|
||
|
self.describe(key, descriptions[alias]);
|
||
|
if (alias in demandedOptions)
|
||
|
yargs.demandOption(key, demandedOptions[alias]);
|
||
|
if (~options.boolean.indexOf(alias))
|
||
|
yargs.boolean(key);
|
||
|
if (~options.count.indexOf(alias))
|
||
|
yargs.count(key);
|
||
|
if (~options.string.indexOf(alias))
|
||
|
yargs.string(key);
|
||
|
if (~options.normalize.indexOf(alias))
|
||
|
yargs.normalize(key);
|
||
|
if (~options.array.indexOf(alias))
|
||
|
yargs.array(key);
|
||
|
if (~options.number.indexOf(alias))
|
||
|
yargs.number(key);
|
||
|
});
|
||
|
});
|
||
|
}
|
||
|
let cachedHelpMessage;
|
||
|
self.cacheHelpMessage = function () {
|
||
|
cachedHelpMessage = this.help();
|
||
|
};
|
||
|
self.clearCachedHelpMessage = function () {
|
||
|
cachedHelpMessage = undefined;
|
||
|
};
|
||
|
function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
|
||
|
let groupedKeys = [];
|
||
|
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) {
|
||
|
return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
|
||
|
yargs.parsed.argv[yargs.getOptions().showHiddenOpt]);
|
||
|
}
|
||
|
self.showHelp = (level) => {
|
||
|
const logger = yargs._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 = [].concat(values);
|
||
|
if (!values || !array.length)
|
||
|
return string;
|
||
|
array.forEach(value => {
|
||
|
if (string.length)
|
||
|
string += sep;
|
||
|
string += JSON.stringify(value);
|
||
|
});
|
||
|
return string;
|
||
|
};
|
||
|
function defaultString(value, defaultDescription) {
|
||
|
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}]`;
|
||
|
}
|
||
|
function windowWidth() {
|
||
|
const maxWidth = 80;
|
||
|
if (shim.process.stdColumns) {
|
||
|
return Math.min(maxWidth, shim.process.stdColumns);
|
||
|
}
|
||
|
else {
|
||
|
return maxWidth;
|
||
|
}
|
||
|
}
|
||
|
let version = null;
|
||
|
self.version = ver => {
|
||
|
version = ver;
|
||
|
};
|
||
|
self.showVersion = () => {
|
||
|
const logger = yargs._getLoggerInstance();
|
||
|
logger.log(version);
|
||
|
};
|
||
|
self.reset = function reset(localLookup) {
|
||
|
failMessage = null;
|
||
|
failureOutput = false;
|
||
|
usages = [];
|
||
|
usageDisabled = false;
|
||
|
epilogs = [];
|
||
|
examples = [];
|
||
|
commands = [];
|
||
|
descriptions = objFilter(descriptions, k => !localLookup[k]);
|
||
|
return self;
|
||
|
};
|
||
|
const frozens = [];
|
||
|
self.freeze = function freeze() {
|
||
|
frozens.push({
|
||
|
failMessage,
|
||
|
failureOutput,
|
||
|
usages,
|
||
|
usageDisabled,
|
||
|
epilogs,
|
||
|
examples,
|
||
|
commands,
|
||
|
descriptions,
|
||
|
});
|
||
|
};
|
||
|
self.unfreeze = function unfreeze() {
|
||
|
const frozen = frozens.pop();
|
||
|
assertNotStrictEqual(frozen, undefined, shim);
|
||
|
({
|
||
|
failMessage,
|
||
|
failureOutput,
|
||
|
usages,
|
||
|
usageDisabled,
|
||
|
epilogs,
|
||
|
examples,
|
||
|
commands,
|
||
|
descriptions,
|
||
|
} = frozen);
|
||
|
};
|
||
|
return self;
|
||
|
}
|
||
|
function isIndentedText(text) {
|
||
|
return typeof text === 'object';
|
||
|
}
|
||
|
function addIndentation(text, indent) {
|
||
|
return isIndentedText(text)
|
||
|
? { text: text.text, indentation: text.indentation + indent }
|
||
|
: { text, indentation: indent };
|
||
|
}
|
||
|
function getIndentation(text) {
|
||
|
return isIndentedText(text) ? text.indentation : 0;
|
||
|
}
|
||
|
function getText(text) {
|
||
|
return isIndentedText(text) ? text.text : text;
|
||
|
}
|
||
|
|
||
|
const completionShTemplate = `###-begin-{{app_name}}-completions-###
|
||
|
#
|
||
|
# yargs command completion script
|
||
|
#
|
||
|
# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
|
||
|
# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
|
||
|
#
|
||
|
_yargs_completions()
|
||
|
{
|
||
|
local cur_word args type_list
|
||
|
|
||
|
cur_word="\${COMP_WORDS[COMP_CWORD]}"
|
||
|
args=("\${COMP_WORDS[@]}")
|
||
|
|
||
|
# ask yargs to generate completions.
|
||
|
type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")
|
||
|
|
||
|
COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )
|
||
|
|
||
|
# if no match was found, fall back to filename completion
|
||
|
if [ \${#COMPREPLY[@]} -eq 0 ]; then
|
||
|
COMPREPLY=()
|
||
|
fi
|
||
|
|
||
|
return 0
|
||
|
}
|
||
|
complete -o default -F _yargs_completions {{app_name}}
|
||
|
###-end-{{app_name}}-completions-###
|
||
|
`;
|
||
|
const completionZshTemplate = `###-begin-{{app_name}}-completions-###
|
||
|
#
|
||
|
# yargs command completion script
|
||
|
#
|
||
|
# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
|
||
|
# or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX.
|
||
|
#
|
||
|
_{{app_name}}_yargs_completions()
|
||
|
{
|
||
|
local reply
|
||
|
local si=$IFS
|
||
|
IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
|
||
|
IFS=$si
|
||
|
_describe 'values' reply
|
||
|
}
|
||
|
compdef _{{app_name}}_yargs_completions {{app_name}}
|
||
|
###-end-{{app_name}}-completions-###
|
||
|
`;
|
||
|
|
||
|
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);
|
||
|
}
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
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
|
||
|
? completionZshTemplate
|
||
|
: 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;
|
||
|
}
|
||
|
|
||
|
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];
|
||
|
}
|
||
|
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];
|
||
|
}
|
||
|
|
||
|
const specialKeys = ['$0', '--', '_'];
|
||
|
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()));
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
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);
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
});
|
||
|
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}`);
|
||
|
}
|
||
|
});
|
||
|
});
|
||
|
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 = levenshtein(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;
|
||
|
}
|
||
|
|
||
|
let shim$1;
|
||
|
function YargsWithShim(_shim) {
|
||
|
shim$1 = _shim;
|
||
|
return Yargs;
|
||
|
}
|
||
|
function Yargs(processArgs = [], cwd = shim$1.process.cwd(), parentRequire) {
|
||
|
const self = {};
|
||
|
let command$1;
|
||
|
let completion$1 = null;
|
||
|
let groups = {};
|
||
|
const globalMiddleware = [];
|
||
|
let output = '';
|
||
|
const preservedGroups = {};
|
||
|
let usage$1;
|
||
|
let validation$1;
|
||
|
let handlerFinishCommand = null;
|
||
|
const y18n = shim$1.y18n;
|
||
|
self.middleware = globalMiddlewareFactory(globalMiddleware, self);
|
||
|
self.scriptName = function (scriptName) {
|
||
|
self.customScriptName = true;
|
||
|
self.$0 = scriptName;
|
||
|
return self;
|
||
|
};
|
||
|
let default$0;
|
||
|
if (/\b(node|iojs|electron)(\.exe)?$/.test(shim$1.process.argv()[0])) {
|
||
|
default$0 = shim$1.process.argv().slice(1, 2);
|
||
|
}
|
||
|
else {
|
||
|
default$0 = shim$1.process.argv().slice(0, 1);
|
||
|
}
|
||
|
self.$0 = default$0
|
||
|
.map(x => {
|
||
|
const b = rebase(cwd, x);
|
||
|
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
|
||
|
})
|
||
|
.join(' ')
|
||
|
.trim();
|
||
|
if (shim$1.getEnv('_') && shim$1.getProcessArgvBin() === shim$1.getEnv('_')) {
|
||
|
self.$0 = shim$1
|
||
|
.getEnv('_')
|
||
|
.replace(`${shim$1.path.dirname(shim$1.process.execPath())}/`, '');
|
||
|
}
|
||
|
const context = { resets: -1, commands: [], fullCommands: [], files: [] };
|
||
|
self.getContext = () => context;
|
||
|
let hasOutput = false;
|
||
|
let exitError = null;
|
||
|
self.exit = (code, err) => {
|
||
|
hasOutput = true;
|
||
|
exitError = err;
|
||
|
if (exitProcess)
|
||
|
shim$1.process.exit(code);
|
||
|
};
|
||
|
let completionCommand = null;
|
||
|
self.completion = function (cmd, desc, fn) {
|
||
|
argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length);
|
||
|
if (typeof desc === 'function') {
|
||
|
fn = desc;
|
||
|
desc = undefined;
|
||
|
}
|
||
|
completionCommand = cmd || completionCommand || 'completion';
|
||
|
if (!desc && desc !== false) {
|
||
|
desc = 'generate completion script';
|
||
|
}
|
||
|
self.command(completionCommand, desc);
|
||
|
if (fn)
|
||
|
completion$1.registerFunction(fn);
|
||
|
return self;
|
||
|
};
|
||
|
let options;
|
||
|
self.resetOptions = self.reset = function resetOptions(aliases = {}) {
|
||
|
context.resets++;
|
||
|
options = options || {};
|
||
|
const tmpOptions = {};
|
||
|
tmpOptions.local = options.local ? options.local : [];
|
||
|
tmpOptions.configObjects = options.configObjects
|
||
|
? options.configObjects
|
||
|
: [];
|
||
|
const localLookup = {};
|
||
|
tmpOptions.local.forEach(l => {
|
||
|
localLookup[l] = true;
|
||
|
(aliases[l] || []).forEach(a => {
|
||
|
localLookup[a] = true;
|
||
|
});
|
||
|
});
|
||
|
Object.assign(preservedGroups, Object.keys(groups).reduce((acc, groupName) => {
|
||
|
const keys = groups[groupName].filter(key => !(key in localLookup));
|
||
|
if (keys.length > 0) {
|
||
|
acc[groupName] = keys;
|
||
|
}
|
||
|
return acc;
|
||
|
}, {}));
|
||
|
groups = {};
|
||
|
const arrayOptions = [
|
||
|
'array',
|
||
|
'boolean',
|
||
|
'string',
|
||
|
'skipValidation',
|
||
|
'count',
|
||
|
'normalize',
|
||
|
'number',
|
||
|
'hiddenOptions',
|
||
|
];
|
||
|
const objectOptions = [
|
||
|
'narg',
|
||
|
'key',
|
||
|
'alias',
|
||
|
'default',
|
||
|
'defaultDescription',
|
||
|
'config',
|
||
|
'choices',
|
||
|
'demandedOptions',
|
||
|
'demandedCommands',
|
||
|
'coerce',
|
||
|
'deprecatedOptions',
|
||
|
];
|
||
|
arrayOptions.forEach(k => {
|
||
|
tmpOptions[k] = (options[k] || []).filter((k) => !localLookup[k]);
|
||
|
});
|
||
|
objectOptions.forEach((k) => {
|
||
|
tmpOptions[k] = objFilter(options[k], k => !localLookup[k]);
|
||
|
});
|
||
|
tmpOptions.envPrefix = options.envPrefix;
|
||
|
options = tmpOptions;
|
||
|
usage$1 = usage$1 ? usage$1.reset(localLookup) : usage(self, y18n, shim$1);
|
||
|
validation$1 = validation$1
|
||
|
? validation$1.reset(localLookup)
|
||
|
: validation(self, usage$1, y18n, shim$1);
|
||
|
command$1 = command$1
|
||
|
? command$1.reset()
|
||
|
: command(self, usage$1, validation$1, globalMiddleware, shim$1);
|
||
|
if (!completion$1)
|
||
|
completion$1 = completion(self, usage$1, command$1, shim$1);
|
||
|
completionCommand = null;
|
||
|
output = '';
|
||
|
exitError = null;
|
||
|
hasOutput = false;
|
||
|
self.parsed = false;
|
||
|
return self;
|
||
|
};
|
||
|
self.resetOptions();
|
||
|
const frozens = [];
|
||
|
function freeze() {
|
||
|
frozens.push({
|
||
|
options,
|
||
|
configObjects: options.configObjects.slice(0),
|
||
|
exitProcess,
|
||
|
groups,
|
||
|
strict,
|
||
|
strictCommands,
|
||
|
strictOptions,
|
||
|
completionCommand,
|
||
|
output,
|
||
|
exitError,
|
||
|
hasOutput,
|
||
|
parsed: self.parsed,
|
||
|
parseFn,
|
||
|
parseContext,
|
||
|
handlerFinishCommand,
|
||
|
});
|
||
|
usage$1.freeze();
|
||
|
validation$1.freeze();
|
||
|
command$1.freeze();
|
||
|
}
|
||
|
function unfreeze() {
|
||
|
const frozen = frozens.pop();
|
||
|
assertNotStrictEqual(frozen, undefined, shim$1);
|
||
|
let configObjects;
|
||
|
({
|
||
|
options,
|
||
|
configObjects,
|
||
|
exitProcess,
|
||
|
groups,
|
||
|
output,
|
||
|
exitError,
|
||
|
hasOutput,
|
||
|
parsed: self.parsed,
|
||
|
strict,
|
||
|
strictCommands,
|
||
|
strictOptions,
|
||
|
completionCommand,
|
||
|
parseFn,
|
||
|
parseContext,
|
||
|
handlerFinishCommand,
|
||
|
} = frozen);
|
||
|
options.configObjects = configObjects;
|
||
|
usage$1.unfreeze();
|
||
|
validation$1.unfreeze();
|
||
|
command$1.unfreeze();
|
||
|
}
|
||
|
self.boolean = function (keys) {
|
||
|
argsert('<array|string>', [keys], arguments.length);
|
||
|
populateParserHintArray('boolean', keys);
|
||
|
return self;
|
||
|
};
|
||
|
self.array = function (keys) {
|
||
|
argsert('<array|string>', [keys], arguments.length);
|
||
|
populateParserHintArray('array', keys);
|
||
|
return self;
|
||
|
};
|
||
|
self.number = function (keys) {
|
||
|
argsert('<array|string>', [keys], arguments.length);
|
||
|
populateParserHintArray('number', keys);
|
||
|
return self;
|
||
|
};
|
||
|
self.normalize = function (keys) {
|
||
|
argsert('<array|string>', [keys], arguments.length);
|
||
|
populateParserHintArray('normalize', keys);
|
||
|
return self;
|
||
|
};
|
||
|
self.count = function (keys) {
|
||
|
argsert('<array|string>', [keys], arguments.length);
|
||
|
populateParserHintArray('count', keys);
|
||
|
return self;
|
||
|
};
|
||
|
self.string = function (keys) {
|
||
|
argsert('<array|string>', [keys], arguments.length);
|
||
|
populateParserHintArray('string', keys);
|
||
|
return self;
|
||
|
};
|
||
|
self.requiresArg = function (keys) {
|
||
|
argsert('<array|string|object> [number]', [keys], arguments.length);
|
||
|
if (typeof keys === 'string' && options.narg[keys]) {
|
||
|
return self;
|
||
|
}
|
||
|
else {
|
||
|
populateParserHintSingleValueDictionary(self.requiresArg, 'narg', keys, NaN);
|
||
|
}
|
||
|
return self;
|
||
|
};
|
||
|
self.skipValidation = function (keys) {
|
||
|
argsert('<array|string>', [keys], arguments.length);
|
||
|
populateParserHintArray('skipValidation', keys);
|
||
|
return self;
|
||
|
};
|
||
|
function populateParserHintArray(type, keys) {
|
||
|
keys = [].concat(keys);
|
||
|
keys.forEach(key => {
|
||
|
key = sanitizeKey(key);
|
||
|
options[type].push(key);
|
||
|
});
|
||
|
}
|
||
|
self.nargs = function (key, value) {
|
||
|
argsert('<string|object|array> [number]', [key, value], arguments.length);
|
||
|
populateParserHintSingleValueDictionary(self.nargs, 'narg', key, value);
|
||
|
return self;
|
||
|
};
|
||
|
self.choices = function (key, value) {
|
||
|
argsert('<object|string|array> [string|array]', [key, value], arguments.length);
|
||
|
populateParserHintArrayDictionary(self.choices, 'choices', key, value);
|
||
|
return self;
|
||
|
};
|
||
|
self.alias = function (key, value) {
|
||
|
argsert('<object|string|array> [string|array]', [key, value], arguments.length);
|
||
|
populateParserHintArrayDictionary(self.alias, 'alias', key, value);
|
||
|
return self;
|
||
|
};
|
||
|
self.default = self.defaults = function (key, value, defaultDescription) {
|
||
|
argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length);
|
||
|
if (defaultDescription) {
|
||
|
assertSingleKey(key, shim$1);
|
||
|
options.defaultDescription[key] = defaultDescription;
|
||
|
}
|
||
|
if (typeof value === 'function') {
|
||
|
assertSingleKey(key, shim$1);
|
||
|
if (!options.defaultDescription[key])
|
||
|
options.defaultDescription[key] = usage$1.functionDescription(value);
|
||
|
value = value.call();
|
||
|
}
|
||
|
populateParserHintSingleValueDictionary(self.default, 'default', key, value);
|
||
|
return self;
|
||
|
};
|
||
|
self.describe = function (key, desc) {
|
||
|
argsert('<object|string|array> [string]', [key, desc], arguments.length);
|
||
|
setKey(key, true);
|
||
|
usage$1.describe(key, desc);
|
||
|
return self;
|
||
|
};
|
||
|
function setKey(key, set) {
|
||
|
populateParserHintSingleValueDictionary(setKey, 'key', key, set);
|
||
|
return self;
|
||
|
}
|
||
|
function demandOption(keys, msg) {
|
||
|
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
|
||
|
populateParserHintSingleValueDictionary(self.demandOption, 'demandedOptions', keys, msg);
|
||
|
return self;
|
||
|
}
|
||
|
self.demandOption = demandOption;
|
||
|
self.coerce = function (keys, value) {
|
||
|
argsert('<object|string|array> [function]', [keys, value], arguments.length);
|
||
|
populateParserHintSingleValueDictionary(self.coerce, 'coerce', keys, value);
|
||
|
return self;
|
||
|
};
|
||
|
function populateParserHintSingleValueDictionary(builder, type, key, value) {
|
||
|
populateParserHintDictionary(builder, type, key, value, (type, key, value) => {
|
||
|
options[type][key] = value;
|
||
|
});
|
||
|
}
|
||
|
function populateParserHintArrayDictionary(builder, type, key, value) {
|
||
|
populateParserHintDictionary(builder, type, key, value, (type, key, value) => {
|
||
|
options[type][key] = (options[type][key] || []).concat(value);
|
||
|
});
|
||
|
}
|
||
|
function populateParserHintDictionary(builder, type, key, value, singleKeyHandler) {
|
||
|
if (Array.isArray(key)) {
|
||
|
key.forEach(k => {
|
||
|
builder(k, value);
|
||
|
});
|
||
|
}
|
||
|
else if (((key) => typeof key === 'object')(key)) {
|
||
|
for (const k of objectKeys(key)) {
|
||
|
builder(k, key[k]);
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
singleKeyHandler(type, sanitizeKey(key), value);
|
||
|
}
|
||
|
}
|
||
|
function sanitizeKey(key) {
|
||
|
if (key === '__proto__')
|
||
|
return '___proto___';
|
||
|
return key;
|
||
|
}
|
||
|
function deleteFromParserHintObject(optionKey) {
|
||
|
objectKeys(options).forEach((hintKey) => {
|
||
|
if (((key) => key === 'configObjects')(hintKey))
|
||
|
return;
|
||
|
const hint = options[hintKey];
|
||
|
if (Array.isArray(hint)) {
|
||
|
if (~hint.indexOf(optionKey))
|
||
|
hint.splice(hint.indexOf(optionKey), 1);
|
||
|
}
|
||
|
else if (typeof hint === 'object') {
|
||
|
delete hint[optionKey];
|
||
|
}
|
||
|
});
|
||
|
delete usage$1.getDescriptions()[optionKey];
|
||
|
}
|
||
|
self.config = function config(key = 'config', msg, parseFn) {
|
||
|
argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length);
|
||
|
if (typeof key === 'object' && !Array.isArray(key)) {
|
||
|
key = applyExtends(key, cwd, self.getParserConfiguration()['deep-merge-config'] || false, shim$1);
|
||
|
options.configObjects = (options.configObjects || []).concat(key);
|
||
|
return self;
|
||
|
}
|
||
|
if (typeof msg === 'function') {
|
||
|
parseFn = msg;
|
||
|
msg = undefined;
|
||
|
}
|
||
|
self.describe(key, msg || usage$1.deferY18nLookup('Path to JSON config file'));
|
||
|
(Array.isArray(key) ? key : [key]).forEach(k => {
|
||
|
options.config[k] = parseFn || true;
|
||
|
});
|
||
|
return self;
|
||
|
};
|
||
|
self.example = function (cmd, description) {
|
||
|
argsert('<string|array> [string]', [cmd, description], arguments.length);
|
||
|
if (Array.isArray(cmd)) {
|
||
|
cmd.forEach(exampleParams => self.example(...exampleParams));
|
||
|
}
|
||
|
else {
|
||
|
usage$1.example(cmd, description);
|
||
|
}
|
||
|
return self;
|
||
|
};
|
||
|
self.command = function (cmd, description, builder, handler, middlewares, deprecated) {
|
||
|
argsert('<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length);
|
||
|
command$1.addHandler(cmd, description, builder, handler, middlewares, deprecated);
|
||
|
return self;
|
||
|
};
|
||
|
self.commandDir = function (dir, opts) {
|
||
|
argsert('<string> [object]', [dir, opts], arguments.length);
|
||
|
const req = parentRequire || shim$1.require;
|
||
|
command$1.addDirectory(dir, self.getContext(), req, shim$1.getCallerFile(), opts);
|
||
|
return self;
|
||
|
};
|
||
|
self.demand = self.required = self.require = function demand(keys, max, msg) {
|
||
|
if (Array.isArray(max)) {
|
||
|
max.forEach(key => {
|
||
|
assertNotStrictEqual(msg, true, shim$1);
|
||
|
demandOption(key, msg);
|
||
|
});
|
||
|
max = Infinity;
|
||
|
}
|
||
|
else if (typeof max !== 'number') {
|
||
|
msg = max;
|
||
|
max = Infinity;
|
||
|
}
|
||
|
if (typeof keys === 'number') {
|
||
|
assertNotStrictEqual(msg, true, shim$1);
|
||
|
self.demandCommand(keys, max, msg, msg);
|
||
|
}
|
||
|
else if (Array.isArray(keys)) {
|
||
|
keys.forEach(key => {
|
||
|
assertNotStrictEqual(msg, true, shim$1);
|
||
|
demandOption(key, msg);
|
||
|
});
|
||
|
}
|
||
|
else {
|
||
|
if (typeof msg === 'string') {
|
||
|
demandOption(keys, msg);
|
||
|
}
|
||
|
else if (msg === true || typeof msg === 'undefined') {
|
||
|
demandOption(keys);
|
||
|
}
|
||
|
}
|
||
|
return self;
|
||
|
};
|
||
|
self.demandCommand = function demandCommand(min = 1, max, minMsg, maxMsg) {
|
||
|
argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length);
|
||
|
if (typeof max !== 'number') {
|
||
|
minMsg = max;
|
||
|
max = Infinity;
|
||
|
}
|
||
|
self.global('_', false);
|
||
|
options.demandedCommands._ = {
|
||
|
min,
|
||
|
max,
|
||
|
minMsg,
|
||
|
maxMsg,
|
||
|
};
|
||
|
return self;
|
||
|
};
|
||
|
self.getDemandedOptions = () => {
|
||
|
argsert([], 0);
|
||
|
return options.demandedOptions;
|
||
|
};
|
||
|
self.getDemandedCommands = () => {
|
||
|
argsert([], 0);
|
||
|
return options.demandedCommands;
|
||
|
};
|
||
|
self.deprecateOption = function deprecateOption(option, message) {
|
||
|
argsert('<string> [string|boolean]', [option, message], arguments.length);
|
||
|
options.deprecatedOptions[option] = message;
|
||
|
return self;
|
||
|
};
|
||
|
self.getDeprecatedOptions = () => {
|
||
|
argsert([], 0);
|
||
|
return options.deprecatedOptions;
|
||
|
};
|
||
|
self.implies = function (key, value) {
|
||
|
argsert('<string|object> [number|string|array]', [key, value], arguments.length);
|
||
|
validation$1.implies(key, value);
|
||
|
return self;
|
||
|
};
|
||
|
self.conflicts = function (key1, key2) {
|
||
|
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
|
||
|
validation$1.conflicts(key1, key2);
|
||
|
return self;
|
||
|
};
|
||
|
self.usage = function (msg, description, builder, handler) {
|
||
|
argsert('<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length);
|
||
|
if (description !== undefined) {
|
||
|
assertNotStrictEqual(msg, null, shim$1);
|
||
|
if ((msg || '').match(/^\$0( |$)/)) {
|
||
|
return self.command(msg, description, builder, handler);
|
||
|
}
|
||
|
else {
|
||
|
throw new YError('.usage() description must start with $0 if being used as alias for .command()');
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
usage$1.usage(msg);
|
||
|
return self;
|
||
|
}
|
||
|
};
|
||
|
self.epilogue = self.epilog = function (msg) {
|
||
|
argsert('<string>', [msg], arguments.length);
|
||
|
usage$1.epilog(msg);
|
||
|
return self;
|
||
|
};
|
||
|
self.fail = function (f) {
|
||
|
argsert('<function>', [f], arguments.length);
|
||
|
usage$1.failFn(f);
|
||
|
return self;
|
||
|
};
|
||
|
self.onFinishCommand = function (f) {
|
||
|
argsert('<function>', [f], arguments.length);
|
||
|
handlerFinishCommand = f;
|
||
|
return self;
|
||
|
};
|
||
|
self.getHandlerFinishCommand = () => handlerFinishCommand;
|
||
|
self.check = function (f, _global) {
|
||
|
argsert('<function> [boolean]', [f, _global], arguments.length);
|
||
|
validation$1.check(f, _global !== false);
|
||
|
return self;
|
||
|
};
|
||
|
self.global = function global(globals, global) {
|
||
|
argsert('<string|array> [boolean]', [globals, global], arguments.length);
|
||
|
globals = [].concat(globals);
|
||
|
if (global !== false) {
|
||
|
options.local = options.local.filter(l => globals.indexOf(l) === -1);
|
||
|
}
|
||
|
else {
|
||
|
globals.forEach(g => {
|
||
|
if (options.local.indexOf(g) === -1)
|
||
|
options.local.push(g);
|
||
|
});
|
||
|
}
|
||
|
return self;
|
||
|
};
|
||
|
self.pkgConf = function pkgConf(key, rootPath) {
|
||
|
argsert('<string> [string]', [key, rootPath], arguments.length);
|
||
|
let conf = null;
|
||
|
const obj = pkgUp(rootPath || cwd);
|
||
|
if (obj[key] && typeof obj[key] === 'object') {
|
||
|
conf = applyExtends(obj[key], rootPath || cwd, self.getParserConfiguration()['deep-merge-config'] || false, shim$1);
|
||
|
options.configObjects = (options.configObjects || []).concat(conf);
|
||
|
}
|
||
|
return self;
|
||
|
};
|
||
|
const pkgs = {};
|
||
|
function pkgUp(rootPath) {
|
||
|
const npath = rootPath || '*';
|
||
|
if (pkgs[npath])
|
||
|
return pkgs[npath];
|
||
|
let obj = {};
|
||
|
try {
|
||
|
let startDir = rootPath || shim$1.mainFilename;
|
||
|
if (!rootPath && shim$1.path.extname(startDir)) {
|
||
|
startDir = shim$1.path.dirname(startDir);
|
||
|
}
|
||
|
const pkgJsonPath = shim$1.findUp(startDir, (dir, names) => {
|
||
|
if (names.includes('package.json')) {
|
||
|
return 'package.json';
|
||
|
}
|
||
|
else {
|
||
|
return undefined;
|
||
|
}
|
||
|
});
|
||
|
assertNotStrictEqual(pkgJsonPath, undefined, shim$1);
|
||
|
obj = JSON.parse(shim$1.readFileSync(pkgJsonPath, 'utf8'));
|
||
|
}
|
||
|
catch (_noop) { }
|
||
|
pkgs[npath] = obj || {};
|
||
|
return pkgs[npath];
|
||
|
}
|
||
|
let parseFn = null;
|
||
|
let parseContext = null;
|
||
|
self.parse = function parse(args, shortCircuit, _parseFn) {
|
||
|
argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length);
|
||
|
freeze();
|
||
|
if (typeof args === 'undefined') {
|
||
|
const argv = self._parseArgs(processArgs);
|
||
|
const tmpParsed = self.parsed;
|
||
|
unfreeze();
|
||
|
self.parsed = tmpParsed;
|
||
|
return argv;
|
||
|
}
|
||
|
if (typeof shortCircuit === 'object') {
|
||
|
parseContext = shortCircuit;
|
||
|
shortCircuit = _parseFn;
|
||
|
}
|
||
|
if (typeof shortCircuit === 'function') {
|
||
|
parseFn = shortCircuit;
|
||
|
shortCircuit = false;
|
||
|
}
|
||
|
if (!shortCircuit)
|
||
|
processArgs = args;
|
||
|
if (parseFn)
|
||
|
exitProcess = false;
|
||
|
const parsed = self._parseArgs(args, !!shortCircuit);
|
||
|
completion$1.setParsed(self.parsed);
|
||
|
if (parseFn)
|
||
|
parseFn(exitError, parsed, output);
|
||
|
unfreeze();
|
||
|
return parsed;
|
||
|
};
|
||
|
self._getParseContext = () => parseContext || {};
|
||
|
self._hasParseCallback = () => !!parseFn;
|
||
|
self.option = self.options = function option(key, opt) {
|
||
|
argsert('<string|object> [object]', [key, opt], arguments.length);
|
||
|
if (typeof key === 'object') {
|
||
|
Object.keys(key).forEach(k => {
|
||
|
self.options(k, key[k]);
|
||
|
});
|
||
|
}
|
||
|
else {
|
||
|
if (typeof opt !== 'object') {
|
||
|
opt = {};
|
||
|
}
|
||
|
options.key[key] = true;
|
||
|
if (opt.alias)
|
||
|
self.alias(key, opt.alias);
|
||
|
const deprecate = opt.deprecate || opt.deprecated;
|
||
|
if (deprecate) {
|
||
|
self.deprecateOption(key, deprecate);
|
||
|
}
|
||
|
const demand = opt.demand || opt.required || opt.require;
|
||
|
if (demand) {
|
||
|
self.demand(key, demand);
|
||
|
}
|
||
|
if (opt.demandOption) {
|
||
|
self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined);
|
||
|
}
|
||
|
if (opt.conflicts) {
|
||
|
self.conflicts(key, opt.conflicts);
|
||
|
}
|
||
|
if ('default' in opt) {
|
||
|
self.default(key, opt.default);
|
||
|
}
|
||
|
if (opt.implies !== undefined) {
|
||
|
self.implies(key, opt.implies);
|
||
|
}
|
||
|
if (opt.nargs !== undefined) {
|
||
|
self.nargs(key, opt.nargs);
|
||
|
}
|
||
|
if (opt.config) {
|
||
|
self.config(key, opt.configParser);
|
||
|
}
|
||
|
if (opt.normalize) {
|
||
|
self.normalize(key);
|
||
|
}
|
||
|
if (opt.choices) {
|
||
|
self.choices(key, opt.choices);
|
||
|
}
|
||
|
if (opt.coerce) {
|
||
|
self.coerce(key, opt.coerce);
|
||
|
}
|
||
|
if (opt.group) {
|
||
|
self.group(key, opt.group);
|
||
|
}
|
||
|
if (opt.boolean || opt.type === 'boolean') {
|
||
|
self.boolean(key);
|
||
|
if (opt.alias)
|
||
|
self.boolean(opt.alias);
|
||
|
}
|
||
|
if (opt.array || opt.type === 'array') {
|
||
|
self.array(key);
|
||
|
if (opt.alias)
|
||
|
self.array(opt.alias);
|
||
|
}
|
||
|
if (opt.number || opt.type === 'number') {
|
||
|
self.number(key);
|
||
|
if (opt.alias)
|
||
|
self.number(opt.alias);
|
||
|
}
|
||
|
if (opt.string || opt.type === 'string') {
|
||
|
self.string(key);
|
||
|
if (opt.alias)
|
||
|
self.string(opt.alias);
|
||
|
}
|
||
|
if (opt.count || opt.type === 'count') {
|
||
|
self.count(key);
|
||
|
}
|
||
|
if (typeof opt.global === 'boolean') {
|
||
|
self.global(key, opt.global);
|
||
|
}
|
||
|
if (opt.defaultDescription) {
|
||
|
options.defaultDescription[key] = opt.defaultDescription;
|
||
|
}
|
||
|
if (opt.skipValidation) {
|
||
|
self.skipValidation(key);
|
||
|
}
|
||
|
const desc = opt.describe || opt.description || opt.desc;
|
||
|
self.describe(key, desc);
|
||
|
if (opt.hidden) {
|
||
|
self.hide(key);
|
||
|
}
|
||
|
if (opt.requiresArg) {
|
||
|
self.requiresArg(key);
|
||
|
}
|
||
|
}
|
||
|
return self;
|
||
|
};
|
||
|
self.getOptions = () => options;
|
||
|
self.positional = function (key, opts) {
|
||
|
argsert('<string> <object>', [key, opts], arguments.length);
|
||
|
if (context.resets === 0) {
|
||
|
throw new YError(".positional() can only be called in a command's builder function");
|
||
|
}
|
||
|
const supportedOpts = [
|
||
|
'default',
|
||
|
'defaultDescription',
|
||
|
'implies',
|
||
|
'normalize',
|
||
|
'choices',
|
||
|
'conflicts',
|
||
|
'coerce',
|
||
|
'type',
|
||
|
'describe',
|
||
|
'desc',
|
||
|
'description',
|
||
|
'alias',
|
||
|
];
|
||
|
opts = objFilter(opts, (k, v) => {
|
||
|
let accept = supportedOpts.indexOf(k) !== -1;
|
||
|
if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1)
|
||
|
accept = false;
|
||
|
return accept;
|
||
|
});
|
||
|
const fullCommand = context.fullCommands[context.fullCommands.length - 1];
|
||
|
const parseOptions = fullCommand
|
||
|
? command$1.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];
|
||
|
}
|
||
|
});
|
||
|
self.group(key, usage$1.getPositionalGroupName());
|
||
|
return self.option(key, opts);
|
||
|
};
|
||
|
self.group = function group(opts, groupName) {
|
||
|
argsert('<string|array> <string>', [opts, groupName], arguments.length);
|
||
|
const existing = preservedGroups[groupName] || groups[groupName];
|
||
|
if (preservedGroups[groupName]) {
|
||
|
delete preservedGroups[groupName];
|
||
|
}
|
||
|
const seen = {};
|
||
|
groups[groupName] = (existing || []).concat(opts).filter(key => {
|
||
|
if (seen[key])
|
||
|
return false;
|
||
|
return (seen[key] = true);
|
||
|
});
|
||
|
return self;
|
||
|
};
|
||
|
self.getGroups = () => Object.assign({}, groups, preservedGroups);
|
||
|
self.env = function (prefix) {
|
||
|
argsert('[string|boolean]', [prefix], arguments.length);
|
||
|
if (prefix === false)
|
||
|
delete options.envPrefix;
|
||
|
else
|
||
|
options.envPrefix = prefix || '';
|
||
|
return self;
|
||
|
};
|
||
|
self.wrap = function (cols) {
|
||
|
argsert('<number|null|undefined>', [cols], arguments.length);
|
||
|
usage$1.wrap(cols);
|
||
|
return self;
|
||
|
};
|
||
|
let strict = false;
|
||
|
self.strict = function (enabled) {
|
||
|
argsert('[boolean]', [enabled], arguments.length);
|
||
|
strict = enabled !== false;
|
||
|
return self;
|
||
|
};
|
||
|
self.getStrict = () => strict;
|
||
|
let strictCommands = false;
|
||
|
self.strictCommands = function (enabled) {
|
||
|
argsert('[boolean]', [enabled], arguments.length);
|
||
|
strictCommands = enabled !== false;
|
||
|
return self;
|
||
|
};
|
||
|
self.getStrictCommands = () => strictCommands;
|
||
|
let strictOptions = false;
|
||
|
self.strictOptions = function (enabled) {
|
||
|
argsert('[boolean]', [enabled], arguments.length);
|
||
|
strictOptions = enabled !== false;
|
||
|
return self;
|
||
|
};
|
||
|
self.getStrictOptions = () => strictOptions;
|
||
|
let parserConfig = {};
|
||
|
self.parserConfiguration = function parserConfiguration(config) {
|
||
|
argsert('<object>', [config], arguments.length);
|
||
|
parserConfig = config;
|
||
|
return self;
|
||
|
};
|
||
|
self.getParserConfiguration = () => parserConfig;
|
||
|
self.showHelp = function (level) {
|
||
|
argsert('[string|function]', [level], arguments.length);
|
||
|
if (!self.parsed)
|
||
|
self._parseArgs(processArgs);
|
||
|
if (command$1.hasDefaultCommand()) {
|
||
|
context.resets++;
|
||
|
command$1.runDefaultBuilderOn(self);
|
||
|
}
|
||
|
usage$1.showHelp(level);
|
||
|
return self;
|
||
|
};
|
||
|
let versionOpt = null;
|
||
|
self.version = function version(opt, msg, ver) {
|
||
|
const defaultVersionOpt = 'version';
|
||
|
argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length);
|
||
|
if (versionOpt) {
|
||
|
deleteFromParserHintObject(versionOpt);
|
||
|
usage$1.version(undefined);
|
||
|
versionOpt = null;
|
||
|
}
|
||
|
if (arguments.length === 0) {
|
||
|
ver = guessVersion();
|
||
|
opt = defaultVersionOpt;
|
||
|
}
|
||
|
else if (arguments.length === 1) {
|
||
|
if (opt === false) {
|
||
|
return self;
|
||
|
}
|
||
|
ver = opt;
|
||
|
opt = defaultVersionOpt;
|
||
|
}
|
||
|
else if (arguments.length === 2) {
|
||
|
ver = msg;
|
||
|
msg = undefined;
|
||
|
}
|
||
|
versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
|
||
|
msg = msg || usage$1.deferY18nLookup('Show version number');
|
||
|
usage$1.version(ver || undefined);
|
||
|
self.boolean(versionOpt);
|
||
|
self.describe(versionOpt, msg);
|
||
|
return self;
|
||
|
};
|
||
|
function guessVersion() {
|
||
|
const obj = pkgUp();
|
||
|
return obj.version || 'unknown';
|
||
|
}
|
||
|
let helpOpt = null;
|
||
|
self.addHelpOpt = self.help = function addHelpOpt(opt, msg) {
|
||
|
const defaultHelpOpt = 'help';
|
||
|
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
|
||
|
if (helpOpt) {
|
||
|
deleteFromParserHintObject(helpOpt);
|
||
|
helpOpt = null;
|
||
|
}
|
||
|
if (arguments.length === 1) {
|
||
|
if (opt === false)
|
||
|
return self;
|
||
|
}
|
||
|
helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
|
||
|
self.boolean(helpOpt);
|
||
|
self.describe(helpOpt, msg || usage$1.deferY18nLookup('Show help'));
|
||
|
return self;
|
||
|
};
|
||
|
const defaultShowHiddenOpt = 'show-hidden';
|
||
|
options.showHiddenOpt = defaultShowHiddenOpt;
|
||
|
self.addShowHiddenOpt = self.showHidden = function addShowHiddenOpt(opt, msg) {
|
||
|
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
|
||
|
if (arguments.length === 1) {
|
||
|
if (opt === false)
|
||
|
return self;
|
||
|
}
|
||
|
const showHiddenOpt = typeof opt === 'string' ? opt : defaultShowHiddenOpt;
|
||
|
self.boolean(showHiddenOpt);
|
||
|
self.describe(showHiddenOpt, msg || usage$1.deferY18nLookup('Show hidden options'));
|
||
|
options.showHiddenOpt = showHiddenOpt;
|
||
|
return self;
|
||
|
};
|
||
|
self.hide = function hide(key) {
|
||
|
argsert('<string>', [key], arguments.length);
|
||
|
options.hiddenOptions.push(key);
|
||
|
return self;
|
||
|
};
|
||
|
self.showHelpOnFail = function showHelpOnFail(enabled, message) {
|
||
|
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
|
||
|
usage$1.showHelpOnFail(enabled, message);
|
||
|
return self;
|
||
|
};
|
||
|
let exitProcess = true;
|
||
|
self.exitProcess = function (enabled = true) {
|
||
|
argsert('[boolean]', [enabled], arguments.length);
|
||
|
exitProcess = enabled;
|
||
|
return self;
|
||
|
};
|
||
|
self.getExitProcess = () => exitProcess;
|
||
|
self.showCompletionScript = function ($0, cmd) {
|
||
|
argsert('[string] [string]', [$0, cmd], arguments.length);
|
||
|
$0 = $0 || self.$0;
|
||
|
_logger.log(completion$1.generateCompletionScript($0, cmd || completionCommand || 'completion'));
|
||
|
return self;
|
||
|
};
|
||
|
self.getCompletion = function (args, done) {
|
||
|
argsert('<array> <function>', [args, done], arguments.length);
|
||
|
completion$1.getCompletion(args, done);
|
||
|
};
|
||
|
self.locale = function (locale) {
|
||
|
argsert('[string]', [locale], arguments.length);
|
||
|
if (!locale) {
|
||
|
guessLocale();
|
||
|
return y18n.getLocale();
|
||
|
}
|
||
|
detectLocale = false;
|
||
|
y18n.setLocale(locale);
|
||
|
return self;
|
||
|
};
|
||
|
self.updateStrings = self.updateLocale = function (obj) {
|
||
|
argsert('<object>', [obj], arguments.length);
|
||
|
detectLocale = false;
|
||
|
y18n.updateLocale(obj);
|
||
|
return self;
|
||
|
};
|
||
|
let detectLocale = true;
|
||
|
self.detectLocale = function (detect) {
|
||
|
argsert('<boolean>', [detect], arguments.length);
|
||
|
detectLocale = detect;
|
||
|
return self;
|
||
|
};
|
||
|
self.getDetectLocale = () => detectLocale;
|
||
|
const _logger = {
|
||
|
log(...args) {
|
||
|
if (!self._hasParseCallback())
|
||
|
console.log(...args);
|
||
|
hasOutput = true;
|
||
|
if (output.length)
|
||
|
output += '\n';
|
||
|
output += args.join(' ');
|
||
|
},
|
||
|
error(...args) {
|
||
|
if (!self._hasParseCallback())
|
||
|
console.error(...args);
|
||
|
hasOutput = true;
|
||
|
if (output.length)
|
||
|
output += '\n';
|
||
|
output += args.join(' ');
|
||
|
},
|
||
|
};
|
||
|
self._getLoggerInstance = () => _logger;
|
||
|
self._hasOutput = () => hasOutput;
|
||
|
self._setHasOutput = () => {
|
||
|
hasOutput = true;
|
||
|
};
|
||
|
let recommendCommands;
|
||
|
self.recommendCommands = function (recommend = true) {
|
||
|
argsert('[boolean]', [recommend], arguments.length);
|
||
|
recommendCommands = recommend;
|
||
|
return self;
|
||
|
};
|
||
|
self.getUsageInstance = () => usage$1;
|
||
|
self.getValidationInstance = () => validation$1;
|
||
|
self.getCommandInstance = () => command$1;
|
||
|
self.terminalWidth = () => {
|
||
|
argsert([], 0);
|
||
|
return shim$1.process.stdColumns;
|
||
|
};
|
||
|
Object.defineProperty(self, 'argv', {
|
||
|
get: () => self._parseArgs(processArgs),
|
||
|
enumerable: true,
|
||
|
});
|
||
|
self._parseArgs = function parseArgs(args, shortCircuit, _calledFromCommand, commandIndex) {
|
||
|
let skipValidation = !!_calledFromCommand;
|
||
|
args = args || processArgs;
|
||
|
options.__ = y18n.__;
|
||
|
options.configuration = self.getParserConfiguration();
|
||
|
const populateDoubleDash = !!options.configuration['populate--'];
|
||
|
const config = Object.assign({}, options.configuration, {
|
||
|
'populate--': true,
|
||
|
});
|
||
|
const parsed = shim$1.Parser.detailed(args, Object.assign({}, options, {
|
||
|
configuration: Object.assign({ 'parse-positional-numbers': false }, config),
|
||
|
}));
|
||
|
let argv = parsed.argv;
|
||
|
if (parseContext)
|
||
|
argv = Object.assign({}, argv, parseContext);
|
||
|
const aliases = parsed.aliases;
|
||
|
argv.$0 = self.$0;
|
||
|
self.parsed = parsed;
|
||
|
try {
|
||
|
guessLocale();
|
||
|
if (shortCircuit) {
|
||
|
return self._postProcess(argv, populateDoubleDash, _calledFromCommand);
|
||
|
}
|
||
|
if (helpOpt) {
|
||
|
const helpCmds = [helpOpt]
|
||
|
.concat(aliases[helpOpt] || [])
|
||
|
.filter(k => k.length > 1);
|
||
|
if (~helpCmds.indexOf('' + argv._[argv._.length - 1])) {
|
||
|
argv._.pop();
|
||
|
argv[helpOpt] = true;
|
||
|
}
|
||
|
}
|
||
|
const handlerKeys = command$1.getCommands();
|
||
|
const requestCompletions = completion$1.completionKey in argv;
|
||
|
const skipRecommendation = argv[helpOpt] || requestCompletions;
|
||
|
const skipDefaultCommand = skipRecommendation &&
|
||
|
(handlerKeys.length > 1 || handlerKeys[0] !== '$0');
|
||
|
if (argv._.length) {
|
||
|
if (handlerKeys.length) {
|
||
|
let firstUnknownCommand;
|
||
|
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
|
||
|
cmd = String(argv._[i]);
|
||
|
if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
|
||
|
const innerArgv = command$1.runCommand(cmd, self, parsed, i + 1);
|
||
|
return self._postProcess(innerArgv, populateDoubleDash);
|
||
|
}
|
||
|
else if (!firstUnknownCommand && cmd !== completionCommand) {
|
||
|
firstUnknownCommand = cmd;
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
if (command$1.hasDefaultCommand() && !skipDefaultCommand) {
|
||
|
const innerArgv = command$1.runCommand(null, self, parsed);
|
||
|
return self._postProcess(innerArgv, populateDoubleDash);
|
||
|
}
|
||
|
if (recommendCommands && firstUnknownCommand && !skipRecommendation) {
|
||
|
validation$1.recommendCommands(firstUnknownCommand, handlerKeys);
|
||
|
}
|
||
|
}
|
||
|
if (completionCommand &&
|
||
|
~argv._.indexOf(completionCommand) &&
|
||
|
!requestCompletions) {
|
||
|
if (exitProcess)
|
||
|
setBlocking(true);
|
||
|
self.showCompletionScript();
|
||
|
self.exit(0);
|
||
|
}
|
||
|
}
|
||
|
else if (command$1.hasDefaultCommand() && !skipDefaultCommand) {
|
||
|
const innerArgv = command$1.runCommand(null, self, parsed);
|
||
|
return self._postProcess(innerArgv, populateDoubleDash);
|
||
|
}
|
||
|
if (requestCompletions) {
|
||
|
if (exitProcess)
|
||
|
setBlocking(true);
|
||
|
args = [].concat(args);
|
||
|
const completionArgs = args.slice(args.indexOf(`--${completion$1.completionKey}`) + 1);
|
||
|
completion$1.getCompletion(completionArgs, completions => {
|
||
|
(completions || []).forEach(completion => {
|
||
|
_logger.log(completion);
|
||
|
});
|
||
|
self.exit(0);
|
||
|
});
|
||
|
return self._postProcess(argv, !populateDoubleDash, _calledFromCommand);
|
||
|
}
|
||
|
if (!hasOutput) {
|
||
|
Object.keys(argv).forEach(key => {
|
||
|
if (key === helpOpt && argv[key]) {
|
||
|
if (exitProcess)
|
||
|
setBlocking(true);
|
||
|
skipValidation = true;
|
||
|
self.showHelp('log');
|
||
|
self.exit(0);
|
||
|
}
|
||
|
else if (key === versionOpt && argv[key]) {
|
||
|
if (exitProcess)
|
||
|
setBlocking(true);
|
||
|
skipValidation = true;
|
||
|
usage$1.showVersion();
|
||
|
self.exit(0);
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
if (!skipValidation && options.skipValidation.length > 0) {
|
||
|
skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true);
|
||
|
}
|
||
|
if (!skipValidation) {
|
||
|
if (parsed.error)
|
||
|
throw new YError(parsed.error.message);
|
||
|
if (!requestCompletions) {
|
||
|
self._runValidation(argv, aliases, {}, parsed.error);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
catch (err) {
|
||
|
if (err instanceof YError)
|
||
|
usage$1.fail(err.message, err);
|
||
|
else
|
||
|
throw err;
|
||
|
}
|
||
|
return self._postProcess(argv, populateDoubleDash, _calledFromCommand);
|
||
|
};
|
||
|
self._postProcess = function (argv, populateDoubleDash, calledFromCommand = false) {
|
||
|
if (isPromise(argv))
|
||
|
return argv;
|
||
|
if (calledFromCommand)
|
||
|
return argv;
|
||
|
if (!populateDoubleDash) {
|
||
|
argv = self._copyDoubleDash(argv);
|
||
|
}
|
||
|
const parsePositionalNumbers = self.getParserConfiguration()['parse-positional-numbers'] ||
|
||
|
self.getParserConfiguration()['parse-positional-numbers'] === undefined;
|
||
|
if (parsePositionalNumbers) {
|
||
|
argv = self._parsePositionalNumbers(argv);
|
||
|
}
|
||
|
return argv;
|
||
|
};
|
||
|
self._copyDoubleDash = function (argv) {
|
||
|
if (!argv._ || !argv['--'])
|
||
|
return argv;
|
||
|
argv._.push.apply(argv._, argv['--']);
|
||
|
try {
|
||
|
delete argv['--'];
|
||
|
}
|
||
|
catch (_err) { }
|
||
|
return argv;
|
||
|
};
|
||
|
self._parsePositionalNumbers = function (argv) {
|
||
|
const args = argv['--'] ? argv['--'] : argv._;
|
||
|
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
|
||
|
if (shim$1.Parser.looksLikeNumber(arg) &&
|
||
|
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
|
||
|
args[i] = Number(arg);
|
||
|
}
|
||
|
}
|
||
|
return argv;
|
||
|
};
|
||
|
self._runValidation = function runValidation(argv, aliases, positionalMap, parseErrors, isDefaultCommand = false) {
|
||
|
if (parseErrors)
|
||
|
throw new YError(parseErrors.message);
|
||
|
validation$1.nonOptionCount(argv);
|
||
|
validation$1.requiredArguments(argv);
|
||
|
let failedStrictCommands = false;
|
||
|
if (strictCommands) {
|
||
|
failedStrictCommands = validation$1.unknownCommands(argv);
|
||
|
}
|
||
|
if (strict && !failedStrictCommands) {
|
||
|
validation$1.unknownArguments(argv, aliases, positionalMap, isDefaultCommand);
|
||
|
}
|
||
|
else if (strictOptions) {
|
||
|
validation$1.unknownArguments(argv, aliases, {}, false, false);
|
||
|
}
|
||
|
validation$1.customChecks(argv, aliases);
|
||
|
validation$1.limitedChoices(argv);
|
||
|
validation$1.implications(argv);
|
||
|
validation$1.conflicting(argv);
|
||
|
};
|
||
|
function guessLocale() {
|
||
|
if (!detectLocale)
|
||
|
return;
|
||
|
const locale = shim$1.getEnv('LC_ALL') ||
|
||
|
shim$1.getEnv('LC_MESSAGES') ||
|
||
|
shim$1.getEnv('LANG') ||
|
||
|
shim$1.getEnv('LANGUAGE') ||
|
||
|
'en_US';
|
||
|
self.locale(locale.replace(/[.:].*/, ''));
|
||
|
}
|
||
|
self.help();
|
||
|
self.version();
|
||
|
return self;
|
||
|
}
|
||
|
const rebase = (base, dir) => shim$1.path.relative(base, dir);
|
||
|
function isYargsInstance(y) {
|
||
|
return !!y && typeof y._parseArgs === 'function';
|
||
|
}
|
||
|
|
||
|
var _a, _b;
|
||
|
const { readFileSync } = require('fs');
|
||
|
const { inspect } = require('util');
|
||
|
const { resolve } = require('path');
|
||
|
const y18n = require('y18n');
|
||
|
const Parser = require('yargs-parser');
|
||
|
var cjsPlatformShim = {
|
||
|
assert: {
|
||
|
notStrictEqual: assert.notStrictEqual,
|
||
|
strictEqual: assert.strictEqual,
|
||
|
},
|
||
|
cliui: require('cliui'),
|
||
|
findUp: require('escalade/sync'),
|
||
|
getEnv: (key) => {
|
||
|
return process.env[key];
|
||
|
},
|
||
|
getCallerFile: require('get-caller-file'),
|
||
|
getProcessArgvBin: getProcessArgvBin,
|
||
|
inspect,
|
||
|
mainFilename: (_b = (_a = require === null || require === void 0 ? void 0 : require.main) === null || _a === void 0 ? void 0 : _a.filename) !== null && _b !== void 0 ? _b : process.cwd(),
|
||
|
Parser,
|
||
|
path: require('path'),
|
||
|
process: {
|
||
|
argv: () => process.argv,
|
||
|
cwd: process.cwd,
|
||
|
execPath: () => process.execPath,
|
||
|
exit: (code) => {
|
||
|
process.exit(code);
|
||
|
},
|
||
|
nextTick: process.nextTick,
|
||
|
stdColumns: typeof process.stdout.columns !== 'undefined'
|
||
|
? process.stdout.columns
|
||
|
: null,
|
||
|
},
|
||
|
readFileSync,
|
||
|
require: require,
|
||
|
requireDirectory: require('require-directory'),
|
||
|
stringWidth: require('string-width'),
|
||
|
y18n: y18n({
|
||
|
directory: resolve(__dirname, '../locales'),
|
||
|
updateFiles: false,
|
||
|
}),
|
||
|
};
|
||
|
|
||
|
const minNodeVersion = process && process.env && process.env.YARGS_MIN_NODE_VERSION
|
||
|
? Number(process.env.YARGS_MIN_NODE_VERSION)
|
||
|
: 10;
|
||
|
if (process && process.version) {
|
||
|
const major = Number(process.version.match(/v([^.]+)/)[1]);
|
||
|
if (major < minNodeVersion) {
|
||
|
throw Error(`yargs supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs#supported-nodejs-versions`);
|
||
|
}
|
||
|
}
|
||
|
const Parser$1 = require('yargs-parser');
|
||
|
const Yargs$1 = YargsWithShim(cjsPlatformShim);
|
||
|
var cjs = {
|
||
|
applyExtends,
|
||
|
cjsPlatformShim,
|
||
|
Yargs: Yargs$1,
|
||
|
argsert,
|
||
|
globalMiddlewareFactory,
|
||
|
isPromise,
|
||
|
objFilter,
|
||
|
parseCommand,
|
||
|
Parser: Parser$1,
|
||
|
processArgv,
|
||
|
rebase,
|
||
|
YError,
|
||
|
};
|
||
|
|
||
|
module.exports = cjs;
|