Repository navigation
Expand file tree
/
Copy pathrun-coverage.mjs
More file actions
648 lines (524 loc) · 15.3 KB
/
Copy pathrun-coverage.mjs
File metadata and controls
648 lines (524 loc) · 15.3 KB
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
import { spawn } from "node:child_process";
import { execFileSync } from "node:child_process";
import {
access,
mkdir,
readFile,
readdir,
rm,
writeFile,
} from "node:fs/promises";
import path from "node:path";
import { createServer } from "node:net";
import ts from "typescript";
import { fileURLToPath } from "node:url";
const rootDir = fileURLToPath(new URL("../", import.meta.url));
const tempDir = path.join(rootDir, ".coverage", "tmp");
const reportDir = path.join(rootDir, "coverage");
const baselinePath = path.join(rootDir, "utils", "coverage-baseline.json");
const shouldCheckExistingReport = process.argv.includes("--check-existing");
const shouldCheckCoverage =
process.argv.includes("--check") || shouldCheckExistingReport;
const shouldUpdateBaseline = process.argv.includes("--update-baseline");
const coverageTestArgs = ["playwright", "test", "src"];
const coverageMetrics = ["branches", "functions", "lines", "statements"];
const gitOutputMaxBuffer = 128 * 1024 * 1024;
const nycSourceArgs = [
"--include",
"src/**/*.js",
"--include",
"src/**/*.ts",
"--extension",
".js",
"--extension",
".ts",
];
if (shouldCheckExistingReport) {
console.log("[coverage] checking existing report");
let existingReportExitCode = await validateReport();
existingReportExitCode = Math.max(
existingReportExitCode,
await checkTouchedFilesCoverage(),
await checkBaseline(),
);
process.exit(existingReportExitCode);
}
console.log("[coverage] preparing output directories");
await rm(tempDir, { recursive: true, force: true });
await rm(reportDir, { recursive: true, force: true });
await mkdir(tempDir, { recursive: true });
const [availableCoveragePort, availableApiPort] = await findAvailablePorts(2);
const coveragePort = process.env.PW_COVERAGE_PORT ?? availableCoveragePort;
const apiPort = process.env.PW_COVERAGE_API_PORT ?? availableApiPort;
if (coveragePort === apiPort) {
throw new Error("Coverage web and API servers must use different ports.");
}
const env = {
...process.env,
PW_API_PORT: apiPort,
PW_BASE_URL: `http://localhost:${coveragePort}`,
PW_COVERAGE: "1",
PORT: coveragePort,
};
console.log(
"[coverage] running Playwright with Istanbul enabled for src/ tests only",
);
const testExitCode = await run("npx", coverageTestArgs, env);
if (testExitCode !== 0) {
console.error(
`[coverage] Playwright failed with exit code ${testExitCode}; skipping coverage report and threshold checks`,
);
process.exit(testExitCode);
}
const coverageFiles = (await readdir(tempDir)).filter((file) =>
file.endsWith(".json"),
);
console.log(
`[coverage] collected ${coverageFiles.length} raw coverage file(s)`,
);
let coverageExitCode = 0;
if (coverageFiles.length > 0) {
console.log("[coverage] generating HTML, lcov and text-summary reports");
coverageExitCode = await run(
"npx",
[
"nyc",
"report",
"--temp-dir",
tempDir,
"--report-dir",
reportDir,
...nycSourceArgs,
"--reporter=html",
"--reporter=text-summary",
"--reporter=lcov",
"--reporter=json-summary",
],
env,
);
console.log(`[coverage] report written to ${reportDir}`);
coverageExitCode = Math.max(coverageExitCode, await validateReport());
if (shouldCheckCoverage) {
console.log("[coverage] checking thresholds");
coverageExitCode = Math.max(
coverageExitCode,
await checkTouchedFilesCoverage(),
);
}
if (shouldCheckCoverage) {
coverageExitCode = Math.max(coverageExitCode, await checkBaseline());
}
if (shouldUpdateBaseline) {
await updateBaseline();
}
} else {
console.warn(
"[coverage] no coverage data was collected; skipping report generation",
);
coverageExitCode = 1;
}
await assertReportExists(reportDir);
process.exit(Math.max(testExitCode, coverageExitCode));
async function findAvailablePorts(count) {
const servers = [];
try {
for (let index = 0; index < count; index++) {
const server = createServer();
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
servers.push(server);
}
return servers.map((server) => {
const address = server.address();
if (!address || typeof address === "string") {
throw new Error("Unable to allocate a coverage server port.");
}
return String(address.port);
});
} finally {
await Promise.all(
servers.map(
(server) =>
new Promise((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
}),
),
);
}
}
async function assertReportExists(directory) {
try {
await access(path.join(directory, "index.html"));
} catch {
if (!shouldCheckCoverage && coverageExitCode === 0) {
console.warn(
`[coverage] expected report missing at ${directory}/index.html`,
);
}
}
}
async function checkBaseline() {
const current = await readSummary();
const baseline = JSON.parse(await readFile(baselinePath, "utf-8"));
const failures = [];
for (const metric of coverageMetrics) {
const currentPct = current.total[metric].pct;
const baselinePct = baseline.total[metric].pct;
if (currentPct < baselinePct) {
failures.push(
`${metric}: ${currentPct}% is below baseline ${baselinePct}%`,
);
}
}
if (failures.length) {
console.error("[coverage] coverage decreased from baseline");
failures.forEach((failure) => console.error(`[coverage] ${failure}`));
return 1;
}
console.log("[coverage] coverage did not decrease from baseline");
return 0;
}
async function validateReport() {
const summary = await readSummary();
const failures = invalidSummaryMetrics(summary);
if (failures.length) {
console.error("[coverage] generated coverage report has no usable data");
failures.forEach((failure) => console.error(`[coverage] ${failure}`));
return 1;
}
return 0;
}
async function checkTouchedFilesCoverage() {
const touchedFiles = getTouchedSourceFiles();
const touchedLines = await getTouchedSourceLines();
const coverage = await readLcov();
const failures = [];
for (const file of touchedFiles) {
if (!isInstrumentableSource(file)) {
continue;
}
const changedLines = touchedLines.get(file) ?? new Set();
if (changedLines.size === 0) {
continue;
}
if (!(await hasExecutableTouchedSource(file, changedLines))) {
continue;
}
const fileCoverage = coverage.get(file);
if (!fileCoverage) {
failures.push(`No coverage collected for touched source file: ${file}`);
continue;
}
for (const line of changedLines) {
const lineHits = fileCoverage.lines.get(line);
if (lineHits !== undefined && lineHits === 0) {
failures.push(`Touched line ${file}:${line} is not covered`);
}
const branchHits = fileCoverage.branches.get(line) ?? [];
for (const branch of branchHits) {
if (branch === 0) {
failures.push(`Touched branch ${file}:${line} is not fully covered`);
}
}
const functionHits = fileCoverage.functions.get(line) ?? [];
for (const hits of functionHits) {
if (hits === 0) {
failures.push(`Touched function ${file}:${line} is not covered`);
}
}
}
}
if (failures.length) {
console.error("[coverage] touched source lines are not 100% covered");
failures.forEach((failure) => console.error(`[coverage] ${failure}`));
return 1;
}
console.log("[coverage] all touched source lines are 100% covered");
return 0;
}
function getTouchedSourceFiles() {
const changed = gitLines([
"diff",
"--name-only",
"--diff-filter=ACMRTUXB",
"HEAD",
"--",
"src",
]);
const untracked = getUntrackedSourceFiles();
return [...new Set([...changed, ...untracked])]
.filter((file) => file.endsWith(".js") || file.endsWith(".ts"))
.map((file) => path.join(rootDir, file));
}
async function getTouchedSourceLines() {
const output = execGit(["diff", "--unified=0", "HEAD", "--", "src"]);
const touched = parseTouchedSourceLines(output);
for (const file of getUntrackedSourceFiles()) {
if (!file.endsWith(".js") && !file.endsWith(".ts")) {
continue;
}
const absoluteFile = path.join(rootDir, file);
const source = await readFile(absoluteFile, "utf-8");
const lineCount = source.split(/\r?\n/).length;
touched.set(
absoluteFile,
new Set(Array.from({ length: lineCount }, (_, index) => index + 1)),
);
}
return touched;
}
function getUntrackedSourceFiles() {
return gitLines(["ls-files", "--others", "--exclude-standard", "--", "src"]);
}
function gitLines(args) {
return execGit(args)
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
}
function execGit(args) {
return execFileSync("git", args, {
cwd: rootDir,
encoding: "utf-8",
maxBuffer: gitOutputMaxBuffer,
});
}
function parseTouchedSourceLines(diff) {
const touched = new Map();
let file;
let nextLine;
for (const line of diff.split("\n")) {
if (line.startsWith("+++ b/")) {
const relative = line.slice("+++ b/".length);
file = path.join(rootDir, relative);
nextLine = undefined;
continue;
}
if (line.startsWith("+++ /dev/null")) {
file = undefined;
nextLine = undefined;
continue;
}
if (!file) {
continue;
}
const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);
if (hunk) {
nextLine = Number(hunk[1]);
continue;
}
if (nextLine === undefined) {
continue;
}
if (line.startsWith("+") && !line.startsWith("+++")) {
if (!touched.has(file)) {
touched.set(file, new Set());
}
touched.get(file).add(nextLine);
nextLine += 1;
continue;
}
if (line.startsWith("-") && !line.startsWith("---")) {
continue;
}
if (line.length > 0) {
nextLine += 1;
}
}
return touched;
}
function isInstrumentableSource(file) {
return (
file.endsWith(".ts") &&
!file.endsWith(".spec.ts") &&
!file.endsWith(".test.ts")
);
}
async function hasExecutableTouchedSource(file, changedLines) {
const source = await readFile(file, "utf-8");
const lines = source.split(/\r?\n/);
const sourceFile = ts.createSourceFile(
file,
source,
ts.ScriptTarget.Latest,
true,
);
for (const line of changedLines) {
const lineText = lines[line - 1] ?? "";
const trimmed = lineText.trim();
if (!trimmed || /^[{}()[\];,]+$/.test(trimmed)) {
continue;
}
const column = lineText.search(/\S/);
const position = sourceFile.getPositionOfLineAndCharacter(
line - 1,
Math.max(column, 0),
);
const node = findSmallestNodeAtPosition(sourceFile, position);
if (!isTypeOnlyNode(node)) {
return true;
}
}
return false;
}
function findSmallestNodeAtPosition(node, position) {
let match = node;
node.forEachChild((child) => {
if (child.getFullStart() <= position && position < child.getEnd()) {
match = findSmallestNodeAtPosition(child, position);
}
});
return match;
}
function isTypeOnlyNode(node) {
for (let current = node; current; current = current.parent) {
if (
ts.isTypeAliasDeclaration(current) ||
ts.isInterfaceDeclaration(current) ||
ts.isTypeParameterDeclaration(current) ||
ts.isTypeReferenceNode(current) ||
ts.isImportTypeNode(current) ||
ts.isTypeLiteralNode(current)
) {
return true;
}
if (
ts.isImportDeclaration(current) &&
current.importClause?.isTypeOnly === true
) {
return true;
}
if (ts.isExportDeclaration(current)) {
return true;
}
}
return false;
}
async function readLcov() {
const lcov = await readFile(path.join(reportDir, "lcov.info"), "utf-8");
const coverage = new Map();
let current;
let functionLines = new Map();
for (const line of lcov.split("\n")) {
if (line.startsWith("SF:")) {
const sourceFile = line.slice("SF:".length);
const file = path.isAbsolute(sourceFile)
? sourceFile
: path.join(rootDir, sourceFile);
current = {
branches: new Map(),
functions: new Map(),
lines: new Map(),
};
functionLines = new Map();
coverage.set(file, current);
continue;
}
if (!current) {
continue;
}
if (line.startsWith("FN:")) {
const payload = line.slice("FN:".length);
const comma = payload.indexOf(",");
if (comma !== -1) {
const functionLine = Number(payload.slice(0, comma));
const name = payload.slice(comma + 1);
functionLines.set(name, functionLine);
}
continue;
}
if (line.startsWith("FNDA:")) {
const payload = line.slice("FNDA:".length);
const comma = payload.indexOf(",");
if (comma !== -1) {
const hits = Number(payload.slice(0, comma));
const name = payload.slice(comma + 1);
const functionLine = functionLines.get(name);
if (functionLine !== undefined) {
appendCoverageValue(current.functions, functionLine, hits);
}
}
continue;
}
if (line.startsWith("DA:")) {
const [lineNumber, hits] = line
.slice("DA:".length)
.split(",", 2)
.map(Number);
current.lines.set(lineNumber, hits);
continue;
}
if (line.startsWith("BRDA:")) {
const [lineNumber, , , taken] = line.slice("BRDA:".length).split(",");
appendCoverageValue(
current.branches,
Number(lineNumber),
taken === "-" ? 0 : Number(taken),
);
continue;
}
if (line === "end_of_record") {
current = undefined;
functionLines = new Map();
}
}
return coverage;
}
function appendCoverageValue(map, line, value) {
if (!map.has(line)) {
map.set(line, []);
}
map.get(line).push(value);
}
function invalidSummaryMetrics(summary) {
const failures = [];
for (const metric of coverageMetrics) {
const values = summary?.total?.[metric];
const pct = values?.pct;
if (!values || !Number.isFinite(pct)) {
failures.push(`${metric}: percentage is ${String(pct)}`);
continue;
}
if (!Number.isFinite(values.total) || values.total <= 0) {
failures.push(`${metric}: total is ${String(values.total)}`);
}
}
return failures;
}
async function updateBaseline() {
const current = await readSummary();
const baseline = {
total: {
branches: current.total.branches,
functions: current.total.functions,
lines: current.total.lines,
statements: current.total.statements,
},
};
await writeFile(baselinePath, `${JSON.stringify(baseline, null, 2)}\n`);
console.log(`[coverage] baseline updated at ${baselinePath}`);
}
async function readSummary() {
return JSON.parse(
await readFile(path.join(reportDir, "coverage-summary.json"), "utf-8"),
);
}
function run(command, args, env) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
cwd: rootDir,
env,
stdio: "inherit",
});
child.on("error", reject);
child.on("exit", (code, signal) => {
if (signal) {
reject(new Error(`${command} exited due to signal ${signal}`));
return;
}
resolve(code ?? 1);
});
});
}