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

414 lines
14 KiB
JavaScript
Raw Normal View History

2017-12-10 21:51:33 +01:00
'use strict'
2017-05-03 15:35:00 +02:00
const inspect = require('util').inspect
2017-12-10 21:51:33 +01:00
const path = require('path')
const Parser = require('yargs-parser')
2017-05-03 15:35:00 +02:00
2017-12-10 21:51:33 +01:00
const DEFAULT_MARKER = /(^\*)|(^\$0)/
2017-08-14 05:01:11 +02:00
2017-05-03 15:35:00 +02:00
// handles parsing positional arguments,
// and populating argv with said positional
// arguments.
2017-12-10 21:51:33 +01:00
module.exports = function command (yargs, usage, validation) {
2017-05-03 15:35:00 +02:00
const self = {}
2017-12-10 21:51:33 +01:00
let handlers = {}
let aliasMap = {}
let defaultCommand
self.addHandler = function addHandler (cmd, description, builder, handler) {
let aliases = []
handler = handler || (() => {})
2017-08-14 05:01:11 +02:00
2017-05-03 15:35:00 +02:00
if (Array.isArray(cmd)) {
aliases = cmd.slice(1)
cmd = cmd[0]
} else if (typeof cmd === 'object') {
2017-12-10 21:51:33 +01:00
let command = (Array.isArray(cmd.command) || typeof cmd.command === 'string') ? cmd.command : moduleName(cmd)
2017-05-03 15:35:00 +02:00
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
2017-12-10 21:51:33 +01:00
const parsedCommand = self.parseCommand(cmd)
2017-08-14 05:01:11 +02:00
// remove positional args from aliases only
2017-12-10 21:51:33 +01:00
aliases = aliases.map(alias => self.parseCommand(alias).cmd)
2017-08-14 05:01:11 +02:00
// check for default and filter out '*''
2017-12-10 21:51:33 +01:00
let isDefault = false
const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => {
if (DEFAULT_MARKER.test(c)) {
2017-08-14 05:01:11 +02:00
isDefault = true
return false
}
return true
})
2017-12-10 21:51:33 +01:00
// standardize on $0 for default command.
if (parsedAliases.length === 0 && isDefault) parsedAliases.push('$0')
2017-08-14 05:01:11 +02:00
// 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
2017-12-10 21:51:33 +01:00
aliases.forEach((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,
2017-12-10 21:51:33 +01:00
description: description,
handler,
2017-05-03 15:35:00 +02:00
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
}
2017-12-10 21:51:33 +01:00
self.addDirectory = function addDirectory (dir, context, req, callerFile, opts) {
2017-05-03 15:35:00 +02:00
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
2017-12-10 21:51:33 +01:00
const parentVisit = typeof opts.visit === 'function' ? opts.visit : o => o
2017-05-03 15:35:00 +02:00
// call addHandler via visitor function
2017-12-10 21:51:33 +01:00
opts.visit = function visit (obj, joined, filename) {
2017-05-03 15:35:00 +02:00
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)
2017-12-10 21:51:33 +01:00
if (!mod) throw new Error(`No command name given for module: ${inspect(obj)}`)
2017-05-03 15:35:00 +02:00
return commandFromFilename(mod.filename)
}
// derive command name from filename
function commandFromFilename (filename) {
return path.basename(filename, path.extname(filename))
}
function extractDesc (obj) {
2017-12-10 21:51:33 +01:00
for (let keys = ['describe', 'description', 'desc'], i = 0, l = keys.length, test; i < l; i++) {
2017-05-03 15:35:00 +02:00
test = obj[keys[i]]
if (typeof test === 'string' || typeof test === 'boolean') return test
}
return false
}
2017-12-10 21:51:33 +01:00
self.parseCommand = function parseCommand (cmd) {
const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ')
const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/)
const bregex = /\.*[\][<>]/g
const parsedCommand = {
2017-05-03 15:35:00 +02:00
cmd: (splitCommand.shift()).replace(bregex, ''),
demanded: [],
optional: []
}
2017-12-10 21:51:33 +01:00
splitCommand.forEach((cmd, i) => {
let variadic = false
2017-05-03 15:35:00 +02:00
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('|'),
2017-12-10 21:51:33 +01:00
variadic
2017-05-03 15:35:00 +02:00
})
} else {
parsedCommand.demanded.push({
cmd: cmd.replace(bregex, '').split('|'),
2017-12-10 21:51:33 +01:00
variadic
2017-05-03 15:35:00 +02:00
})
}
})
return parsedCommand
}
2017-12-10 21:51:33 +01:00
self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap))
2017-05-03 15:35:00 +02:00
2017-12-10 21:51:33 +01:00
self.getCommandHandlers = () => handlers
2017-05-03 15:35:00 +02:00
2017-12-10 21:51:33 +01:00
self.hasDefaultCommand = () => !!defaultCommand
2017-08-14 05:01:11 +02:00
2017-12-10 21:51:33 +01:00
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()
2017-08-14 05:01:11 +02:00
// what does yargs look like after the buidler is run?
2017-12-10 21:51:33 +01:00
let innerArgv = parsed.argv
let innerYargs = null
let positionalMap = {}
if (command) {
currentContext.commands.push(command)
currentContext.fullCommands.push(commandHandler.original)
}
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) {
2017-12-10 21:51:33 +01:00
if (shouldUpdateUsage(yargs)) {
yargs.getUsageInstance().usage(
usageFromParentCommandsCommandHandler(parentCommands, commandHandler),
commandHandler.description
)
2017-05-03 15:35:00 +02:00
}
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)
2017-12-10 21:51:33 +01:00
if (shouldUpdateUsage(innerYargs)) {
innerYargs.getUsageInstance().usage(
usageFromParentCommandsCommandHandler(parentCommands, commandHandler),
commandHandler.description
)
}
Object.keys(commandHandler.builder).forEach((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
2017-12-10 21:51:33 +01:00
if (command) {
currentContext.commands.pop()
currentContext.fullCommands.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
}
2017-12-10 21:51:33 +01:00
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) {
if (shouldUpdateUsage(yargs)) {
// build the root-level command string from the default string.
const commandString = DEFAULT_MARKER.test(defaultCommand.original)
? defaultCommand.original : defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ')
yargs.getUsageInstance().usage(
commandString,
defaultCommand.description
)
}
const builder = defaultCommand.builder
if (typeof builder === 'function') {
builder(yargs)
} else {
Object.keys(builder).forEach((key) => {
yargs.option(key, builder[key])
})
}
}
2017-05-03 15:35:00 +02:00
// 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
2017-12-10 21:51:33 +01:00
const demanded = commandHandler.demanded.slice(0)
const optional = commandHandler.optional.slice(0)
const positionalMap = {}
2017-05-03 15:35:00 +02:00
validation.positionalCount(demanded.length, argv._.length)
while (demanded.length) {
2017-12-10 21:51:33 +01:00
const demand = demanded.shift()
populatePositional(demand, argv, positionalMap)
2017-05-03 15:35:00 +02:00
}
while (optional.length) {
2017-12-10 21:51:33 +01:00
const maybe = optional.shift()
populatePositional(maybe, argv, positionalMap)
2017-05-03 15:35:00 +02:00
}
argv._ = context.commands.concat(argv._)
2017-12-10 21:51:33 +01:00
postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original))
2017-08-14 05:01:11 +02:00
return positionalMap
2017-05-03 15:35:00 +02:00
}
2017-12-10 21:51:33 +01:00
function populatePositional (positional, argv, positionalMap, parseOptions) {
const cmd = positional.cmd[0]
if (positional.variadic) {
positionalMap[cmd] = argv._.splice(0).map(String)
} else {
if (argv._.length) positionalMap[cmd] = [String(argv._.shift())]
2017-05-03 15:35:00 +02:00
}
}
2017-12-10 21:51:33 +01:00
// we run yargs-parser against the positional arguments
// applying the same parsing logic used for flags.
function postProcessPositionals (argv, positionalMap, parseOptions) {
// combine the parsing hints we've inferred from the command
// string with explicitly configured parsing hints.
const options = Object.assign({}, yargs.getOptions())
options.default = Object.assign(parseOptions.default, options.default)
options.alias = Object.assign(parseOptions.alias, options.alias)
options.array = options.array.concat(parseOptions.array)
const unparsed = []
Object.keys(positionalMap).forEach((key) => {
positionalMap[key].map((value) => {
unparsed.push(`--${key}`)
unparsed.push(value)
})
})
// short-circuit parse.
if (!unparsed.length) return
const parsed = Parser.detailed(unparsed, options)
if (parsed.error) {
yargs.getUsageInstance().fail(parsed.error.message, parsed.error)
} else {
// only copy over positional keys (don't overwrite
// flag arguments that were already parsed).
const positionalKeys = Object.keys(positionalMap)
Object.keys(positionalMap).forEach((key) => {
[].push.apply(positionalKeys, parsed.aliases[key])
})
Object.keys(parsed.argv).forEach((key) => {
if (positionalKeys.indexOf(key) !== -1) {
argv[key] = parsed.argv[key]
}
})
2017-05-03 15:35:00 +02:00
}
}
2017-12-10 21:51:33 +01:00
self.cmdToParseOptions = function (cmdString) {
const parseOptions = {
array: [],
default: {},
alias: {},
demand: {}
2017-05-03 15:35:00 +02:00
}
2017-12-10 21:51:33 +01:00
const parsed = self.parseCommand(cmdString)
parsed.demanded.forEach((d) => {
const cmds = d.cmd.slice(0)
const cmd = cmds.shift()
if (d.variadic) {
parseOptions.array.push(cmd)
parseOptions.default[cmd] = []
}
cmds.forEach((c) => {
parseOptions.alias[cmd] = c
})
parseOptions.demand[cmd] = true
})
parsed.optional.forEach((o) => {
const cmds = o.cmd.slice(0)
const cmd = cmds.shift()
if (o.variadic) {
parseOptions.array.push(cmd)
parseOptions.default[cmd] = []
}
cmds.forEach((c) => {
parseOptions.alias[cmd] = c
})
})
return parseOptions
2017-05-03 15:35:00 +02:00
}
2017-12-10 21:51:33 +01:00
self.reset = () => {
2017-05-03 15:35:00 +02:00
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.
2017-12-10 21:51:33 +01:00
let frozen
self.freeze = () => {
2017-05-03 15:35:00 +02:00
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
}
2017-12-10 21:51:33 +01:00
self.unfreeze = () => {
2017-05-03 15:35:00 +02:00
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
}