reporter.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. Copyright 2012-2015, Yahoo Inc.
  3. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
  4. */
  5. var path = require('path'),
  6. configuration = require('./config'),
  7. inputError = require('./input-error'),
  8. libReport = require('istanbul-lib-report'),
  9. libReports = require('istanbul-reports');
  10. function Reporter(cfg, opts) {
  11. opts = opts || {};
  12. this.config = cfg || configuration.loadFile();
  13. this.dir = path.resolve(this.config.reporting.dir());
  14. this.reports = {};
  15. var summarizer = opts.summarizer,
  16. s = this.config.reporting.summarizer();
  17. if (summarizer && typeof summarizer === 'function') {
  18. this.summarizer = summarizer;
  19. } else {
  20. summarizer = libReport.summarizers[s];
  21. if (!summarizer) {
  22. throw inputError.create('Invalid summarizer in report config: ' + s);
  23. }
  24. this.summarizer = summarizer;
  25. }
  26. }
  27. Reporter.prototype = {
  28. /**
  29. * adds a report to be generated. Must be one of the entries returned
  30. * by `Report.getReportList()`
  31. * @method add
  32. * @param {String} fmt the format of the report to generate
  33. */
  34. add: function (fmt) {
  35. if (this.reports[fmt]) { // already added
  36. return;
  37. }
  38. var config = this.config,
  39. rptConfig = config.reporting.reportConfig()[fmt] || {};
  40. rptConfig.verbose = config.verbose;
  41. try {
  42. if (this.config.verbose) {
  43. console.error('Create report', fmt,' with', rptConfig);
  44. }
  45. this.reports[fmt] = libReports.create(fmt, rptConfig);
  46. } catch (ex) {
  47. throw inputError.create('Invalid report format [' + fmt + ']');
  48. }
  49. },
  50. /**
  51. * adds an array of report formats to be generated
  52. * @method addAll
  53. * @param {Array} fmts an array of report formats
  54. */
  55. addAll: function (fmts) {
  56. var that = this;
  57. fmts.forEach(function (f) {
  58. that.add(f);
  59. });
  60. },
  61. /**
  62. * writes all reports added
  63. * @method write
  64. */
  65. write: function (coverageMap, opts) {
  66. opts = opts || {};
  67. var that = this,
  68. sourceFinder = opts.sourceFinder || null,
  69. context,
  70. tree;
  71. context = libReport.createContext({
  72. dir: this.dir,
  73. watermarks: this.config.reporting.watermarks(),
  74. sourceFinder: sourceFinder
  75. });
  76. tree = this.summarizer(coverageMap);
  77. Object.keys(this.reports).forEach(function (name) {
  78. var report = that.reports[name];
  79. tree.visit(report, context);
  80. });
  81. }
  82. };
  83. module.exports = Reporter;