coverage-check 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jonathan Ong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # coverage-check
2
+
3
+ Patch-coverage gate for CI: checks that newly added lines meet per-path coverage thresholds using LCOV reports and `git diff`. Supports per-suite LCOV accumulation for conditional CI pipelines.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install coverage-check
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Basic (single run)
14
+
15
+ ```sh
16
+ coverage-check check \
17
+ --rules .coverage-rules.yml \
18
+ --artifacts ./coverage-artifacts \
19
+ --base origin/main \
20
+ --head HEAD
21
+ ```
22
+
23
+ Exits `0` on pass, `1` on failure, `2` on configuration error.
24
+
25
+ ### Suite store (conditional CI)
26
+
27
+ When only some CI suites run per PR (e.g. backend tests only when backend files change), store each suite's LCOV on every run and merge them when checking:
28
+
29
+ ```sh
30
+ # After backend tests run — store this suite's coverage
31
+ coverage-check store-put \
32
+ --suite backend \
33
+ --store ./coverage-store \
34
+ --artifacts ./coverage-artifacts \
35
+ --sha "$GITHUB_SHA" \
36
+ --ref "$GITHUB_REF"
37
+
38
+ # Sync the store directory to persistent storage (e.g. S3, git orphan branch)
39
+ aws s3 sync ./coverage-store s3://my-bucket/coverage-store/
40
+
41
+ # --- On the next PR that runs only frontend tests ---
42
+
43
+ # Pull the store
44
+ aws s3 sync s3://my-bucket/coverage-store/ ./coverage-store
45
+
46
+ # Store-put the current suite
47
+ coverage-check store-put --suite frontend --store ./coverage-store --artifacts ./coverage-artifacts
48
+
49
+ # Check: merges all stored suites (backend from baseline + frontend from this run)
50
+ coverage-check check \
51
+ --rules .coverage-rules.yml \
52
+ --artifacts ./coverage-artifacts \
53
+ --store ./coverage-store \
54
+ --suite frontend \
55
+ --base origin/main \
56
+ --head HEAD
57
+ ```
58
+
59
+ The `--suite` flag on `check` tells the tool to replace the same-named suite in the store with the fresh `--artifacts` (so you always see this PR's coverage for the suite that ran, and historical coverage for suites that didn't).
60
+
61
+ ### GitHub PR sticky comment
62
+
63
+ Pass `--pr` and `--repo` to post (or update) a sticky comment on a pull request. Requires the `gh` CLI and `GH_TOKEN`/`GITHUB_TOKEN`.
64
+
65
+ ```sh
66
+ coverage-check check \
67
+ --rules .coverage-rules.yml \
68
+ --artifacts ./coverage-artifacts \
69
+ --pr "${{ github.event.pull_request.number }}" \
70
+ --repo "${{ github.repository }}"
71
+ ```
72
+
73
+ ## Rules file
74
+
75
+ ```yaml
76
+ # .coverage-rules.yml
77
+ rules:
78
+ - paths: backend/**
79
+ patch_coverage_min: 90
80
+ - paths: web/lib/api/**
81
+ patch_coverage_min: 100
82
+ - paths: web/**
83
+ patch_coverage_min: 5
84
+ ```
85
+
86
+ Rules are matched in order; the first match wins. Files in the diff not matched by any rule are reported as informational (not gated).
87
+
88
+ ## CLI reference
89
+
90
+ ### `coverage-check check`
91
+
92
+ | Flag | Default | Description |
93
+ | ---------------- | ---------------------- | ---------------------------------------------------------------------------- |
94
+ | `--rules` | `.coverage-rules.yml` | Path to YAML rules file |
95
+ | `--artifacts` | `./coverage-artifacts` | Directory to scan for `lcov.info` files |
96
+ | `--base` | `origin/main` | Base git ref for `git diff` |
97
+ | `--head` | `HEAD` | Head git ref for `git diff` |
98
+ | `--store` | — | Path to a suite store directory |
99
+ | `--suite` | — | Name of the current suite (fresh artifacts override this suite in the store) |
100
+ | `--strip-prefix` | — | Extra path prefix to strip from LCOV `SF:` lines (repeatable) |
101
+ | `--pr` | — | Pull request number for sticky comment |
102
+ | `--repo` | `$GITHUB_REPOSITORY` | `owner/repo` for sticky comment |
103
+ | `--json` | — | Write JSON result to this path |
104
+
105
+ ### `coverage-check store-put`
106
+
107
+ | Flag | Default | Description |
108
+ | ---------------- | ---------------------- | --------------------------------------- |
109
+ | `--suite` | required | Suite name to store |
110
+ | `--store` | required | Path to the suite store directory |
111
+ | `--artifacts` | `./coverage-artifacts` | Directory to scan for `lcov.info` files |
112
+ | `--strip-prefix` | — | Extra path prefix to strip (repeatable) |
113
+ | `--sha` | — | Git SHA to record in metadata |
114
+ | `--ref` | — | Git ref to record in metadata |
115
+
116
+ ## Programmatic API
117
+
118
+ ```ts
119
+ import { runCheck, runStorePut, FileSystemSuiteStore } from "coverage-check";
120
+
121
+ // Custom store adapter (e.g. S3)
122
+ import { SuiteStore } from "coverage-check";
123
+
124
+ class S3SuiteStore implements SuiteStore {
125
+ async list() {
126
+ /* ... */
127
+ }
128
+ async get(suite: string) {
129
+ /* ... */
130
+ }
131
+ async put(suite: string, lcov: Buffer, meta?: SuiteMeta) {
132
+ /* ... */
133
+ }
134
+ }
135
+
136
+ await runCheck({
137
+ rules: ".coverage-rules.yml",
138
+ artifacts: "./coverage",
139
+ base: "origin/main",
140
+ head: "HEAD",
141
+ pr: null,
142
+ repo: "",
143
+ json: null,
144
+ stripPrefixes: [],
145
+ store: new S3SuiteStore(),
146
+ suite: "backend",
147
+ });
148
+ ```
149
+
150
+ ## License
151
+
152
+ [MIT](LICENSE)
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env -S node --experimental-strip-types --no-warnings
2
+
3
+ import { main } from "../src/cli.mts";
4
+
5
+ /* c8 ignore next */
6
+ process.exit(await main(process.argv.slice(2)));
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "coverage-check",
3
+ "version": "0.1.0",
4
+ "description": "Patch-coverage gate: checks that newly added lines meet per-path coverage thresholds. Supports per-suite LCOV accumulation for conditional CI.",
5
+ "license": "MIT",
6
+ "author": "Jonathan Ong",
7
+ "type": "module",
8
+ "bin": {
9
+ "coverage-check": "./bin/coverage-check.mts"
10
+ },
11
+ "files": [
12
+ "bin/**",
13
+ "src/**",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22.0.0"
19
+ },
20
+ "dependencies": {
21
+ "js-yaml": "^4.1.1"
22
+ },
23
+ "devDependencies": {
24
+ "@types/js-yaml": "^4.0.9",
25
+ "@types/node": "^25.8.0",
26
+ "@vitest/coverage-v8": "^4.1.6",
27
+ "husky": "^9.1.7",
28
+ "oxfmt": "^0.50.0",
29
+ "oxlint": "^1.65.0",
30
+ "typescript": "^6.0.3",
31
+ "vitest": "^4.1.6"
32
+ },
33
+ "scripts": {
34
+ "prepare": "husky",
35
+ "prepublishOnly": "npm run typecheck && npm test",
36
+ "typecheck": "tsc --noEmit",
37
+ "lint": "oxlint src/ bin/",
38
+ "format": "oxfmt src/ bin/ README.md",
39
+ "format:check": "oxfmt --check src/ bin/ README.md",
40
+ "test": "vitest run",
41
+ "test:coverage": "vitest run --coverage"
42
+ },
43
+ "keywords": [
44
+ "coverage",
45
+ "lcov",
46
+ "patch-coverage",
47
+ "github",
48
+ "ci",
49
+ "test-coverage"
50
+ ],
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/jonathanong/coverage-check.git"
54
+ },
55
+ "bugs": {
56
+ "url": "https://github.com/jonathanong/coverage-check/issues"
57
+ },
58
+ "homepage": "https://github.com/jonathanong/coverage-check"
59
+ }
package/src/cli.mts ADDED
@@ -0,0 +1,15 @@
1
+ import { main as checkMain } from "./commands/check.mts";
2
+ import { main as storePutMain } from "./commands/store-put.mts";
3
+
4
+ const stderr = (msg: string) => process.stderr.write(`${msg}\n`);
5
+
6
+ export async function main(argv: string[]): Promise<number> {
7
+ const sub = argv[0];
8
+
9
+ if (!sub || sub.startsWith("-")) return checkMain(argv);
10
+ if (sub === "check") return checkMain(argv.slice(1));
11
+ if (sub === "store-put") return storePutMain(argv.slice(1));
12
+
13
+ stderr(`coverage-check: unknown subcommand: ${JSON.stringify(sub)}`);
14
+ return 2;
15
+ }
@@ -0,0 +1,45 @@
1
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { tmpdir } from "node:os";
4
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
+ import { main } from "./cli.mts";
6
+
7
+ describe("cli subcommand dispatch", () => {
8
+ let tmpDir: string;
9
+ let rulesPath: string;
10
+ let artifactsDir: string;
11
+
12
+ beforeEach(() => {
13
+ tmpDir = mkdtempSync(join(tmpdir(), "cli-dispatch-"));
14
+ rulesPath = join(tmpDir, "rules.yml");
15
+ artifactsDir = join(tmpDir, "artifacts");
16
+ mkdirSync(artifactsDir);
17
+ writeFileSync(rulesPath, "rules:\n - paths: backend/**\n patch_coverage_min: 90\n");
18
+ });
19
+
20
+ afterEach(() => {
21
+ rmSync(tmpDir, { recursive: true, force: true });
22
+ });
23
+
24
+ it("defaults to check when no args given", async () => {
25
+ // No args → check → no lcov files → returns 0
26
+ expect(await main(["--rules", rulesPath, "--artifacts", artifactsDir])).toBe(0);
27
+ });
28
+
29
+ it("explicit check subcommand works", async () => {
30
+ expect(await main(["check", "--rules", rulesPath, "--artifacts", artifactsDir])).toBe(0);
31
+ });
32
+
33
+ it("explicit store-put subcommand returns 2 when --suite is missing", async () => {
34
+ expect(await main(["store-put", "--store", "/tmp/store"])).toBe(2);
35
+ });
36
+
37
+ it("returns 2 for unknown subcommand", async () => {
38
+ expect(await main(["unknown-command"])).toBe(2);
39
+ });
40
+
41
+ it("flags-first argument (starting with --) goes to check", async () => {
42
+ // '--rules' starts with '-', so dispatch goes to check
43
+ expect(await main(["--rules", rulesPath, "--artifacts", artifactsDir])).toBe(0);
44
+ });
45
+ });
@@ -0,0 +1,200 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { parseLcov } from "../lcov-parser.mts";
3
+ import { mergeLcov } from "../lcov-merge.mts";
4
+ import { getChangedLines } from "../diff-parser.mts";
5
+ import { loadRules } from "../rules.mts";
6
+ import { computePatchCoverage } from "../patch-coverage.mts";
7
+ import { collapseRanges, renderFailureComment, renderPassComment } from "../report.mts";
8
+ import { upsertComment } from "../github-comment.mts";
9
+ import { collectLcovFiles, buildStripPrefixes } from "../load-artifacts.mts";
10
+ import { FileSystemSuiteStore } from "../suite-store.mts";
11
+ import type { LcovData } from "../types.mts";
12
+ import type { SuiteStore } from "../suite-store.mts";
13
+ import type { GhRunner } from "../github-comment.mts";
14
+
15
+ const stdout = (msg: string) => process.stdout.write(`${msg}\n`);
16
+ const stderr = (msg: string) => process.stderr.write(`${msg}\n`);
17
+
18
+ export type CheckArgs = {
19
+ rules: string;
20
+ artifacts: string;
21
+ base: string;
22
+ head: string;
23
+ pr: number | null;
24
+ repo: string;
25
+ json: string | null;
26
+ stripPrefixes: string[];
27
+ store: SuiteStore | null;
28
+ suite: string | null;
29
+ gh?: GhRunner;
30
+ };
31
+
32
+ function parseArgs(argv: string[]): CheckArgs {
33
+ const args: CheckArgs = {
34
+ rules: ".coverage-rules.yml",
35
+ artifacts: "./coverage-artifacts",
36
+ base: "origin/main",
37
+ head: "HEAD",
38
+ pr: null,
39
+ repo: process.env["GITHUB_REPOSITORY"] ?? "",
40
+ json: null,
41
+ stripPrefixes: [],
42
+ store: null,
43
+ suite: null,
44
+ };
45
+
46
+ for (let i = 0; i < argv.length; i++) {
47
+ const flag = argv[i]!;
48
+ const next = argv[i + 1];
49
+ const val = (): string => {
50
+ if (next === undefined) throw new Error(`${flag} requires a value`);
51
+ i++;
52
+ return next;
53
+ };
54
+ switch (flag) {
55
+ case "--rules":
56
+ args.rules = val();
57
+ break;
58
+ case "--artifacts":
59
+ args.artifacts = val();
60
+ break;
61
+ case "--base":
62
+ args.base = val();
63
+ break;
64
+ case "--head":
65
+ args.head = val();
66
+ break;
67
+ case "--pr": {
68
+ const raw = val();
69
+ if (!/^\d+$/.test(raw) || raw === "0")
70
+ throw new Error(`--pr must be a positive integer, got: ${JSON.stringify(raw)}`);
71
+ args.pr = parseInt(raw, 10);
72
+ break;
73
+ }
74
+ case "--repo":
75
+ args.repo = val();
76
+ break;
77
+ case "--json":
78
+ args.json = val();
79
+ break;
80
+ case "--strip-prefix":
81
+ args.stripPrefixes.push(val());
82
+ break;
83
+ case "--store":
84
+ args.store = new FileSystemSuiteStore(val());
85
+ break;
86
+ case "--suite":
87
+ args.suite = val();
88
+ break;
89
+ default:
90
+ throw new Error(`unknown flag: ${flag}`);
91
+ }
92
+ }
93
+
94
+ return args;
95
+ }
96
+
97
+ export async function main(argv: string[]): Promise<number> {
98
+ let args: CheckArgs;
99
+ try {
100
+ args = parseArgs(argv);
101
+ } catch (err) {
102
+ /* c8 ignore next */
103
+ stderr(`coverage-check: ${err instanceof Error ? err.message : err}`);
104
+ return 2;
105
+ }
106
+ return runCheck(args);
107
+ }
108
+
109
+ export async function runCheck(args: CheckArgs): Promise<number> {
110
+ let rules;
111
+ try {
112
+ rules = loadRules(args.rules);
113
+ } catch (err) {
114
+ stderr(`coverage-check: failed to load rules: ${err}`);
115
+ return 2;
116
+ }
117
+
118
+ const stripPrefixes = buildStripPrefixes(args.stripPrefixes);
119
+ const reports: LcovData[] = [];
120
+
121
+ // Merge in suites from the store (skip the current suite — fresh artifacts take precedence)
122
+ if (args.store !== null) {
123
+ const suites = await args.store.list();
124
+ for (const suite of suites) {
125
+ if (suite === args.suite) continue;
126
+ const buf = await args.store.get(suite);
127
+ if (buf !== null) {
128
+ reports.push(parseLcov(buf.toString("utf8"), stripPrefixes));
129
+ }
130
+ }
131
+ }
132
+
133
+ // Add current run's lcov files
134
+ const lcovFiles = collectLcovFiles(args.artifacts);
135
+ for (const f of lcovFiles) {
136
+ reports.push(parseLcov(readFileSync(f, "utf8"), stripPrefixes));
137
+ }
138
+
139
+ if (reports.length === 0) {
140
+ stderr(`coverage-check: no coverage data found — skipping`);
141
+ return 0;
142
+ }
143
+
144
+ const lcov = mergeLcov(reports);
145
+
146
+ let diff;
147
+ try {
148
+ diff = await getChangedLines(args.base, args.head);
149
+ } catch (err) {
150
+ stderr(`coverage-check: git diff failed: ${err}`);
151
+ return 2;
152
+ }
153
+
154
+ const { buckets, informational } = computePatchCoverage(diff, lcov, rules);
155
+ const passed = buckets.every((b) => b.passed);
156
+ const result = { buckets, informational, passed };
157
+
158
+ if (args.json) {
159
+ writeFileSync(args.json, JSON.stringify(result, null, 2));
160
+ }
161
+
162
+ const runUrl =
163
+ process.env["GITHUB_SERVER_URL"] && process.env["GITHUB_RUN_ID"]
164
+ ? `${process.env["GITHUB_SERVER_URL"]}/${args.repo}/actions/runs/${process.env["GITHUB_RUN_ID"]}`
165
+ : "N/A";
166
+
167
+ if (!passed) {
168
+ stdout("\ncoverage-check: FAILED\n");
169
+ for (const bucket of buckets.filter((b) => !b.passed)) {
170
+ /* c8 ignore next -- buckets always have coverable>0 by construction */
171
+ const pct =
172
+ bucket.coverable > 0 ? `${((bucket.hit / bucket.coverable) * 100).toFixed(1)}%` : "—";
173
+ stdout(
174
+ ` ${bucket.rule}: ${pct} (${bucket.hit}/${bucket.coverable}) — threshold ${bucket.threshold}%`,
175
+ );
176
+ for (const file of bucket.files.filter((f) => f.uncoveredLines.length > 0)) {
177
+ stdout(` ${file.file}: ${collapseRanges(file.uncoveredLines)}`);
178
+ }
179
+ }
180
+ } else {
181
+ stdout("\ncoverage-check: PASSED\n");
182
+ for (const bucket of buckets) {
183
+ /* c8 ignore next -- buckets always have coverable>0 by construction */
184
+ const pct =
185
+ bucket.coverable > 0 ? `${((bucket.hit / bucket.coverable) * 100).toFixed(1)}%` : "—";
186
+ stdout(` ${bucket.rule}: ${pct} ✓`);
187
+ }
188
+ }
189
+
190
+ if (args.pr !== null && args.repo) {
191
+ const body = passed ? renderPassComment(runUrl) : renderFailureComment(result, runUrl);
192
+ try {
193
+ await upsertComment(body, args.repo, args.pr, passed, args.gh);
194
+ } catch (err) {
195
+ stderr(`coverage-check: failed to post PR comment: ${err}`);
196
+ }
197
+ }
198
+
199
+ return passed ? 0 : 1;
200
+ }