usage.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. // this file handles outputting usage instructions,
  2. // failures, etc. keeps logging in one place.
  3. var cliui = require('cliui'),
  4. decamelize = require('decamelize'),
  5. wsize = require('window-size')
  6. module.exports = function (yargs) {
  7. var self = {}
  8. // methods for ouputting/building failure message.
  9. var fails = []
  10. self.failFn = function (f) {
  11. fails.push(f)
  12. }
  13. var failMessage = null
  14. var showHelpOnFail = true
  15. self.showHelpOnFail = function (enabled, message) {
  16. if (typeof enabled === 'string') {
  17. message = enabled
  18. enabled = true
  19. } else if (typeof enabled === 'undefined') {
  20. enabled = true
  21. }
  22. failMessage = message
  23. showHelpOnFail = enabled
  24. return self
  25. }
  26. self.fail = function (msg) {
  27. if (fails.length) {
  28. fails.forEach(function (f) {
  29. f(msg)
  30. })
  31. } else {
  32. if (showHelpOnFail) yargs.showHelp('error')
  33. if (msg) console.error(msg)
  34. if (failMessage) {
  35. if (msg) console.error('')
  36. console.error(failMessage)
  37. }
  38. if (yargs.getExitProcess()) {
  39. process.exit(1)
  40. } else {
  41. throw new Error(msg)
  42. }
  43. }
  44. }
  45. // methods for ouputting/building help (usage) message.
  46. var usage
  47. self.usage = function (msg) {
  48. usage = msg
  49. }
  50. var examples = []
  51. self.example = function (cmd, description) {
  52. examples.push([cmd, description || ''])
  53. }
  54. var commands = []
  55. self.command = function (cmd, description) {
  56. commands.push([cmd, description || ''])
  57. }
  58. self.getCommands = function () {
  59. return commands
  60. }
  61. var descriptions = {}
  62. self.describe = function (key, desc) {
  63. if (typeof key === 'object') {
  64. Object.keys(key).forEach(function (k) {
  65. self.describe(k, key[k])
  66. })
  67. } else {
  68. descriptions[key] = desc
  69. }
  70. }
  71. self.getDescriptions = function () {
  72. return descriptions
  73. }
  74. var epilog
  75. self.epilog = function (msg) {
  76. epilog = msg
  77. }
  78. var wrap = windowWidth()
  79. self.wrap = function (cols) {
  80. wrap = cols
  81. }
  82. self.help = function () {
  83. normalizeAliases()
  84. var demanded = yargs.getDemanded(),
  85. options = yargs.getOptions(),
  86. keys = Object.keys(
  87. Object.keys(descriptions)
  88. .concat(Object.keys(demanded))
  89. .concat(Object.keys(options.default))
  90. .reduce(function (acc, key) {
  91. if (key !== '_') acc[key] = true
  92. return acc
  93. }, {})
  94. ),
  95. ui = cliui({
  96. width: wrap,
  97. wrap: !!wrap
  98. })
  99. // the usage string.
  100. if (usage) {
  101. var u = usage.replace(/\$0/g, yargs.$0)
  102. ui.div(u + '\n')
  103. }
  104. // your application's commands, i.e., non-option
  105. // arguments populated in '_'.
  106. if (commands.length) {
  107. ui.div('Commands:')
  108. commands.forEach(function (command) {
  109. ui.div(
  110. {text: command[0], padding: [0, 2, 0, 2], width: maxWidth(commands) + 4},
  111. {text: command[1]}
  112. )
  113. })
  114. ui.div()
  115. }
  116. // the options table.
  117. var aliasKeys = (Object.keys(options.alias) || [])
  118. .concat(Object.keys(yargs.parsed.newAliases) || [])
  119. keys = keys.filter(function (key) {
  120. return !yargs.parsed.newAliases[key] && aliasKeys.every(function (alias) {
  121. return (options.alias[alias] || []).indexOf(key) === -1
  122. })
  123. })
  124. var switches = keys.reduce(function (acc, key) {
  125. acc[key] = [ key ].concat(options.alias[key] || [])
  126. .map(function (sw) {
  127. return (sw.length > 1 ? '--' : '-') + sw
  128. })
  129. .join(', ')
  130. return acc
  131. }, {})
  132. if (keys.length) {
  133. ui.div('Options:')
  134. keys.forEach(function (key) {
  135. var kswitch = switches[key]
  136. var desc = descriptions[key] || ''
  137. var type = null
  138. if (~options.boolean.indexOf(key)) type = '[boolean]'
  139. if (~options.count.indexOf(key)) type = '[count]'
  140. if (~options.string.indexOf(key)) type = '[string]'
  141. if (~options.normalize.indexOf(key)) type = '[string]'
  142. if (~options.array.indexOf(key)) type = '[array]'
  143. var extra = [
  144. type,
  145. demanded[key] ? '[required]' : null,
  146. defaultString(options.default[key], options.defaultDescription[key])
  147. ].filter(Boolean).join(' ')
  148. ui.span(
  149. {text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches) + 4},
  150. desc
  151. )
  152. if (extra) ui.div({text: extra, padding: [0, 0, 0, 2], align: 'right'})
  153. else ui.div()
  154. })
  155. ui.div()
  156. }
  157. // describe some common use-cases for your application.
  158. if (examples.length) {
  159. ui.div('Examples:')
  160. examples.forEach(function (example) {
  161. example[0] = example[0].replace(/\$0/g, yargs.$0)
  162. })
  163. examples.forEach(function (example) {
  164. ui.div(
  165. {text: example[0], padding: [0, 2, 0, 2], width: maxWidth(examples) + 4},
  166. example[1]
  167. )
  168. })
  169. ui.div()
  170. }
  171. // the usage string.
  172. if (epilog) {
  173. var e = epilog.replace(/\$0/g, yargs.$0)
  174. ui.div(e + '\n')
  175. }
  176. return ui.toString()
  177. }
  178. // return the maximum width of a string
  179. // in the left-hand column of a table.
  180. function maxWidth (table) {
  181. var width = 0
  182. // table might be of the form [leftColumn],
  183. // or {key: leftColumn}}
  184. if (!Array.isArray(table)) {
  185. table = Object.keys(table).map(function (key) {
  186. return [table[key]]
  187. })
  188. }
  189. table.forEach(function (v) {
  190. width = Math.max(v[0].length, width)
  191. })
  192. // if we've enabled 'wrap' we should limit
  193. // the max-width of the left-column.
  194. if (wrap) width = Math.min(width, parseInt(wrap * 0.5, 10))
  195. return width
  196. }
  197. // make sure any options set for aliases,
  198. // are copied to the keys being aliased.
  199. function normalizeAliases () {
  200. var options = yargs.getOptions(),
  201. demanded = yargs.getDemanded()
  202. ;(Object.keys(options.alias) || []).forEach(function (key) {
  203. options.alias[key].forEach(function (alias) {
  204. // copy descriptions.
  205. if (descriptions[alias]) self.describe(key, descriptions[alias])
  206. // copy demanded.
  207. if (demanded[alias]) yargs.demand(key, demanded[alias].msg)
  208. // type messages.
  209. if (~options.boolean.indexOf(alias)) yargs.boolean(key)
  210. if (~options.count.indexOf(alias)) yargs.count(key)
  211. if (~options.string.indexOf(alias)) yargs.string(key)
  212. if (~options.normalize.indexOf(alias)) yargs.normalize(key)
  213. if (~options.array.indexOf(alias)) yargs.array(key)
  214. })
  215. })
  216. }
  217. self.showHelp = function (level) {
  218. level = level || 'error'
  219. console[level](self.help())
  220. }
  221. self.functionDescription = function (fn, defaultDescription) {
  222. if (defaultDescription) {
  223. return defaultDescription
  224. }
  225. var description = fn.name ? decamelize(fn.name, '-') : 'generated-value'
  226. return ['(', description, ')'].join('')
  227. }
  228. // format the default-value-string displayed in
  229. // the right-hand column.
  230. function defaultString (value, defaultDescription) {
  231. var string = '[default: '
  232. if (value === undefined) return null
  233. if (defaultDescription) {
  234. string += defaultDescription
  235. } else {
  236. switch (typeof value) {
  237. case 'string':
  238. string += JSON.stringify(value)
  239. break
  240. case 'object':
  241. string += JSON.stringify(value)
  242. break
  243. default:
  244. string += value
  245. }
  246. }
  247. return string + ']'
  248. }
  249. // guess the width of the console window, max-width 80.
  250. function windowWidth () {
  251. return wsize.width ? Math.min(80, wsize.width) : null
  252. }
  253. // logic for displaying application version.
  254. var version = null
  255. self.version = function (ver, opt, msg) {
  256. version = ver
  257. }
  258. self.showVersion = function () {
  259. if (typeof version === 'function') console.log(version())
  260. else console.log(version)
  261. }
  262. return self
  263. }