table.js 2.4 KB

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