command.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. const path = require('path')
  2. const inspect = require('util').inspect
  3. const camelCase = require('camelcase')
  4. const DEFAULT_MARKER = '*'
  5. // handles parsing positional arguments,
  6. // and populating argv with said positional
  7. // arguments.
  8. module.exports = function (yargs, usage, validation) {
  9. const self = {}
  10. var handlers = {}
  11. var aliasMap = {}
  12. var defaultCommand
  13. self.addHandler = function (cmd, description, builder, handler) {
  14. var aliases = []
  15. handler = handler || function () {}
  16. if (Array.isArray(cmd)) {
  17. aliases = cmd.slice(1)
  18. cmd = cmd[0]
  19. } else if (typeof cmd === 'object') {
  20. var command = (Array.isArray(cmd.command) || typeof cmd.command === 'string') ? cmd.command : moduleName(cmd)
  21. if (cmd.aliases) command = [].concat(command).concat(cmd.aliases)
  22. self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler)
  23. return
  24. }
  25. // allow a module to be provided instead of separate builder and handler
  26. if (typeof builder === 'object' && builder.builder && typeof builder.handler === 'function') {
  27. self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler)
  28. return
  29. }
  30. // parse positionals out of cmd string
  31. var parsedCommand = self.parseCommand(cmd)
  32. // remove positional args from aliases only
  33. aliases = aliases.map(function (alias) {
  34. return self.parseCommand(alias).cmd
  35. })
  36. // check for default and filter out '*''
  37. var isDefault = false
  38. var parsedAliases = [parsedCommand.cmd].concat(aliases).filter(function (c) {
  39. if (c === DEFAULT_MARKER) {
  40. isDefault = true
  41. return false
  42. }
  43. return true
  44. })
  45. // short-circuit if default with no aliases
  46. if (isDefault && parsedAliases.length === 0) {
  47. defaultCommand = {
  48. original: cmd.replace(DEFAULT_MARKER, '').trim(),
  49. handler: handler,
  50. builder: builder || {},
  51. demanded: parsedCommand.demanded,
  52. optional: parsedCommand.optional
  53. }
  54. return
  55. }
  56. // shift cmd and aliases after filtering out '*'
  57. if (isDefault) {
  58. parsedCommand.cmd = parsedAliases[0]
  59. aliases = parsedAliases.slice(1)
  60. cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd)
  61. }
  62. // populate aliasMap
  63. aliases.forEach(function (alias) {
  64. aliasMap[alias] = parsedCommand.cmd
  65. })
  66. if (description !== false) {
  67. usage.command(cmd, description, isDefault, aliases)
  68. }
  69. handlers[parsedCommand.cmd] = {
  70. original: cmd,
  71. handler: handler,
  72. builder: builder || {},
  73. demanded: parsedCommand.demanded,
  74. optional: parsedCommand.optional
  75. }
  76. if (isDefault) defaultCommand = handlers[parsedCommand.cmd]
  77. }
  78. self.addDirectory = function (dir, context, req, callerFile, opts) {
  79. opts = opts || {}
  80. // disable recursion to support nested directories of subcommands
  81. if (typeof opts.recurse !== 'boolean') opts.recurse = false
  82. // exclude 'json', 'coffee' from require-directory defaults
  83. if (!Array.isArray(opts.extensions)) opts.extensions = ['js']
  84. // allow consumer to define their own visitor function
  85. const parentVisit = typeof opts.visit === 'function' ? opts.visit : function (o) { return o }
  86. // call addHandler via visitor function
  87. opts.visit = function (obj, joined, filename) {
  88. const visited = parentVisit(obj, joined, filename)
  89. // allow consumer to skip modules with their own visitor
  90. if (visited) {
  91. // check for cyclic reference
  92. // each command file path should only be seen once per execution
  93. if (~context.files.indexOf(joined)) return visited
  94. // keep track of visited files in context.files
  95. context.files.push(joined)
  96. self.addHandler(visited)
  97. }
  98. return visited
  99. }
  100. require('require-directory')({ require: req, filename: callerFile }, dir, opts)
  101. }
  102. // lookup module object from require()d command and derive name
  103. // if module was not require()d and no name given, throw error
  104. function moduleName (obj) {
  105. const mod = require('which-module')(obj)
  106. if (!mod) throw new Error('No command name given for module: ' + inspect(obj))
  107. return commandFromFilename(mod.filename)
  108. }
  109. // derive command name from filename
  110. function commandFromFilename (filename) {
  111. return path.basename(filename, path.extname(filename))
  112. }
  113. function extractDesc (obj) {
  114. for (var keys = ['describe', 'description', 'desc'], i = 0, l = keys.length, test; i < l; i++) {
  115. test = obj[keys[i]]
  116. if (typeof test === 'string' || typeof test === 'boolean') return test
  117. }
  118. return false
  119. }
  120. self.parseCommand = function (cmd) {
  121. var extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ')
  122. var splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/)
  123. var bregex = /\.*[\][<>]/g
  124. var parsedCommand = {
  125. cmd: (splitCommand.shift()).replace(bregex, ''),
  126. demanded: [],
  127. optional: []
  128. }
  129. splitCommand.forEach(function (cmd, i) {
  130. var variadic = false
  131. cmd = cmd.replace(/\s/g, '')
  132. if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) variadic = true
  133. if (/^\[/.test(cmd)) {
  134. parsedCommand.optional.push({
  135. cmd: cmd.replace(bregex, '').split('|'),
  136. variadic: variadic
  137. })
  138. } else {
  139. parsedCommand.demanded.push({
  140. cmd: cmd.replace(bregex, '').split('|'),
  141. variadic: variadic
  142. })
  143. }
  144. })
  145. return parsedCommand
  146. }
  147. self.getCommands = function () {
  148. return Object.keys(handlers).concat(Object.keys(aliasMap))
  149. }
  150. self.getCommandHandlers = function () {
  151. return handlers
  152. }
  153. self.hasDefaultCommand = function () {
  154. return !!defaultCommand
  155. }
  156. self.runCommand = function (command, yargs, parsed, commandIndex) {
  157. var aliases = parsed.aliases
  158. var commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand
  159. var currentContext = yargs.getContext()
  160. var numFiles = currentContext.files.length
  161. var parentCommands = currentContext.commands.slice()
  162. // what does yargs look like after the buidler is run?
  163. var innerArgv = parsed.argv
  164. var innerYargs = null
  165. var positionalMap = {}
  166. if (command) currentContext.commands.push(command)
  167. if (typeof commandHandler.builder === 'function') {
  168. // a function can be provided, which builds
  169. // up a yargs chain and possibly returns it.
  170. innerYargs = commandHandler.builder(yargs.reset(parsed.aliases))
  171. // if the builder function did not yet parse argv with reset yargs
  172. // and did not explicitly set a usage() string, then apply the
  173. // original command string as usage() for consistent behavior with
  174. // options object below.
  175. if (yargs.parsed === false) {
  176. if (typeof yargs.getUsageInstance().getUsage() === 'undefined') {
  177. yargs.usage('$0 ' + (parentCommands.length ? parentCommands.join(' ') + ' ' : '') + commandHandler.original)
  178. }
  179. innerArgv = innerYargs ? innerYargs._parseArgs(null, null, true, commandIndex) : yargs._parseArgs(null, null, true, commandIndex)
  180. } else {
  181. innerArgv = yargs.parsed.argv
  182. }
  183. if (innerYargs && yargs.parsed === false) aliases = innerYargs.parsed.aliases
  184. else aliases = yargs.parsed.aliases
  185. } else if (typeof commandHandler.builder === 'object') {
  186. // as a short hand, an object can instead be provided, specifying
  187. // the options that a command takes.
  188. innerYargs = yargs.reset(parsed.aliases)
  189. innerYargs.usage('$0 ' + (parentCommands.length ? parentCommands.join(' ') + ' ' : '') + commandHandler.original)
  190. Object.keys(commandHandler.builder).forEach(function (key) {
  191. innerYargs.option(key, commandHandler.builder[key])
  192. })
  193. innerArgv = innerYargs._parseArgs(null, null, true, commandIndex)
  194. aliases = innerYargs.parsed.aliases
  195. }
  196. if (!yargs._hasOutput()) {
  197. positionalMap = populatePositionals(commandHandler, innerArgv, currentContext, yargs)
  198. }
  199. // we apply validation post-hoc, so that custom
  200. // checks get passed populated positional arguments.
  201. if (!yargs._hasOutput()) yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error)
  202. if (commandHandler.handler && !yargs._hasOutput()) {
  203. yargs._setHasOutput()
  204. commandHandler.handler(innerArgv)
  205. }
  206. if (command) currentContext.commands.pop()
  207. numFiles = currentContext.files.length - numFiles
  208. if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles)
  209. return innerArgv
  210. }
  211. // transcribe all positional arguments "command <foo> <bar> [apple]"
  212. // onto argv.
  213. function populatePositionals (commandHandler, argv, context, yargs) {
  214. argv._ = argv._.slice(context.commands.length) // nuke the current commands
  215. var demanded = commandHandler.demanded.slice(0)
  216. var optional = commandHandler.optional.slice(0)
  217. var positionalMap = {}
  218. validation.positionalCount(demanded.length, argv._.length)
  219. while (demanded.length) {
  220. var demand = demanded.shift()
  221. populatePositional(demand, argv, yargs, positionalMap)
  222. }
  223. while (optional.length) {
  224. var maybe = optional.shift()
  225. populatePositional(maybe, argv, yargs, positionalMap)
  226. }
  227. argv._ = context.commands.concat(argv._)
  228. return positionalMap
  229. }
  230. // populate a single positional argument and its
  231. // aliases onto argv.
  232. function populatePositional (positional, argv, yargs, positionalMap) {
  233. // "positional" consists of the positional.cmd, an array representing
  234. // the positional's name and aliases, and positional.variadic
  235. // indicating whether or not it is a variadic array.
  236. var variadics = null
  237. var value = null
  238. for (var i = 0, cmd; (cmd = positional.cmd[i]) !== undefined; i++) {
  239. if (positional.variadic) {
  240. if (variadics) argv[cmd] = variadics.slice(0)
  241. else argv[cmd] = variadics = argv._.splice(0)
  242. } else {
  243. if (!value && !argv._.length) continue
  244. if (value) argv[cmd] = value
  245. else argv[cmd] = value = argv._.shift()
  246. }
  247. positionalMap[cmd] = true
  248. postProcessPositional(yargs, argv, cmd)
  249. addCamelCaseExpansions(argv, cmd)
  250. }
  251. }
  252. // TODO move positional arg logic to yargs-parser and remove this duplication
  253. function postProcessPositional (yargs, argv, key) {
  254. var coerce = yargs.getOptions().coerce[key]
  255. if (typeof coerce === 'function') {
  256. try {
  257. argv[key] = coerce(argv[key])
  258. } catch (err) {
  259. yargs.getUsageInstance().fail(err.message, err)
  260. }
  261. }
  262. }
  263. function addCamelCaseExpansions (argv, option) {
  264. if (/-/.test(option)) {
  265. const cc = camelCase(option)
  266. if (typeof argv[option] === 'object') argv[cc] = argv[option].slice(0)
  267. else argv[cc] = argv[option]
  268. }
  269. }
  270. self.reset = function () {
  271. handlers = {}
  272. aliasMap = {}
  273. defaultCommand = undefined
  274. return self
  275. }
  276. // used by yargs.parse() to freeze
  277. // the state of commands such that
  278. // we can apply .parse() multiple times
  279. // with the same yargs instance.
  280. var frozen
  281. self.freeze = function () {
  282. frozen = {}
  283. frozen.handlers = handlers
  284. frozen.aliasMap = aliasMap
  285. frozen.defaultCommand = defaultCommand
  286. }
  287. self.unfreeze = function () {
  288. handlers = frozen.handlers
  289. aliasMap = frozen.aliasMap
  290. defaultCommand = frozen.defaultCommand
  291. frozen = undefined
  292. }
  293. return self
  294. }