usage.js 15 KB

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