Open History to see the last commit
1// Compares coverage between two runs and fails when a package regressed.
2//
3// Both sides are measured in the same CI job — the PR head and its merge-base
4// with main — so there is no baseline file to keep in sync, no per-platform
5// skew, and packages can be added or removed without anyone updating a
6// checked-in number.
7//
8// Usage:
9// node scripts/coverage-check.mjs --collect <dir> [--expect pkg,pkg]
10// node scripts/coverage-check.mjs --base <dir> --head <dir>
11import {
12 appendFileSync,
13 mkdirSync,
14 readFileSync,
15 readdirSync,
16 writeFileSync,
17} from 'node:fs'
18import { join } from 'node:path'
19
20const METRICS = ['statements', 'branches', 'functions', 'lines']
21
22// Coverage percentages wobble slightly between runs (v8 attributes some bytes
23// differently depending on JIT timing), so require a real drop.
24const TOLERANCE = 0.5
25
26function arg(name) {
27 const i = process.argv.indexOf(name)
28 return i === -1 ? undefined : process.argv[i + 1]
29}
30
31function totals(summary) {
32 // A package with no source loaded reports totals of 0/0 as 100%; that is not
33 // a number worth comparing.
34 if (summary.total.statements.total === 0) return undefined
35 return Object.fromEntries(
36 METRICS.map((metric) => [metric, summary.total[metric].pct]),
37 )
38}
39
40function packageDirs() {
41 const dirs = {}
42 for (const entry of readdirSync('packages', { withFileTypes: true })) {
43 if (!entry.isDirectory()) continue
44 dirs[entry.name] = entry.name
45 try {
46 const pkg = JSON.parse(
47 readFileSync(join('packages', entry.name, 'package.json'), 'utf8'),
48 )
49 if (pkg.name) dirs[pkg.name] = entry.name
50 } catch {
51 // Directory with no package.json is still collectable by folder name.
52 }
53 }
54 return dirs
55}
56
57function expectedDirs() {
58 const raw = arg('--expect')
59 if (raw === undefined) return undefined
60 const names = raw
61 .split(',')
62 .map((name) => name.trim())
63 .filter(Boolean)
64 const dirs = packageDirs()
65 const resolved = []
66 const unknown = []
67 for (const name of names) {
68 const dir = dirs[name]
69 if (!dir) unknown.push(name)
70 else resolved.push(dir)
71 }
72 if (unknown.length > 0) {
73 console.error(`Unknown package(s): ${unknown.join(', ')}`)
74 process.exit(1)
75 }
76 return resolved
77}
78
79function readSummary(dirName) {
80 try {
81 return JSON.parse(
82 readFileSync(
83 join('packages', dirName, 'coverage', 'coverage-summary.json'),
84 'utf8',
85 ),
86 )
87 } catch (error) {
88 if (error && error.code === 'ENOENT') return null
89 throw error
90 }
91}
92
93function collect(dir) {
94 mkdirSync(dir, { recursive: true })
95 const expected = expectedDirs()
96 const names =
97 expected ??
98 readdirSync('packages', { withFileTypes: true })
99 .filter((entry) => entry.isDirectory())
100 .map((entry) => entry.name)
101 const missing = []
102 let n = 0
103 for (const name of names) {
104 const summary = readSummary(name)
105 if (!summary) {
106 if (expected) missing.push(`${name} (no coverage-summary.json)`)
107 continue
108 }
109 const values = totals(summary)
110 if (!values) {
111 if (expected) missing.push(`${name} (0 statements)`)
112 continue
113 }
114 writeFileSync(join(dir, `${name}.json`), JSON.stringify(values))
115 n++
116 }
117 if (missing.length > 0) {
118 console.error(
119 `Coverage collect failed for ${missing.length} package(s):\n ${missing.join('\n ')}`,
120 )
121 process.exit(1)
122 }
123 console.log(`Collected ${n} coverage summary/summaries into ${dir}`)
124}
125
126function read(dir) {
127 let files
128 try {
129 files = readdirSync(dir)
130 } catch (error) {
131 if (error && error.code === 'ENOENT') return {}
132 throw error
133 }
134 return Object.fromEntries(
135 files
136 .filter((file) => file.endsWith('.json'))
137 .map((file) => [
138 file.replace(/\.json$/, ''),
139 JSON.parse(readFileSync(join(dir, file), 'utf8')),
140 ]),
141 )
142}
143
144const collectDir = arg('--collect')
145if (collectDir) {
146 collect(collectDir)
147 process.exit(0)
148}
149
150const baseDir = arg('--base')
151const headDir = arg('--head')
152if (!baseDir || !headDir) {
153 console.error(
154 'Usage: coverage-check.mjs --collect <dir> [--expect pkg,pkg] | --base <dir> --head <dir>',
155 )
156 process.exit(2)
157}
158
159const base = read(baseDir)
160const head = read(headDir)
161const names = Object.keys(head).sort()
162
163if (names.length === 0) {
164 console.error('No packages were measured — nothing to compare.')
165 process.exit(1)
166}
167
168const regressions = []
169const additions = []
170const rows = []
171
172for (const name of names) {
173 const before = base[name]
174 const after = head[name]
175 if (!before) {
176 additions.push(name)
177 rows.push([
178 name,
179 ...METRICS.map((metric) => `${after[metric].toFixed(2)}%`),
180 'new',
181 ])
182 continue
183 }
184 const deltas = METRICS.map((metric) => after[metric] - before[metric])
185 const dropped = METRICS.filter((metric, i) => deltas[i] < -TOLERANCE)
186 if (dropped.length > 0) regressions.push({ name, before, after, dropped })
187 rows.push([
188 name,
189 ...METRICS.map((metric, i) => {
190 const sign = deltas[i] > 0 ? '+' : ''
191 return `${after[metric].toFixed(2)}% (${sign}${deltas[i].toFixed(2)})`
192 }),
193 dropped.length > 0 ? 'DROP' : 'ok',
194 ])
195}
196
197for (const name of Object.keys(base)
198 .filter((name) => !head[name])
199 .sort()) {
200 const before = base[name]
201 regressions.push({ name, before, after: null, dropped: ['missing'] })
202 rows.push([
203 name,
204 ...METRICS.map((metric) => `missing (${before[metric].toFixed(2)}%)`),
205 'DROP',
206 ])
207}
208
209const compared = names.filter((name) => base[name]).length
210
211const header = ['package', ...METRICS, '']
212const widths = header.map((_, column) =>
213 Math.max(header[column].length, ...rows.map((row) => row[column].length)),
214)
215const line = (cells) =>
216 cells
217 .map((cell, i) => cell.padEnd(widths[i]))
218 .join(' ')
219 .trimEnd()
220
221console.log(line(header))
222console.log(widths.map((width) => '-'.repeat(width)).join(' '))
223for (const row of rows) console.log(line(row))
224
225if (additions.length > 0) {
226 console.log(
227 `\n${additions.length} package(s) had no coverage on the base commit` +
228 ` (new, or unmeasurable there): ${additions.join(', ')}`,
229 )
230}
231
232const headline =
233 regressions.length > 0
234 ? `❌ Coverage dropped in ${regressions.length} package(s).`
235 : compared > 0
236 ? `✅ Coverage held across ${compared} compared package(s).`
237 : `${additions.length} package(s) are new; nothing to compare against.`
238
239if (process.env.GITHUB_STEP_SUMMARY) {
240 const md = [
241 `## Coverage`,
242 ``,
243 headline,
244 ``,
245 `Each package is measured twice in this job — on this PR and on its merge-base` +
246 ` with \`main\` — and compared. A drop of more than ${TOLERANCE}pp in any metric fails.` +
247 ` Packages your PR doesn't affect are not measured and not listed.`,
248 ``,
249 `| package | ${METRICS.join(' | ')} | |`,
250 `| --- | ${METRICS.map(() => '---:').join(' | ')} | --- |`,
251 ...rows.map((row) => `| ${row.join(' | ')} |`),
252 ]
253 if (additions.length > 0) {
254 md.push(
255 ``,
256 `> No coverage on the base commit, so nothing to compare against:` +
257 ` ${additions.join(', ')}.`,
258 )
259 }
260 appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${md.join('\n')}\n`)
261}
262
263if (regressions.length > 0) {
264 console.error(`\nCoverage dropped in ${regressions.length} package(s):`)
265 for (const { name, before, after, dropped } of regressions) {
266 if (!after) {
267 console.error(` ${name}: measured on base, missing on this PR`)
268 continue
269 }
270 for (const metric of dropped) {
271 console.error(
272 ` ${name} ${metric}: ${before[metric].toFixed(2)}% -> ${after[metric].toFixed(2)}%`,
273 )
274 }
275 }
276 console.error(`\nAdd tests covering the code this PR changed.`)
277 process.exit(1)
278}
279
280if (compared === 0) {
281 console.log(
282 `\n${additions.length} package(s) are new; nothing to compare against.`,
283 )
284} else {
285 console.log(`\nCoverage held across ${compared} compared package(s).`)
286}