This repository has been archived by the owner on Jan 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Coverage.js
205 lines (178 loc) · 6.74 KB
/
Coverage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
'use strict';
var fs = require('fs');
var path = require('path');
var istanbul = require('istanbul');
var shjs = require('shelljs');
shjs.config.fatal = true; //tell shelljs to fail on errors
var supplant = function(string, object) {
return string.replace(/\{(\w+)\}/g, function(match, key) {
var replacer = object[key];
return (replacer !== undefined) ? replacer : match;
});
};
var UNCOVERED_LINE = 'ERROR: Uncovered count for {0} ({1}) exceeds threshold ({2})';
var UNCOVERED_PERCENT = 'ERROR: Coverage for {0} ({1}%) does not meet threshold ({2}%)';
/**
* Wraper around [istanbul](https://github.com/gotwarlost/istanbul) for code coverage.
*
* @class Coverage
* @constructor
*
* @param config {Object}
* @param [config.baseDir=process.cwd()] {String} Base project directory
* @param [config.src=`config.baseDir`/src] {String} Source folder to instrument
* @param [config.coverageDir=`config.baseDir`/coverage] {String} Folder to use for instrumented source and coverage
* results
* @param [config.copyall=false] {Boolean} Copy files that are not covered to the output dir. Useful if your JS files
* are using some resources.
* @param [config.filter] {Function} Method used to check if a file/folder need to be processed. The method should
* return a boolean. Returning true on a directory just create or not a directory in
* the destination folder. Returning false as no effect (It doesn't stop the processing of the
* files in that directory). It take the following parameters:
* @param config.filter.file {Object}
* @param config.filter.file.path {String} Full path of the file
* @param config.filter.file.relative {String} Path relative from the base dir
* @param config.filter.file.stat {fs.Stat} Info on the file/directory
* @param [config.minCoverage] {Number|Object} Fail if coverage is lower than `minCoverage`. Positive values are treated
* as a minimum percentage of coverage. Negative values are a maximum number of uncovered lines.
* Setting this a a number has the same effect as setting all four properties to the same value
* @param [config.minCoverage.statements] {Number}
* @param [config.minCoverage.branches] {Number}
* @param [config.minCoverage.functions] {Number}
* @param [config.minCoverage.lines] {Number}
*/
var Coverage = function(config) {
this.config = config;
this.normaliseConfig();
};
/**
* Prepare the source code for code coverage. All files with `.js` extension in `config.src` will be
* copied to `config.coverageDir + "/src"` and instrumented.
*
* @method prepare
*/
Coverage.prototype.prepare = function() {
var coverageDirSrc = path.join(this.config.coverageDir, 'src');
var dataDir = path.join(this.config.coverageDir, 'data');
shjs.rm('-rf', dataDir);
shjs.mkdir('-p', dataDir);
var files = shjs.find(this.config.src);
var instrumenter = new istanbul.Instrumenter();
var collector = new istanbul.Collector();
var filesPerDot = Math.ceil(files.length / 50);
if (!this.config.filter) {
this.config.filter = function(file) {
return file.stat.isFile() && file.path.match(/\.js$/);
};
}
files.forEach(function(file, index) {
var stat = fs.statSync(file);
var relPath = path.relative(this.config.src, file);
if (path.sep === '\\') relPath = relPath.replace(/\\/g, '/');
var instrument = this.config.filter({
path: file,
stat: stat,
relative: relPath
});
if (index % filesPerDot === 0) process.stdout.write('.');
if (!instrument && !this.config.copyall) return;
file = path.normalize(file);
var dest = path.resolve(coverageDirSrc, relPath);
var destDir = path.dirname(dest);
shjs.mkdir('-p', destDir);
if (stat.isFile()) {
var data = fs.readFileSync(file, 'utf8');
if (instrument) {
data = instrumenter.instrumentSync(data, file);
var baseline = instrumenter.lastFileCoverage();
var coverage = {};
coverage[baseline.path] = baseline;
collector.add(coverage);
}
fs.writeFileSync(dest, data, 'utf8');
}
}, this);
fs.writeFileSync(dataDir + '/baseline.json', JSON.stringify(collector.getFinalCoverage()), 'utf8');
};
/**
* Write a coverage report.
*
* @method writeFile
*
* @param data {String} Coverage report
* @param [filename] {String} name of the file
*/
Coverage.prototype.writeFile = function(data, filename) {
filename = filename || (Math.random() * 99999999).toFixed(0) + '.json';
fs.writeFileSync(path.join(this.config.coverageDir, 'data', filename), data, 'utf8');
};
/**
* Prepare the source code for code coverage. All files with `.js` extension in `config.src` will be
* copied to `config.coverageDir + "/src"` and instrumented.
*
* @method report
*/
Coverage.prototype.report = function(cb) {
var Report = istanbul.Report;
var Collector = istanbul.Collector;
var reporters = [];
reporters.push(Report.create('html', {
dir: path.join(this.config.coverageDir, 'html-report')
}));
reporters.push(Report.create('text-summary'));
reporters.push(Report.create('lcovonly', {
dir: this.config.coverageDir
}));
var collector = new Collector();
shjs.find(path.join(this.config.coverageDir, 'data')).forEach(function (file) {
if (file.match(/\.json$/)) {
var cov = JSON.parse(fs.readFileSync(file, 'utf8'));
collector.add(cov);
}
});
reporters.forEach(function(reporter) {
reporter.writeReport(collector, true);
});
console.log('\n');
if (this.config.minCoverage) {
var errors = [];
var actuals = istanbul.utils.summarizeCoverage(collector.getFinalCoverage());
Object.keys(this.config.minCoverage).forEach(function (key) {
var threshold = this.config.minCoverage[key];
if (threshold < 0) {
var actualUncovered = actuals[key].total - actuals[key].covered;
if (-threshold < actualUncovered) {
errors.push(supplant(UNCOVERED_LINE, [key, actualUncovered, -threshold]));
}
} else {
var actual = actuals[key].pct;
if (actual < threshold) {
errors.push(supplant(UNCOVERED_PERCENT, [key, actual, threshold]));
}
}
}, this);
return cb(errors.join('\n'));
}
cb();
};
/**
* Make sure that `config.src` and `config.coverageDir` exist.
* Normalise `config.minCoverage`
*
* @method normaliseConfig
* @private
*/
Coverage.prototype.normaliseConfig = function() {
this.config.baseDir = this.config.baseDir || process.cwd();
this.config.src = this.config.src || path.join(this.config.baseDir, 'src');
this.config.coverageDir = this.config.coverageDir || path.join(this.config.baseDir, 'coverage');
if (typeof this.config.minCoverage === 'number') {
this.config.minCoverage = {
statements: this.config.minCoverage,
branches: this.config.minCoverage,
functions: this.config.minCoverage,
lines: this.config.minCoverage
};
}
};
exports = module.exports = Coverage;