usage.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. 'use strict'
  2. // this file handles outputting usage instructions,
  3. // failures, etc. keeps logging in one place.
  4. const stringWidth = require('string-width')
  5. const objFilter = require('./obj-filter')
  6. const path = require('path')
  7. const setBlocking = require('set-blocking')
  8. const YError = require('./yerror')
  9. module.exports = function usage (yargs, y18n) {
  10. const __ = y18n.__
  11. const self = {}
  12. // methods for ouputting/building failure message.
  13. const fails = []
  14. self.failFn = function failFn (f) {
  15. fails.push(f)
  16. }
  17. let failMessage = null
  18. let showHelpOnFail = true
  19. self.showHelpOnFail = function showHelpOnFailFn (enabled, message) {
  20. if (typeof enabled === 'string') {
  21. message = enabled
  22. enabled = true
  23. } else if (typeof enabled === 'undefined') {
  24. enabled = true
  25. }
  26. failMessage = message
  27. showHelpOnFail = enabled
  28. return self
  29. }
  30. let failureOutput = false
  31. self.fail = function fail (msg, err) {
  32. const logger = yargs._getLoggerInstance()
  33. if (fails.length) {
  34. for (let i = fails.length - 1; i >= 0; --i) {
  35. fails[i](msg, err, self)
  36. }
  37. } else {
  38. if (yargs.getExitProcess()) setBlocking(true)
  39. // don't output failure message more than once
  40. if (!failureOutput) {
  41. failureOutput = true
  42. if (showHelpOnFail) yargs.showHelp('error')
  43. if (msg || err) logger.error(msg || err)
  44. if (failMessage) {
  45. if (msg || err) logger.error('')
  46. logger.error(failMessage)
  47. }
  48. }
  49. err = err || new YError(msg)
  50. if (yargs.getExitProcess()) {
  51. return yargs.exit(1)
  52. } else if (yargs._hasParseCallback()) {
  53. return yargs.exit(1, err)
  54. } else {
  55. throw err
  56. }
  57. }
  58. }
  59. // methods for ouputting/building help (usage) message.
  60. let usages = []
  61. let usageDisabled = false
  62. self.usage = (msg, description) => {
  63. if (msg === null) {
  64. usageDisabled = true
  65. usages = []
  66. return
  67. }
  68. usageDisabled = false
  69. usages.push([msg, description || ''])
  70. return self
  71. }
  72. self.getUsage = () => {
  73. return usages
  74. }
  75. self.getUsageDisabled = () => {
  76. return usageDisabled
  77. }
  78. self.getPositionalGroupName = () => {
  79. return __('Positionals:')
  80. }
  81. let examples = []
  82. self.example = (cmd, description) => {
  83. examples.push([cmd, description || ''])
  84. }
  85. let commands = []
  86. self.command = function command (cmd, description, isDefault, aliases) {
  87. // the last default wins, so cancel out any previously set default
  88. if (isDefault) {
  89. commands = commands.map((cmdArray) => {
  90. cmdArray[2] = false
  91. return cmdArray
  92. })
  93. }
  94. commands.push([cmd, description || '', isDefault, aliases])
  95. }
  96. self.getCommands = () => commands
  97. let descriptions = {}
  98. self.describe = function describe (key, desc) {
  99. if (typeof key === 'object') {
  100. Object.keys(key).forEach((k) => {
  101. self.describe(k, key[k])
  102. })
  103. } else {
  104. descriptions[key] = desc
  105. }
  106. }
  107. self.getDescriptions = () => descriptions
  108. let epilog
  109. self.epilog = (msg) => {
  110. epilog = msg
  111. }
  112. let wrapSet = false
  113. let wrap
  114. self.wrap = (cols) => {
  115. wrapSet = true
  116. wrap = cols
  117. }
  118. function getWrap () {
  119. if (!wrapSet) {
  120. wrap = windowWidth()
  121. wrapSet = true
  122. }
  123. return wrap
  124. }
  125. const deferY18nLookupPrefix = '__yargsString__:'
  126. self.deferY18nLookup = str => deferY18nLookupPrefix + str
  127. const defaultGroup = 'Options:'
  128. self.help = function help () {
  129. normalizeAliases()
  130. // handle old demanded API
  131. const base$0 = path.basename(yargs.$0)
  132. const demandedOptions = yargs.getDemandedOptions()
  133. const demandedCommands = yargs.getDemandedCommands()
  134. const groups = yargs.getGroups()
  135. const options = yargs.getOptions()
  136. let keys = Object.keys(
  137. Object.keys(descriptions)
  138. .concat(Object.keys(demandedOptions))
  139. .concat(Object.keys(demandedCommands))
  140. .concat(Object.keys(options.default))
  141. .reduce((acc, key) => {
  142. if (key !== '_') acc[key] = true
  143. return acc
  144. }, {})
  145. )
  146. const theWrap = getWrap()
  147. const ui = require('cliui')({
  148. width: theWrap,
  149. wrap: !!theWrap
  150. })
  151. // the usage string.
  152. if (!usageDisabled) {
  153. if (usages.length) {
  154. // user-defined usage.
  155. usages.forEach((usage) => {
  156. ui.div(`${usage[0].replace(/\$0/g, base$0)}`)
  157. if (usage[1]) {
  158. ui.div({text: `${usage[1]}`, padding: [1, 0, 0, 0]})
  159. }
  160. })
  161. ui.div()
  162. } else if (commands.length) {
  163. let u = null
  164. // demonstrate how commands are used.
  165. if (demandedCommands._) {
  166. u = `${base$0} <${__('command')}>\n`
  167. } else {
  168. u = `${base$0} [${__('command')}]\n`
  169. }
  170. ui.div(`${u}`)
  171. }
  172. }
  173. // your application's commands, i.e., non-option
  174. // arguments populated in '_'.
  175. if (commands.length) {
  176. ui.div(__('Commands:'))
  177. const context = yargs.getContext()
  178. const parentCommands = context.commands.length ? `${context.commands.join(' ')} ` : ''
  179. commands.forEach((command) => {
  180. const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}` // drop $0 from default commands.
  181. ui.span(
  182. {
  183. text: commandString,
  184. padding: [0, 2, 0, 2],
  185. width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4
  186. },
  187. {text: command[1]}
  188. )
  189. const hints = []
  190. if (command[2]) hints.push(`[${__('default:').slice(0, -1)}]`) // TODO hacking around i18n here
  191. if (command[3] && command[3].length) {
  192. hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`)
  193. }
  194. if (hints.length) {
  195. ui.div({text: hints.join(' '), padding: [0, 0, 0, 2], align: 'right'})
  196. } else {
  197. ui.div()
  198. }
  199. })
  200. ui.div()
  201. }
  202. // perform some cleanup on the keys array, making it
  203. // only include top-level keys not their aliases.
  204. const aliasKeys = (Object.keys(options.alias) || [])
  205. .concat(Object.keys(yargs.parsed.newAliases) || [])
  206. keys = keys.filter(key => !yargs.parsed.newAliases[key] && aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1))
  207. // populate 'Options:' group with any keys that have not
  208. // explicitly had a group set.
  209. if (!groups[defaultGroup]) groups[defaultGroup] = []
  210. addUngroupedKeys(keys, options.alias, groups)
  211. // display 'Options:' table along with any custom tables:
  212. Object.keys(groups).forEach((groupName) => {
  213. if (!groups[groupName].length) return
  214. ui.div(__(groupName))
  215. // if we've grouped the key 'f', but 'f' aliases 'foobar',
  216. // normalizedKeys should contain only 'foobar'.
  217. const normalizedKeys = groups[groupName].map((key) => {
  218. if (~aliasKeys.indexOf(key)) return key
  219. for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
  220. if (~(options.alias[aliasKey] || []).indexOf(key)) return aliasKey
  221. }
  222. return key
  223. })
  224. // actually generate the switches string --foo, -f, --bar.
  225. const switches = normalizedKeys.reduce((acc, key) => {
  226. acc[key] = [ key ].concat(options.alias[key] || [])
  227. .map(sw => {
  228. // for the special positional group don't
  229. // add '--' or '-' prefix.
  230. if (groupName === self.getPositionalGroupName()) return sw
  231. else return (sw.length > 1 ? '--' : '-') + sw
  232. })
  233. .join(', ')
  234. return acc
  235. }, {})
  236. normalizedKeys.forEach((key) => {
  237. const kswitch = switches[key]
  238. let desc = descriptions[key] || ''
  239. let type = null
  240. if (~desc.lastIndexOf(deferY18nLookupPrefix)) desc = __(desc.substring(deferY18nLookupPrefix.length))
  241. if (~options.boolean.indexOf(key)) type = `[${__('boolean')}]`
  242. if (~options.count.indexOf(key)) type = `[${__('count')}]`
  243. if (~options.string.indexOf(key)) type = `[${__('string')}]`
  244. if (~options.normalize.indexOf(key)) type = `[${__('string')}]`
  245. if (~options.array.indexOf(key)) type = `[${__('array')}]`
  246. if (~options.number.indexOf(key)) type = `[${__('number')}]`
  247. const extra = [
  248. type,
  249. (key in demandedOptions) ? `[${__('required')}]` : null,
  250. options.choices && options.choices[key] ? `[${__('choices:')} ${
  251. self.stringifiedValues(options.choices[key])}]` : null,
  252. defaultString(options.default[key], options.defaultDescription[key])
  253. ].filter(Boolean).join(' ')
  254. ui.span(
  255. {text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4},
  256. desc
  257. )
  258. if (extra) ui.div({text: extra, padding: [0, 0, 0, 2], align: 'right'})
  259. else ui.div()
  260. })
  261. ui.div()
  262. })
  263. // describe some common use-cases for your application.
  264. if (examples.length) {
  265. ui.div(__('Examples:'))
  266. examples.forEach((example) => {
  267. example[0] = example[0].replace(/\$0/g, base$0)
  268. })
  269. examples.forEach((example) => {
  270. if (example[1] === '') {
  271. ui.div(
  272. {
  273. text: example[0],
  274. padding: [0, 2, 0, 2]
  275. }
  276. )
  277. } else {
  278. ui.div(
  279. {
  280. text: example[0],
  281. padding: [0, 2, 0, 2],
  282. width: maxWidth(examples, theWrap) + 4
  283. }, {
  284. text: example[1]
  285. }
  286. )
  287. }
  288. })
  289. ui.div()
  290. }
  291. // the usage string.
  292. if (epilog) {
  293. const e = epilog.replace(/\$0/g, base$0)
  294. ui.div(`${e}\n`)
  295. }
  296. return ui.toString()
  297. }
  298. // return the maximum width of a string
  299. // in the left-hand column of a table.
  300. function maxWidth (table, theWrap, modifier) {
  301. let width = 0
  302. // table might be of the form [leftColumn],
  303. // or {key: leftColumn}
  304. if (!Array.isArray(table)) {
  305. table = Object.keys(table).map(key => [table[key]])
  306. }
  307. table.forEach((v) => {
  308. width = Math.max(
  309. stringWidth(modifier ? `${modifier} ${v[0]}` : v[0]),
  310. width
  311. )
  312. })
  313. // if we've enabled 'wrap' we should limit
  314. // the max-width of the left-column.
  315. if (theWrap) width = Math.min(width, parseInt(theWrap * 0.5, 10))
  316. return width
  317. }
  318. // make sure any options set for aliases,
  319. // are copied to the keys being aliased.
  320. function normalizeAliases () {
  321. // handle old demanded API
  322. const demandedOptions = yargs.getDemandedOptions()
  323. const options = yargs.getOptions()
  324. ;(Object.keys(options.alias) || []).forEach((key) => {
  325. options.alias[key].forEach((alias) => {
  326. // copy descriptions.
  327. if (descriptions[alias]) self.describe(key, descriptions[alias])
  328. // copy demanded.
  329. if (alias in demandedOptions) yargs.demandOption(key, demandedOptions[alias])
  330. // type messages.
  331. if (~options.boolean.indexOf(alias)) yargs.boolean(key)
  332. if (~options.count.indexOf(alias)) yargs.count(key)
  333. if (~options.string.indexOf(alias)) yargs.string(key)
  334. if (~options.normalize.indexOf(alias)) yargs.normalize(key)
  335. if (~options.array.indexOf(alias)) yargs.array(key)
  336. if (~options.number.indexOf(alias)) yargs.number(key)
  337. })
  338. })
  339. }
  340. // given a set of keys, place any keys that are
  341. // ungrouped under the 'Options:' grouping.
  342. function addUngroupedKeys (keys, aliases, groups) {
  343. let groupedKeys = []
  344. let toCheck = null
  345. Object.keys(groups).forEach((group) => {
  346. groupedKeys = groupedKeys.concat(groups[group])
  347. })
  348. keys.forEach((key) => {
  349. toCheck = [key].concat(aliases[key])
  350. if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
  351. groups[defaultGroup].push(key)
  352. }
  353. })
  354. return groupedKeys
  355. }
  356. self.showHelp = (level) => {
  357. const logger = yargs._getLoggerInstance()
  358. if (!level) level = 'error'
  359. const emit = typeof level === 'function' ? level : logger[level]
  360. emit(self.help())
  361. }
  362. self.functionDescription = (fn) => {
  363. const description = fn.name ? require('decamelize')(fn.name, '-') : __('generated-value')
  364. return ['(', description, ')'].join('')
  365. }
  366. self.stringifiedValues = function stringifiedValues (values, separator) {
  367. let string = ''
  368. const sep = separator || ', '
  369. const array = [].concat(values)
  370. if (!values || !array.length) return string
  371. array.forEach((value) => {
  372. if (string.length) string += sep
  373. string += JSON.stringify(value)
  374. })
  375. return string
  376. }
  377. // format the default-value-string displayed in
  378. // the right-hand column.
  379. function defaultString (value, defaultDescription) {
  380. let string = `[${__('default:')} `
  381. if (value === undefined && !defaultDescription) return null
  382. if (defaultDescription) {
  383. string += defaultDescription
  384. } else {
  385. switch (typeof value) {
  386. case 'string':
  387. string += `"${value}"`
  388. break
  389. case 'object':
  390. string += JSON.stringify(value)
  391. break
  392. default:
  393. string += value
  394. }
  395. }
  396. return `${string}]`
  397. }
  398. // guess the width of the console window, max-width 80.
  399. function windowWidth () {
  400. const maxWidth = 80
  401. if (typeof process === 'object' && process.stdout && process.stdout.columns) {
  402. return Math.min(maxWidth, process.stdout.columns)
  403. } else {
  404. return maxWidth
  405. }
  406. }
  407. // logic for displaying application version.
  408. let version = null
  409. self.version = (ver) => {
  410. version = ver
  411. }
  412. self.showVersion = () => {
  413. const logger = yargs._getLoggerInstance()
  414. logger.log(version)
  415. }
  416. self.reset = function reset (localLookup) {
  417. // do not reset wrap here
  418. // do not reset fails here
  419. failMessage = null
  420. failureOutput = false
  421. usages = []
  422. usageDisabled = false
  423. epilog = undefined
  424. examples = []
  425. commands = []
  426. descriptions = objFilter(descriptions, (k, v) => !localLookup[k])
  427. return self
  428. }
  429. let frozen
  430. self.freeze = function freeze () {
  431. frozen = {}
  432. frozen.failMessage = failMessage
  433. frozen.failureOutput = failureOutput
  434. frozen.usages = usages
  435. frozen.usageDisabled = usageDisabled
  436. frozen.epilog = epilog
  437. frozen.examples = examples
  438. frozen.commands = commands
  439. frozen.descriptions = descriptions
  440. }
  441. self.unfreeze = function unfreeze () {
  442. failMessage = frozen.failMessage
  443. failureOutput = frozen.failureOutput
  444. usages = frozen.usages
  445. usageDisabled = frozen.usageDisabled
  446. epilog = frozen.epilog
  447. examples = frozen.examples
  448. commands = frozen.commands
  449. descriptions = frozen.descriptions
  450. frozen = undefined
  451. }
  452. return self
  453. }