usage.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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 epilog
  113. self.epilog = (msg) => {
  114. epilog = 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. normalizeAliases()
  134. // handle old demanded API
  135. const base$0 = path.basename(yargs.$0)
  136. const demandedOptions = yargs.getDemandedOptions()
  137. const demandedCommands = yargs.getDemandedCommands()
  138. const groups = yargs.getGroups()
  139. const options = yargs.getOptions()
  140. let keys = []
  141. keys = keys.concat(Object.keys(descriptions))
  142. keys = keys.concat(Object.keys(demandedOptions))
  143. keys = keys.concat(Object.keys(demandedCommands))
  144. keys = keys.concat(Object.keys(options.default))
  145. keys = keys.filter(filterHiddenOptions)
  146. keys = Object.keys(keys.reduce((acc, key) => {
  147. if (key !== '_') acc[key] = true
  148. return acc
  149. }, {}))
  150. const theWrap = getWrap()
  151. const ui = require('cliui')({
  152. width: theWrap,
  153. wrap: !!theWrap
  154. })
  155. // the usage string.
  156. if (!usageDisabled) {
  157. if (usages.length) {
  158. // user-defined usage.
  159. usages.forEach((usage) => {
  160. ui.div(`${usage[0].replace(/\$0/g, base$0)}`)
  161. if (usage[1]) {
  162. ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] })
  163. }
  164. })
  165. ui.div()
  166. } else if (commands.length) {
  167. let u = null
  168. // demonstrate how commands are used.
  169. if (demandedCommands._) {
  170. u = `${base$0} <${__('command')}>\n`
  171. } else {
  172. u = `${base$0} [${__('command')}]\n`
  173. }
  174. ui.div(`${u}`)
  175. }
  176. }
  177. // your application's commands, i.e., non-option
  178. // arguments populated in '_'.
  179. if (commands.length) {
  180. ui.div(__('Commands:'))
  181. const context = yargs.getContext()
  182. const parentCommands = context.commands.length ? `${context.commands.join(' ')} ` : ''
  183. if (yargs.getParserConfiguration()['sort-commands'] === true) {
  184. commands = commands.sort((a, b) => a[0].localeCompare(b[0]))
  185. }
  186. commands.forEach((command) => {
  187. const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}` // drop $0 from default commands.
  188. ui.span(
  189. {
  190. text: commandString,
  191. padding: [0, 2, 0, 2],
  192. width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4
  193. },
  194. { text: command[1] }
  195. )
  196. const hints = []
  197. if (command[2]) hints.push(`[${__('default:').slice(0, -1)}]`) // TODO hacking around i18n here
  198. if (command[3] && command[3].length) {
  199. hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`)
  200. }
  201. if (hints.length) {
  202. ui.div({ text: hints.join(' '), padding: [0, 0, 0, 2], align: 'right' })
  203. } else {
  204. ui.div()
  205. }
  206. })
  207. ui.div()
  208. }
  209. // perform some cleanup on the keys array, making it
  210. // only include top-level keys not their aliases.
  211. const aliasKeys = (Object.keys(options.alias) || [])
  212. .concat(Object.keys(yargs.parsed.newAliases) || [])
  213. keys = keys.filter(key => !yargs.parsed.newAliases[key] && aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1))
  214. // populate 'Options:' group with any keys that have not
  215. // explicitly had a group set.
  216. if (!groups[defaultGroup]) groups[defaultGroup] = []
  217. addUngroupedKeys(keys, options.alias, groups)
  218. // display 'Options:' table along with any custom tables:
  219. Object.keys(groups).forEach((groupName) => {
  220. if (!groups[groupName].length) return
  221. // if we've grouped the key 'f', but 'f' aliases 'foobar',
  222. // normalizedKeys should contain only 'foobar'.
  223. const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => {
  224. if (~aliasKeys.indexOf(key)) return key
  225. for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
  226. if (~(options.alias[aliasKey] || []).indexOf(key)) return aliasKey
  227. }
  228. return key
  229. })
  230. if (normalizedKeys.length < 1) return
  231. ui.div(__(groupName))
  232. // actually generate the switches string --foo, -f, --bar.
  233. const switches = normalizedKeys.reduce((acc, key) => {
  234. acc[key] = [ key ].concat(options.alias[key] || [])
  235. .map(sw => {
  236. // for the special positional group don't
  237. // add '--' or '-' prefix.
  238. if (groupName === self.getPositionalGroupName()) return sw
  239. else return (sw.length > 1 ? '--' : '-') + sw
  240. })
  241. .join(', ')
  242. return acc
  243. }, {})
  244. normalizedKeys.forEach((key) => {
  245. const kswitch = switches[key]
  246. let desc = descriptions[key] || ''
  247. let type = null
  248. if (~desc.lastIndexOf(deferY18nLookupPrefix)) desc = __(desc.substring(deferY18nLookupPrefix.length))
  249. if (~options.boolean.indexOf(key)) type = `[${__('boolean')}]`
  250. if (~options.count.indexOf(key)) type = `[${__('count')}]`
  251. if (~options.string.indexOf(key)) type = `[${__('string')}]`
  252. if (~options.normalize.indexOf(key)) type = `[${__('string')}]`
  253. if (~options.array.indexOf(key)) type = `[${__('array')}]`
  254. if (~options.number.indexOf(key)) type = `[${__('number')}]`
  255. const extra = [
  256. type,
  257. (key in demandedOptions) ? `[${__('required')}]` : null,
  258. options.choices && options.choices[key] ? `[${__('choices:')} ${
  259. self.stringifiedValues(options.choices[key])}]` : null,
  260. defaultString(options.default[key], options.defaultDescription[key])
  261. ].filter(Boolean).join(' ')
  262. ui.span(
  263. { text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4 },
  264. desc
  265. )
  266. if (extra) ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' })
  267. else ui.div()
  268. })
  269. ui.div()
  270. })
  271. // describe some common use-cases for your application.
  272. if (examples.length) {
  273. ui.div(__('Examples:'))
  274. examples.forEach((example) => {
  275. example[0] = example[0].replace(/\$0/g, base$0)
  276. })
  277. examples.forEach((example) => {
  278. if (example[1] === '') {
  279. ui.div(
  280. {
  281. text: example[0],
  282. padding: [0, 2, 0, 2]
  283. }
  284. )
  285. } else {
  286. ui.div(
  287. {
  288. text: example[0],
  289. padding: [0, 2, 0, 2],
  290. width: maxWidth(examples, theWrap) + 4
  291. }, {
  292. text: example[1]
  293. }
  294. )
  295. }
  296. })
  297. ui.div()
  298. }
  299. // the usage string.
  300. if (epilog) {
  301. const e = epilog.replace(/\$0/g, base$0)
  302. ui.div(`${e}\n`)
  303. }
  304. // Remove the trailing white spaces
  305. return ui.toString().replace(/\s*$/, '')
  306. }
  307. // return the maximum width of a string
  308. // in the left-hand column of a table.
  309. function maxWidth (table, theWrap, modifier) {
  310. let width = 0
  311. // table might be of the form [leftColumn],
  312. // or {key: leftColumn}
  313. if (!Array.isArray(table)) {
  314. table = Object.keys(table).map(key => [table[key]])
  315. }
  316. table.forEach((v) => {
  317. width = Math.max(
  318. stringWidth(modifier ? `${modifier} ${v[0]}` : v[0]),
  319. width
  320. )
  321. })
  322. // if we've enabled 'wrap' we should limit
  323. // the max-width of the left-column.
  324. if (theWrap) width = Math.min(width, parseInt(theWrap * 0.5, 10))
  325. return width
  326. }
  327. // make sure any options set for aliases,
  328. // are copied to the keys being aliased.
  329. function normalizeAliases () {
  330. // handle old demanded API
  331. const demandedOptions = yargs.getDemandedOptions()
  332. const options = yargs.getOptions()
  333. ;(Object.keys(options.alias) || []).forEach((key) => {
  334. options.alias[key].forEach((alias) => {
  335. // copy descriptions.
  336. if (descriptions[alias]) self.describe(key, descriptions[alias])
  337. // copy demanded.
  338. if (alias in demandedOptions) yargs.demandOption(key, demandedOptions[alias])
  339. // type messages.
  340. if (~options.boolean.indexOf(alias)) yargs.boolean(key)
  341. if (~options.count.indexOf(alias)) yargs.count(key)
  342. if (~options.string.indexOf(alias)) yargs.string(key)
  343. if (~options.normalize.indexOf(alias)) yargs.normalize(key)
  344. if (~options.array.indexOf(alias)) yargs.array(key)
  345. if (~options.number.indexOf(alias)) yargs.number(key)
  346. })
  347. })
  348. }
  349. // given a set of keys, place any keys that are
  350. // ungrouped under the 'Options:' grouping.
  351. function addUngroupedKeys (keys, aliases, groups) {
  352. let groupedKeys = []
  353. let toCheck = null
  354. Object.keys(groups).forEach((group) => {
  355. groupedKeys = groupedKeys.concat(groups[group])
  356. })
  357. keys.forEach((key) => {
  358. toCheck = [key].concat(aliases[key])
  359. if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
  360. groups[defaultGroup].push(key)
  361. }
  362. })
  363. return groupedKeys
  364. }
  365. function filterHiddenOptions (key) {
  366. return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt]
  367. }
  368. self.showHelp = (level) => {
  369. const logger = yargs._getLoggerInstance()
  370. if (!level) level = 'error'
  371. const emit = typeof level === 'function' ? level : logger[level]
  372. emit(self.help())
  373. }
  374. self.functionDescription = (fn) => {
  375. const description = fn.name ? decamelize(fn.name, '-') : __('generated-value')
  376. return ['(', description, ')'].join('')
  377. }
  378. self.stringifiedValues = function stringifiedValues (values, separator) {
  379. let string = ''
  380. const sep = separator || ', '
  381. const array = [].concat(values)
  382. if (!values || !array.length) return string
  383. array.forEach((value) => {
  384. if (string.length) string += sep
  385. string += JSON.stringify(value)
  386. })
  387. return string
  388. }
  389. // format the default-value-string displayed in
  390. // the right-hand column.
  391. function defaultString (value, defaultDescription) {
  392. let string = `[${__('default:')} `
  393. if (value === undefined && !defaultDescription) return null
  394. if (defaultDescription) {
  395. string += defaultDescription
  396. } else {
  397. switch (typeof value) {
  398. case 'string':
  399. string += `"${value}"`
  400. break
  401. case 'object':
  402. string += JSON.stringify(value)
  403. break
  404. default:
  405. string += value
  406. }
  407. }
  408. return `${string}]`
  409. }
  410. // guess the width of the console window, max-width 80.
  411. function windowWidth () {
  412. const maxWidth = 80
  413. if (typeof process === 'object' && process.stdout && process.stdout.columns) {
  414. return Math.min(maxWidth, process.stdout.columns)
  415. } else {
  416. return maxWidth
  417. }
  418. }
  419. // logic for displaying application version.
  420. let version = null
  421. self.version = (ver) => {
  422. version = ver
  423. }
  424. self.showVersion = () => {
  425. const logger = yargs._getLoggerInstance()
  426. logger.log(version)
  427. }
  428. self.reset = function reset (localLookup) {
  429. // do not reset wrap here
  430. // do not reset fails here
  431. failMessage = null
  432. failureOutput = false
  433. usages = []
  434. usageDisabled = false
  435. epilog = undefined
  436. examples = []
  437. commands = []
  438. descriptions = objFilter(descriptions, (k, v) => !localLookup[k])
  439. return self
  440. }
  441. let frozen
  442. self.freeze = function freeze () {
  443. frozen = {}
  444. frozen.failMessage = failMessage
  445. frozen.failureOutput = failureOutput
  446. frozen.usages = usages
  447. frozen.usageDisabled = usageDisabled
  448. frozen.epilog = epilog
  449. frozen.examples = examples
  450. frozen.commands = commands
  451. frozen.descriptions = descriptions
  452. }
  453. self.unfreeze = function unfreeze () {
  454. failMessage = frozen.failMessage
  455. failureOutput = frozen.failureOutput
  456. usages = frozen.usages
  457. usageDisabled = frozen.usageDisabled
  458. epilog = frozen.epilog
  459. examples = frozen.examples
  460. commands = frozen.commands
  461. descriptions = frozen.descriptions
  462. frozen = undefined
  463. }
  464. return self
  465. }