table.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. const stripAnsi = require('strip-ansi')
  2. const log = require('../util/log')
  3. function normalizeCols (rows, max) {
  4. function padEnd (string, maxLength, fillString) {
  5. while ((stripAnsi(string) + '').length < maxLength) {
  6. string = string + fillString
  7. }
  8. return string
  9. }
  10. var widths = []
  11. max = max || rows[0].length
  12. for (let i = 0; i < rows.length; i++) {
  13. for (let j = 0; j < rows[i].length && j < max; j++) {
  14. if (!widths[j] || widths[j] < (stripAnsi(rows[i][j]) + '').length) {
  15. widths[j] = (stripAnsi(rows[i][j] + '') + '').length
  16. }
  17. }
  18. }
  19. for (let i = 0; i < rows.length; i++) {
  20. for (let j = 0; j < rows[i].length && j < max; j++) {
  21. if (rows[i][j] === '-') {
  22. rows[i][j] = padEnd(rows[i][j], widths[j], '-')
  23. } else {
  24. rows[i][j] = padEnd(rows[i][j], widths[j], ' ')
  25. }
  26. }
  27. }
  28. return rows
  29. }
  30. function keyValueArray (columns, keys, obj) {
  31. return keys.map(el => columns[el](obj))
  32. }
  33. module.exports.format = function (data, options) {
  34. // Keys for each column
  35. var keys = []
  36. // Separators for each column
  37. var separators = []
  38. // Add to collection of keys
  39. for (var key in options.columns) {
  40. keys.push(key)
  41. separators.push('-')
  42. }
  43. // Create the rows
  44. var items = [
  45. keys,
  46. separators,
  47. ...data.map(data => keyValueArray(options.columns, keys, data))
  48. ]
  49. // Normalize column widths.
  50. items = normalizeCols(items).map(el => {
  51. return el.join(' | ').replace(/\n/g, '')
  52. }).join('\n')
  53. if (options.program) {
  54. // Disable color output
  55. if (!options.program.color) { items = stripAnsi(items) }
  56. // If reporting output is defined, ignore console log here.
  57. if (options.program.output === undefined) {
  58. log.raw(items)
  59. }
  60. } else {
  61. log.raw(items)
  62. }
  63. return items
  64. }
  65. const fs = require('fs-extra')
  66. const path = require('path')
  67. module.exports.finalReport = async function (reports, program) {
  68. if (program.output === undefined) {
  69. return
  70. }
  71. // Ensure the output directory exists.
  72. fs.ensureDirSync(program.output)
  73. // Write each report to the disk
  74. for (var report of reports) {
  75. var outPath = path.join(program.output, report.name + '.txt')
  76. log.action('saving', outPath)
  77. fs.writeFileSync(outPath, report.contents, 'utf8')
  78. }
  79. }