This commit is contained in:
tatianamac
2019-11-26 14:50:43 -08:00
parent 8a55660ed0
commit 6d5445ecc5
13894 changed files with 2233957 additions and 0 deletions

15
node_modules/yargs/lib/assign.js generated vendored Normal file
View File

@ -0,0 +1,15 @@
// lazy Object.assign logic that only works for merging
// two objects; eventually we should replace this with Object.assign.
module.exports = function assign (defaults, configuration) {
var o = {}
configuration = configuration || {}
Object.keys(defaults).forEach(function (k) {
o[k] = defaults[k]
})
Object.keys(configuration).forEach(function (k) {
o[k] = configuration[k]
})
return o
}

250
node_modules/yargs/lib/command.js generated vendored Normal file
View File

@ -0,0 +1,250 @@
const path = require('path')
const inspect = require('util').inspect
const camelCase = require('camelcase')
// handles parsing positional arguments,
// and populating argv with said positional
// arguments.
module.exports = function (yargs, usage, validation) {
const self = {}
var handlers = {}
var aliasMap = {}
self.addHandler = function (cmd, description, builder, handler) {
var aliases = []
if (Array.isArray(cmd)) {
aliases = cmd.slice(1)
cmd = cmd[0]
} else if (typeof cmd === 'object') {
var 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)
return
}
// allow a module to be provided instead of separate builder and handler
if (typeof builder === 'object' && builder.builder && typeof builder.handler === 'function') {
self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler)
return
}
var parsedCommand = parseCommand(cmd)
aliases = aliases.map(function (alias) {
alias = parseCommand(alias).cmd // remove positional args
aliasMap[alias] = parsedCommand.cmd
return alias
})
if (description !== false) {
usage.command(cmd, description, aliases)
}
handlers[parsedCommand.cmd] = {
original: cmd,
handler: handler,
builder: builder || {},
demanded: parsedCommand.demanded,
optional: parsedCommand.optional
}
}
self.addDirectory = function (dir, context, req, callerFile, opts) {
opts = opts || {}
// disable recursion to support nested directories of subcommands
if (typeof opts.recurse !== 'boolean') opts.recurse = false
// exclude 'json', 'coffee' from require-directory defaults
if (!Array.isArray(opts.extensions)) opts.extensions = ['js']
// allow consumer to define their own visitor function
const parentVisit = typeof opts.visit === 'function' ? opts.visit : function (o) { return o }
// call addHandler via visitor function
opts.visit = function (obj, joined, filename) {
const visited = parentVisit(obj, joined, filename)
// allow consumer to skip modules with their own visitor
if (visited) {
// check for cyclic reference
// each command file path should only be seen once per execution
if (~context.files.indexOf(joined)) return visited
// keep track of visited files in context.files
context.files.push(joined)
self.addHandler(visited)
}
return visited
}
require('require-directory')({ require: req, filename: callerFile }, dir, opts)
}
// lookup module object from require()d command and derive name
// if module was not require()d and no name given, throw error
function moduleName (obj) {
const mod = require('which-module')(obj)
if (!mod) throw new Error('No command name given for module: ' + inspect(obj))
return commandFromFilename(mod.filename)
}
// derive command name from filename
function commandFromFilename (filename) {
return path.basename(filename, path.extname(filename))
}
function extractDesc (obj) {
for (var keys = ['describe', 'description', 'desc'], i = 0, l = keys.length, test; i < l; i++) {
test = obj[keys[i]]
if (typeof test === 'string' || typeof test === 'boolean') return test
}
return false
}
function parseCommand (cmd) {
var extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ')
var splitCommand = extraSpacesStrippedCommand.split(/\s/)
var bregex = /\.*[\][<>]/g
var parsedCommand = {
cmd: (splitCommand.shift()).replace(bregex, ''),
demanded: [],
optional: []
}
splitCommand.forEach(function (cmd, i) {
var variadic = false
if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) variadic = true
if (/^\[/.test(cmd)) {
parsedCommand.optional.push({
cmd: cmd.replace(bregex, ''),
variadic: variadic
})
} else {
parsedCommand.demanded.push({
cmd: cmd.replace(bregex, ''),
variadic: variadic
})
}
})
return parsedCommand
}
self.getCommands = function () {
return Object.keys(handlers).concat(Object.keys(aliasMap))
}
self.getCommandHandlers = function () {
return handlers
}
self.runCommand = function (command, yargs, parsed) {
var argv = parsed.argv
var commandHandler = handlers[command] || handlers[aliasMap[command]]
var innerArgv = argv
var currentContext = yargs.getContext()
var numFiles = currentContext.files.length
var parentCommands = currentContext.commands.slice()
currentContext.commands.push(command)
if (typeof commandHandler.builder === 'function') {
// a function can be provided, which builds
// up a yargs chain and possibly returns it.
innerArgv = commandHandler.builder(yargs.reset(parsed.aliases))
// if the builder function did not yet parse argv with reset yargs
// and did not explicitly set a usage() string, then apply the
// original command string as usage() for consistent behavior with
// options object below
if (yargs.parsed === false) {
if (typeof yargs.getUsageInstance().getUsage() === 'undefined') {
yargs.usage('$0 ' + (parentCommands.length ? parentCommands.join(' ') + ' ' : '') + commandHandler.original)
}
innerArgv = innerArgv ? innerArgv.argv : yargs.argv
} else {
innerArgv = yargs.parsed.argv
}
} else if (typeof commandHandler.builder === 'object') {
// as a short hand, an object can instead be provided, specifying
// the options that a command takes.
innerArgv = yargs.reset(parsed.aliases)
innerArgv.usage('$0 ' + (parentCommands.length ? parentCommands.join(' ') + ' ' : '') + commandHandler.original)
Object.keys(commandHandler.builder).forEach(function (key) {
innerArgv.option(key, commandHandler.builder[key])
})
innerArgv = innerArgv.argv
}
if (!yargs._hasOutput()) populatePositional(commandHandler, innerArgv, currentContext, yargs)
if (commandHandler.handler && !yargs._hasOutput()) {
commandHandler.handler(innerArgv)
}
currentContext.commands.pop()
numFiles = currentContext.files.length - numFiles
if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles)
return innerArgv
}
function populatePositional (commandHandler, argv, context, yargs) {
argv._ = argv._.slice(context.commands.length) // nuke the current commands
var demanded = commandHandler.demanded.slice(0)
var optional = commandHandler.optional.slice(0)
validation.positionalCount(demanded.length, argv._.length)
while (demanded.length) {
var demand = demanded.shift()
if (demand.variadic) argv[demand.cmd] = []
if (!argv._.length) break
if (demand.variadic) argv[demand.cmd] = argv._.splice(0)
else argv[demand.cmd] = argv._.shift()
postProcessPositional(yargs, argv, demand.cmd)
addCamelCaseExpansions(argv, demand.cmd)
}
while (optional.length) {
var maybe = optional.shift()
if (maybe.variadic) argv[maybe.cmd] = []
if (!argv._.length) break
if (maybe.variadic) argv[maybe.cmd] = argv._.splice(0)
else argv[maybe.cmd] = argv._.shift()
postProcessPositional(yargs, argv, maybe.cmd)
addCamelCaseExpansions(argv, maybe.cmd)
}
argv._ = context.commands.concat(argv._)
}
// TODO move positional arg logic to yargs-parser and remove this duplication
function postProcessPositional (yargs, argv, key) {
var coerce = yargs.getOptions().coerce[key]
if (typeof coerce === 'function') {
try {
argv[key] = coerce(argv[key])
} catch (err) {
yargs.getUsageInstance().fail(err.message, err)
}
}
}
function addCamelCaseExpansions (argv, option) {
if (/-/.test(option)) {
const cc = camelCase(option)
if (typeof argv[option] === 'object') argv[cc] = argv[option].slice(0)
else argv[cc] = argv[option]
}
}
self.reset = function () {
handlers = {}
aliasMap = {}
return self
}
// used by yargs.parse() to freeze
// the state of commands such that
// we can apply .parse() multiple times
// with the same yargs instance.
var frozen
self.freeze = function () {
frozen = {}
frozen.handlers = handlers
frozen.aliasMap = aliasMap
}
self.unfreeze = function () {
handlers = frozen.handlers
aliasMap = frozen.aliasMap
frozen = undefined
}
return self
}

