-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
552 lines (501 loc) · 19.5 KB
/
index.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright (c) WarnerMedia Direct, LLC. All rights reserved. Licensed under the MIT license.
// See the LICENSE file for license information.
//
// Copyright 2012-2015, Yahoo Inc.
// Copyrights licensed under the New BSD License. See the accompanying ThirdPartyNotices.txt file for terms.
const fs = require('fs');
const path = require('path');
const html = require('html-escaper');
const { ReportBase } = require('istanbul-lib-report');
const annotator = require('./lib/annotator');
const Path = require('./lib/path');
const { ReportNode, ReportTree, findOrCreateParent } = require('./lib/utils');
// Invent a pathname that is very unlikely to be encountered in a real build.
// (Needs to be a valid path, because we will place HTML files under this folder.)
const DEFAULT_PLACEHOLDER = '___otherfiles___';
const CONFIG_FILE = 'istanbul-reporter-options.json';
const CONFIG_ENV_VAR = 'ISTANBUL_REPORTER_CONFIG';
function htmlHead(details) {
return `
<head>
<title>Code coverage report for ${html.escape(details.entity)}</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="${html.escape(details.prettify.css)}" />
<link rel="stylesheet" href="${html.escape(details.base.css)}" />
<link rel="shortcut icon" type="image/x-icon" href="${html.escape(
details.favicon
)}" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type='text/css'>
.coverage-summary .sorter {
background-image: url(${html.escape(details.sorter.image)});
}
</style>
</head>
`;
}
function headerTemplate(details) {
function metricsTemplate({ pct, covered, total }, kind) {
return `
<div class='fl pad1y space-right2'>
<span class="strong">${pct}% </span>
<span class="quiet">${kind}</span>
<span class='fraction'>${covered}/${total}</span>
</div>
`;
}
function skipTemplate(metrics) {
const statements = metrics.statements.skipped;
const branches = metrics.branches.skipped;
const functions = metrics.functions.skipped;
const countLabel = (c, label, plural) =>
c === 0 ? [] : `${c} ${label}${c === 1 ? '' : plural}`;
const skips = [].concat(
countLabel(statements, 'statement', 's'),
countLabel(functions, 'function', 's'),
countLabel(branches, 'branch', 'es')
);
if (skips.length === 0) {
return '';
}
return `
<div class='fl pad1y'>
<span class="strong">${skips.join(', ')}</span>
<span class="quiet">Ignored</span>
</div>
`;
}
return `
<!doctype html>
<html lang="en">
${htmlHead(details)}
<body>
<div class='wrapper'>
<div class='pad1'>
<h1>${details.pathHtml}</h1>
<div class='clearfix'>
${metricsTemplate(details.metrics.statements, 'Statements')}
${metricsTemplate(details.metrics.branches, 'Branches')}
${metricsTemplate(details.metrics.functions, 'Functions')}
${metricsTemplate(details.metrics.lines, 'Lines')}
${skipTemplate(details.metrics)}
</div>
<p class="quiet">
Press <em>n</em> or <em>j</em> to go to the next uncovered block, <em>b</em>, <em>p</em> or <em>k</em> for the previous block.
</p>
</div>
<div class='status-line ${details.reportClass}'></div>
`;
}
function footerTemplate(details) {
return `
<div class='push'></div><!-- for sticky footer -->
</div><!-- /wrapper -->
<div class='footer quiet pad2 space-top1 center small'>
Code coverage generated by
<a href="https://istanbul.js.org/" target="_blank">istanbul</a>
at ${html.escape(details.datetime)}
</div>
</div>
<script src="${html.escape(details.prettify.js)}"></script>
<script>
window.onload = function () {
prettyPrint();
};
</script>
<script src="${html.escape(details.sorter.js)}"></script>
<script src="${html.escape(details.blockNavigation.js)}"></script>
</body>
</html>
`;
}
function detailTemplate(data) {
const lineNumbers = new Array(data.maxLines).fill().map((_, i) => i + 1);
const lineLink = num =>
`<a name='L${num}'></a><a href='#L${num}'>${num}</a>`;
const lineCount = line =>
`<span class="cline-any cline-${line.covered}">${line.hits}</span>`;
/* This is rendered in a `<pre>`, need control of all whitespace. */
return [
'<tr>',
`<td class="line-count quiet">${lineNumbers
.map(lineLink)
.join('\n')}</td>`,
`<td class="line-coverage quiet">${data.lineCoverage
.map(lineCount)
.join('\n')}</td>`,
`<td class="text"><pre class="prettyprint lang-js">${data.annotatedCode.join(
'\n'
)}</pre></td>`,
'</tr>'
].join('');
}
const summaryTableHeader = [
'<div class="pad1">',
'<table class="coverage-summary">',
'<thead>',
'<tr>',
' <th data-col="file" data-fmt="html" data-html="true" class="file">File</th>',
' <th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th>',
' <th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th>',
' <th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th>',
' <th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th>',
' <th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th>',
' <th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th>',
' <th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th>',
' <th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th>',
' <th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th>',
'</tr>',
'</thead>',
'<tbody>'
].join('\n');
function summaryLineTemplate(details) {
const { reportClasses, metrics, file, output } = details;
const percentGraph = pct => {
if (!isFinite(pct)) {
return '';
}
const cls = ['cover-fill'];
if (pct === 100) {
cls.push('cover-full');
}
pct = Math.floor(pct);
return [
`<div class="${cls.join(' ')}" style="width: ${pct}%"></div>`,
`<div class="cover-empty" style="width: ${100 - pct}%"></div>`
].join('');
};
const summaryType = (type, showGraph = false) => {
const info = metrics[type];
const reportClass = reportClasses[type];
const result = [
`<td data-value="${info.pct}" class="pct ${reportClass}">${info.pct}%</td>`,
`<td data-value="${info.total}" class="abs ${reportClass}">${info.covered}/${info.total}</td>`
];
if (showGraph) {
result.unshift(
`<td data-value="${info.pct}" class="pic ${reportClass}">`,
`<div class="chart">${percentGraph(info.pct)}</div>`,
`</td>`
);
}
return result;
};
return []
.concat(
'<tr>',
`<td class="file ${
reportClasses.statements
}" data-value="${html.escape(file)}"><a href="${html.escape(
output
)}">${html.escape(file)}</a></td>`,
summaryType('statements', true),
summaryType('branches'),
summaryType('functions'),
summaryType('lines'),
'</tr>\n'
)
.join('\n\t');
}
const summaryTableFooter = ['</tbody>', '</table>', '</div>'].join('\n');
const emptyClasses = {
statements: 'empty',
lines: 'empty',
functions: 'empty',
branches: 'empty'
};
const standardLinkMapper = {
getPath(node) {
if (typeof node === 'string') {
return node;
}
let filePath = node.getQualifiedName();
if (node.isSummary()) {
if (filePath !== '') {
filePath += '/index.html';
} else {
filePath = 'index.html';
}
} else {
filePath += '.html';
}
return filePath;
},
relativePath(source, target) {
const targetPath = this.getPath(target);
const sourcePath = path.dirname(this.getPath(source));
return path.posix.relative(sourcePath, targetPath);
},
assetPath(node, name) {
return this.relativePath(this.getPath(node), name);
}
};
function fixPct(metrics) {
Object.keys(emptyClasses).forEach(key => {
metrics[key].pct = 0;
});
return metrics;
}
class HtmlMonorepoReporter extends ReportBase {
constructor(opts) {
let config = HtmlMonorepoReporter.loadOptionsFromConfigFile();
for (let key of Object.keys(config)) {
if ([
'skipEmpty',
'reportTitle',
'projects',
'defaultProjectName'
].includes(key)) {
opts[key] = config[key];
} else {
console.error(`Ignoring unknown property '${key}' in istanbul reporter config file`);
}
}
super(opts);
this.verbose = opts.verbose;
this.linkMapper = opts.linkMapper || standardLinkMapper;
this.subdir = opts.subdir || '';
this.date = Date();
this.skipEmpty = opts.skipEmpty;
// Additional options (beyond HtmlReport)
this.reportTitle = opts.reportTitle || 'All files';
this.projects = opts.projects || [];
this.defaultProjectName = opts.defaultProjectName === false
? undefined
: (opts.defaultProjectName || 'Other Files');
// Basic option validation/massaging
this.projects.forEach(project => {
if (!project.name) {
throw new Error(`html-monorepo projects entry: missing 'name' key`);
}
if (!project.path) {
throw new Error(`html-monorepo projects entry: missing 'path' key`);
}
project.path = project.path.replace(/\\/g, '/').replace(/^\//, '');
});
}
static loadOptionsFromConfigFile() {
let file = process.env[CONFIG_ENV_VAR];
if (file) {
try {
return JSON.parse(fs.readFileSync(file, 'utf8'));
} catch (error) {
throw new Error(`Attempted to load ${file} (specified by ${CONFIG_ENV_VAR}), but it does not exist or does not contain valid JSON: ${error.message}`);
}
} else {
try {
return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
} catch (error) {
if (error.code === 'ENOENT') {
return {};
}
throw new Error(`Attempted to load ${CONFIG_FILE}, but it does not contain valid JSON: ${error.message}`);
}
}
}
// Override the behavior of ReportBase#execute, so we can insert a custom
// report tree method instead of one of the built-in summarizers.
execute(context) {
const initialList = context._summarizerFactory._initialList;
const commonParent = context._summarizerFactory._commonParent;
// NOTE: This should not be necessary, as this normalization of the common parent
// already happens in the summarizer factory constructor. Unfortunately, due to a
// bug in istanbul-lib-report, any reporter that executes before ours that uses the
// 'pkg' summarizer modifies the list in place, breaking the file paths we want to
// display.
//
// To work around this bug, we'll make sure before continuing that all file paths
// are correctly normalized relative to the common parent path.
if (commonParent.length > 0) {
initialList.forEach(o => {
o.path = new Path(o.filePath);
o.path.splice(0, commonParent.length);
});
}
return this.getTree(
initialList,
commonParent,
this.projects,
this.defaultProjectName
).visit(this, context);
}
// Our summarizer is sort of a mix of the built-in `nested` and `flat` summarizers,
// where we nest based on defined folder paths instead of any folder path.
getTree(initialList, commonParent, projects, defaultProjectName) {
const nodeMap = Object.create(null);
const topPaths = [];
const defaultNode = defaultProjectName ? new ReportNode(new Path(DEFAULT_PLACEHOLDER)) : undefined;
let defaultNodeAdded = false;
initialList.forEach(o => {
const node = new ReportNode(o.path, o.fileCoverage);
const project = projects.find(project => new Path(project.path).ancestorOf(o.path));
if (project) {
const parent = findOrCreateParent(
new Path(project.path),
nodeMap,
(parentPath, parent) => {
topPaths.push(parent);
}
);
parent.addChild(node);
} else if (defaultNode) {
defaultNode.addChild(node);
if (!defaultNodeAdded) {
defaultNodeAdded = true;
topPaths.push(defaultNode);
}
} else {
topPaths.push(node);
}
});
return new ReportTree(ReportNode.createRoot(topPaths));
}
// Nodes that match a known path can be displayed by their project name instead
// of the path (in general this should be EVERY node, since our tree summarizer
// uses the list of projects when creating the node list).
getDisplayName(node) {
const pathString = node.path.toString();
if (pathString === DEFAULT_PLACEHOLDER) {
return this.defaultProjectName;
}
const project = this.projects.find(project => project.path === node.path.toString());
return project ? project.name : (node.getRelativeName() || this.reportTitle);
}
getBreadcrumbHtml(node) {
let parent = node.getParent();
const nodePath = [];
while (parent) {
nodePath.push(parent);
parent = parent.getParent();
}
const linkPath = nodePath.map(ancestor => {
const target = this.linkMapper.relativePath(node, ancestor);
return '<a href="' + target + '">' + this.getDisplayName(ancestor) + '</a>';
});
linkPath.reverse();
return linkPath.length > 0
? linkPath.join(' / ') + ' ' + this.getDisplayName(node)
: this.reportTitle;
}
fillTemplate(node, templateData, context) {
const linkMapper = this.linkMapper;
const summary = node.getCoverageSummary();
templateData.entity = node.getQualifiedName() || 'All files';
templateData.metrics = summary;
templateData.reportClass = context.classForPercent(
'statements',
summary.statements.pct
);
templateData.pathHtml = this.getBreadcrumbHtml(node);
templateData.base = {
css: linkMapper.assetPath(node, 'base.css')
};
templateData.sorter = {
js: linkMapper.assetPath(node, 'sorter.js'),
image: linkMapper.assetPath(node, 'sort-arrow-sprite.png')
};
templateData.blockNavigation = {
js: linkMapper.assetPath(node, 'block-navigation.js')
};
templateData.prettify = {
js: linkMapper.assetPath(node, 'prettify.js'),
css: linkMapper.assetPath(node, 'prettify.css')
};
templateData.favicon = linkMapper.assetPath(node, 'favicon.png');
}
getTemplateData() {
return { datetime: this.date };
}
getWriter(context) {
if (!this.subdir) {
return context.writer;
}
return context.writer.writerForDir(this.subdir);
}
onStart(root, context) {
const assetHeaders = {
'.js': '/* eslint-disable */\n'
};
['.', 'vendor'].forEach(subdir => {
const writer = this.getWriter(context);
const srcDir = path.resolve(__dirname, 'assets', subdir);
fs.readdirSync(srcDir).forEach(f => {
const resolvedSource = path.resolve(srcDir, f);
const resolvedDestination = '.';
const stat = fs.statSync(resolvedSource);
let dest;
if (stat.isFile()) {
dest = resolvedDestination + '/' + f;
if (this.verbose) {
console.log('Write asset: ' + dest);
}
writer.copyFile(
resolvedSource,
dest,
assetHeaders[path.extname(f)]
);
}
});
});
}
onSummary(node, context) {
const linkMapper = this.linkMapper;
const templateData = this.getTemplateData();
const children = node.getChildren();
const skipEmpty = this.skipEmpty;
this.fillTemplate(node, templateData, context);
const cw = this.getWriter(context).writeFile(linkMapper.getPath(node));
cw.write(headerTemplate(templateData));
cw.write(summaryTableHeader);
children.forEach(child => {
const metrics = child.getCoverageSummary();
const isEmpty = metrics.isEmpty();
if (skipEmpty && isEmpty) {
return;
}
const reportClasses = isEmpty
? emptyClasses
: {
statements: context.classForPercent(
'statements',
metrics.statements.pct
),
lines: context.classForPercent(
'lines',
metrics.lines.pct
),
functions: context.classForPercent(
'functions',
metrics.functions.pct
),
branches: context.classForPercent(
'branches',
metrics.branches.pct
)
};
const data = {
metrics: isEmpty ? fixPct(metrics) : metrics,
reportClasses,
file: this.getDisplayName(child),
output: linkMapper.relativePath(node, child)
};
cw.write(summaryLineTemplate(data) + '\n');
});
cw.write(summaryTableFooter);
cw.write(footerTemplate(templateData));
cw.close();
}
onDetail(node, context) {
const linkMapper = this.linkMapper;
const templateData = this.getTemplateData();
this.fillTemplate(node, templateData, context);
const cw = this.getWriter(context).writeFile(linkMapper.getPath(node));
cw.write(headerTemplate(templateData));
cw.write('<pre><table class="coverage">\n');
cw.write(detailTemplate(annotator(node.getFileCoverage(), context)));
cw.write('</table></pre>\n');
cw.write(footerTemplate(templateData));
cw.close();
}
}
module.exports = HtmlMonorepoReporter;