import fs from 'node:fs/promises' import path from 'node:path' import { pathToFileURL } from 'node:url' import { execa } from 'execa' import { projectRoot } from '../build/workspaces.ts' import { readLineCoverage, readTestPassRate, renderCoverageBadge, renderTestPassRateBadge } from './coverage-badge.ts' async function runCoverageTests(root: string): Promise { const result = await execa(process.execPath, [path.join(root, '.yarn/releases/yarn-4.13.0.cjs'), 'exec', 'vitest', 'run', '--project', 'checks', '--coverage', '--reporter=default', '--reporter=json', '--outputFile.json=coverage/test-results.json'], { cwd: root, stdio: 'inherit', reject: false, }) return result.exitCode ?? 1 } export async function collectCoverage(root = projectRoot, runTests = runCoverageTests): Promise { const directory = path.join(root, 'coverage') // Invalidate any previous successful run before invoking the test runner. for (const file of ['coverage.svg', 'test-pass-rate.svg', 'test-results.json', 'badge-run.json']) await fs.rm(path.join(directory, file), { force: true }) const git = async (args: string[]) => (await execa('git', args, { cwd: root })).stdout.trim() const commit = await git(['rev-parse', 'HEAD']) const exitCode = await runTests(root) if (commit !== await git(['rev-parse', 'HEAD'])) throw new Error('Git HEAD changed during tests; rerun coverage before publishing.') const tests = readTestPassRate(JSON.parse(await fs.readFile(path.join(directory, 'test-results.json'), 'utf8')), exitCode) const lines = tests.state === 'passed' ? readLineCoverage(JSON.parse(await fs.readFile(path.join(directory, 'coverage-summary.json'), 'utf8'))) : undefined const branch = process.env.CI_COMMIT_BRANCH || await git(['branch', '--show-current']) await fs.writeFile(path.join(directory, 'test-pass-rate.svg'), renderTestPassRateBadge(tests)) if (lines) await fs.writeFile(path.join(directory, 'coverage.svg'), renderCoverageBadge(lines)) await fs.writeFile(path.join(directory, 'badge-run.json'), JSON.stringify({ schema: 2, commit, branch, project: 'checks', generatedAt: new Date().toISOString(), exitCode, tests, lines, }, null, 2) + '\n') console.log(`Repository test pass rate: ${tests.pct?.toFixed(2) ?? 'n/a'}% (${tests.passed} passed, ${tests.failed} failed, state: ${tests.state})`) if (lines) console.log(`Repository line coverage: ${lines.pct.toFixed(2)}%`) console.log('Local reports and badge: coverage/ (not uploaded).') if (exitCode !== 0 || tests.state !== 'passed') throw new Error('Test run did not pass. Test-status badge generated; coverage badge was not generated.') } if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { if (process.argv.length > 2) throw new Error('test:coverage does not accept filters; the badge requires the complete checks project.') await collectCoverage() }