99
node_modules/yargs/lib/completion.js generated vendored Normal file
View File

@ -0,0 +1,99 @@
const fs = require('fs')
const path = require('path')
// add bash completions to your
// yargs-powered applications.
module.exports = function (yargs, usage, command) {
const self = {
completionKey: 'get-yargs-completions'
}
// get a list of completion commands.
// 'args' is the array of strings from the line to be completed
self.getCompletion = function (args, done) {
const completions = []
const current = args.length ? args[args.length - 1] : ''
const argv = yargs.parse(args, true)
const aliases = yargs.parsed.aliases
// a custom completion function can be provided
// to completion().
if (completionFunction) {
if (completionFunction.length < 3) {
var result = completionFunction(current, argv)
// promise based completion function.
if (typeof result.then === 'function') {
return result.then(function (list) {
process.nextTick(function () { done(list) })
}).catch(function (err) {
process.nextTick(function () { throw err })
})
}
// synchronous completion function.
return done(result)
} else {
// asynchronous completion function
return completionFunction(current, argv, function (completions) {
done(completions)
})
}
}
var handlers = command.getCommandHandlers()
for (var i = 0, ii = args.length; i < ii; ++i) {
if (handlers[args[i]] && handlers[args[i]].builder) {
return handlers[args[i]].builder(yargs.reset()).argv
}
}
if (!current.match(/^-/)) {
usage.getCommands().forEach(function (command) {
if (args.indexOf(command[0]) === -1) {
completions.push(command[0])
}
})
}
if (current.match(/^-/)) {
Object.keys(yargs.getOptions().key).forEach(function (key) {
// If the key and its aliases aren't in 'args', add the key to 'completions'
var keyAndAliases = [key].concat(aliases[key] || [])
var notInArgs = keyAndAliases.every(function (val) {
return args.indexOf('--' + val) === -1
})
if (notInArgs) {
completions.push('--' + key)
}
})
}
done(completions)
}
// generate the completion script to add to your .bashrc.
self.generateCompletionScript = function ($0) {
var script = fs.readFileSync(
path.resolve(__dirname, '../completion.sh.hbs'),
'utf-8'
)
var name = path.basename($0)
// add ./to applications not yet installed as bin.
if ($0.match(/\.js$/)) $0 = './' + $0
script = script.replace(/{{app_name}}/g, name)
return script.replace(/{{app_path}}/g, $0)
}
// register a function to perform your own custom
// completions., this function can be either
// synchrnous or asynchronous.
var completionFunction = null
self.registerFunction = function (fn) {
completionFunction = fn
}
return self
}

