wallet-core/node_modules/yargs/lib/command.js

337 lines
11 KiB
JavaScript
Raw Normal View History

2017-05-03 15:35:00 +02:00
const path = require('path')
const inspect = require('util').inspect
const camelCase = require('camelcase')
2017-08-14 05:01:11 +02:00
const DEFAULT_MARKER = '*'
2017-05-03 15:35:00 +02:00
// handles parsing positional arguments,
// and populating argv with said positional
// arguments.
module.exports = function (yargs, usage, validation) {
const self = {}
var handlers = {}
var aliasMap = {}
2017-08-14 05:01:11 +02:00
var defaultCommand
2017-05-03 15:35:00 +02:00
self.addHandler = function (cmd, description, builder, handler) {
var aliases = []
2017-08-14 05:01:11 +02:00
handler = handler || function () {}
2017-05-03 15:35:00 +02:00
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
}
2017-08-14 05:01:11 +02:00
// parse positionals out of cmd string
var parsedCommand = self.parseCommand(cmd)
// remove positional args from aliases only
2017-05-03 15:35:00 +02:00
aliases = aliases.map(function (alias) {
2017-08-14 05:01:11 +02:00
return self.parseCommand(alias).cmd
})
// check for default and filter out '*''
var isDefault = false
var parsedAliases = [parsedCommand.cmd].concat(aliases).filter(function (c) {
if (c === DEFAULT_MARKER) {
isDefault = true
return false
}
return true
})
// short-circuit if default with no aliases
if (isDefault && parsedAliases.length === 0) {
defaultCommand = {
original: cmd.replace(DEFAULT_MARKER, '').trim(),
handler: handler,
builder: builder || {},
demanded: parsedCommand.demanded,
optional: parsedCommand.optional
}
return
}
// shift cmd and aliases after filtering out '*'
if (isDefault) {
parsedCommand.cmd = parsedAliases[0]
aliases = parsedAliases.slice(1)
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd)
}
// populate aliasMap
aliases.forEach(function (alias) {
2017-05-03 15:35:00 +02:00
aliasMap[alias] = parsedCommand.cmd
})
if (description !== false) {
2017-08-14 05:01:11 +02:00
usage.command(cmd, description, isDefault, aliases)
2017-05-03 15:35:00 +02:00
}
handlers[parsedCommand.cmd] = {
original: cmd,
handler: handler,
builder: builder || {},
demanded: parsedCommand.demanded,
optional: parsedCommand.optional
}
2017-08-14 05:01:11 +02:00
if (isDefault) defaultCommand = handlers[parsedCommand.cmd]
2017-05-03 15:35:00 +02:00
}
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
}
2017-08-14 05:01:11 +02:00
self.parseCommand = function (cmd) {
2017-05-03 15:35:00 +02:00
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
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: variadic
})
} else {
parsedCommand.demanded.push({
cmd: cmd.replace(bregex, '').split('|'),
variadic: variadic
})
}
})
return parsedCommand
}
self.getCommands = function () {
return Object.keys(handlers).concat(Object.keys(aliasMap))
}
self.getCommandHandlers = function () {
return handlers
}
2017-08-14 05:01:11 +02:00
self.hasDefaultCommand = function () {
return !!defaultCommand
}
self.runCommand = function (command, yargs, parsed, commandIndex) {
var aliases = parsed.aliases
var commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand
2017-05-03 15:35:00 +02:00
var currentContext = yargs.getContext()
var numFiles = currentContext.files.length
var parentCommands = currentContext.commands.slice()
2017-08-14 05:01:11 +02:00
// what does yargs look like after the buidler is run?
var innerArgv = parsed.argv
var innerYargs = null
var positionalMap = {}
if (command) currentContext.commands.push(command)
2017-05-03 15:35:00 +02:00
if (typeof commandHandler.builder === 'function') {
// a function can be provided, which builds
// up a yargs chain and possibly returns it.
2017-08-14 05:01:11 +02:00
innerYargs = commandHandler.builder(yargs.reset(parsed.aliases))
2017-05-03 15:35:00 +02:00
// 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
2017-08-14 05:01:11 +02:00
// options object below.
2017-05-03 15:35:00 +02:00
if (yargs.parsed === false) {
if (typeof yargs.getUsageInstance().getUsage() === 'undefined') {
yargs.usage('$0 ' + (parentCommands.length ? parentCommands.join(' ') + ' ' : '') + commandHandler.original)
}
2017-08-14 05:01:11 +02:00
innerArgv = innerYargs ? innerYargs._parseArgs(null, null, true, commandIndex) : yargs._parseArgs(null, null, true, commandIndex)
2017-05-03 15:35:00 +02:00
} else {
innerArgv = yargs.parsed.argv
}
2017-08-14 05:01:11 +02:00
if (innerYargs && yargs.parsed === false) aliases = innerYargs.parsed.aliases
else aliases = yargs.parsed.aliases
2017-05-03 15:35:00 +02:00
} else if (typeof commandHandler.builder === 'object') {
// as a short hand, an object can instead be provided, specifying
// the options that a command takes.
2017-08-14 05:01:11 +02:00
innerYargs = yargs.reset(parsed.aliases)
innerYargs.usage('$0 ' + (parentCommands.length ? parentCommands.join(' ') + ' ' : '') + commandHandler.original)
2017-05-03 15:35:00 +02:00
Object.keys(commandHandler.builder).forEach(function (key) {
2017-08-14 05:01:11 +02:00
innerYargs.option(key, commandHandler.builder[key])
2017-05-03 15:35:00 +02:00
})
2017-08-14 05:01:11 +02:00
innerArgv = innerYargs._parseArgs(null, null, true, commandIndex)
aliases = innerYargs.parsed.aliases
}
if (!yargs._hasOutput()) {
positionalMap = populatePositionals(commandHandler, innerArgv, currentContext, yargs)
2017-05-03 15:35:00 +02:00
}
2017-08-14 05:01:11 +02:00
// we apply validation post-hoc, so that custom
// checks get passed populated positional arguments.
if (!yargs._hasOutput()) yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error)
2017-05-03 15:35:00 +02:00
if (commandHandler.handler && !yargs._hasOutput()) {
2017-08-14 05:01:11 +02:00
yargs._setHasOutput()
2017-05-03 15:35:00 +02:00
commandHandler.handler(innerArgv)
}
2017-08-14 05:01:11 +02:00
if (command) currentContext.commands.pop()
2017-05-03 15:35:00 +02:00
numFiles = currentContext.files.length - numFiles
if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles)
2017-08-14 05:01:11 +02:00
2017-05-03 15:35:00 +02:00
return innerArgv
}
// transcribe all positional arguments "command <foo> <bar> [apple]"
// onto argv.
function populatePositionals (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)
2017-08-14 05:01:11 +02:00
var positionalMap = {}
2017-05-03 15:35:00 +02:00
validation.positionalCount(demanded.length, argv._.length)
while (demanded.length) {
var demand = demanded.shift()
2017-08-14 05:01:11 +02:00
populatePositional(demand, argv, yargs, positionalMap)
2017-05-03 15:35:00 +02:00
}
while (optional.length) {
var maybe = optional.shift()
2017-08-14 05:01:11 +02:00
populatePositional(maybe, argv, yargs, positionalMap)
2017-05-03 15:35:00 +02:00
}
argv._ = context.commands.concat(argv._)
2017-08-14 05:01:11 +02:00
return positionalMap
2017-05-03 15:35:00 +02:00
}
// populate a single positional argument and its
// aliases onto argv.
2017-08-14 05:01:11 +02:00
function populatePositional (positional, argv, yargs, positionalMap) {
2017-05-03 15:35:00 +02:00
// "positional" consists of the positional.cmd, an array representing
// the positional's name and aliases, and positional.variadic
// indicating whether or not it is a variadic array.
var variadics = null
var value = null
for (var i = 0, cmd; (cmd = positional.cmd[i]) !== undefined; i++) {
if (positional.variadic) {
if (variadics) argv[cmd] = variadics.slice(0)
else argv[cmd] = variadics = argv._.splice(0)
} else {
if (!value && !argv._.length) continue
if (value) argv[cmd] = value
else argv[cmd] = value = argv._.shift()
}
2017-08-14 05:01:11 +02:00
positionalMap[cmd] = true
2017-05-03 15:35:00 +02:00
postProcessPositional(yargs, argv, cmd)
addCamelCaseExpansions(argv, cmd)
}
}
// 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 = {}
2017-08-14 05:01:11 +02:00
defaultCommand = undefined
2017-05-03 15:35:00 +02:00
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
2017-08-14 05:01:11 +02:00
frozen.defaultCommand = defaultCommand
2017-05-03 15:35:00 +02:00
}
self.unfreeze = function () {
handlers = frozen.handlers
aliasMap = frozen.aliasMap
2017-08-14 05:01:11 +02:00
defaultCommand = frozen.defaultCommand
2017-05-03 15:35:00 +02:00
frozen = undefined
}
return self
}