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