47
node_modules/yargs/lib/levenshtein.js generated vendored Normal file
View File

@ -0,0 +1,47 @@
/*
Copyright (c) 2011 Andrei Mackenzie
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed.
// gist, which can be found here: https://gist.github.com/andrei-m/982927
// Compute the edit distance between the two given strings
module.exports = function (a, b) {
if (a.length === 0) return b.length
if (b.length === 0) return a.length
var matrix = []
// increment along the first column of each row
var i
for (i = 0; i <= b.length; i++) {
matrix[i] = [i]
}
// increment each column in the first row
var j
for (j = 0; j <= a.length; j++) {
matrix[0][j] = j
}
// Fill in the rest of the matrix
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, // substitution
Math.min(matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j] + 1)) // deletion
}
}
}
return matrix[b.length][a.length]
}

10
node_modules/yargs/lib/obj-filter.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
module.exports = function (original, filter) {
const obj = {}
filter = filter || function (k, v) { return true }
Object.keys(original || {}).forEach(function (key) {
if (filter(key, original[key])) {
obj[key] = original[key]
}
})
return obj
}

454
node_modules/yargs/lib/usage.js generated vendored Normal file
View File

@ -0,0 +1,454 @@
// this file handles outputting usage instructions,
// failures, etc. keeps logging in one place.
const stringWidth = require('string-width')
const objFilter = require('./obj-filter')
const setBlocking = require('set-blocking')
module.exports = function (yargs, y18n) {
const __ = y18n.__
const self = {}
// methods for ouputting/building failure message.
var fails = []
self.failFn = function (f) {
fails.push(f)
}
var failMessage = null
var showHelpOnFail = true
self.showHelpOnFail = function (enabled, message) {
if (typeof enabled === 'string') {
message = enabled
enabled = true
} else if (typeof enabled === 'undefined') {
enabled = true
}
failMessage = message
showHelpOnFail = enabled
return self
}
var failureOutput = false
self.fail = function (msg, err) {
const logger = yargs._getLoggerInstance()
if (fails.length) {
for (var i = fails.length - 1; i >= 0; --i) {
fails[i](msg, err, self)
}
} else {
if (yargs.getExitProcess()) setBlocking(true)
// don't output failure message more than once
if (!failureOutput) {
failureOutput = true
if (showHelpOnFail) yargs.showHelp('error')
if (msg) logger.error(msg)
if (failMessage) {
if (msg) logger.error('')
logger.error(failMessage)
}
}
err = err || new Error(msg)
if (yargs.getExitProcess()) {
return yargs.exit(1)
} else if (yargs._hasParseCallback()) {
return yargs.exit(1, err)
} else {
throw err
}
}
}
// methods for ouputting/building help (usage) message.
var usage
self.usage = function (msg) {
usage = msg
}
self.getUsage = function () {
return usage
}
var examples = []
self.example = function (cmd, description) {
examples.push([cmd, description || ''])
}
var commands = []
self.command = function (cmd, description, aliases) {
commands.push([cmd, description || '', aliases])
}
self.getCommands = function () {
return commands
}
var descriptions = {}
self.describe = function (key, desc) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.describe(k, key[k])
})
} else {
descriptions[key] = desc
}
}
self.getDescriptions = function () {
return descriptions
}
var epilog
self.epilog = function (msg) {
epilog = msg
}
var wrapSet = false
var wrap
self.wrap = function (cols) {
wrapSet = true
wrap = cols
}
function getWrap () {
// lazily call windowWidth() because it's very expensive,
// and only needs to be called if the user wants to show usage/help
if (!wrapSet) {
wrap = windowWidth()
wrapSet = true
}
return wrap
}
var deferY18nLookupPrefix = '__yargsString__:'
self.deferY18nLookup = function (str) {
return deferY18nLookupPrefix + str
}
var defaultGroup = 'Options:'
self.help = function () {
normalizeAliases()
var demanded = yargs.getDemanded()
var groups = yargs.getGroups()
var options = yargs.getOptions()
var keys = Object.keys(
Object.keys(descriptions)
.concat(Object.keys(demanded))
.concat(Object.keys(options.default))
.reduce(function (acc, key) {
if (key !== '_') acc[key] = true
return acc
}, {})
)
var theWrap = getWrap()
var ui = require('cliui')({
width: theWrap,
wrap: !!theWrap
})
// the usage string.
if (usage) {
var u = usage.replace(/\$0/g, yargs.$0)
ui.div(u + '\n')
}
// your application's commands, i.e., non-option
// arguments populated in '_'.
if (commands.length) {
ui.div(__('Commands:'))
commands.forEach(function (command) {
ui.span(
{text: command[0], padding: [0, 2, 0, 2], width: maxWidth(commands, theWrap) + 4},
{text: command[1]}
)
if (command[2] && command[2].length) {
ui.div({text: '[' + __('aliases:') + ' ' + command[2].join(', ') + ']', padding: [0, 0, 0, 2], align: 'right'})
} else {
ui.div()
}
})
ui.div()
}
// perform some cleanup on the keys array, making it
// only include top-level keys not their aliases.
var aliasKeys = (Object.keys(options.alias) || [])
.concat(Object.keys(yargs.parsed.newAliases) || [])
keys = keys.filter(function (key) {
return !yargs.parsed.newAliases[key] && aliasKeys.every(function (alias) {
return (options.alias[alias] || []).indexOf(key) === -1
})
})
// populate 'Options:' group with any keys that have not
// explicitly had a group set.
if (!groups[defaultGroup]) groups[defaultGroup] = []
addUngroupedKeys(keys, options.alias, groups)
// display 'Options:' table along with any custom tables:
Object.keys(groups).forEach(function (groupName) {
if (!groups[groupName].length) return
ui.div(__(groupName))
// if we've grouped the key 'f', but 'f' aliases 'foobar',
// normalizedKeys should contain only 'foobar'.
var normalizedKeys = groups[groupName].map(function (key) {
if (~aliasKeys.indexOf(key)) return key
for (var i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
if (~(options.alias[aliasKey] || []).indexOf(key)) return aliasKey
}
return key
})
// actually generate the switches string --foo, -f, --bar.
var switches = normalizedKeys.reduce(function (acc, key) {
acc[key] = [ key ].concat(options.alias[key] || [])
.map(function (sw) {
return (sw.length > 1 ? '--' : '-') + sw
})
.join(', ')
return acc
}, {})
normalizedKeys.forEach(function (key) {
var kswitch = switches[key]
var desc = descriptions[key] || ''
var 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') + ']'
var extra = [
type,
demanded[key] ? '[' + __('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: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4},
desc
)
if (extra) ui.div({text: extra, padding: [0, 0, 0, 2], align: 'right'})
else ui.div()
})
ui.div()
})
// describe some common use-cases for your application.
if (examples.length) {
ui.div(__('Examples:'))
examples.forEach(function (example) {
example[0] = example[0].replace(/\$0/g, yargs.$0)
})
examples.forEach(function (example) {
ui.div(
{text: example[0], padding: [0, 2, 0, 2], width: maxWidth(examples, theWrap) + 4},
example[1]
)
})
ui.div()
}
// the usage string.
if (epilog) {
var e = epilog.replace(/\$0/g, yargs.$0)
ui.div(e + '\n')
}
return ui.toString()
}
// return the maximum width of a string
// in the left-hand column of a table.
function maxWidth (table, theWrap) {
var width = 0
// table might be of the form [leftColumn],
// or {key: leftColumn}
if (!Array.isArray(table)) {
table = Object.keys(table).map(function (key) {
return [table[key]]
})
}
table.forEach(function (v) {
width = Math.max(stringWidth(v[0]), width)
})
// if we've enabled 'wrap' we should limit
// the max-width of the left-column.
if (theWrap) width = Math.min(width, parseInt(theWrap * 0.5, 10))
return width
}
// make sure any options set for aliases,
// are copied to the keys being aliased.
function normalizeAliases () {
var demanded = yargs.getDemanded()
var options = yargs.getOptions()
;(Object.keys(options.alias) || []).forEach(function (key) {
options.alias[key].forEach(function (alias) {
// copy descriptions.
if (descriptions[alias]) self.describe(key, descriptions[alias])
// copy demanded.
if (demanded[alias]) yargs.demand(key, demanded[alias].msg)
// type messages.
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)
})
})
}
// given a set of keys, place any keys that are
// ungrouped under the 'Options:' grouping.
function addUngroupedKeys (keys, aliases, groups) {
var groupedKeys = []
var toCheck = null
Object.keys(groups).forEach(function (group) {
groupedKeys = groupedKeys.concat(groups[group])
})
keys.forEach(function (key) {
toCheck = [key].concat(aliases[key])
if (!toCheck.some(function (k) {
return groupedKeys.indexOf(k) !== -1
})) {
groups[defaultGroup].push(key)
}
})
return groupedKeys
}
self.showHelp = function (level) {
const logger = yargs._getLoggerInstance()
if (!level) level = 'error'
var emit = typeof level === 'function' ? level : logger[level]
emit(self.help())
}
self.functionDescription = function (fn) {
var description = fn.name ? require('decamelize')(fn.name, '-') : __('generated-value')
return ['(', description, ')'].join('')
}
self.stringifiedValues = function (values, separator) {
var string = ''
var sep = separator || ', '
var array = [].concat(values)
if (!values || !array.length) return string
array.forEach(function (value) {
if (string.length) string += sep
string += JSON.stringify(value)
})
return string
}
// format the default-value-string displayed in
// the right-hand column.
function defaultString (value, defaultDescription) {
var string = '[' + __('default:') + ' '
if (value === undefined && !defaultDescription) return null
if (defaultDescription) {
string += defaultDescription
} else {
switch (typeof value) {
case 'string':
string += JSON.stringify(value)
break
case 'object':
string += JSON.stringify(value)
break
default:
string += value
}
}
return string + ']'
}
// guess the width of the console window, max-width 80.
function windowWidth () {
const wsize = require('window-size')
return wsize.width ? Math.min(80, wsize.width) : null
}
// logic for displaying application version.
var version = null
self.version = function (ver) {
version = ver
}
self.showVersion = function () {
const logger = yargs._getLoggerInstance()
if (typeof version === 'function') logger.log(version())
else logger.log(version)
}
self.reset = function (globalLookup) {
// do not reset wrap here
// do not reset fails here
failMessage = null
failureOutput = false
usage = undefined
epilog = undefined
examples = []
commands = []
descriptions = objFilter(descriptions, function (k, v) {
return globalLookup[k]
})
return self
}
var frozen
self.freeze = function () {
frozen = {}
frozen.failMessage = failMessage
frozen.failureOutput = failureOutput
frozen.usage = usage
frozen.epilog = epilog
frozen.examples = examples
frozen.commands = commands
frozen.descriptions = descriptions
}
self.unfreeze = function () {
failMessage = frozen.failMessage
failureOutput = frozen.failureOutput
usage = frozen.usage
epilog = frozen.epilog
examples = frozen.examples
commands = frozen.commands
descriptions = frozen.descriptions
frozen = undefined
}
return self
}

318
node_modules/yargs/lib/validation.js generated vendored Normal file
View File

@ -0,0 +1,318 @@
const objFilter = require('./obj-filter')
// validation-type-stuff, missing params,
// bad implications, custom checks.
module.exports = function (yargs, usage, y18n) {
const __ = y18n.__
const __n = y18n.__n
const self = {}
// validate appropriate # of non-option
// arguments were provided, i.e., '_'.
self.nonOptionCount = function (argv) {
const demanded = yargs.getDemanded()
// don't count currently executing commands
const _s = argv._.length - yargs.getContext().commands.length
if (demanded._ && (_s < demanded._.count || _s > demanded._.max)) {
if (demanded._.msg !== undefined) {
usage.fail(demanded._.msg)
} else if (_s < demanded._.count) {
usage.fail(
__('Not enough non-option arguments: got %s, need at least %s', _s, demanded._.count)
)
} else {
usage.fail(
__('Too many non-option arguments: got %s, maximum of %s', _s, demanded._.max)
)
}
}
}
// validate the appropriate # of <required>
// positional arguments were provided:
self.positionalCount = function (required, observed) {
if (observed < required) {
usage.fail(
__('Not enough non-option arguments: got %s, need at least %s', observed, required)
)
}
}
// make sure that any args that require an
// value (--foo=bar), have a value.
self.missingArgumentValue = function (argv) {
const defaultValues = [true, false, '']
const options = yargs.getOptions()
if (options.requiresArg.length > 0) {
const missingRequiredArgs = []
options.requiresArg.forEach(function (key) {
const value = argv[key]
// if a value is explicitly requested,
// flag argument as missing if it does not
// look like foo=bar was entered.
if (~defaultValues.indexOf(value) ||
(Array.isArray(value) && !value.length)) {
missingRequiredArgs.push(key)
}
})
if (missingRequiredArgs.length > 0) {
usage.fail(__n(
'Missing argument value: %s',
'Missing argument values: %s',
missingRequiredArgs.length,
missingRequiredArgs.join(', ')
))
}
}
}
// make sure all the required arguments are present.
self.requiredArguments = function (argv) {
const demanded = yargs.getDemanded()
var missing = null
Object.keys(demanded).forEach(function (key) {
if (!argv.hasOwnProperty(key)) {
missing = missing || {}
missing[key] = demanded[key]
}
})
if (missing) {
const customMsgs = []
Object.keys(missing).forEach(function (key) {
const msg = missing[key].msg
if (msg && customMsgs.indexOf(msg) < 0) {
customMsgs.push(msg)
}
})
const customMsg = customMsgs.length ? '\n' + customMsgs.join('\n') : ''
usage.fail(__n(
'Missing required argument: %s',
'Missing required arguments: %s',
Object.keys(missing).length,
Object.keys(missing).join(', ') + customMsg
))
}
}
// check for unknown arguments (strict-mode).
self.unknownArguments = function (argv, aliases) {
const aliasLookup = {}
const descriptions = usage.getDescriptions()
const demanded = yargs.getDemanded()
const commandKeys = yargs.getCommandInstance().getCommands()
const unknown = []
const currentContext = yargs.getContext()
Object.keys(aliases).forEach(function (key) {
aliases[key].forEach(function (alias) {
aliasLookup[alias] = key
})
})
Object.keys(argv).forEach(function (key) {
if (key !== '$0' && key !== '_' &&
!descriptions.hasOwnProperty(key) &&
!demanded.hasOwnProperty(key) &&
!aliasLookup.hasOwnProperty(key)) {
unknown.push(key)
}
})
if (commandKeys.length > 0) {
argv._.slice(currentContext.commands.length).forEach(function (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(', ')
))
}
}
// validate arguments limited to enumerated choices
self.limitedChoices = function (argv) {
const options = yargs.getOptions()
const invalid = {}
if (!Object.keys(options.choices).length) return
Object.keys(argv).forEach(function (key) {
if (key !== '$0' && key !== '_' &&
options.choices.hasOwnProperty(key)) {
[].concat(argv[key]).forEach(function (value) {
// TODO case-insensitive configurability
if (options.choices[key].indexOf(value) === -1) {
invalid[key] = (invalid[key] || []).concat(value)
}
})
}
})
const invalidKeys = Object.keys(invalid)
if (!invalidKeys.length) return
var msg = __('Invalid values:')
invalidKeys.forEach(function (key) {
msg += '\n ' + __(
'Argument: %s, Given: %s, Choices: %s',
key,
usage.stringifiedValues(invalid[key]),
usage.stringifiedValues(options.choices[key])
)
})
usage.fail(msg)
}
// custom checks, added using the `check` option on yargs.
var checks = []
self.check = function (f) {
checks.push(f)
}
self.customChecks = function (argv, aliases) {
for (var i = 0, f; (f = checks[i]) !== undefined; i++) {
var result = null
try {
result = f(argv, aliases)
} catch (err) {
usage.fail(err.message ? err.message : err, err)
continue
}
if (!result) {
usage.fail(__('Argument check failed: %s', f.toString()))
} else if (typeof result === 'string' || result instanceof Error) {
usage.fail(result.toString(), result)
}
}
}
// check implications, argument foo implies => argument bar.
var implied = {}
self.implies = function (key, value) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.implies(k, key[k])
})
} else {
implied[key] = value
}
}
self.getImplied = function () {
return implied
}
self.implications = function (argv) {
const implyFail = []
Object.keys(implied).forEach(function (key) {
var booleanNegation
if (yargs.getOptions().configuration['boolean-negation'] === false) {
booleanNegation = false
} else {
booleanNegation = true
}
var num
const origKey = key
var value = implied[key]
// convert string '1' to number 1
num = Number(key)
key = isNaN(num) ? key : num
if (typeof key === 'number') {
// check length of argv._
key = argv._.length >= key
} else if (key.match(/^--no-.+/) && booleanNegation) {
// check if key doesn't exist
key = key.match(/^--no-(.+)/)[1]
key = !argv[key]
} else {
// check if key exists
key = argv[key]
}
num = Number(value)
value = isNaN(num) ? value : num
if (typeof value === 'number') {
value = argv._.length >= value
} else if (value.match(/^--no-.+/) && booleanNegation) {
value = value.match(/^--no-(.+)/)[1]
value = !argv[value]
} else {
value = argv[value]
}
if (key && !value) {
implyFail.push(origKey)
}
})
if (implyFail.length) {
var msg = __('Implications failed:') + '\n'
implyFail.forEach(function (key) {
msg += (' ' + key + ' -> ' + implied[key])
})
usage.fail(msg)
}
}
self.recommendCommands = function (cmd, potentialCommands) {
const distance = require('./levenshtein')
const threshold = 3 // if it takes more than three edits, let's move on.
potentialCommands = potentialCommands.sort(function (a, b) { return b.length - a.length })
var recommended = null
var bestDistance = Infinity
for (var i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
var d = distance(cmd, candidate)
if (d <= threshold && d < bestDistance) {
bestDistance = d
recommended = candidate
}
}
if (recommended) usage.fail(__('Did you mean %s?', recommended))
}
self.reset = function (globalLookup) {
implied = objFilter(implied, function (k, v) {
return globalLookup[k]
})
checks = []
return self
}
var frozen
self.freeze = function () {
frozen = {}
frozen.implied = implied
frozen.checks = checks
}
self.unfreeze = function () {
implied = frozen.implied
checks = frozen.checks
frozen = undefined
}
return self
}