command.js 14 KB

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