usage.js 16 KB

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