You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

433 lines
14 KiB

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