import { existsSync, readFileSync } from 'node:fs'; import { resolve } from 'node:path'; type CoverageMetric = { hit: number; found: number; percent: number; }; const threshold = Number(process.env.COVERAGE_THRESHOLD ?? 90); const lcovFile = resolve(process.cwd(), 'coverage/lcov.info'); if (!existsSync(lcovFile)) { console.error('[coverage] coverage/lcov.info not found. Run `bun test --coverage` first.'); process.exit(1); } const content = readFileSync(lcovFile, 'utf8'); const records = content.split('end_of_record'); const isTestFile = (sourceFilePath: string): boolean => { return ( sourceFilePath.startsWith('test/') || sourceFilePath.includes('/test/') || sourceFilePath.includes('\\test\\') ); }; let linesFound = 0; let linesHit = 0; let branchesFound = 0; let branchesHit = 0; let functionsFound = 0; let functionsHit = 0; for (const record of records) { const lines = record .split('\n') .map((line) => line.trim()) .filter(Boolean); if (lines.length === 0) { continue; } const sourceFileLine = lines.find((line) => line.startsWith('SF:')); if (!sourceFileLine) { continue; } const sourceFilePath = sourceFileLine.slice(3); if (isTestFile(sourceFilePath)) { continue; } for (const line of lines) { if (line.startsWith('LF:')) { linesFound += Number(line.slice(3)); continue; } if (line.startsWith('LH:')) { linesHit += Number(line.slice(3)); continue; } if (line.startsWith('BRF:')) { branchesFound += Number(line.slice(4)); continue; } if (line.startsWith('BRH:')) { branchesHit += Number(line.slice(4)); continue; } if (line.startsWith('FNF:')) { functionsFound += Number(line.slice(4)); continue; } if (line.startsWith('FNH:')) { functionsHit += Number(line.slice(4)); } } } const toMetric = (hit: number, found: number): CoverageMetric => ({ hit, found, percent: found === 0 ? 100 : (hit / found) * 100, }); const metrics = { lines: toMetric(linesHit, linesFound), branches: toMetric(branchesHit, branchesFound), functions: toMetric(functionsHit, functionsFound), }; const failing = Object.entries(metrics).filter(([, metric]) => metric.percent < threshold); for (const [name, metric] of Object.entries(metrics)) { console.log( `[coverage] ${name}: ${metric.percent.toFixed(2)}% (${metric.hit}/${metric.found})`, ); } if (failing.length > 0) { console.error( `[coverage] Minimum ${threshold}% not reached for: ${failing .map(([name]) => name) .join(', ')}`, ); process.exit(1); } console.log(`[coverage] ✅ Global threshold ${threshold}% reached.`);