1 |
3a515b92
|
cagy
|
'use strict'
|
2 |
|
|
|
3 |
|
|
const inspect = require('util').inspect
|
4 |
|
|
const path = require('path')
|
5 |
|
|
const Parser = require('yargs-parser')
|
6 |
|
|
|
7 |
|
|
const DEFAULT_MARKER = /(^\*)|(^\$0)/
|
8 |
|
|
|
9 |
|
|
// handles parsing positional arguments,
|
10 |
|
|
// and populating argv with said positional
|
11 |
|
|
// arguments.
|
12 |
|
|
module.exports = function command (yargs, usage, validation, globalMiddleware) {
|
13 |
|
|
const self = {}
|
14 |
|
|
let handlers = {}
|
15 |
|
|
let aliasMap = {}
|
16 |
|
|
let defaultCommand
|
17 |
|
|
globalMiddleware = globalMiddleware || []
|
18 |
|
|
self.addHandler = function addHandler (cmd, description, builder, handler, middlewares) {
|
19 |
|
|
let aliases = []
|
20 |
|
|
handler = handler || (() => {})
|
21 |
|
|
middlewares = middlewares || []
|
22 |
|
|
globalMiddleware.push(...middlewares)
|
23 |
|
|
middlewares = globalMiddleware
|
24 |
|
|
if (Array.isArray(cmd)) {
|
25 |
|
|
aliases = cmd.slice(1)
|
26 |
|
|
cmd = cmd[0]
|
27 |
|
|
} else if (typeof cmd === 'object') {
|
28 |
|
|
let command = (Array.isArray(cmd.command) || typeof cmd.command === 'string') ? cmd.command : moduleName(cmd)
|
29 |
|
|
if (cmd.aliases) command = [].concat(command).concat(cmd.aliases)
|
30 |
|
|
self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares)
|
31 |
|
|
return
|
32 |
|
|
}
|
33 |
|
|
|
34 |
|
|
// allow a module to be provided instead of separate builder and handler
|
35 |
|
|
if (typeof builder === 'object' && builder.builder && typeof builder.handler === 'function') {
|
36 |
|
|
self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares)
|
37 |
|
|
return
|
38 |
|
|
}
|
39 |
|
|
|
40 |
|
|
// parse positionals out of cmd string
|
41 |
|
|
const parsedCommand = self.parseCommand(cmd)
|
42 |
|
|
|
43 |
|
|
// remove positional args from aliases only
|
44 |
|
|
aliases = aliases.map(alias => self.parseCommand(alias).cmd)
|
45 |
|
|
|
46 |
|
|
// check for default and filter out '*''
|
47 |
|
|
let isDefault = false
|
48 |
|
|
const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => {
|
49 |
|
|
if (DEFAULT_MARKER.test(c)) {
|
50 |
|
|
isDefault = true
|
51 |
|
|
return false
|
52 |
|
|
}
|
53 |
|
|
return true
|
54 |
|
|
})
|
55 |
|
|
|
56 |
|
|
// standardize on $0 for default command.
|
57 |
|
|
if (parsedAliases.length === 0 && isDefault) parsedAliases.push('$0')
|
58 |
|
|
|
59 |
|
|
// shift cmd and aliases after filtering out '*'
|
60 |
|
|
if (isDefault) {
|
61 |
|
|
parsedCommand.cmd = parsedAliases[0]
|
62 |
|
|
aliases = parsedAliases.slice(1)
|
63 |
|
|
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd)
|
64 |
|
|
}
|
65 |
|
|
|
66 |
|
|
// populate aliasMap
|
67 |
|
|
aliases.forEach((alias) => {
|
68 |
|
|
aliasMap[alias] = parsedCommand.cmd
|
69 |
|
|
})
|
70 |
|
|
|
71 |
|
|
if (description !== false) {
|
72 |
|
|
usage.command(cmd, description, isDefault, aliases)
|
73 |
|
|
}
|
74 |
|
|
|
75 |
|
|
handlers[parsedCommand.cmd] = {
|
76 |
|
|
original: cmd,
|
77 |
|
|
description: description,
|
78 |
|
|
handler,
|
79 |
|
|
builder: builder || {},
|
80 |
|
|
middlewares: middlewares || [],
|
81 |
|
|
demanded: parsedCommand.demanded,
|
82 |
|
|
optional: parsedCommand.optional
|
83 |
|
|
}
|
84 |
|
|
|
85 |
|
|
if (isDefault) defaultCommand = handlers[parsedCommand.cmd]
|
86 |
|
|
}
|
87 |
|
|
|
88 |
|
|
self.addDirectory = function addDirectory (dir, context, req, callerFile, opts) {
|
89 |
|
|
opts = opts || {}
|
90 |
|
|
// disable recursion to support nested directories of subcommands
|
91 |
|
|
if (typeof opts.recurse !== 'boolean') opts.recurse = false
|
92 |
|
|
// exclude 'json', 'coffee' from require-directory defaults
|
93 |
|
|
if (!Array.isArray(opts.extensions)) opts.extensions = ['js']
|
94 |
|
|
// allow consumer to define their own visitor function
|
95 |
|
|
const parentVisit = typeof opts.visit === 'function' ? opts.visit : o => o
|
96 |
|
|
// call addHandler via visitor function
|
97 |
|
|
opts.visit = function visit (obj, joined, filename) {
|
98 |
|
|
const visited = parentVisit(obj, joined, filename)
|
99 |
|
|
// allow consumer to skip modules with their own visitor
|
100 |
|
|
if (visited) {
|
101 |
|
|
// check for cyclic reference
|
102 |
|
|
// each command file path should only be seen once per execution
|
103 |
|
|
if (~context.files.indexOf(joined)) return visited
|
104 |
|
|
// keep track of visited files in context.files
|
105 |
|
|
context.files.push(joined)
|
106 |
|
|
self.addHandler(visited)
|
107 |
|
|
}
|
108 |
|
|
return visited
|
109 |
|
|
}
|
110 |
|
|
require('require-directory')({ require: req, filename: callerFile }, dir, opts)
|
111 |
|
|
}
|
112 |
|
|
|
113 |
|
|
// lookup module object from require()d command and derive name
|
114 |
|
|
// if module was not require()d and no name given, throw error
|
115 |
|
|
function moduleName (obj) {
|
116 |
|
|
const mod = require('which-module')(obj)
|
117 |
|
|
if (!mod) throw new Error(`No command name given for module: ${inspect(obj)}`)
|
118 |
|
|
return commandFromFilename(mod.filename)
|
119 |
|
|
}
|
120 |
|
|
|
121 |
|
|
// derive command name from filename
|
122 |
|
|
function commandFromFilename (filename) {
|
123 |
|
|
return path.basename(filename, path.extname(filename))
|
124 |
|
|
}
|
125 |
|
|
|
126 |
|
|
function extractDesc (obj) {
|
127 |
|
|
for (let keys = ['describe', 'description', 'desc'], i = 0, l = keys.length, test; i < l; i++) {
|
128 |
|
|
test = obj[keys[i]]
|
129 |
|
|
if (typeof test === 'string' || typeof test === 'boolean') return test
|
130 |
|
|
}
|
131 |
|
|
return false
|
132 |
|
|
}
|
133 |
|
|
|
134 |
|
|
self.parseCommand = function parseCommand (cmd) {
|
135 |
|
|
const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ')
|
136 |
|
|
const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/)
|
137 |
|
|
const bregex = /\.*[\][<>]/g
|
138 |
|
|
const parsedCommand = {
|
139 |
|
|
cmd: (splitCommand.shift()).replace(bregex, ''),
|
140 |
|
|
demanded: [],
|
141 |
|
|
optional: []
|
142 |
|
|
}
|
143 |
|
|
splitCommand.forEach((cmd, i) => {
|
144 |
|
|
let variadic = false
|
145 |
|
|
cmd = cmd.replace(/\s/g, '')
|
146 |
|
|
if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) variadic = true
|
147 |
|
|
if (/^\[/.test(cmd)) {
|
148 |
|
|
parsedCommand.optional.push({
|
149 |
|
|
cmd: cmd.replace(bregex, '').split('|'),
|
150 |
|
|
variadic
|
151 |
|
|
})
|
152 |
|
|
} else {
|
153 |
|
|
parsedCommand.demanded.push({
|
154 |
|
|
cmd: cmd.replace(bregex, '').split('|'),
|
155 |
|
|
variadic
|
156 |
|
|
})
|
157 |
|
|
}
|
158 |
|
|
})
|
159 |
|
|
return parsedCommand
|
160 |
|
|
}
|
161 |
|
|
|
162 |
|
|
self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap))
|
163 |
|
|
|
164 |
|
|
self.getCommandHandlers = () => handlers
|
165 |
|
|
|
166 |
|
|
self.hasDefaultCommand = () => !!defaultCommand
|
167 |
|
|
|
168 |
|
|
self.runCommand = function runCommand (command, yargs, parsed, commandIndex) {
|
169 |
|
|
let aliases = parsed.aliases
|
170 |
|
|
const commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand
|
171 |
|
|
const currentContext = yargs.getContext()
|
172 |
|
|
let numFiles = currentContext.files.length
|
173 |
|
|
const parentCommands = currentContext.commands.slice()
|
174 |
|
|
|
175 |
|
|
// what does yargs look like after the buidler is run?
|
176 |
|
|
let innerArgv = parsed.argv
|
177 |
|
|
let innerYargs = null
|
178 |
|
|
let positionalMap = {}
|
179 |
|
|
if (command) {
|
180 |
|
|
currentContext.commands.push(command)
|
181 |
|
|
currentContext.fullCommands.push(commandHandler.original)
|
182 |
|
|
}
|
183 |
|
|
if (typeof commandHandler.builder === 'function') {
|
184 |
|
|
// a function can be provided, which builds
|
185 |
|
|
// up a yargs chain and possibly returns it.
|
186 |
|
|
innerYargs = commandHandler.builder(yargs.reset(parsed.aliases))
|
187 |
|
|
// if the builder function did not yet parse argv with reset yargs
|
188 |
|
|
// and did not explicitly set a usage() string, then apply the
|
189 |
|
|
// original command string as usage() for consistent behavior with
|
190 |
|
|
// options object below.
|
191 |
|
|
if (yargs.parsed === false) {
|
192 |
|
|
if (shouldUpdateUsage(yargs)) {
|
193 |
|
|
yargs.getUsageInstance().usage(
|
194 |
|
|
usageFromParentCommandsCommandHandler(parentCommands, commandHandler),
|
195 |
|
|
commandHandler.description
|
196 |
|
|
)
|
197 |
|
|
}
|
198 |
|
|
innerArgv = innerYargs ? innerYargs._parseArgs(null, null, true, commandIndex) : yargs._parseArgs(null, null, true, commandIndex)
|
199 |
|
|
} else {
|
200 |
|
|
innerArgv = yargs.parsed.argv
|
201 |
|
|
}
|
202 |
|
|
|
203 |
|
|
if (innerYargs && yargs.parsed === false) aliases = innerYargs.parsed.aliases
|
204 |
|
|
else aliases = yargs.parsed.aliases
|
205 |
|
|
} else if (typeof commandHandler.builder === 'object') {
|
206 |
|
|
// as a short hand, an object can instead be provided, specifying
|
207 |
|
|
// the options that a command takes.
|
208 |
|
|
innerYargs = yargs.reset(parsed.aliases)
|
209 |
|
|
if (shouldUpdateUsage(innerYargs)) {
|
210 |
|
|
innerYargs.getUsageInstance().usage(
|
211 |
|
|
usageFromParentCommandsCommandHandler(parentCommands, commandHandler),
|
212 |
|
|
commandHandler.description
|
213 |
|
|
)
|
214 |
|
|
}
|
215 |
|
|
Object.keys(commandHandler.builder).forEach((key) => {
|
216 |
|
|
innerYargs.option(key, commandHandler.builder[key])
|
217 |
|
|
})
|
218 |
|
|
innerArgv = innerYargs._parseArgs(null, null, true, commandIndex)
|
219 |
|
|
aliases = innerYargs.parsed.aliases
|
220 |
|
|
}
|
221 |
|
|
|
222 |
|
|
if (!yargs._hasOutput()) {
|
223 |
|
|
positionalMap = populatePositionals(commandHandler, innerArgv, currentContext, yargs)
|
224 |
|
|
}
|
225 |
|
|
|
226 |
|
|
// we apply validation post-hoc, so that custom
|
227 |
|
|
// checks get passed populated positional arguments.
|
228 |
|
|
if (!yargs._hasOutput()) yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error)
|
229 |
|
|
|
230 |
|
|
if (commandHandler.handler && !yargs._hasOutput()) {
|
231 |
|
|
yargs._setHasOutput()
|
232 |
|
|
if (commandHandler.middlewares.length > 0) {
|
233 |
|
|
const middlewareArgs = commandHandler.middlewares.reduce(function (initialObj, middleware) {
|
234 |
|
|
return Object.assign(initialObj, middleware(innerArgv))
|
235 |
|
|
}, {})
|
236 |
|
|
Object.assign(innerArgv, middlewareArgs)
|
237 |
|
|
}
|
238 |
|
|
const handlerResult = commandHandler.handler(innerArgv)
|
239 |
|
|
if (handlerResult && typeof handlerResult.then === 'function') {
|
240 |
|
|
handlerResult.then(
|
241 |
|
|
null,
|
242 |
|
|
(error) => yargs.getUsageInstance().fail(null, error)
|
243 |
|
|
)
|
244 |
|
|
}
|
245 |
|
|
}
|
246 |
|
|
|
247 |
|
|
if (command) {
|
248 |
|
|
currentContext.commands.pop()
|
249 |
|
|
currentContext.fullCommands.pop()
|
250 |
|
|
}
|
251 |
|
|
numFiles = currentContext.files.length - numFiles
|
252 |
|
|
if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles)
|
253 |
|
|
|
254 |
|
|
return innerArgv
|
255 |
|
|
}
|
256 |
|
|
|
257 |
|
|
function shouldUpdateUsage (yargs) {
|
258 |
|
|
return !yargs.getUsageInstance().getUsageDisabled() &&
|
259 |
|
|
yargs.getUsageInstance().getUsage().length === 0
|
260 |
|
|
}
|
261 |
|
|
|
262 |
|
|
function usageFromParentCommandsCommandHandler (parentCommands, commandHandler) {
|
263 |
|
|
const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() : commandHandler.original
|
264 |
|
|
const pc = parentCommands.filter((c) => { return !DEFAULT_MARKER.test(c) })
|
265 |
|
|
pc.push(c)
|
266 |
|
|
return `$0 ${pc.join(' ')}`
|
267 |
|
|
}
|
268 |
|
|
|
269 |
|
|
self.runDefaultBuilderOn = function (yargs) {
|
270 |
|
|
if (shouldUpdateUsage(yargs)) {
|
271 |
|
|
// build the root-level command string from the default string.
|
272 |
|
|
const commandString = DEFAULT_MARKER.test(defaultCommand.original)
|
273 |
|
|
? defaultCommand.original : defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ')
|
274 |
|
|
yargs.getUsageInstance().usage(
|
275 |
|
|
commandString,
|
276 |
|
|
defaultCommand.description
|
277 |
|
|
)
|
278 |
|
|
}
|
279 |
|
|
const builder = defaultCommand.builder
|
280 |
|
|
if (typeof builder === 'function') {
|
281 |
|
|
builder(yargs)
|
282 |
|
|
} else {
|
283 |
|
|
Object.keys(builder).forEach((key) => {
|
284 |
|
|
yargs.option(key, builder[key])
|
285 |
|
|
})
|
286 |
|
|
}
|
287 |
|
|
}
|
288 |
|
|
|
289 |
|
|
// transcribe all positional arguments "command <foo> <bar> [apple]"
|
290 |
|
|
// onto argv.
|
291 |
|
|
function populatePositionals (commandHandler, argv, context, yargs) {
|
292 |
|
|
argv._ = argv._.slice(context.commands.length) // nuke the current commands
|
293 |
|
|
const demanded = commandHandler.demanded.slice(0)
|
294 |
|
|
const optional = commandHandler.optional.slice(0)
|
295 |
|
|
const positionalMap = {}
|
296 |
|
|
|
297 |
|
|
validation.positionalCount(demanded.length, argv._.length)
|
298 |
|
|
|
299 |
|
|
while (demanded.length) {
|
300 |
|
|
const demand = demanded.shift()
|
301 |
|
|
populatePositional(demand, argv, positionalMap)
|
302 |
|
|
}
|
303 |
|
|
|
304 |
|
|
while (optional.length) {
|
305 |
|
|
const maybe = optional.shift()
|
306 |
|
|
populatePositional(maybe, argv, positionalMap)
|
307 |
|
|
}
|
308 |
|
|
|
309 |
|
|
argv._ = context.commands.concat(argv._)
|
310 |
|
|
|
311 |
|
|
postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original))
|
312 |
|
|
|
313 |
|
|
return positionalMap
|
314 |
|
|
}
|
315 |
|
|
|
316 |
|
|
function populatePositional (positional, argv, positionalMap, parseOptions) {
|
317 |
|
|
const cmd = positional.cmd[0]
|
318 |
|
|
if (positional.variadic) {
|
319 |
|
|
positionalMap[cmd] = argv._.splice(0).map(String)
|
320 |
|
|
} else {
|
321 |
|
|
if (argv._.length) positionalMap[cmd] = [String(argv._.shift())]
|
322 |
|
|
}
|
323 |
|
|
}
|
324 |
|
|
|
325 |
|
|
// we run yargs-parser against the positional arguments
|
326 |
|
|
// applying the same parsing logic used for flags.
|
327 |
|
|
function postProcessPositionals (argv, positionalMap, parseOptions) {
|
328 |
|
|
// combine the parsing hints we've inferred from the command
|
329 |
|
|
// string with explicitly configured parsing hints.
|
330 |
|
|
const options = Object.assign({}, yargs.getOptions())
|
331 |
|
|
options.default = Object.assign(parseOptions.default, options.default)
|
332 |
|
|
options.alias = Object.assign(parseOptions.alias, options.alias)
|
333 |
|
|
options.array = options.array.concat(parseOptions.array)
|
334 |
|
|
delete options.config // don't load config when processing positionals.
|
335 |
|
|
|
336 |
|
|
const unparsed = []
|
337 |
|
|
Object.keys(positionalMap).forEach((key) => {
|
338 |
|
|
positionalMap[key].map((value) => {
|
339 |
|
|
unparsed.push(`--${key}`)
|
340 |
|
|
unparsed.push(value)
|
341 |
|
|
})
|
342 |
|
|
})
|
343 |
|
|
|
344 |
|
|
// short-circuit parse.
|
345 |
|
|
if (!unparsed.length) return
|
346 |
|
|
|
347 |
|
|
const parsed = Parser.detailed(unparsed, options)
|
348 |
|
|
|
349 |
|
|
if (parsed.error) {
|
350 |
|
|
yargs.getUsageInstance().fail(parsed.error.message, parsed.error)
|
351 |
|
|
} else {
|
352 |
|
|
// only copy over positional keys (don't overwrite
|
353 |
|
|
// flag arguments that were already parsed).
|
354 |
|
|
const positionalKeys = Object.keys(positionalMap)
|
355 |
|
|
Object.keys(positionalMap).forEach((key) => {
|
356 |
|
|
[].push.apply(positionalKeys, parsed.aliases[key])
|
357 |
|
|
})
|
358 |
|
|
|
359 |
|
|
Object.keys(parsed.argv).forEach((key) => {
|
360 |
|
|
if (positionalKeys.indexOf(key) !== -1) {
|
361 |
|
|
// any new aliases need to be placed in positionalMap, which
|
362 |
|
|
// is used for validation.
|
363 |
|
|
if (!positionalMap[key]) positionalMap[key] = parsed.argv[key]
|
364 |
|
|
argv[key] = parsed.argv[key]
|
365 |
|
|
}
|
366 |
|
|
})
|
367 |
|
|
}
|
368 |
|
|
}
|
369 |
|
|
|
370 |
|
|
self.cmdToParseOptions = function (cmdString) {
|
371 |
|
|
const parseOptions = {
|
372 |
|
|
array: [],
|
373 |
|
|
default: {},
|
374 |
|
|
alias: {},
|
375 |
|
|
demand: {}
|
376 |
|
|
}
|
377 |
|
|
|
378 |
|
|
const parsed = self.parseCommand(cmdString)
|
379 |
|
|
parsed.demanded.forEach((d) => {
|
380 |
|
|
const cmds = d.cmd.slice(0)
|
381 |
|
|
const cmd = cmds.shift()
|
382 |
|
|
if (d.variadic) {
|
383 |
|
|
parseOptions.array.push(cmd)
|
384 |
|
|
parseOptions.default[cmd] = []
|
385 |
|
|
}
|
386 |
|
|
cmds.forEach((c) => {
|
387 |
|
|
parseOptions.alias[cmd] = c
|
388 |
|
|
})
|
389 |
|
|
parseOptions.demand[cmd] = true
|
390 |
|
|
})
|
391 |
|
|
|
392 |
|
|
parsed.optional.forEach((o) => {
|
393 |
|
|
const cmds = o.cmd.slice(0)
|
394 |
|
|
const cmd = cmds.shift()
|
395 |
|
|
if (o.variadic) {
|
396 |
|
|
parseOptions.array.push(cmd)
|
397 |
|
|
parseOptions.default[cmd] = []
|
398 |
|
|
}
|
399 |
|
|
cmds.forEach((c) => {
|
400 |
|
|
parseOptions.alias[cmd] = c
|
401 |
|
|
})
|
402 |
|
|
})
|
403 |
|
|
|
404 |
|
|
return parseOptions
|
405 |
|
|
}
|
406 |
|
|
|
407 |
|
|
self.reset = () => {
|
408 |
|
|
handlers = {}
|
409 |
|
|
aliasMap = {}
|
410 |
|
|
defaultCommand = undefined
|
411 |
|
|
return self
|
412 |
|
|
}
|
413 |
|
|
|
414 |
|
|
// used by yargs.parse() to freeze
|
415 |
|
|
// the state of commands such that
|
416 |
|
|
// we can apply .parse() multiple times
|
417 |
|
|
// with the same yargs instance.
|
418 |
|
|
let frozen
|
419 |
|
|
self.freeze = () => {
|
420 |
|
|
frozen = {}
|
421 |
|
|
frozen.handlers = handlers
|
422 |
|
|
frozen.aliasMap = aliasMap
|
423 |
|
|
frozen.defaultCommand = defaultCommand
|
424 |
|
|
}
|
425 |
|
|
self.unfreeze = () => {
|
426 |
|
|
handlers = frozen.handlers
|
427 |
|
|
aliasMap = frozen.aliasMap
|
428 |
|
|
defaultCommand = frozen.defaultCommand
|
429 |
|
|
frozen = undefined
|
430 |
|
|
}
|
431 |
|
|
|
432 |
|
|
return self
|
433 |
|
|
}
|