You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.4 KiB

8 years ago
8 years ago
  1. 'use strict'
  2. class CliView {
  3. constructor (localWebServer) {
  4. this.localWebServer = localWebServer
  5. }
  6. /**
  7. * @example
  8. * { log: 'whatever' }
  9. * { config: { static: { root: 1, hidden: 2 } } }
  10. */
  11. write (msg) {
  12. const writeToStdout = [ 'log', 'info' ]
  13. Object.keys(msg).forEach(key => {
  14. if (writeToStdout.includes(key)) {
  15. console.log(msg[key])
  16. } else if (key === 'config' && msg.config && this.localWebServer.options.verbose) {
  17. printLine(msg.config)
  18. } else if (key === 'error') {
  19. const ansi = require('ansi-escape-sequences')
  20. console.error(ansi.format(msg.error, 'red'))
  21. }
  22. })
  23. }
  24. }
  25. module.exports = CliView
  26. function printLine (config) {
  27. const output = objectToTable(config)
  28. process.stderr.write(output)
  29. }
  30. /**
  31. * create a nested table for deep object trees
  32. */
  33. function objectToTable (object) {
  34. const ansi = require('ansi-escape-sequences')
  35. const tableLayout = require('table-layout')
  36. const t = require('typical')
  37. const data = Object.keys(object).map(key => {
  38. if (t.isObject(object[key])) {
  39. return { key: ansi.format(key, 'bold'), value: objectToTable(object[key]) }
  40. } else {
  41. return { key: ansi.format(key, 'bold'), value: object[key] }
  42. }
  43. })
  44. return tableLayout(data, {
  45. padding: { left: '', right: ' ' },
  46. columns: [
  47. // { name: 'key', width: 18 },
  48. // { name: 'value', nowrap: true }
  49. ]
  50. })
  51. }