usage.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // this file handles outputting usage instructions,
  2. // failures, etc. keeps logging in one place.
  3. var cliui = require('cliui')
  4. var decamelize = require('decamelize')
  5. var stringWidth = require('string-width')
  6. var wsize = require('window-size')
  7. module.exports = function (yargs, y18n) {
  8. var __ = y18n.__
  9. var self = {}
  10. // methods for ouputting/building failure message.
  11. var fails = []
  12. self.failFn = function (f) {
  13. fails.push(f)
  14. }
  15. var failMessage = null
  16. var showHelpOnFail = true
  17. self.showHelpOnFail = function (enabled, message) {
  18. if (typeof enabled === 'string') {
  19. message = enabled
  20. enabled = true
  21. } else if (typeof enabled === 'undefined') {
  22. enabled = true
  23. }
  24. failMessage = message
  25. showHelpOnFail = enabled
  26. return self
  27. }
  28. var failureOutput = false
  29. self.fail = function (msg) {
  30. if (fails.length) {
  31. fails.forEach(function (f) {
  32. f(msg)
  33. })
  34. } else {
  35. // don't output failure message more than once
  36. if (!failureOutput) {
  37. failureOutput = true
  38. if (showHelpOnFail) yargs.showHelp('error')
  39. if (msg) console.error(msg)
  40. if (failMessage) {
  41. if (msg) console.error('')
  42. console.error(failMessage)
  43. }
  44. }
  45. if (yargs.getExitProcess()) {
  46. process.exit(1)
  47. } else {
  48. throw new Error(msg)
  49. }
  50. }
  51. }
  52. // methods for ouputting/building help (usage) message.
  53. var usage
  54. self.usage = function (msg) {
  55. usage = msg
  56. }
  57. var examples = []
  58. self.example = function (cmd, description) {
  59. examples.push([cmd, description || ''])
  60. }
  61. var commands = []
  62. self.command = function (cmd, description) {
  63. commands.push([cmd, description || ''])
  64. }
  65. self.getCommands = function () {
  66. return commands
  67. }
  68. var descriptions = {}
  69. self.describe = function (key, desc) {
  70. if (typeof key === 'object') {
  71. Object.keys(key).forEach(function (k) {
  72. self.describe(k, key[k])
  73. })
  74. } else {
  75. descriptions[key] = desc
  76. }
  77. }
  78. self.getDescriptions = function () {
  79. return descriptions
  80. }
  81. var epilog
  82. self.epilog = function (msg) {
  83. epilog = msg
  84. }
  85. var wrap = windowWidth()
  86. self.wrap = function (cols) {
  87. wrap = cols
  88. }
  89. var deferY18nLookupPrefix = '__yargsString__:'
  90. self.deferY18nLookup = function (str) {
  91. return deferY18nLookupPrefix + str
  92. }
  93. var defaultGroup = 'Options:'
  94. self.help = function () {
  95. normalizeAliases()
  96. var demanded = yargs.getDemanded()
  97. var groups = yargs.getGroups()
  98. var options = yargs.getOptions()
  99. var keys = Object.keys(
  100. Object.keys(descriptions)
  101. .concat(Object.keys(demanded))
  102. .concat(Object.keys(options.default))
  103. .reduce(function (acc, key) {
  104. if (key !== '_') acc[key] = true
  105. return acc
  106. }, {})
  107. )
  108. var ui = cliui({
  109. width: wrap,
  110. wrap: !!wrap
  111. })
  112. // the usage string.
  113. if (usage) {
  114. var u = usage.replace(/\$0/g, yargs.$0)
  115. ui.div(u + '\n')
  116. }
  117. // your application's commands, i.e., non-option
  118. // arguments populated in '_'.
  119. if (commands.length) {
  120. ui.div(__('Commands:'))
  121. commands.forEach(function (command) {
  122. ui.div(
  123. {text: command[0], padding: [0, 2, 0, 2], width: maxWidth(commands) + 4},
  124. {text: command[1]}
  125. )
  126. })
  127. ui.div()
  128. }
  129. // perform some cleanup on the keys array, making it
  130. // only include top-level keys not their aliases.
  131. var aliasKeys = (Object.keys(options.alias) || [])
  132. .concat(Object.keys(yargs.parsed.newAliases) || [])
  133. keys = keys.filter(function (key) {
  134. return !yargs.parsed.newAliases[key] && aliasKeys.every(function (alias) {
  135. return (options.alias[alias] || []).indexOf(key) === -1
  136. })
  137. })
  138. // populate 'Options:' group with any keys that have not
  139. // explicitly had a group set.
  140. if (!groups[defaultGroup]) groups[defaultGroup] = []
  141. addUngroupedKeys(keys, options.alias, groups)
  142. // display 'Options:' table along with any custom tables:
  143. Object.keys(groups).forEach(function (groupName) {
  144. if (!groups[groupName].length) return
  145. ui.div(__(groupName))
  146. // if we've grouped the key 'f', but 'f' aliases 'foobar',
  147. // normalizedKeys should contain only 'foobar'.
  148. var normalizedKeys = groups[groupName].map(function (key) {
  149. if (~aliasKeys.indexOf(key)) return key
  150. for (var i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
  151. if (~(options.alias[aliasKey] || []).indexOf(key)) return aliasKey
  152. }
  153. return key
  154. })
  155. // actually generate the switches string --foo, -f, --bar.
  156. var switches = normalizedKeys.reduce(function (acc, key) {
  157. acc[key] = [ key ].concat(options.alias[key] || [])
  158. .map(function (sw) {
  159. return (sw.length > 1 ? '--' : '-') + sw
  160. })
  161. .join(', ')
  162. return acc
  163. }, {})
  164. normalizedKeys.forEach(function (key) {
  165. var kswitch = switches[key]
  166. var desc = descriptions[key] || ''
  167. var type = null
  168. if (~desc.lastIndexOf(deferY18nLookupPrefix)) desc = __(desc.substring(deferY18nLookupPrefix.length))
  169. if (~options.boolean.indexOf(key)) type = '[' + __('boolean') + ']'
  170. if (~options.count.indexOf(key)) type = '[' + __('count') + ']'
  171. if (~options.string.indexOf(key)) type = '[' + __('string') + ']'
  172. if (~options.normalize.indexOf(key)) type = '[' + __('string') + ']'
  173. if (~options.array.indexOf(key)) type = '[' + __('array') + ']'
  174. var extra = [
  175. type,
  176. demanded[key] ? '[' + __('required') + ']' : null,
  177. options.choices && options.choices[key] ? '[' + __('choices:') + ' ' +
  178. self.stringifiedValues(options.choices[key]) + ']' : null,
  179. defaultString(options.default[key], options.defaultDescription[key])
  180. ].filter(Boolean).join(' ')
  181. ui.span(
  182. {text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches) + 4},
  183. desc
  184. )
  185. if (extra) ui.div({text: extra, padding: [0, 0, 0, 2], align: 'right'})
  186. else ui.div()
  187. })
  188. ui.div()
  189. })
  190. // describe some common use-cases for your application.
  191. if (examples.length) {
  192. ui.div(__('Examples:'))
  193. examples.forEach(function (example) {
  194. example[0] = example[0].replace(/\$0/g, yargs.$0)
  195. })
  196. examples.forEach(function (example) {
  197. ui.div(
  198. {text: example[0], padding: [0, 2, 0, 2], width: maxWidth(examples) + 4},
  199. example[1]
  200. )
  201. })
  202. ui.div()
  203. }
  204. // the usage string.
  205. if (epilog) {
  206. var e = epilog.replace(/\$0/g, yargs.$0)
  207. ui.div(e + '\n')
  208. }
  209. return ui.toString()
  210. }
  211. // return the maximum width of a string
  212. // in the left-hand column of a table.
  213. function maxWidth (table) {
  214. var width = 0
  215. // table might be of the form [leftColumn],
  216. // or {key: leftColumn}}
  217. if (!Array.isArray(table)) {
  218. table = Object.keys(table).map(function (key) {
  219. return [table[key]]
  220. })
  221. }
  222. table.forEach(function (v) {
  223. width = Math.max(stringWidth(v[0]), width)
  224. })
  225. // if we've enabled 'wrap' we should limit
  226. // the max-width of the left-column.
  227. if (wrap) width = Math.min(width, parseInt(wrap * 0.5, 10))
  228. return width
  229. }
  230. // make sure any options set for aliases,
  231. // are copied to the keys being aliased.
  232. function normalizeAliases () {
  233. var demanded = yargs.getDemanded()
  234. var options = yargs.getOptions()
  235. ;(Object.keys(options.alias) || []).forEach(function (key) {
  236. options.alias[key].forEach(function (alias) {
  237. // copy descriptions.
  238. if (descriptions[alias]) self.describe(key, descriptions[alias])
  239. // copy demanded.
  240. if (demanded[alias]) yargs.demand(key, demanded[alias].msg)
  241. // type messages.
  242. if (~options.boolean.indexOf(alias)) yargs.boolean(key)
  243. if (~options.count.indexOf(alias)) yargs.count(key)
  244. if (~options.string.indexOf(alias)) yargs.string(key)
  245. if (~options.normalize.indexOf(alias)) yargs.normalize(key)
  246. if (~options.array.indexOf(alias)) yargs.array(key)
  247. })
  248. })
  249. }
  250. // given a set of keys, place any keys that are
  251. // ungrouped under the 'Options:' grouping.
  252. function addUngroupedKeys (keys, aliases, groups) {
  253. var groupedKeys = []
  254. var toCheck = null
  255. Object.keys(groups).forEach(function (group) {
  256. groupedKeys = groupedKeys.concat(groups[group])
  257. })
  258. keys.forEach(function (key) {
  259. toCheck = [key].concat(aliases[key])
  260. if (!toCheck.some(function (k) {
  261. return groupedKeys.indexOf(k) !== -1
  262. })) {
  263. groups[defaultGroup].push(key)
  264. }
  265. })
  266. return groupedKeys
  267. }
  268. self.showHelp = function (level) {
  269. level = level || 'error'
  270. console[level](self.help())
  271. }
  272. self.functionDescription = function (fn) {
  273. var description = fn.name ? decamelize(fn.name, '-') : __('generated-value')
  274. return ['(', description, ')'].join('')
  275. }
  276. self.stringifiedValues = function (values, separator) {
  277. var string = ''
  278. var sep = separator || ', '
  279. var array = [].concat(values)
  280. if (!values || !array.length) return string
  281. array.forEach(function (value) {
  282. if (string.length) string += sep
  283. string += JSON.stringify(value)
  284. })
  285. return string
  286. }
  287. // format the default-value-string displayed in
  288. // the right-hand column.
  289. function defaultString (value, defaultDescription) {
  290. var string = '[' + __('default:') + ' '
  291. if (value === undefined && !defaultDescription) return null
  292. if (defaultDescription) {
  293. string += defaultDescription
  294. } else {
  295. switch (typeof value) {
  296. case 'string':
  297. string += JSON.stringify(value)
  298. break
  299. case 'object':
  300. string += JSON.stringify(value)
  301. break
  302. default:
  303. string += value
  304. }
  305. }
  306. return string + ']'
  307. }
  308. // guess the width of the console window, max-width 80.
  309. function windowWidth () {
  310. return wsize.width ? Math.min(80, wsize.width) : null
  311. }
  312. // logic for displaying application version.
  313. var version = null
  314. self.version = function (ver, opt, msg) {
  315. version = ver
  316. }
  317. self.showVersion = function () {
  318. if (typeof version === 'function') console.log(version())
  319. else console.log(version)
  320. }
  321. return self
  322. }