Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

coverage-check.mjs

304 lines8.3 KB

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