command.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. 'use strict'
  2. const inspect = require('util').inspect
  3. const isPromise = require('./is-promise')
  4. const { applyMiddleware, commandMiddlewareFactory } = require('./middleware')
  5. const path = require('path')
  6. const Parser = require('yargs-parser')
  7. const DEFAULT_MARKER = /(^\*)|(^\$0)/
  8. // handles parsing positional arguments,
  9. // and populating argv with said positional
  10. // arguments.
  11. module.exports = function command (yargs, usage, validation, globalMiddleware) {
  12. const self = {}
  13. let handlers = {}
  14. let aliasMap = {}
  15. let defaultCommand
  16. globalMiddleware = globalMiddleware || []
  17. self.addHandler = function addHandler (cmd, description, builder, handler, commandMiddleware) {
  18. let aliases = []
  19. const middlewares = commandMiddlewareFactory(commandMiddleware)
  20. handler = handler || (() => {})
  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. const middlewares = globalMiddleware.slice(0).concat(commandHandler.middlewares || [])
  201. applyMiddleware(innerArgv, yargs, middlewares, true)
  202. // we apply validation post-hoc, so that custom
  203. // checks get passed populated positional arguments.
  204. if (!yargs._hasOutput()) yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error)
  205. if (commandHandler.handler && !yargs._hasOutput()) {
  206. yargs._setHasOutput()
  207. innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false)
  208. const handlerResult = isPromise(innerArgv)
  209. ? innerArgv.then(argv => commandHandler.handler(argv))
  210. : commandHandler.handler(innerArgv)
  211. if (isPromise(handlerResult)) {
  212. handlerResult.catch(error =>
  213. yargs.getUsageInstance().fail(null, error)
  214. )
  215. }
  216. }
  217. if (command) {
  218. currentContext.commands.pop()
  219. currentContext.fullCommands.pop()
  220. }
  221. numFiles = currentContext.files.length - numFiles
  222. if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles)
  223. return innerArgv
  224. }
  225. function shouldUpdateUsage (yargs) {
  226. return !yargs.getUsageInstance().getUsageDisabled() &&
  227. yargs.getUsageInstance().getUsage().length === 0
  228. }
  229. function usageFromParentCommandsCommandHandler (parentCommands, commandHandler) {
  230. const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() : commandHandler.original
  231. const pc = parentCommands.filter((c) => { return !DEFAULT_MARKER.test(c) })
  232. pc.push(c)
  233. return `$0 ${pc.join(' ')}`
  234. }
  235. self.runDefaultBuilderOn = function (yargs) {
  236. if (shouldUpdateUsage(yargs)) {
  237. // build the root-level command string from the default string.
  238. const commandString = DEFAULT_MARKER.test(defaultCommand.original)
  239. ? defaultCommand.original : defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ')
  240. yargs.getUsageInstance().usage(
  241. commandString,
  242. defaultCommand.description
  243. )
  244. }
  245. const builder = defaultCommand.builder
  246. if (typeof builder === 'function') {
  247. builder(yargs)
  248. } else {
  249. Object.keys(builder).forEach((key) => {
  250. yargs.option(key, builder[key])
  251. })
  252. }
  253. }
  254. // transcribe all positional arguments "command <foo> <bar> [apple]"
  255. // onto argv.
  256. function populatePositionals (commandHandler, argv, context, yargs) {
  257. argv._ = argv._.slice(context.commands.length) // nuke the current commands
  258. const demanded = commandHandler.demanded.slice(0)
  259. const optional = commandHandler.optional.slice(0)
  260. const positionalMap = {}
  261. validation.positionalCount(demanded.length, argv._.length)
  262. while (demanded.length) {
  263. const demand = demanded.shift()
  264. populatePositional(demand, argv, positionalMap)
  265. }
  266. while (optional.length) {
  267. const maybe = optional.shift()
  268. populatePositional(maybe, argv, positionalMap)
  269. }
  270. argv._ = context.commands.concat(argv._)
  271. postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original))
  272. return positionalMap
  273. }
  274. function populatePositional (positional, argv, positionalMap, parseOptions) {
  275. const cmd = positional.cmd[0]
  276. if (positional.variadic) {
  277. positionalMap[cmd] = argv._.splice(0).map(String)
  278. } else {
  279. if (argv._.length) positionalMap[cmd] = [String(argv._.shift())]
  280. }
  281. }
  282. // we run yargs-parser against the positional arguments
  283. // applying the same parsing logic used for flags.
  284. function postProcessPositionals (argv, positionalMap, parseOptions) {
  285. // combine the parsing hints we've inferred from the command
  286. // string with explicitly configured parsing hints.
  287. const options = Object.assign({}, yargs.getOptions())
  288. options.default = Object.assign(parseOptions.default, options.default)
  289. options.alias = Object.assign(parseOptions.alias, options.alias)
  290. options.array = options.array.concat(parseOptions.array)
  291. delete options.config // don't load config when processing positionals.
  292. const unparsed = []
  293. Object.keys(positionalMap).forEach((key) => {
  294. positionalMap[key].map((value) => {
  295. unparsed.push(`--${key}`)
  296. unparsed.push(value)
  297. })
  298. })
  299. // short-circuit parse.
  300. if (!unparsed.length) return
  301. const parsed = Parser.detailed(unparsed, options)
  302. if (parsed.error) {
  303. yargs.getUsageInstance().fail(parsed.error.message, parsed.error)
  304. } else {
  305. // only copy over positional keys (don't overwrite
  306. // flag arguments that were already parsed).
  307. const positionalKeys = Object.keys(positionalMap)
  308. Object.keys(positionalMap).forEach((key) => {
  309. [].push.apply(positionalKeys, parsed.aliases[key])
  310. })
  311. Object.keys(parsed.argv).forEach((key) => {
  312. if (positionalKeys.indexOf(key) !== -1) {
  313. // any new aliases need to be placed in positionalMap, which
  314. // is used for validation.
  315. if (!positionalMap[key]) positionalMap[key] = parsed.argv[key]
  316. argv[key] = parsed.argv[key]
  317. }
  318. })
  319. }
  320. }
  321. self.cmdToParseOptions = function (cmdString) {
  322. const parseOptions = {
  323. array: [],
  324. default: {},
  325. alias: {},
  326. demand: {}
  327. }
  328. const parsed = self.parseCommand(cmdString)
  329. parsed.demanded.forEach((d) => {
  330. const cmds = d.cmd.slice(0)
  331. const cmd = cmds.shift()
  332. if (d.variadic) {
  333. parseOptions.array.push(cmd)
  334. parseOptions.default[cmd] = []
  335. }
  336. cmds.forEach((c) => {
  337. parseOptions.alias[cmd] = c
  338. })
  339. parseOptions.demand[cmd] = true
  340. })
  341. parsed.optional.forEach((o) => {
  342. const cmds = o.cmd.slice(0)
  343. const cmd = cmds.shift()
  344. if (o.variadic) {
  345. parseOptions.array.push(cmd)
  346. parseOptions.default[cmd] = []
  347. }
  348. cmds.forEach((c) => {
  349. parseOptions.alias[cmd] = c
  350. })
  351. })
  352. return parseOptions
  353. }
  354. self.reset = () => {
  355. handlers = {}
  356. aliasMap = {}
  357. defaultCommand = undefined
  358. return self
  359. }
  360. // used by yargs.parse() to freeze
  361. // the state of commands such that
  362. // we can apply .parse() multiple times
  363. // with the same yargs instance.
  364. let frozen
  365. self.freeze = () => {
  366. frozen = {}
  367. frozen.handlers = handlers
  368. frozen.aliasMap = aliasMap
  369. frozen.defaultCommand = defaultCommand
  370. }
  371. self.unfreeze = () => {
  372. handlers = frozen.handlers
  373. aliasMap = frozen.aliasMap
  374. defaultCommand = frozen.defaultCommand
  375. frozen = undefined
  376. }
  377. return self
  378. }