Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(coverage): gate a change on its patch coverage in CI (#2630)

Raghav Chamadiyaa01f7ec64efe
diff --git a/README.md b/README.md
index 55ed6bfca..cd25c6fb2 100644
--- a/README.md
+++ b/README.md
@@ -231,10 +231,10 @@ request. Zero LLM calls.
## Which tests cover this file, without a coverage report
-Ingest LCOV, Cobertura or Clover and you get the measured answer. **Most
-repositories never produce one**, so the graph answers instead: a test file that
-imports a source file *reaches* it, which is a recorded edge rather than the
-name-shaped guess everything else falls back to.
+Ingest LCOV, Cobertura, Clover, JaCoCo or a Go coverprofile and you get the
+measured answer. **Most repositories never produce one**, so the graph answers
+instead: a test file that imports a source file *reaches* it, which is a
+recorded edge rather than the name-shaped guess everything else falls back to.
That fallback fails in both directions, and this repo is the proof. Five of its
six worst bug-magnet files have no test named for them and read as untested while
@@ -861,7 +861,7 @@ August 2026. Unmarked rows are capability presence, not measurements.</sub>
| Bus factor analysis | ✅ | ✅ |
| Concrete cross-file refactoring plans | ✅ graph-aware + blast radius | ⚠️ within-function only |
| Dataflow-verified within-function plans | ✅ CFG + reaching definitions | ⚠️ LLM-generated, unverified |
-| Test-coverage intelligence | ✅ LCOV/Cobertura/Clover | ❌ |
+| Test-coverage intelligence | ✅ LCOV/Cobertura/Clover/JaCoCo/Go | ❌ |
| Untested-hotspot detection | ✅ coverage × hotspot | ❌ |
| Dead code detection | ✅ | ❌ |
| Serves it to an AI agent over MCP | ✅ | ✅ |
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 586eb9391..1f1b1745d 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -590,7 +590,7 @@ compares the two revisions directly and needs no index refresh.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
-| `revspec` | string | No | Commit or `base..head` range to score. Omit it to score uncommitted work, or pass `HEAD` when the tree is clean |
+| `revspec` | string | No | Commit, `base..head` range, or `base...head` (diffed from the merge-base) to score. Omit it to score uncommitted work, or pass `HEAD` when the tree is clean |
| `repo` | string | No | *(workspace only)* Target repo alias |
| `extensions` | list[string] | No | File suffixes to count, such as `[".py", ".ts"]` |
| `exclude_patterns` | list[string] | No | Gitignore-style paths to omit; combined with root `.riskignore` rules |
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index cd116d03c..54a6ec3a0 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -86,6 +86,8 @@ analysis/health/
│ ├── lcov.py # LCOV parser (stdlib only)
│ ├── cobertura.py # Cobertura XML parser
│ ├── clover.py # Clover XML parser
+│ ├── jacoco.py # JaCoCo XML parser
+│ ├── goprofile.py # Go coverprofile parser (line-based)
│ └── repowise_json.py # normalized repowise-coverage-v1 JSON parser
│
├── duplication/ # native Rabin-Karp clone detection
@@ -205,7 +207,7 @@ tests/unit/health/ # 99+ tests
├── test_organizational_biomarkers.py
├── test_dry_violation.py
├── test_duplication.py # tokenizer, hash, detector
-├── test_coverage_parsers.py # LCOV/Cobertura/Clover/JSON
+├── test_coverage_parsers.py # LCOV/Cobertura/Clover/JaCoCo/Go/JSON
├── test_scoring.py # category caps, clamping
├── test_scoring_snapshot.py # stability snapshot: locks caps + deductions
├── test_health_config.py # .repowise/health-rules.json
@@ -716,6 +718,7 @@ repowise health --refactoring-targets # ranked by impact / effort
repowise health --trend # last 10 snapshots + active alerts
repowise coverage add coverage.lcov # ingest coverage; can repeat
repowise coverage add coverage.xml --format cobertura
+repowise coverage check --fail-under 80 # patch-coverage gate for CI, no index needed
repowise health --format json | jq ...
```
@@ -894,7 +897,7 @@ Other perf notes:
| `tests/unit/health/test_complexity_walker.py` | Per-language CCN, nesting, cognitive assertions on handcrafted fixtures |
| `tests/unit/health/test_<biomarker>.py` | Each marker: positive in two languages + one negative |
| `tests/unit/health/test_duplication.py` | Tokenizer normalization, rolling-hash determinism, co-change weighting |
-| `tests/unit/health/test_coverage_parsers.py` | LCOV / Cobertura / Clover / repowise-JSON happy paths + edge cases |
+| `tests/unit/health/test_coverage_parsers.py` | LCOV / Cobertura / Clover / JaCoCo / Go coverprofile / repowise-JSON happy paths + edge cases |
| `tests/unit/health/test_scoring.py` | Deduction caps, clamping, KPI math |
| `tests/unit/health/test_scoring_snapshot.py` | **Stability guard**: caps, severity table, marker-to-category mapping, two known fixture scores |
| `tests/unit/health/test_trends.py` | Declining + predicted alerts, ordering, per-file series + `file_trend` |
diff --git a/docs/business/COMMERCIAL.md b/docs/business/COMMERCIAL.md
index 215471bc7..64770c5a2 100644
--- a/docs/business/COMMERCIAL.md
+++ b/docs/business/COMMERCIAL.md
@@ -80,11 +80,12 @@ All of the following ship in `pip install repowise` today, free for internal use
- **Dead-code detection**: pure graph traversal, confidence-tiered, framework-aware
(ASP.NET, Django, FastAPI, Flask, Rails, Laravel), dynamic-import aware.
- **Test intelligence, from a coverage report and from the call graph.** Ingests
- LCOV / Cobertura / Clover like a coverage service, then does the half a coverage
- service structurally cannot: answers *which tests reach this file* and *which
- tests does this diff exercise* **with no report at all**, at **95.7% and 97.5%
- precision** measured against a real `coverage run --contexts=test`. Measured and
- inferred rows are labelled and never averaged. Zero LLM calls, no CI integration.
+ LCOV / Cobertura / Clover / JaCoCo / Go coverprofile like a coverage service,
+ then does the half a coverage service structurally cannot: answers *which
+ tests reach this file* and *which tests does this diff exercise* **with no
+ report at all**, at **95.7% and 97.5% precision** measured against a real
+ `coverage run --contexts=test`. Measured and inferred rows are labelled and
+ never averaged. Zero LLM calls, no CI integration needed.
([TEST_INTELLIGENCE.md](../layers/TEST_INTELLIGENCE.md))
- **Privacy** (self-hosted): source never leaves your infrastructure, BYOK or fully
offline via Ollama. Anonymous, opt-out usage telemetry (command names and coarse
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.md
index fbf1774bf..41f317366 100644
--- a/docs/layers/CODE_HEALTH.md
+++ b/docs/layers/CODE_HEALTH.md
@@ -635,7 +635,8 @@ repowise health --trend
```
Coverage reports light up the test-coverage markers. **LCOV**, **Cobertura**,
-**Clover** and a normalized JSON format are auto-detected:
+**Clover**, **JaCoCo**, **Go coverprofile** and a normalized JSON format are
+auto-detected:
```bash
pytest --cov --cov-report=lcov:coverage.lcov
diff --git a/docs/layers/INTELLIGENCE_LAYERS.md b/docs/layers/INTELLIGENCE_LAYERS.md
index bcf403fb2..7cbc47851 100644
--- a/docs/layers/INTELLIGENCE_LAYERS.md
+++ b/docs/layers/INTELLIGENCE_LAYERS.md
@@ -253,8 +253,9 @@ Reference: [`CHANGE_RISK.md`](CHANGE_RISK.md).
Which tests actually exercise the code you changed, which changed files have no
guarding test at all, and per-file coverage merged across every test that touches
-it. Coverage ingests from LCOV, Cobertura, Clover or normalized JSON and feeds the
-code-health coverage markers.
+it. Coverage ingests from LCOV, Cobertura, Clover, JaCoCo, Go coverprofile or
+normalized JSON and feeds the code-health coverage markers. The same report gates
+a pull request on its patch coverage with `repowise coverage check`.
**It answers with or without that ingest.** Most repositories never produce a
report, so where one is missing the layer walks the call graph instead: a test
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index 0999bed68..89de01dce 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -3,7 +3,9 @@
Ingest a coverage report and repowise can answer two questions your CI cannot:
which files are risky *and* untested, and which tests a given diff actually
exercises. That second one turns a 4,000-test suite into the 40 tests that guard
-the change you just made.
+the change you just made. The same report also gates a pull request on its
+patch coverage, with no index at all (see
+[Patch coverage in CI](#patch-coverage-in-ci)).
Without a coverage report there is still an answer, a weaker one. The dependency
graph records which test files import which source files, so repowise can say
@@ -74,22 +76,39 @@ line up.
| **LCOV** | Leading `TN:` / `SF:`, or any `TN\|SF\|DA\|BRDA\|LF\|LH\|BRF\|BRH:` line | Yes, when each record carries a non-blank `TN:` test name |
| **Cobertura** XML | `<coverage` plus `<packages` or `line-rate` | No |
| **Clover** XML | `<coverage` plus `<project` | No |
+| **JaCoCo** XML | The JaCoCo doctype, or a `<report` root | No |
+| **Go coverprofile** (`go test -coverprofile`) | Leading `mode:` line | No |
| **coverage.py `.coverage`** | SQLite magic bytes | Yes, when written with `--contexts` |
| **Normalized JSON** (`repowise-coverage-v1`) | Leading `{` plus `repowise-coverage` or `line_coverage_pct` | No |
-Force a parser with `--format lcov|cobertura|clover|repowise-json`. The normalized
-JSON shape lets you feed any runner once you map it:
+A UTF-8 byte-order mark at the start of a report is ignored. Go percentages are
+line-based, not the statement percentage `go tool cover -func` prints. A Go
+profile records blocks rather than lines, so every line a block spans counts as
+executable, and a comment inside an unexecuted block reads as uncovered.
+
+Force a parser with
+`--format lcov|cobertura|clover|repowise-json|go-coverprofile|jacoco`. The
+normalized JSON shape lets you feed any runner once you map it:
```json
{ "format": "repowise-coverage-v1",
"files": { "src/foo.py": { "line_coverage_pct": 87.5,
- "total_coverable_lines": 40 } } }
+ "total_coverable_lines": 40,
+ "covered_lines": [1, 2, 5],
+ "coverable_lines": [1, 2, 3, 5] } } }
```
+`covered_lines` and `coverable_lines` are optional. Patch coverage needs
+`coverable_lines` (the executable-line set); without it a file reads as having
+no line data, never as 0%.
+
With no path argument, `add` auto-discovers `coverage/lcov.info`, `lcov.info`,
`coverage.lcov`, `coverage.xml`, `**/cobertura.xml`, `**/clover.xml`,
-`target/llvm-cov/**/*.lcov`, and a repo-root `.coverage`. Multiple reports merge
-with hit-wins: covered lines union, coverable counts take the max.
+`target/llvm-cov/**/*.lcov`, `coverage.out`, `cover.out`,
+`**/target/site/jacoco*/jacoco.xml`, a root-module
+`build/reports/jacoco/**/*.xml` (pass a nested Gradle module's report
+explicitly), and a repo-root `.coverage`. Multiple reports merge with hit-wins:
+covered lines and coverable lines are each unioned.
Report paths are matched to indexed files by exact key first, then basename, then
the longest trailing-path overlap. A tie refuses to guess and is reported as
@@ -133,7 +152,8 @@ map, and returns the tests whose recorded coverage intersects them.
```bash
repowise impacted-tests # staged changes (the default)
-repowise impacted-tests main..HEAD # a branch or PR range
+repowise impacted-tests main...HEAD # a branch or PR, from the merge-base
+repowise impacted-tests main..HEAD # a plain range
repowise impacted-tests abc123 # a single commit
repowise impacted-tests main..HEAD --format list | xargs pytest
```
@@ -160,6 +180,75 @@ With `--format list` the caveats go to stderr so the stdout pipe into `pytest`
stays clean. The command exits `0` in every one of these cases, including "no
tests found": it is a reporting tool, not a gate.
+A `base...head` range diffs from the merge-base of the two, so it is what a pull
+request changed: commits that landed on `base` after the branch forked stay out.
+`base..head` is the plain range. Every command that reads a range follows the
+same rule, change risk (`repowise risk`, `get_change_risk`) included.
+
+## Patch coverage in CI
+
+`repowise coverage check [REVSPEC]` is the gate: of the lines a change touched
+that the report calls executable, what share did the tests run?
+
+```bash
+repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80
+```
+
+It needs git and a report, nothing else: no index, no ingest, no LLM key.
+Report paths are resolved against `git ls-files` rather than an index, so a file
+the change adds resolves too. Without `REVSPEC` the base comes from the CI's
+pull-request variables, else the default branch; pass it explicitly in CI so the
+job says what it measures. Reports come from `--report`, else `coverage.paths`,
+else discovery.
+
+The denominator is changed lines the report marks executable, so a changed
+comment or blank line is neither covered nor uncovered. What counts is decided by
+the report:
+
+| Status | Meaning | In the % |
+|--------|---------|----------|
+| `measured` | The report names the file and some changed lines are executable | Yes |
+| `no_coverable_changes` | The report names the file, but no changed line is executable | No |
+| `not_in_report` | The report does not name the file, but it has an extension the report measures, e.g. a new source file no test loaded | No. Listed as "not in report", never 0% |
+| `no_line_data` | The report names the file but gives no executable-line set for it | No |
+
+Changed test files, and file types the report never measures (docs, config), are
+out of scope and only counted. A change with no measured lines has nothing to
+judge and passes.
+
+The threshold comes from `--fail-under`, else `coverage.fail_under` in
+`.repowise/config.yaml` (read at the repository root, even with `--path`); with
+neither, the check reports without gating. The gate compares the unrounded
+figure; the displayed one is floored to one decimal, so 79.99% reads 79.9% and
+fails an 80% gate. Exit `0` passes (or had nothing to judge), `1` is below the
+gate, `2` means the check could not run: no report found, readable or matching a
+repository file, an unknown revision, no merge-base (a shallow clone), a single
+commit at a shallow clone's boundary, bad config, or not a git repository.
+
+`--format github` writes up to 10 `::warning` annotations (largest uncovered
+ranges first), a notice counting the rest, and an `::error::` when the gate
+fails, then appends the markdown summary to `$GITHUB_STEP_SUMMARY`. `markdown`
+and `json` suit other CI systems. A coverage.py `.coverage` database is not a
+text report: export it with `coverage lcov` or `coverage xml` first.
+
+CI checkouts are often shallow, which leaves no merge-base to diff from. Fetch
+full history (`fetch-depth: 0` on GitHub Actions, `GIT_DEPTH: 0` on GitLab).
+Workflow snippets for GitHub Actions, GitLab and Jenkins are in the
+[CLI reference](../reference/CLI_REFERENCE.md#repowise-coverage-check-revspec).
+
+A new file no test loads must still appear in the report, or it reads "not in
+report" and is not counted. Per language:
+
+- **Python:** `pytest --cov=<src> --cov-report=lcov` (prefer lcov: its paths are
+ relative to the working directory).
+- **JavaScript / TypeScript:** `c8 --all --reporter=lcov`, or jest with
+ `collectCoverageFrom` set.
+- **Go:** `go test -coverprofile=coverage.out ./...`; add `-coverpkg=./...` to
+ include packages that have no tests.
+- **Java:** Maven `jacoco:report` (`report-aggregate` for multi-module), or Gradle
+ `jacocoTestReport`.
+- **Rust:** `cargo llvm-cov --lcov --output-path lcov.info`.
+
## Untested hotspots
Coverage feeds the [code health](CODE_HEALTH.md) layer's test-coverage markers.
@@ -279,7 +368,7 @@ no setup at all.
| Comes from | a coverage report you ingested | the call graph, already indexed |
| Granularity | lines | files |
| Proves | this test executed these lines | this test's calls reach this file |
-| Decays | yes, see the coverage age report | no |
+| Decays | yes: rows carry the commit they were ingested at, and `test_impact.coverage.freshness` reads `stale` once the index moves past it | no |
| May produce a percentage | yes | **never** |
| Labelled | `basis: "measured"` | `basis: "inferred"` |
@@ -415,6 +504,7 @@ coverage:
format: lcov # skip format sniffing
strip_prefix: "/build/src/" # trim an absolute prefix from report paths
reingest_on_update: false
+ fail_under: 80 # patch-coverage gate for `coverage check` (0-100)
```
Coverage is also auto-discovered and ingested during `init` and `update`, and
@@ -428,6 +518,7 @@ Note that `--coverage-report` is test coverage, while `--coverage` controls
|---------|--------------|
| `repowise coverage add [PATHS...]` | Ingest reports. Auto-discovers when no path is given, merges multiple, builds the per-test map when contexts are present. Flags: `--path`, `--format`, `--verbose` |
| `repowise coverage status` | Coverage summary plus test-to-code map counts. Flag: `--path` |
+| `repowise coverage check [REVSPEC]` | Patch-coverage gate for CI, no index needed. Flags: `--report`, `--report-format`, `--fail-under`, `--path`, `--format` |
| `repowise impacted-tests [REVSPEC]` | The tests a change exercises. Flags: `--path`, `--staged`, `--format` |
Full reference: [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-coverage).
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 3ef4eb40f..dda6cebbe 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -161,7 +161,7 @@ All three reach the indexing knobs; the LLM-only knobs appear only when model-wr
| `--concurrency` | Max concurrent LLM calls (default: 10) |
| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` (default: `auto`) |
| `--max-file-pages` | Most file pages to emit, highest importance first. Omit to let the size policy decide (see Page volume above), `0` for one page per eligible file however many that is, or a positive number for a hard cap. Saved to `config.yaml`. |
-| `--coverage-report` | Test-coverage report to ingest (LCOV / Cobertura / Clover). Repeatable. Auto-discovered when omitted. This is test coverage for code-health, not a documentation-breadth knob: every code file is documented either way. |
+| `--coverage-report` | Test-coverage report to ingest (LCOV / Cobertura / Clover / JaCoCo / Go coverprofile). Repeatable. Auto-discovered when omitted. This is test coverage for code-health, not a documentation-breadth knob: every code file is documented either way. |
| `--onboarding` / `--no-onboarding` | Generate the curated Onboarding collection (up to 8 overview pages). Default: on; slots without enough signal are skipped. |
| `--wiki-style` | Documentation voice/density: `comprehensive` (default), `caveman` (token-condensed, AI-first), `reference` (API-manual), `tutorial` (beginner-friendly). Interactive full runs prompt when omitted. Saved to config so `update` keeps the style. See [WIKI.md](../layers/WIKI.md#styles). |
| `--language` | Output language for generated wiki pages: `en` (default), `ar`, `de`, `es`, `fr`, `hi`, `it`, `ja`, `ko`, `nl`, `pl`, `pt`, `ru`, `tr`, `zh`. Code, file paths, and symbol names stay untranslated. Saved to config so `update` keeps the language. Also asked in advanced interactive mode. To switch an existing wiki's language, set the flag and re-run `init --force`. |
@@ -776,7 +776,8 @@ risk of a change from the same calibrated signals the code-health layer uses -
no LLM calls, and it works without `repowise init` (pure git + learned
constants). With no `REVSPEC` it scores your uncommitted work, falling back to
`HEAD` when the tree is clean; pass `HEAD` to always mean the last commit, or a
-`base..head` range to score a whole branch / PR as one change.
+`base..head` range to score a whole branch / PR as one change (`base...head`
+diffs from the merge-base, so commits that landed on `base` meanwhile stay out).
The headline is **repo-relative**: the change's percentile and review priority
(`Below typical` / `Typical` / `Elevated`) within the repo's own recent commits,
@@ -920,8 +921,9 @@ built by [`repowise coverage add`](#repowise-coverage) and returns the tests
whose recorded coverage intersects the diff. No LLM, no network - a straight
index lookup.
-`REVSPEC` is a `base..head` range or a single commit; with no argument (or
-`--staged`) it diffs the staged changes. It is honest about what it does not
+`REVSPEC` is a `base...head` range (the change since the branch forked from
+`base`, what a pull request shows), a `base..head` range, or a single commit;
+with no argument (or `--staged`) it diffs the staged changes. It is honest about what it does not
know, and always says which path fired:
- a changed file with per-test coverage -> the exact covering tests (`via: coverage`);
@@ -950,7 +952,8 @@ line up.
```bash
repowise impacted-tests # staged changes
-repowise impacted-tests main..HEAD # a branch / PR range
+repowise impacted-tests main...HEAD # a branch / PR (diffed from the merge-base)
+repowise impacted-tests main..HEAD # a plain range
repowise impacted-tests abc123 # a single commit
repowise impacted-tests main..HEAD --format list | xargs pytest
```
@@ -1161,17 +1164,19 @@ typo from a successful transition. `dismiss` skips its confirmation prompt under
### `repowise coverage`
-Ingest and inspect test-coverage reports. Coverage is auto-discovered and
-ingested during `init` / `update`; this group is the manual path, point it at
-a report (or let it auto-discover one) to populate per-file line/branch
-coverage, which clears `untested_hotspot` findings for files that are tested
-regardless of where their tests live.
+Ingest and inspect test-coverage reports, and gate a change on its patch
+coverage in CI. Coverage is auto-discovered and ingested during `init` /
+`update`; `add` is the manual path, point it at a report (or let it
+auto-discover one) to populate per-file line/branch coverage, which clears
+`untested_hotspot` findings for files that are tested regardless of where
+their tests live.
**Subcommands:**
```bash
repowise coverage add [PATHS...] # ingest coverage reports (+ per-test map when contexts are present)
repowise coverage status # show ingested coverage + the map
+repowise coverage check [REVSPEC] # gate a change on its patch coverage (CI)
```
**`add` options:**
@@ -1179,12 +1184,14 @@ repowise coverage status # show ingested coverage + the map
| Flag | Description |
|------|-------------|
| `--path` | Repo path (defaults to cwd / workspace primary) |
-| `--format` | Force a parser instead of auto-detecting: `lcov`, `cobertura`, `clover`, `repowise-json` |
+| `--format` | Force a parser instead of auto-detecting: `lcov`, `cobertura`, `clover`, `repowise-json`, `go-coverprofile`, `jacoco` |
| `--verbose` / `-v` | Show debug logs while discovering and ingesting coverage |
-`add` ingests per-file line/branch coverage from LCOV, Cobertura, Clover, or a
-coverage.py `.coverage` file. It auto-discovers `coverage/lcov.info`,
-`.coverage`, and similar reports at the repo root when no path is given, and
+`add` ingests per-file line/branch coverage from LCOV, Cobertura, Clover,
+JaCoCo XML, a Go coverprofile (`go test -coverprofile`), or a coverage.py
+`.coverage` file. It auto-discovers `coverage/lcov.info`, `.coverage`,
+`coverage.out`, `target/site/jacoco/jacoco.xml`, and similar reports when no
+path is given, and
merges multiple reports (hit wins). When the report carries per-test contexts,
a coverage.py `.coverage` written with `coverage run --contexts=test`, or a
per-test lcov, `add` also builds the per-test *test-to-code map*, which test
@@ -1206,6 +1213,130 @@ repowise coverage status --format json # machine-readable (note: the --form
> `add` always stores (a file is covered, merged over all tests) and from what
> `health` reads. It's used to answer "which tests exercise this change".
+#### `repowise coverage check [REVSPEC]`
+
+Gate a change on its **patch coverage**: of the changed lines the report calls
+executable, the share the tests ran. Built for CI: it needs git and a coverage
+report, nothing else (no index, no LLM key). Report paths are resolved against
+`git ls-files`, so a file the change adds resolves too.
+
+`REVSPEC` is the change: `base...head` (the change since the branch forked
+from `base`, the pull-request view), `base..head`, or a single commit. Without
+it the check diffs `<base>...HEAD`, taking the base branch from `GITHUB_BASE_REF`,
+`CI_MERGE_REQUEST_TARGET_BRANCH_NAME`, `CHANGE_TARGET` or
+`BITBUCKET_PR_DESTINATION_BRANCH` (read as `origin/<name>`),
+else `origin/HEAD`, a local `main` / `master`, or `origin/main` /
+`origin/master`; with none of those it exits 2 and asks for `REVSPEC`. Pass it
+explicitly in CI so the job says what it measures.
+
+Reports come from `--report`, else `coverage.paths` in `.repowise/config.yaml`,
+else discovery (when `coverage.auto_discover` is on) of the usual locations,
+including `coverage/lcov.info`, `coverage.xml`, `coverage.out`,
+`**/target/site/jacoco*/jacoco.xml` and a root-module
+`build/reports/jacoco/**/*.xml`. A nested Gradle module's report needs
+`--report`. Config is read at the repository root (git toplevel), even with
+`--path`.
+
+A changed comment or blank line is neither covered nor uncovered. Each changed
+file lands in one status:
+
+| Status | Meaning | Counts toward the % |
+|--------|---------|---------------------|
+| `measured` | The report names the file and some changed lines are executable | Yes |
+| `no_coverable_changes` | The report names the file, but no changed line is executable | No |
+| `not_in_report` | Code of a kind the report measures (same extension), but the report does not name it, e.g. a new untested file | No, listed as "not in report", never 0% |
+| `no_line_data` | The report names the file but carries no executable-line set for it | No |
+
+Changed test files and file types the report never measures (docs, config)
+are out of scope and only counted.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--report` | Coverage report to read. Repeatable, merged hit-wins. Defaults to `coverage.paths`, else discovery |
+| `--report-format` | Force a parser: `lcov`, `cobertura`, `clover`, `repowise-json`, `go-coverprofile`, `jacoco` |
+| `--fail-under` | Exit 1 when patch coverage is below this percentage (0-100). Defaults to `coverage.fail_under` in `.repowise/config.yaml`; with neither set the command reports without gating |
+| `--path` | A path inside the repository (defaults to cwd) |
+| `--format` | `table` (default), `json`, `markdown`, or `github` |
+
+`github` writes up to 10 `::warning` annotations (largest uncovered ranges
+first), a `::notice` counting the rest, and an `::error::` when the gate fails,
+then appends the markdown summary to `$GITHUB_STEP_SUMMARY` when set.
+`json` carries `patch_coverage_pct`, `covered_line_count`,
+`coverable_line_count`, `threshold`, `gate` (`pass`, `fail`, `no_data`,
+`not_set`), `file_counts` (`measured`, `not_in_report`, `no_line_data`,
+`no_coverable_changes`, `out_of_scope`), `files[]` (`file_path`, `status`,
+`changed_line_count`, `coverable_line_count`, `covered_line_count`,
+`patch_coverage_pct`, `uncovered_ranges`) and `scope` (`label`,
+`source_formats`, `reports`, `report_path_count`,
+`unmatched_report_path_count`). Percentages are shown floored to one decimal
+(79.99% reads 79.9%); the gate compares the unrounded figure.
+
+**Exit codes:** `0` the gate passes or there is nothing to judge (no threshold,
+or no measurable changed lines); `1` patch coverage is below `--fail-under`;
+`2` the check could not run: no report found, none readable, or none matching a
+repository file; an unknown revision; no merge-base (a shallow clone); a single
+commit at a shallow clone's boundary; bad config or a malformed
+`coverage.fail_under`; not a git repository.
+
+A coverage.py `.coverage` database is not a text report: export it first with
+`coverage lcov` or `coverage xml`. A new file no test loads must still appear
+in the report, or it is "not in report" and not counted; the per-language
+commands are in
+[Patch coverage in CI](../layers/TEST_INTELLIGENCE.md#patch-coverage-in-ci).
+
+```bash
+repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80
+repowise coverage check HEAD --format json # one commit, machine-readable
+repowise coverage check origin/main...HEAD --report coverage.out --report-format go-coverprofile
+```
+
+CI clones are often shallow, so the merge-base is missing and the check exits 2.
+Fetch full history.
+
+GitHub Actions (`pull_request` only: `github.base_ref` is empty on `push`, where
+`"${{ github.event.before }}..${{ github.sha }}"` is the range instead):
+
+```yaml
+- uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+- run: pytest --cov=src --cov-report=lcov:coverage/lcov.info
+- run: pip install repowise
+- run: >
+ repowise coverage check "origin/${{ github.base_ref }}...HEAD"
+ --report coverage/lcov.info --fail-under 80 --format github
+```
+
+A cheaper checkout: `fetch-depth: 2` and `HEAD^1..HEAD`, which on a
+`pull_request` run diffs the merge commit GitHub builds against the base.
+
+GitLab merge request (`markdown` goes to the job log; redirect it to a file to
+post it as a note or keep it as an artifact):
+
+```yaml
+coverage-gate:
+ variables:
+ GIT_DEPTH: 0
+ script:
+ - git fetch --no-tags origin "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"
+ - pytest --cov=src --cov-report=lcov:coverage/lcov.info
+ - pip install repowise
+ - >
+ repowise coverage check "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME...HEAD"
+ --report coverage/lcov.info --fail-under 80 --format markdown
+ rules:
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event"
+```
+
+Jenkins multibranch pull request:
+
+```bash
+git fetch --no-tags origin "+refs/heads/$CHANGE_TARGET:refs/remotes/origin/$CHANGE_TARGET"
+repowise coverage check "origin/$CHANGE_TARGET...HEAD" --report coverage/lcov.info --fail-under 80
+```
+
---
### `repowise distill <command>`
diff --git a/docs/start/USER_GUIDE.md b/docs/start/USER_GUIDE.md
index 1dbadcf02..811e171a2 100644
--- a/docs/start/USER_GUIDE.md
+++ b/docs/start/USER_GUIDE.md
@@ -412,6 +412,17 @@ repowise risk "$BASE_SHA..$HEAD_SHA" # gate or annotate on review priority
repowise export --format markdown --output ./docs/wiki/ # static hosting
```
+To gate a pull request on the coverage of the lines it changed, run the tests
+with a coverage report and add:
+
+```bash
+repowise coverage check "origin/$BASE_BRANCH...HEAD" --report coverage/lcov.info --fail-under 80
+```
+
+It needs no index and no key, only git and the report. A shallow clone needs
+full history for the merge-base. Exit `1` means below the gate, `2` means it could not
+run. See [Patch coverage in CI](../layers/TEST_INTELLIGENCE.md#patch-coverage-in-ci).
+
### Changing provider or model
```bash
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md
index 815aeb619..faad4ab3d 100644
--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md
@@ -1,5 +1,5 @@
---
-description: Ingest or inspect test-coverage reports — LCOV, Cobertura/Clover, or coverage.py .coverage (builds the per-test map when contexts are present).
+description: Ingest or inspect test-coverage reports (LCOV, Cobertura, Clover, Go cover profiles, JaCoCo, repowise JSON, or coverage.py .coverage; builds the per-test map when contexts are present), or gate a change on its patch coverage in CI.
---
# Repowise Coverage
@@ -24,13 +24,31 @@ repowise coverage status
Handle `$ARGUMENTS`:
- "status" / "show" → `repowise coverage status`
-- A report path (`coverage.lcov`, `lcov.info`, `coverage.xml`, `.coverage`, …)
- → `repowise coverage add <path>`
+- A report path (`coverage.lcov`, `lcov.info`, `coverage.xml`, `coverage.out`,
+ `jacoco.xml`, `.coverage`, …) → `repowise coverage add <path>`
- "add" with no path → `repowise coverage add` (auto-discover common report paths)
- Multiple paths → `repowise coverage add <a> <b>` (merged; hit wins)
+- "check" / "gate" / "patch coverage" → `repowise coverage check [REVSPEC]`
Useful flags on `add`: `--verbose` for ingestion debug logs; `--path <dir>`
-to point at a different repo.
+to point at a different repo; `--format <parser>` to force a parser instead
+of auto-detecting from content.
+
+## Gating a change in CI
+
+`repowise coverage check` reports patch coverage: the share of a change's
+executable lines the tests ran. It needs no index, so it runs in CI.
+REVSPEC is the change (`origin/main...HEAD`, `base..head`, or one commit;
+defaults to the default branch `...HEAD`).
+```
+repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80
+```
+- `--report FILE` (repeatable; discovered from the usual locations when omitted)
+- `--fail-under PCT` exits 1 below the threshold (defaults to
+ `coverage.fail_under` in `.repowise/config.yaml`)
+- `--report-format <parser>` forces a parser
+- `--format github` writes annotations plus a step summary in GitHub Actions;
+ `--format json|markdown` for other consumers
## Notes
diff --git a/packages/cli/src/repowise/cli/ci.py b/packages/cli/src/repowise/cli/ci.py
new file mode 100644
index 000000000..ca787e5c7
--- /dev/null
+++ b/packages/cli/src/repowise/cli/ci.py
@@ -0,0 +1,65 @@
+"""The CLI side of CI gates: exit codes, output channels, the step summary.
+
+Every gating command (``coverage check``, ``doc-drift --check``, ...) exits
+with the same codes and writes to the same channels, so a pipeline treats them
+alike: ``1`` means the gate failed, ``2`` means it could not be evaluated
+(broken setup, not broken code). Content rendering stays with each feature;
+the workflow-command strings come from :mod:`repowise.core.ci.github`.
+"""
+
+from __future__ import annotations
+
+import os
+from collections.abc import Mapping
+from typing import Any, NoReturn
+
+import click
+
+#: The gate ran and the change failed it.
+EXIT_GATE_FAILED = 1
+#: The gate could not run: no report, unknown revision, bad config, ...
+EXIT_CANNOT_EVALUATE = 2
+
+#: Output formats every gating command offers; a command may add more (SARIF).
+CI_FORMATS = ("table", "json", "markdown", "github")
+
+
+def ci_notices(fmt: str) -> Any:
+ """Where asides go: stdout for the table, stderr for every machine format."""
+ from repowise.cli.helpers import console, err_console
+
+ return console if fmt == "table" else err_console
+
+
+def cannot_evaluate(fmt: str, code: str, message: str) -> NoReturn:
+ """Report why the gate could not run and exit :data:`EXIT_CANNOT_EVALUATE`.
+
+ ``json`` gets a ``{"error", "message"}`` document on stdout, ``github`` an
+ ``::error::`` line; the message always reaches stderr for a human.
+ """
+ from rich.markup import escape
+
+ from repowise.cli.helpers import err_console
+ from repowise.cli.output import emit_json
+ from repowise.core.ci.github import error
+
+ if fmt == "json":
+ emit_json({"error": code, "message": message})
+ elif fmt == "github":
+ click.echo(error(message))
+ if fmt != "json":
+ err_console.print(f"[red]{escape(message)}[/red]")
+ raise click.exceptions.Exit(EXIT_CANNOT_EVALUATE)
+
+
+def append_step_summary(markdown: str, *, env: Mapping[str, str] | None = None) -> bool:
+ """Add *markdown* to the GitHub Actions job summary; ``False`` when not in Actions."""
+ target = (os.environ if env is None else env).get("GITHUB_STEP_SUMMARY")
+ if not target:
+ return False
+ try:
+ with open(target, "a", encoding="utf-8") as fh:
+ fh.write(markdown.rstrip("\n") + "\n")
+ except OSError:
+ return False
+ return True
diff --git a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
new file mode 100644
index 000000000..86e85afe9
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
@@ -0,0 +1,271 @@
+"""``repowise coverage check``: gate a change on its patch coverage, in CI.
+
+Needs git and a coverage report, nothing else: no index, no API key. Report
+paths are resolved against ``git ls-files``, so a file added by the change
+resolves too (an index cached from the base branch would not know it).
+
+Exit codes and output channels are the shared CI ones (:mod:`repowise.cli.ci`):
+0 when the gate passes or there is nothing to judge, 1 when patch coverage is
+below ``--fail-under``, 2 when the check could not run (no report, unreadable
+report, unknown revision, missing history, bad config).
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import click
+from rich.markup import escape
+
+from repowise.cli.ci import (
+ CI_FORMATS,
+ EXIT_GATE_FAILED,
+ append_step_summary,
+ cannot_evaluate,
+ ci_notices,
+)
+from repowise.cli.helpers import console
+from repowise.cli.output import emit_json, format_option
+from repowise.core.analysis.health.coverage import PARSERS as COVERAGE_PARSERS
+
+
+class _CannotEvaluateError(Exception):
+ """The check could not run; *code* names why, the message what to do instead."""
+
+ def __init__(self, code: str, message: str) -> None:
+ super().__init__(message)
+ self.code = code
+
+
[email protected]("revspec", required=False, default=None)
+ "--report",
+ "reports",
+ multiple=True,
+ type=click.Path(exists=True, dir_okay=False),
+ help="Coverage report to read (repeatable; merged hit-wins). "
+ "Defaults to coverage.paths in .repowise/config.yaml, else discovery.",
+)
+ "--report-format",
+ type=click.Choice(list(COVERAGE_PARSERS)),
+ default=None,
+ help="Force a report parser instead of detecting it from the content.",
+)
+ "--fail-under",
+ type=click.FloatRange(0, 100),
+ default=None,
+ help="Exit 1 when patch coverage is below this percentage. "
+ "Defaults to coverage.fail_under in .repowise/config.yaml.",
+)
+ "--path",
+ "repo",
+ default=None,
+ help="A path inside the repository (defaults to cwd). Config is read at the repo root.",
+)
+@format_option(
+ choices=CI_FORMATS,
+ help="Output format. ``github`` writes annotations to stdout and the "
+ "markdown summary to $GITHUB_STEP_SUMMARY when set.",
+)
+def coverage_check(
+ revspec: str | None,
+ reports: tuple[str, ...],
+ report_format: str | None,
+ fail_under: float | None,
+ repo: str | None,
+ fmt: str,
+) -> None:
+ """Gate a change on its patch coverage (no index needed, built for CI).
+
+ Patch coverage is the share of the change's executable lines the tests
+ ran. REVSPEC is the change: ``origin/main...HEAD`` (what the branch did
+ since it forked, the pull-request view), ``base..head``, or one commit.
+ Without it, the base comes from the CI's pull-request variables (GitHub,
+ GitLab, Jenkins, Bitbucket), else the remote's default branch.
+
+ Examples:
+
+ repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80
+ repowise coverage check --report coverage.out --format github
+ repowise coverage check HEAD --format json
+ """
+ notices = ci_notices(fmt)
+ try:
+ pc = _evaluate(revspec, reports, report_format, fail_under, repo, notices)
+ except _CannotEvaluateError as exc:
+ cannot_evaluate(fmt, exc.code, str(exc))
+ _emit(pc, fmt)
+ if pc.gate == "fail":
+ raise click.exceptions.Exit(EXIT_GATE_FAILED)
+
+
+def _evaluate(revspec, reports, report_format, fail_under, repo, notices):
+ from repowise.core.analysis.patch_coverage import patch_coverage_from_resolved
+
+ root = _repo_root(repo)
+ cfg = _coverage_config(root, validate_threshold=fail_under is None)
+ report_paths = [Path(p) for p in reports] or cfg.report_paths(root)
+ if not report_paths:
+ raise _CannotEvaluateError(
+ "no_report",
+ "No coverage report found. Pass one with --report (lcov.info, coverage.xml, "
+ "coverage.out, jacoco.xml, ...) or set coverage.paths in .repowise/config.yaml."
+ )
+ if notices is console:
+ # Machine formats carry the list in ``scope.reports`` instead.
+ notices.print(f"[dim]Reading {', '.join(escape(str(p)) for p in report_paths)}[/dim]")
+
+ changed, label = _changed_lines(str(root), revspec or _default_revspec(str(root)))
+ return patch_coverage_from_resolved(
+ changed,
+ _resolve_reports(root, cfg, report_paths, report_format, notices),
+ threshold=fail_under if fail_under is not None else cfg.fail_under,
+ label=label,
+ reports=[str(p) for p in report_paths],
+ )
+
+
+def _resolve_reports(root, cfg, report_paths, report_format, notices):
+ """Parse the reports against the files git tracks, failing when nothing usable remains."""
+ from repowise.core import git_refs
+ from repowise.core.analysis.health.coverage import build_coverage_map
+
+ resolved, errors = build_coverage_map(
+ root,
+ report_paths,
+ set(git_refs.tracked_paths(str(root))),
+ coverage_format=report_format or cfg.format,
+ strip_prefix=cfg.strip_prefix,
+ path_prefix=cfg.path_prefix,
+ )
+ for path, err in errors:
+ notices.print(f"[yellow]{escape(path.name)}: {escape(err)}[/yellow]")
+ if len(errors) == len(report_paths):
+ raise _CannotEvaluateError(
+ "report_unreadable", "No coverage report could be read; see the messages above."
+ )
+ if not resolved.files:
+ raise _CannotEvaluateError(
+ "report_unmatched",
+ "No report path matched a file in this repository. If the report paths "
+ "carry a build prefix, set coverage.strip_prefix in .repowise/config.yaml."
+ )
+ if resolved.mapping_partial:
+ notices.print(
+ "[yellow]More than half the report paths did not match a file in this "
+ "repository; check coverage.strip_prefix / coverage.path_prefix.[/yellow]"
+ )
+ return resolved
+
+
+def _repo_root(repo: str | None) -> Path:
+ from repowise.core import git_refs
+
+ root = git_refs.toplevel(str(Path(repo or ".").resolve()))
+ if not root:
+ raise _CannotEvaluateError(
+ "not_a_git_repository", "Not a git repository (or git is not installed)."
+ )
+ return Path(root)
+
+
+def _coverage_config(root: Path, *, validate_threshold: bool):
+ from repowise.core.analysis.health.coverage import CoverageConfig
+ from repowise.core.repo_config import RepoConfigError, load_repo_config
+
+ try:
+ raw = load_repo_config(root)
+ except RepoConfigError as exc:
+ raise _CannotEvaluateError("config_invalid", str(exc)) from exc
+ cfg = CoverageConfig.from_repo_config(raw)
+ block = raw.get("coverage")
+ bad = isinstance(block, dict) and block.get("fail_under") is not None and cfg.fail_under is None
+ if validate_threshold and bad:
+ # A gate that silently stops gating is worse than no gate.
+ raise _CannotEvaluateError(
+ "config_invalid",
+ f"coverage.fail_under must be a number from 0 to 100, got {block['fail_under']!r}."
+ )
+ return cfg
+
+
+def _default_revspec(root: str) -> str:
+ from repowise.core.ci.base import BaseNotFoundError, default_revspec
+
+ try:
+ return default_revspec(root)
+ except BaseNotFoundError as exc:
+ raise _CannotEvaluateError("base_not_found", str(exc)) from exc
+
+
+def _changed_lines(root: str, revspec: str) -> tuple[dict[str, set[int]], str]:
+ import subprocess
+
+ from repowise.core.analysis.changed_lines import changed_lines
+
+ try:
+ return changed_lines(root, revspec)
+ except ValueError as exc:
+ raise _CannotEvaluateError(
+ "diff_failed",
+ f"Could not diff {revspec}: {exc}. A shallow CI clone needs the base "
+ "branch and enough history for a merge-base (fetch-depth: 0, or "
+ "git fetch --deepen)."
+ ) from exc
+ except (subprocess.SubprocessError, OSError) as exc:
+ raise _CannotEvaluateError("git_failed", f"Could not run git: {exc}") from exc
+
+
+def _emit(pc, fmt: str) -> None:
+ from repowise.core.analysis.patch_coverage import github_annotations, render_markdown
+
+ if fmt == "json":
+ emit_json(pc.to_dict())
+ elif fmt == "markdown":
+ click.echo(render_markdown(pc), nl=False)
+ elif fmt == "github":
+ for line in github_annotations(pc):
+ click.echo(line)
+ append_step_summary(render_markdown(pc))
+ _print_summary(pc)
+ else:
+ _print_summary(pc)
+ _print_table(pc)
+
+
+def _print_summary(pc) -> None:
+ from repowise.core.analysis.patch_coverage import headline, scope_line
+
+ console.print(escape(headline(pc, markdown=False)))
+ console.print(f"[dim]{escape(scope_line(pc, markdown=False))}[/dim]")
+
+
+def _print_table(pc) -> None:
+ from rich.table import Table
+
+ from repowise.core.analysis.patch_coverage import (
+ RANGE_LIMIT,
+ STATUS_TEXT,
+ attention_rows,
+ format_ranges,
+ )
+
+ rows = attention_rows(pc)
+ if not rows:
+ return
+ table = Table(show_edge=False, pad_edge=False)
+ table.add_column("File")
+ table.add_column("Covered", justify="right")
+ table.add_column("Uncovered changed lines")
+ for f in rows:
+ if f.status == "measured":
+ covered = f"{f.covered_line_count} of {f.coverable_line_count}"
+ gaps = format_ranges(f.uncovered_ranges, RANGE_LIMIT)
+ else:
+ covered, gaps = "", STATUS_TEXT[f.status]
+ table.add_row(escape(f.file_path), covered, gaps)
+ console.print(table)
diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
index 208ef7827..2e478ad22 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
@@ -15,6 +15,7 @@ from pathlib import Path
import click
from repowise.cli._setup import configure_cli_logging
+from repowise.cli.commands.coverage_check_cmd import coverage_check
from repowise.cli.helpers import (
console,
ensure_repowise_dir,
@@ -23,6 +24,7 @@ from repowise.cli.helpers import (
run_async,
)
from repowise.cli.output import emit_json, format_option, notice_console
+from repowise.core.analysis.health.coverage import PARSERS as COVERAGE_PARSERS
from repowise.core.workspace.update import get_head_commit
@@ -53,7 +55,10 @@ async def _repo_file_keys(session, repo_id: str) -> set[str]:
@click.group("coverage")
def coverage_group() -> None:
- """Ingest and inspect test-coverage reports."""
+ """Ingest and inspect test-coverage reports, and gate changes on them in CI."""
+
+
+coverage_group.add_command(coverage_check)
@coverage_group.command("add")
@@ -64,7 +69,7 @@ def coverage_group() -> None:
@click.option(
"--format",
"coverage_format",
- type=click.Choice(["lcov", "cobertura", "clover", "repowise-json"]),
+ type=click.Choice(list(COVERAGE_PARSERS)),
default=None,
help="Force a parser instead of auto-detecting from content.",
)
@@ -190,7 +195,7 @@ def coverage_add(
or getattr(repo_row, "head_commit", None)
)
- # --- Per-file aggregate coverage (lcov / cobertura / clover / json).
+ # --- Per-file aggregate coverage (any format in COVERAGE_PARSERS).
agg_matched = 0
unmapped = 0
mapping_partial = False
@@ -348,7 +353,7 @@ def _discover_context_reports(repo_path: Path) -> list[Path]:
"--path", "repo", default=None, help="Repo path (defaults to cwd / workspace primary)."
)
# Safe to spell this ``--format`` here: the ``--format`` that names an *input*
-# parser (lcov / cobertura / clover) lives on ``coverage add``, not on the
+# parser (a COVERAGE_PARSERS key) lives on ``coverage add``, not on the
# group, so the two never meet on one command line.
@format_option()
def coverage_status(repo: str | None, fmt: str) -> None:
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index 3b617b55a..004ec7eae 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -77,6 +77,7 @@ from repowise.cli.ui import (
should_offer_fast_mode,
)
from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
+from repowise.core.analysis.health.coverage import PARSERS as COVERAGE_PARSERS
from repowise.core.docs_mode import docs_mode_state_fields, resolve_docs_mode
from repowise.core.generation.languages import SUPPORTED_LANGUAGES
from repowise.core.generation.styles import DEFAULT_STYLE, list_styles, resolve_style
@@ -755,7 +756,7 @@ def _interactive_gate(
multiple=True,
metavar="PATH",
help=(
- "Test-coverage report(s) to ingest (lcov / Cobertura / Clover). "
+ f"Test-coverage report(s) to ingest ({' / '.join(COVERAGE_PARSERS)}). "
"Repeatable. When omitted, common locations (coverage/lcov.info, "
"**/cobertura.xml, ...) are auto-discovered. This is test coverage for "
"code-health, not a documentation-breadth knob."
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index af1e132a8..721ef42ae 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -118,15 +118,16 @@ async def _coverage_for_rescore(
from repowise.core.analysis.health.coverage import (
CoverageConfig,
build_coverage_map,
- discover_artifacts,
)
from repowise.core.persistence.crud import load_coverage_for_repo
from repowise.core.repo_config import load_repo_config
cfg = CoverageConfig.from_repo_config(load_repo_config(repo_path))
- if cfg.reingest_on_update and cfg.auto_discover:
- report_paths = discover_artifacts(repo_path, globs=cfg.artifacts or None)
+ # Without paths or discovery there is nothing to re-read, so the stored
+ # rows (e.g. from `coverage add`) stay authoritative.
+ if cfg.reingest_on_update and (cfg.paths or cfg.auto_discover):
+ report_paths = cfg.report_paths(repo_path)
if report_paths:
repo_keys = {pf.file_info.path for pf in parsed_files}
resolved, _errors = build_coverage_map(
diff --git a/packages/core/src/repowise/core/analysis/change_health/sources.py b/packages/core/src/repowise/core/analysis/change_health/sources.py
index b90e6f0c5..8b562bffd 100644
--- a/packages/core/src/repowise/core/analysis/change_health/sources.py
+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py
@@ -14,6 +14,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Protocol
+from ..change_risk.features import split_revspec
from ..changed_lines import FileDiff, parse_unified_diff
GIT_TIMEOUT_SECONDS = 120
@@ -157,8 +158,8 @@ class GitRevisionSource:
def resolve(self, revspec: str | None) -> RevisionPair:
if not revspec:
return self._resolve_working_tree()
- if ".." in revspec:
- return self._resolve_range(revspec)
+ if (parts := split_revspec(revspec)) is not None:
+ return self._resolve_range(*parts)
return self._resolve_commit(revspec)
def _sha(self, ref: str) -> str:
@@ -199,17 +200,15 @@ class GitRevisionSource:
self._changes(["diff", f"-M{_RENAME_SIMILARITY}%", base, head]),
)
- def _resolve_range(self, revspec: str) -> RevisionPair:
- base, _, head = revspec.partition("..")
- three_dot = head.startswith(".")
- head = head.lstrip(".") or "HEAD"
- base = base or "HEAD"
+ def _resolve_range(self, base: str, sep: str, head: str) -> RevisionPair:
base_sha = self._sha(base)
head_sha = self._sha(head)
- if three_dot:
- base_sha = (
- _git(["merge-base", base, head], self.repo_path, check=False).strip() or base_sha
- )
+ if sep == "...":
+ # Same meaning as change risk and changed lines: no merge-base (a
+ # shallow clone) is an error, not a silent two-dot diff.
+ base_sha = _git(["merge-base", base, head], self.repo_path, check=False).strip()
+ if not base_sha:
+ raise ValueError(f"No merge-base between {base!r} and {head!r}.")
return RevisionPair(
base,
head,
diff --git a/packages/core/src/repowise/core/analysis/change_review/models.py b/packages/core/src/repowise/core/analysis/change_review/models.py
index 120d1ebda..2b32bab01 100644
--- a/packages/core/src/repowise/core/analysis/change_review/models.py
+++ b/packages/core/src/repowise/core/analysis/change_review/models.py
@@ -26,6 +26,7 @@ from ..change_contracts import ContractImpact
from ..change_health.models import ChangeHealthDelta, RevisionId
from ..change_health.sources import FileChange
from ..change_risk import ChangeRiskResult, change_risk_payload
+from ..changed_lines import line_ranges
from ..independent_changes import IndependentChanges
from ..review_directive import EvidenceState, ReviewDirective
@@ -59,17 +60,6 @@ class LaneState:
return {"state": self.state, "reason": self.reason}
-def _collapse(lines: set[int]) -> tuple[tuple[int, int], ...]:
- """Adjacent line numbers as inclusive spans: ``{1,2,3,7}`` -> ``((1,3),(7,7))``."""
- spans: list[tuple[int, int]] = []
- for line in sorted(lines):
- if spans and line == spans[-1][1] + 1:
- spans[-1] = (spans[-1][0], line)
- else:
- spans.append((line, line))
- return tuple(spans)
-
-
@dataclass(frozen=True, slots=True)
class ChangeManifestEntry:
"""One changed path, as every lane of the review counts it.
@@ -104,7 +94,7 @@ class ChangeManifestEntry:
head_path=change.head_path,
status=change.status,
diff_reliability=change.diff_reliability,
- added_ranges=_collapse(change.added_lines),
+ added_ranges=line_ranges(change.added_lines),
)
def as_dict(self) -> dict[str, Any]:
diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.py
index d1cd4cf7d..72dbbc986 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/features.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py
@@ -62,6 +62,20 @@ class ChangeFeatures:
GIT_TIMEOUT_SECONDS = 60
+def split_revspec(revspec: str) -> tuple[str, str, str] | None:
+ """Split ``base..head`` / ``base...head`` into ``(base, sep, head)``.
+
+ ``None`` for a single revision. An empty side means ``HEAD``, as in git. Three dots
+ keep their git meaning (diff from the merge-base), so every reader of a
+ range measures the same change.
+ """
+ sep = "..." if "..." in revspec else ".." if ".." in revspec else None
+ if sep is None:
+ return None
+ base, _, head = revspec.partition(sep)
+ return base or "HEAD", sep, head or "HEAD"
+
+
def _git(args: list[str], cwd: str, *, check: bool = True) -> str:
# stdin=DEVNULL: on MCP stdio transport a child that inherits the JSON-RPC
# pipe handles can wedge the session (same failure mode _meta.py guards
@@ -367,14 +381,15 @@ def extract_range_features(
*,
extensions: tuple[str, ...] = (),
exclude_patterns: tuple[str, ...] = (),
+ sep: str = "..",
) -> ChangeFeatures:
"""Extract features for a ``base..head`` range scored as one change.
- Diff size/diffusion come from the cumulative ``base..head`` diff; author and
- fix-flag come from the head commit; experience is the head author's prior
- commit count at *base*.
+ Diff size/diffusion come from the cumulative ``base{sep}head`` diff (``...``
+ diffs from the merge-base); author and fix-flag come from the head commit;
+ experience is the head author's prior commit count at *base*.
"""
- numstat = _git(["diff", "--numstat", f"{base}..{head}"], repo_path)
+ numstat = _git(["diff", "--numstat", f"{base}{sep}{head}"], repo_path)
la, ld, nf, dirs, subs, per_file, files = _accumulate_numstat(
numstat, extensions, exclude_patterns
)
@@ -395,6 +410,6 @@ def extract_range_features(
is_fix=is_fix,
author=author,
subject=subject,
- ref=f"{base}..{head}",
+ ref=f"{base}{sep}{head}",
file_churn=tuple(files),
)
diff --git a/packages/core/src/repowise/core/analysis/change_risk/service.py b/packages/core/src/repowise/core/analysis/change_risk/service.py
index d9fc44bca..d5ddc34eb 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/service.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py
@@ -16,6 +16,7 @@ from .features import (
extract_commit_features,
extract_range_features,
extract_worktree_features,
+ split_revspec,
working_tree_is_dirty,
)
from .fix_history import (
@@ -162,12 +163,15 @@ def score_live_change(
if working_tree:
features = uncommitted
anchor, excluded_ref = "HEAD", ""
- elif ".." in target:
- base, _, head = target.partition("..")
- # Strip leading dot(s) so three-dot syntax (main...HEAD) gives a valid anchor ref.
- head = head.lstrip(".") or "HEAD"
+ elif (parts := split_revspec(target)) is not None:
+ base, sep, head = parts
features = extract_range_features(
- repo_path, base, head, extensions=extensions, exclude_patterns=effective_excludes
+ repo_path,
+ base,
+ head,
+ extensions=extensions,
+ exclude_patterns=effective_excludes,
+ sep=sep,
)
# Fix history is read at the fork point, not at ``base``'s tip: with
# three-dot syntax the diff starts at the merge-base, so base's later
diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.py
index d3287624e..8d65a3651 100644
--- a/packages/core/src/repowise/core/analysis/changed_lines.py
+++ b/packages/core/src/repowise/core/analysis/changed_lines.py
@@ -21,9 +21,11 @@ feature extractor (no new dependency, deterministic).
from __future__ import annotations
import re
+import subprocess
+from collections.abc import Iterable
from dataclasses import dataclass, field
-from .change_risk.features import _git
+from .change_risk.features import _git, split_revspec
# ``@@ -a,b +c,d @@`` - both sides. ``b``/``d`` default to 1 when omitted; a
# count of 0 means "nothing on that side" (pure insertion / pure deletion).
@@ -116,6 +118,17 @@ def parse_unified_diff(diff: str) -> dict[str, FileDiff]:
return result
+def line_ranges(lines: Iterable[int]) -> tuple[tuple[int, int], ...]:
+ """Adjacent line numbers as inclusive spans: ``{1,2,3,7}`` -> ``((1,3),(7,7))``."""
+ spans: list[tuple[int, int]] = []
+ for line in sorted(lines):
+ if spans and line == spans[-1][1] + 1:
+ spans[-1] = (spans[-1][0], line)
+ else:
+ spans.append((line, line))
+ return tuple(spans)
+
+
def _parse_unified_diff(diff: str) -> dict[str, set[int]]:
"""New-side changed lines per file - the coverage-intersection view.
@@ -143,8 +156,8 @@ def changed_lines(
) -> tuple[dict[str, set[int]], str]:
"""Return ``({file: changed_lines}, label)`` for a change.
- *revspec* mirrors ``repowise risk``: ``base..head`` is a range, a bare ref
- is a single commit. With no *revspec* (or *staged*), the staged diff
+ *revspec* mirrors ``repowise risk``: ``base..head`` is a range,
+ ``base...head`` the change since the two forked, a bare ref a single commit. With no *revspec* (or *staged*), the staged diff
(``git diff --cached``) is used - the "what will I commit" case.
*working_tree* widens that to everything ``HEAD`` does not have, staged or
not, matching what change risk counts for an uncommitted change. *label*
@@ -162,17 +175,37 @@ def changed_lines(
diff = _git(["diff", "--cached", "--unified=0"], repo_path)
return _parse_unified_diff(diff), "staged changes"
- if ".." in revspec:
- base, _, head = revspec.partition("..")
- head = head or "HEAD"
+ if (parts := split_revspec(revspec)) is not None:
+ # ``base...head`` is what a pull request changed: git diffs from the
+ # merge-base, so commits that landed on base meanwhile stay out.
+ base, sep, head = parts
_verify_ref(repo_path, base)
_verify_ref(repo_path, head)
- diff = _git(["diff", "--unified=0", f"{base}..{head}"], repo_path)
- return _parse_unified_diff(diff), f"{base}..{head}"
+ label = f"{base}{sep}{head}"
+ return _parse_unified_diff(_diff(repo_path, ["diff", "--unified=0", label])), label
_verify_ref(repo_path, revspec)
+ if _is_shallow_root(repo_path, revspec):
+ # A shallow clone's oldest commit has its parents cut off, so git would
+ # diff it against the empty tree and every line would read as changed.
+ raise ValueError(f"{revspec!r} has no parent in this shallow clone; fetch more history")
# --format= drops the commit message so only the diff body is parsed.
# -m --first-parent matches what change risk counts on a merge; without it
# git's combined diff emits nothing at all and a merged PR reads as empty.
- diff = _git(["show", "--unified=0", "--format=", "-m", "--first-parent", revspec], repo_path)
- return _parse_unified_diff(diff), revspec
+ args = ["show", "--unified=0", "--format=", "-m", "--first-parent", revspec]
+ return _parse_unified_diff(_diff(repo_path, args)), revspec
+
+
+def _diff(repo_path: str, args: list[str]) -> str:
+ """Run a diff, turning git's refusal (e.g. no merge-base) into ``ValueError``."""
+ try:
+ return _git(args, repo_path)
+ except subprocess.CalledProcessError as exc:
+ detail = (exc.stderr or "").strip().splitlines()
+ raise ValueError(detail[-1] if detail else f"git {args[0]} failed") from exc
+
+
+def _is_shallow_root(repo_path: str, rev: str) -> bool:
+ if _git(["rev-parse", "--is-shallow-repository"], repo_path, check=False).strip() != "true":
+ return False
+ return not _git(["rev-parse", "--verify", "--quiet", f"{rev}^"], repo_path, check=False).strip()
diff --git a/packages/core/src/repowise/core/analysis/health/README.md b/packages/core/src/repowise/core/analysis/health/README.md
index e200cbac1..064493eb0 100644
--- a/packages/core/src/repowise/core/analysis/health/README.md
+++ b/packages/core/src/repowise/core/analysis/health/README.md
@@ -150,7 +150,9 @@ orchestrator (falls back to the top-level directory). The MCP tool
- `complexity/` — tree-sitter AST walker. CCN, max nesting, cognitive,
parameter count, bumps. Single AST pass per file. Writes
`Symbol.complexity_estimate` as a side effect.
-- `coverage/` — LCOV / Cobertura / Clover parsers + test-file heuristic.
+- `coverage/` — coverage report parsers (LCOV, Cobertura, Clover, Go cover
+ profiles, JaCoCo, repowise JSON; `coverage.PARSERS` is the registry) +
+ test-file heuristic.
- `duplication/` — Rabin–Karp over tree-sitter tokens. Co-change correlation
via `git_meta_map[path]["co_change_partners_json"]`.
- `biomarkers/` — one detector per file. Implements the `Biomarker`
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/README.md b/packages/core/src/repowise/core/analysis/health/coverage/README.md
index ce25695cd..c4fd026a5 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/README.md
+++ b/packages/core/src/repowise/core/analysis/health/coverage/README.md
@@ -17,10 +17,17 @@ from repowise.core.analysis.health.coverage import (
- `parse(text, format=None)` → `CoverageReport`. Auto-detects format
when `format` is ``None``; pass an explicit ``"lcov" | "cobertura" |
- "clover" | "repowise-json"`` to override.
+ "clover" | "repowise-json" | "go-coverprofile" | "jacoco"`` to override
+ (`detector.PARSERS` is the registry).
- `parse_lcov(text)`, `parse_cobertura(text)`, `parse_clover(text)`,
- `parse_repowise_json(text)` — format-specific entry points (used by
+ `parse_repowise_json(text)`, `parse_go_coverprofile(text)`,
+ `parse_jacoco(text)` — format-specific entry points (used by
tests / programmatic callers).
+- Go cover profiles (`go test -coverprofile`) are expanded from statement
+ blocks to lines, so their percentages are line-based, not Go's statement
+ percentage. JaCoCo XML is read from per-line `<sourcefile>` data (lines
+ and branches); package paths such as `com/foo/Bar.java` and Go module
+ paths are mapped to repo files by suffix matching.
### Repowise normalized JSON (`repowise-coverage-v1`)
@@ -63,7 +70,9 @@ writes paths relative to its own `<source>` root — so we reconcile them.
- `discover_artifacts(repo_root, globs=None)` — glob the filesystem for
report files (`coverage/lcov.info`, `**/cobertura.xml`, ...). The report
dirs are excluded from the indexed file set, so discovery hits the FS
- directly; results are pruned of vendored dirs and capped.
+ directly; results are pruned of vendored dirs and capped. A pruned dir
+ spelled literally in a pattern (Gradle's `build/reports/jacoco/**/*.xml`)
+ is searched; one reached only through `**` is not.
- `resolve_reports(reports, repo_keys, ...)` — map each report path to a
canonical key by **longest trailing-segment overlap**, refusing to guess
on a true tie. Merges multiple reports hit-wins. Returns a
@@ -96,7 +105,8 @@ coverage:
## Inputs
- A raw coverage report (the contents of `coverage.lcov`, a Cobertura
- `coverage.xml`, or a Clover `clover.xml`).
+ `coverage.xml`, a Clover `clover.xml`, a Go `coverage.out`, or a JaCoCo
+ `jacoco.xml`).
- For the test-file heuristic: a POSIX-style relative path and optionally
the file contents (used to detect framework imports for files that
don't follow naming conventions).
@@ -110,8 +120,9 @@ coverage:
## Extension points
-- Add a parser: drop a new file (e.g. `jacoco.py`), return a
- `CoverageReport`, and route to it from `detector.parse`.
+- Add a parser: drop a new file, return a `CoverageReport` built with
+ `model.file_coverage`, register it in `detector.PARSERS` and add a sniff
+ rule to `detector.detect_format`.
- Tune the test-file heuristic: edit the module-level `_TEST_*` tuples in
`detector.py`. Keep the rule deterministic (no globs that require
recursion).
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
index 91a8521b3..c278d8dde 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
@@ -17,7 +17,7 @@ from .decay import (
decay_since,
measurement_ref,
)
-from .detector import detect_format, is_test_file, paired_test_file, parse
+from .detector import PARSERS, detect_format, is_test_file, paired_test_file, parse
from .discovery import (
CoverageConfig,
ResolvedCoverage,
@@ -28,16 +28,20 @@ from .discovery import (
resolve_reports,
resolve_test_reports,
)
+from .goprofile import parse_go_coverprofile
+from .jacoco import parse_jacoco
from .lcov import parse_lcov
from .model import (
ContextCoverageReport,
CoverageReport,
FileCoverage,
TestCoverage,
+ file_coverage,
)
from .repowise_json import parse_repowise_json
__all__ = [
+ "PARSERS",
"STALE_DRIFT_PCT",
"STALE_MIN_MEASURED",
"ContextCoverageReport",
@@ -53,6 +57,7 @@ __all__ = [
"decay_since",
"detect_format",
"discover_artifacts",
+ "file_coverage",
"is_test_file",
"measurement_ref",
"normalize_report_path",
@@ -62,6 +67,8 @@ __all__ = [
"parse_cobertura",
"parse_contexts_file",
"parse_coverage_sqlite",
+ "parse_go_coverprofile",
+ "parse_jacoco",
"parse_lcov",
"parse_lcov_contexts",
"parse_repowise_json",
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/clover.py b/packages/core/src/repowise/core/analysis/health/coverage/clover.py
index 2c79583f9..62444ec82 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/clover.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/clover.py
@@ -24,15 +24,13 @@ is derived from ``type="cond"`` lines (truecount + falsecount).
from __future__ import annotations
from pathlib import Path
-from xml.etree import ElementTree as ET
-from .model import CoverageReport, FileCoverage
+from .model import CoverageReport, FileCoverage, file_coverage, parse_xml
def parse_clover(text: str) -> CoverageReport:
- try:
- root = ET.fromstring(text)
- except ET.ParseError:
+ root = parse_xml(text)
+ if root is None:
return CoverageReport(source_format="clover", files=[])
files: list[FileCoverage] = []
@@ -40,13 +38,11 @@ def parse_clover(text: str) -> CoverageReport:
path = file_el.get("path") or file_el.get("name") or ""
if not path:
continue
- norm = Path(path).as_posix()
covered: set[int] = set()
- total: set[int] = set()
+ coverable: set[int] = set()
branches_found = 0
branches_hit = 0
- has_branches = False
for line in file_el.iter("line"):
try:
@@ -55,16 +51,14 @@ def parse_clover(text: str) -> CoverageReport:
continue
if line_no <= 0:
continue
- ltype = line.get("type", "stmt")
try:
count = int(line.get("count", "0"))
except ValueError:
count = 0
- total.add(line_no)
+ coverable.add(line_no)
if count > 0:
covered.add(line_no)
- if ltype == "cond":
- has_branches = True
+ if line.get("type", "stmt") == "cond":
try:
tc = int(line.get("truecount", "0"))
fc = int(line.get("falsecount", "0"))
@@ -73,21 +67,13 @@ def parse_clover(text: str) -> CoverageReport:
branches_found += 2
branches_hit += (1 if tc > 0 else 0) + (1 if fc > 0 else 0)
- total_n = len(total)
- line_pct = (len(covered) / total_n * 100.0) if total_n else 0.0
- branch_pct: float | None
- if has_branches and branches_found:
- branch_pct = branches_hit / branches_found * 100.0
- else:
- branch_pct = None
-
files.append(
- FileCoverage(
- file_path=norm,
- line_coverage_pct=round(line_pct, 2),
- branch_coverage_pct=round(branch_pct, 2) if branch_pct is not None else None,
- covered_lines=sorted(covered),
- total_coverable_lines=total_n,
+ file_coverage(
+ Path(path).as_posix(),
+ covered,
+ coverable,
+ branches_found=branches_found,
+ branches_hit=branches_hit,
)
)
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py b/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py
index 08e3d1f79..98072f890 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py
@@ -27,38 +27,27 @@ same file (one per top-level class).
from __future__ import annotations
import re
+from dataclasses import dataclass, field
from pathlib import Path
-from xml.etree import ElementTree as ET
-from .model import CoverageReport, FileCoverage
+from .model import CoverageReport, file_coverage, parse_xml
_CONDITION_RE = re.compile(r"\((\d+)\s*/\s*(\d+)\)")
def parse_cobertura(text: str) -> CoverageReport:
- try:
- root = ET.fromstring(text)
- except ET.ParseError:
+ root = parse_xml(text)
+ if root is None:
return CoverageReport(source_format="cobertura", files=[])
- # Aggregate by filename.
- per_file: dict[str, dict[str, object]] = {}
+ # Aggregate by filename: several <class> rows can share one file.
+ per_file: dict[str, _FileLines] = {}
for cls in root.iter("class"):
filename = cls.get("filename") or ""
if not filename:
continue
- norm = Path(filename).as_posix()
- bucket = per_file.setdefault(
- norm,
- {
- "covered_lines": set(),
- "total_lines": set(),
- "branches_found": 0,
- "branches_hit": 0,
- "has_branches": False,
- },
- )
+ bucket = per_file.setdefault(Path(filename).as_posix(), _FileLines())
for line in cls.iter("line"):
try:
line_no = int(line.get("number", "0"))
@@ -67,45 +56,35 @@ def parse_cobertura(text: str) -> CoverageReport:
continue
if line_no <= 0:
continue
- assert isinstance(bucket["total_lines"], set)
- assert isinstance(bucket["covered_lines"], set)
- bucket["total_lines"].add(line_no)
+ bucket.coverable.add(line_no)
if hits > 0:
- bucket["covered_lines"].add(line_no)
+ bucket.covered.add(line_no)
if line.get("branch") == "true":
- bucket["has_branches"] = True
- cc = line.get("condition-coverage", "")
- m = _CONDITION_RE.search(cc)
+ m = _CONDITION_RE.search(line.get("condition-coverage", ""))
if m:
- hit, total = int(m.group(1)), int(m.group(2))
- bucket["branches_found"] = int(bucket["branches_found"]) + total
- bucket["branches_hit"] = int(bucket["branches_hit"]) + hit
+ bucket.branches_hit += int(m.group(1))
+ bucket.branches_found += int(m.group(2))
else:
- bucket["branches_found"] = int(bucket["branches_found"]) + 2
- bucket["branches_hit"] = int(bucket["branches_hit"]) + (2 if hits > 0 else 0)
+ bucket.branches_found += 2
+ bucket.branches_hit += 2 if hits > 0 else 0
- files: list[FileCoverage] = []
- for path, bucket in per_file.items():
- covered = bucket["covered_lines"]
- total_set = bucket["total_lines"]
- assert isinstance(covered, set)
- assert isinstance(total_set, set)
- total = len(total_set)
- hit = len(covered)
- line_pct = (hit / total * 100.0) if total else 0.0
- branch_pct: float | None
- bf = int(bucket["branches_found"])
- bh = int(bucket["branches_hit"])
- branch_pct = bh / bf * 100.0 if bucket["has_branches"] and bf else None
- files.append(
- FileCoverage(
- file_path=path,
- line_coverage_pct=round(line_pct, 2),
- branch_coverage_pct=round(branch_pct, 2) if branch_pct is not None else None,
- covered_lines=sorted(covered),
- total_coverable_lines=total,
- )
+ files = [
+ file_coverage(
+ path,
+ b.covered,
+ b.coverable,
+ branches_found=b.branches_found,
+ branches_hit=b.branches_hit,
)
-
+ for path, b in per_file.items()
+ ]
return CoverageReport(source_format="cobertura", files=files)
+
+
+@dataclass
+class _FileLines:
+ covered: set[int] = field(default_factory=set)
+ coverable: set[int] = field(default_factory=set)
+ branches_found: int = 0
+ branches_hit: int = 0
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/detector.py b/packages/core/src/repowise/core/analysis/health/coverage/detector.py
index 4656a4a18..ce3950303 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/detector.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/detector.py
@@ -1,16 +1,25 @@
-"""Format auto-detection + test-file heuristic.
+"""Coverage parser registry, format auto-detection, and test-file heuristics.
+
+:data:`PARSERS` is the one list of supported report formats: dispatch, the CLI
+``--format`` choice and user-facing format lists all read it, so a new parser
+is one module plus one registry entry.
``repowise coverage add <path>`` accepts a report without a format flag in
-the common case. We sniff the content to decide which parser to dispatch to.
+the common case. We sniff the content (never the filename) to decide which
+parser to dispatch to.
-Sniffing rules (cheap, deterministic):
+Sniffing rules (cheap, deterministic), after stripping a UTF-8 BOM:
+- Repowise JSON starts with ``{`` and names ``repowise-coverage`` or
+ ``line_coverage_pct``.
- LCOV files start with ``TN:`` or ``SF:`` on the first non-blank line
(and the format is line-oriented).
+- Clover XML has a ``<coverage`` root with a ``<project>`` child.
- Cobertura XML has a ``<coverage`` root and a ``<packages>`` child (or
is referenced by the ``coverage`` DTD).
-- Clover XML has a ``<coverage generated=`` root with a ``<project>``
- child.
+- Go cover profiles start with ``mode:`` on the first non-blank line.
+- JaCoCo XML declares the ``-//JACOCO//DTD`` doctype or has a ``<report``
+ root (and no ``<coverage`` element).
If detection is ambiguous, callers can pass ``coverage add --format`` to
override.
@@ -19,11 +28,14 @@ override.
from __future__ import annotations
import re
+from collections.abc import Callable
from pathlib import Path
from ....test_paths import is_test_related_path
from .clover import parse_clover
from .cobertura import parse_cobertura
+from .goprofile import parse_go_coverprofile
+from .jacoco import parse_jacoco
from .lcov import parse_lcov
from .model import CoverageReport
from .repowise_json import parse_repowise_json
@@ -45,42 +57,94 @@ _FRAMEWORK_IMPORTS = (
)
-def detect_format(text: str) -> str | None:
- """Return ``"lcov" | "cobertura" | "clover"`` or ``None``."""
- sample = text.lstrip()[:2048]
- if not sample:
- return None
- if sample.startswith("{"):
- # Repowise normalized JSON — tagged by ``format`` or recognizable by its
- # per-file coverage keys. Checked before LCOV/XML since none start with ``{``.
- if "repowise-coverage" in sample or "line_coverage_pct" in sample:
- return "repowise-json"
- return None
- if sample.startswith(("TN:", "SF:")) or _LCOV_LINE_RE.match(sample):
- return "lcov"
- if sample.startswith("<?xml") or sample.startswith("<"):
- if "<coverage" in sample and "<project" in sample[:4096]:
- return "clover"
- if "<coverage" in sample and ("<packages" in sample[:4096] or "line-rate" in sample[:4096]):
- return "cobertura"
- return None
+#: Report format -> parser. Insertion order is the order formats are listed
+#: to users.
+PARSERS: dict[str, Callable[[str], CoverageReport]] = {
+ "lcov": parse_lcov,
+ "cobertura": parse_cobertura,
+ "clover": parse_clover,
+ "repowise-json": parse_repowise_json,
+ "go-coverprofile": parse_go_coverprofile,
+ "jacoco": parse_jacoco,
+}
+
+#: Accepted spellings that are not canonical format names.
+_ALIASES = {"json": "repowise-json"}
+
+#: A UTF-8 byte-order mark decodes to this; some Windows tools prepend it.
+_BOM = "\ufeff"
_LCOV_LINE_RE = re.compile(r"^(TN|SF|DA|BRDA|LF|LH|BRF|BRH):", re.MULTILINE)
+# Sniffers take the BOM-stripped, left-stripped 2048-char sample. The leading
+# character already separates JSON (``{``), XML (``<``) and the line formats,
+# so only the XML sniffers depend on their relative order.
+
+
+def _is_repowise_json(sample: str) -> bool:
+ # Tagged by ``format`` or recognizable by its per-file coverage keys.
+ return sample.startswith("{") and (
+ "repowise-coverage" in sample or "line_coverage_pct" in sample
+ )
+
+
+def _is_lcov(sample: str) -> bool:
+ return sample.startswith(("TN:", "SF:")) or _LCOV_LINE_RE.match(sample) is not None
+
+
+def _is_go_coverprofile(sample: str) -> bool:
+ return sample.startswith("mode:")
+
+
+def _is_jacoco_doctype(sample: str) -> bool:
+ return sample.startswith("<") and "-//JACOCO//DTD" in sample
+
+
+def _is_clover(sample: str) -> bool:
+ return sample.startswith("<") and "<coverage" in sample and "<project" in sample
+
+
+def _is_cobertura(sample: str) -> bool:
+ return (
+ sample.startswith("<")
+ and "<coverage" in sample
+ and ("<packages" in sample or "line-rate" in sample)
+ )
+
+
+def _is_jacoco_report(sample: str) -> bool:
+ return sample.startswith("<") and "<report" in sample and "<coverage" not in sample
+
+
+#: ``(format, sniffer)`` in priority order; the first match wins.
+_SNIFFERS: tuple[tuple[str, Callable[[str], bool]], ...] = (
+ ("repowise-json", _is_repowise_json),
+ ("lcov", _is_lcov),
+ ("go-coverprofile", _is_go_coverprofile),
+ ("jacoco", _is_jacoco_doctype),
+ ("clover", _is_clover),
+ ("cobertura", _is_cobertura),
+ ("jacoco", _is_jacoco_report),
+)
+
+
+def detect_format(text: str) -> str | None:
+ """Return a :data:`PARSERS` key for *text*, or ``None`` when unrecognised."""
+ sample = text.lstrip(_BOM).lstrip()[:2048]
+ if not sample:
+ return None
+ return next((fmt for fmt, sniff in _SNIFFERS if sniff(sample)), None)
+
+
def parse(text: str, *, format: str | None = None) -> CoverageReport:
"""Parse coverage text, auto-detecting format when not provided."""
fmt = format or detect_format(text)
- if fmt == "lcov":
- return parse_lcov(text)
- if fmt == "cobertura":
- return parse_cobertura(text)
- if fmt == "clover":
- return parse_clover(text)
- if fmt in ("repowise-json", "json"):
- return parse_repowise_json(text)
- return CoverageReport(source_format="unknown")
+ parser = PARSERS.get(_ALIASES.get(fmt, fmt)) if fmt else None
+ if parser is None:
+ return CoverageReport(source_format="unknown")
+ return parser(text.lstrip(_BOM))
def is_test_file(rel_path: str, source: str | None = None) -> bool:
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
index 65e4b30a9..e1d8a48a8 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
@@ -29,7 +29,7 @@ from dataclasses import dataclass, field
from itertools import chain
from pathlib import Path
-from repowise.core.fs_walk import PRUNED_DIRS, WalkSnapshot
+from repowise.core.fs_walk import PRUNED_DIRS, WalkSnapshot, iter_glob
from .detector import parse as parse_coverage
from .model import ContextCoverageReport, CoverageReport, FileCoverage, TestCoverage
@@ -52,13 +52,21 @@ DEFAULT_DISCOVERY_GLOBS: tuple[str, ...] = (
"**/clover.xml",
"target/llvm-cov/**/*.lcov",
"target/nextest/**/*.xml",
+ "coverage.out",
+ "cover.out",
+ "target/site/jacoco/jacoco.xml",
+ "**/target/site/jacoco*/jacoco.xml",
+ # Root module only: ``build`` is pruned under ``**``, so a nested
+ # module's report is passed explicitly.
+ "build/reports/jacoco/**/*.xml",
)
# Directories we never descend into when expanding ``**`` patterns — heavy,
# vendored, or irrelevant. The shared junk set plus derived-output names;
# NOT ``coverage``/``target`` (that is where the reports live). Applied at
# traversal time via the shared pruned walk, and post-hoc as a safety net
-# for the non-recursive glob paths.
+# for the non-recursive glob paths. A pruned name spelled literally in a
+# pattern (``build/reports/...``) is an explicit opt-in and is not pruned.
_PRUNE_DIRS = PRUNED_DIRS | frozenset({"dist", "build"})
# Hard cap on discovered artifacts — a sane upper bound that still covers
@@ -87,6 +95,8 @@ class CoverageConfig:
# Re-discover + re-parse reports on every ``repowise update`` (default:
# reuse the rows already in the DB; only re-ingest if a report is found).
reingest_on_update: bool = False
+ # Patch-coverage gate for ``repowise coverage check`` (percent, 0-100).
+ fail_under: float | None = None
@classmethod
def from_repo_config(cls, repo_config: dict | None) -> CoverageConfig:
@@ -109,8 +119,24 @@ class CoverageConfig:
strip_prefix=block.get("strip_prefix") or None,
path_prefix=block.get("path_prefix") or None,
reingest_on_update=bool(block.get("reingest_on_update", False)),
+ fail_under=_percent(block.get("fail_under")),
)
+ def report_paths(self, repo_root: Path) -> list[Path]:
+ """The reports this config names: explicit ``paths``, else discovery when on."""
+ if self.paths:
+ return [repo_root / p for p in self.paths if (repo_root / p).is_file()]
+ if self.auto_discover:
+ return discover_artifacts(repo_root, globs=self.artifacts or None)
+ return []
+
+
+def _percent(value: object) -> float | None:
+ """A 0-100 percentage from config, ``None`` when absent or not one."""
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ return float(value) if 0 <= value <= 100 else None
+
@dataclass
class ResolvedCoverage:
@@ -122,7 +148,10 @@ class ResolvedCoverage:
# ``FileCoverage`` rows with ``file_path`` rewritten to canonical keys,
# for DB persistence (``save_coverage_files``).
files: list[FileCoverage] = field(default_factory=list)
+ # The first report's format (the single-valued persisted column) and every
+ # distinct format merged, in report order.
source_format: str | None = None
+ source_formats: list[str] = field(default_factory=list)
# Diagnostics — surfaced to the user so "coverage didn't show up" is
# never silent.
matched_exact: int = 0
@@ -164,6 +193,15 @@ def discover_artifacts(
patterns = tuple(globs) if globs else DEFAULT_DISCOVERY_GLOBS
snapshot: WalkSnapshot | None = None
+ def _literal_depth(pattern: str) -> int:
+ """How many leading directory segments of *pattern* are spelled literally."""
+ depth = 0
+ for seg in pattern.split("/")[:-1]:
+ if any(ch in seg for ch in "*?["):
+ break
+ depth += 1
+ return depth
+
def _expand(pattern: str) -> Iterable[Path]:
nonlocal snapshot
if not any(ch in pattern for ch in "*?["):
@@ -184,11 +222,16 @@ def discover_artifacts(
roots = [d for d in repo_root.glob(prefix) if d.is_dir()]
else:
roots = [repo_root / prefix]
+ # The snapshot never enters a pruned dir, so a root spelled under
+ # one is walked live (still pruning below it).
+ if any(part in _PRUNE_DIRS for part in Path(prefix).parts):
+ return iter_glob(roots[0], tail, prune_dirs=_PRUNE_DIRS)
return chain.from_iterable(snap.iter_glob(r, tail) for r in roots)
seen: set[Path] = set()
out: list[Path] = []
for pattern in patterns:
+ literal = _literal_depth(pattern)
for match in _expand(pattern):
if not match.is_file():
continue
@@ -196,7 +239,7 @@ def discover_artifacts(
rel_parts = match.relative_to(repo_root).parts
except ValueError:
rel_parts = match.parts
- if any(part in _PRUNE_DIRS for part in rel_parts[:-1]):
+ if any(part in _PRUNE_DIRS for part in rel_parts[literal:-1]):
continue
resolved = match.resolve()
if resolved in seen:
@@ -302,8 +345,10 @@ def _merge_into(dst: FileCoverage, src: FileCoverage) -> None:
multi-suite / multi-language ingestion with no config.
"""
covered = set(dst.covered_lines) | set(src.covered_lines)
+ coverable = set(dst.coverable_lines) | set(src.coverable_lines)
total = max(dst.total_coverable_lines, src.total_coverable_lines, len(covered))
dst.covered_lines = sorted(covered)
+ dst.coverable_lines = sorted(coverable)
dst.total_coverable_lines = total
dst.line_coverage_pct = round(len(covered) / total * 100.0, 2) if total else 0.0
if src.branch_coverage_pct is not None:
@@ -332,8 +377,11 @@ def resolve_reports(
by_key: dict[str, FileCoverage] = {}
report_file_count = 0
for report in reports:
- if result.source_format is None and report.source_format not in (None, "unknown"):
- result.source_format = report.source_format
+ if report.source_format not in (None, "unknown"):
+ if result.source_format is None:
+ result.source_format = report.source_format
+ if report.source_format not in result.source_formats:
+ result.source_formats.append(report.source_format)
for fc in report.files:
report_file_count += 1
norm = normalize_report_path(
@@ -356,6 +404,7 @@ def resolve_reports(
branch_coverage_pct=fc.branch_coverage_pct,
covered_lines=list(fc.covered_lines),
total_coverable_lines=fc.total_coverable_lines,
+ coverable_lines=list(fc.coverable_lines),
)
if key in by_key:
_merge_into(by_key[key], resolved_fc)
@@ -504,6 +553,11 @@ def build_coverage_map(
except OSError as exc:
errors.append((path, f"could not read: {exc}"))
continue
+ except UnicodeDecodeError:
+ # A binary artifact, most often a coverage.py ``.coverage`` database:
+ # export it with ``coverage lcov`` or ``coverage xml`` first.
+ errors.append((path, "not a text coverage report"))
+ continue
report = parse_coverage(text, format=coverage_format)
if not report.files:
errors.append((path, f"no coverage entries (detected={report.source_format})"))
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/goprofile.py b/packages/core/src/repowise/core/analysis/health/coverage/goprofile.py
new file mode 100644
index 000000000..e8102e5ba
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/coverage/goprofile.py
@@ -0,0 +1,106 @@
+"""Go ``go test -coverprofile`` parser.
+
+A cover profile is line-oriented:
+
+ mode: set
+ example.com/mod/pkg/file.go:10.2,12.16 2 1
+ example.com/mod/pkg/file.go:12.16,14.3 1 0
+
+Each block line is ``path:startLine.startCol,endLine.endCol numStmts count``.
+Paths are usually module import paths, not repo paths; resolution to repo
+keys happens later by suffix matching, so they are kept verbatim.
+
+Concatenated profiles (several test binaries, ``-coverpkg``) repeat the
+``mode:`` header and the same block; a block counts as covered when any of
+its records has ``count > 0``. Each block expands to the source lines it
+spans, and a line is covered when any block covering it was hit.
+
+Percentages are therefore **line-based**, not the statement percentage
+``go tool cover -func`` prints. Go profiles carry no branch data, and no
+per-line data either: every line a block spans counts as executable, so a
+comment inside an unexecuted block reads as an uncovered line.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from pathlib import Path
+
+from .model import CoverageReport, file_coverage
+
+# (startLine, startCol, endLine, endCol)
+_Block = tuple[int, int, int, int]
+
+
+def _parse_block_line(line: str) -> tuple[str, _Block, int, int] | None:
+ """Parse one block record into ``(path, block, numStmts, count)``, or ``None``."""
+ # Split from the right: paths may contain spaces and colons.
+ fields = line.rsplit(" ", 2)
+ if len(fields) != 3:
+ return None
+ location, stmts_s, count_s = fields
+ path, sep, spec = location.rpartition(":")
+ if not sep or not path:
+ return None
+ try:
+ start, end = spec.split(",")
+ start_line, start_col = (int(x) for x in start.split("."))
+ end_line, end_col = (int(x) for x in end.split("."))
+ num_stmts = int(stmts_s)
+ count = int(count_s)
+ except ValueError:
+ return None
+ if start_line <= 0 or end_line < start_line:
+ return None
+ return path, (start_line, start_col, end_line, end_col), num_stmts, count
+
+
+def _block_lines(block: _Block) -> range:
+ """The source lines *block* spans."""
+ start_line, _start_col, end_line, end_col = block
+ # A block ending at column 1 stops before any code on its last line.
+ last = end_line - 1 if end_col <= 1 and end_line > start_line else end_line
+ return range(start_line, last + 1)
+
+
+def _collect_blocks(text: str) -> dict[str, dict[_Block, tuple[int, bool]]]:
+ """path -> block -> (numStmts, covered), merging repeated records hit-wins."""
+ blocks: dict[str, dict[_Block, tuple[int, bool]]] = defaultdict(dict)
+ for raw_line in text.splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith("mode:"):
+ continue
+ parsed = _parse_block_line(line)
+ if parsed is None:
+ continue
+ path, key, num_stmts, count = parsed
+ per_file = blocks[path]
+ prev = per_file.get(key)
+ covered = count > 0 or (prev is not None and prev[1])
+ per_file[key] = (max(num_stmts, prev[0] if prev else 0), covered)
+ return blocks
+
+
+def _expand_file(per_file: dict[_Block, tuple[int, bool]]) -> tuple[set[int], set[int]]:
+ """Expand one file's blocks into ``(hit, coverable)`` line sets."""
+ coverable: set[int] = set()
+ hit: set[int] = set()
+ for block, (num_stmts, covered) in per_file.items():
+ if num_stmts <= 0:
+ continue
+ lines = _block_lines(block)
+ coverable.update(lines)
+ if covered:
+ hit.update(lines)
+ return hit, coverable
+
+
+def parse_go_coverprofile(text: str) -> CoverageReport:
+ files = []
+ for path, per_file in _collect_blocks(text).items():
+ hit, coverable = _expand_file(per_file)
+ if not coverable:
+ # Only zero-statement blocks: nothing measured, which is not 0%.
+ continue
+ files.append(file_coverage(Path(path).as_posix(), hit, coverable))
+ return CoverageReport(source_format="go-coverprofile", files=files)
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/jacoco.py b/packages/core/src/repowise/core/analysis/health/coverage/jacoco.py
new file mode 100644
index 000000000..f650f795b
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/coverage/jacoco.py
@@ -0,0 +1,99 @@
+"""JaCoCo XML parser (stdlib ``xml.etree``).
+
+JaCoCo layout (abbreviated):
+
+ <!DOCTYPE report PUBLIC "-//JACOCO//DTD Report 1.1//EN" "report.dtd">
+ <report name="...">
+ <group name="..."> <!-- aggregate reports only -->
+ <package name="com/foo">
+ <class name="com/foo/Bar" sourcefilename="Bar.java">...</class>
+ <sourcefile name="Bar.java">
+ <line nr="3" mi="0" ci="2" mb="1" cb="1"/>
+ <counter type="LINE" missed="1" covered="4"/>
+ </sourcefile>
+ </package>
+ </group>
+ </report>
+
+Per-line data lives on ``<sourcefile>``; ``mi``/``ci`` are missed/covered
+instructions and ``mb``/``cb`` missed/covered branches. A line is coverable
+when it has any instruction and covered when any ran. ``<class>``,
+``<method>`` and ``<counter>`` summaries are ignored.
+
+Paths are ``package/SourceFile.java`` (package dirs, not repo dirs); suffix
+matching maps them to ``src/main/java/...`` later. The DTD is never fetched.
+"""
+
+from __future__ import annotations
+
+from xml.etree import ElementTree as ET
+
+from .model import CoverageReport, file_coverage, parse_xml
+
+
+def _int(value: str | None) -> int:
+ try:
+ return int(value or 0)
+ except ValueError:
+ return 0
+
+
+#: (covered lines, coverable lines, line -> (branches, branches hit))
+_FileLines = tuple[set[int], set[int], dict[int, tuple[int, int]]]
+
+
+def _merge_line(line: ET.Element, acc: _FileLines) -> None:
+ """Fold one ``<line>`` element into *acc*: hit-wins, branch counts take the max."""
+ covered, coverable, branches = acc
+ nr = _int(line.get("nr"))
+ if nr <= 0:
+ return
+ ci = _int(line.get("ci"))
+ if _int(line.get("mi")) + ci > 0:
+ coverable.add(nr)
+ if ci > 0:
+ covered.add(nr)
+ cb = _int(line.get("cb"))
+ total = _int(line.get("mb")) + cb
+ if total:
+ prev_total, prev_hit = branches.get(nr, (0, 0))
+ branches[nr] = (max(prev_total, total), max(prev_hit, cb))
+
+
+def _merge_package(package: ET.Element, merged: dict[str, _FileLines]) -> None:
+ """Fold every ``<sourcefile>`` of one ``<package>`` into *merged*, keyed by path."""
+ pkg_name = (package.get("name") or "").strip("/")
+ for sourcefile in package.findall("sourcefile"):
+ name = sourcefile.get("name") or ""
+ if not name:
+ continue
+ path = f"{pkg_name}/{name}" if pkg_name else name
+ acc = merged.setdefault(path, (set(), set(), {}))
+ for line in sourcefile.findall("line"):
+ _merge_line(line, acc)
+
+
+def parse_jacoco(text: str) -> CoverageReport:
+ root = parse_xml(text)
+ if root is None:
+ return CoverageReport(source_format="jacoco", files=[])
+
+ # The same source file can appear under several groups: merged hit-wins,
+ # and branches per line take the max so a duplicate never double counts.
+ merged: dict[str, _FileLines] = {}
+ for package in root.iter("package"):
+ _merge_package(package, merged)
+
+ files = [
+ file_coverage(
+ path,
+ covered,
+ coverable,
+ branches_found=sum(t for t, _ in branches.values()),
+ branches_hit=sum(h for _, h in branches.values()),
+ )
+ for path, (covered, coverable, branches) in merged.items()
+ # No executable lines (e.g. an interface) means unmeasured, not 0%.
+ if coverable
+ ]
+ return CoverageReport(source_format="jacoco", files=files)
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/lcov.py b/packages/core/src/repowise/core/analysis/health/coverage/lcov.py
index eaf8116c9..2a41474ab 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/lcov.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/lcov.py
@@ -21,7 +21,7 @@ from __future__ import annotations
import contextlib
from pathlib import Path
-from .model import CoverageReport, FileCoverage
+from .model import CoverageReport, FileCoverage, file_coverage
def parse_lcov(text: str) -> CoverageReport:
@@ -32,30 +32,23 @@ def parse_lcov(text: str) -> CoverageReport:
total_lines: set[int] = set()
branches_found = 0
branches_hit = 0
- has_branches = False
explicit_lf: int | None = None
explicit_lh: int | None = None
def flush() -> None:
nonlocal current_path, covered_lines, total_lines
- nonlocal branches_found, branches_hit, has_branches, explicit_lf, explicit_lh
+ nonlocal branches_found, branches_hit, explicit_lf, explicit_lh
if current_path is None:
return
- total = explicit_lf if explicit_lf is not None else len(total_lines)
- hit = explicit_lh if explicit_lh is not None else len(covered_lines)
- line_pct = (hit / total * 100.0) if total else 0.0
- branch_pct: float | None
- if has_branches and branches_found:
- branch_pct = branches_hit / branches_found * 100.0
- else:
- branch_pct = None
files.append(
- FileCoverage(
- file_path=current_path,
- line_coverage_pct=round(line_pct, 2),
- branch_coverage_pct=round(branch_pct, 2) if branch_pct is not None else None,
- covered_lines=sorted(covered_lines),
- total_coverable_lines=total,
+ file_coverage(
+ current_path,
+ covered_lines,
+ total_lines,
+ branches_found=branches_found,
+ branches_hit=branches_hit,
+ total=explicit_lf,
+ hit=explicit_lh,
)
)
current_path = None
@@ -63,7 +56,6 @@ def parse_lcov(text: str) -> CoverageReport:
total_lines = set()
branches_found = 0
branches_hit = 0
- has_branches = False
explicit_lf = None
explicit_lh = None
@@ -93,7 +85,6 @@ def parse_lcov(text: str) -> CoverageReport:
elif tag == "BRDA":
parts = rest.split(",")
if len(parts) == 4:
- has_branches = True
branches_found += 1
if parts[3] not in ("-", "0"):
branches_hit += 1
@@ -104,17 +95,11 @@ def parse_lcov(text: str) -> CoverageReport:
with contextlib.suppress(ValueError):
explicit_lh = int(rest)
elif tag == "BRF":
- try:
+ with contextlib.suppress(ValueError):
branches_found = max(branches_found, int(rest))
- has_branches = True
- except ValueError:
- pass
elif tag == "BRH":
- try:
+ with contextlib.suppress(ValueError):
branches_hit = max(branches_hit, int(rest))
- has_branches = True
- except ValueError:
- pass
# Some reports omit the final end_of_record.
flush()
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/model.py b/packages/core/src/repowise/core/analysis/health/coverage/model.py
index 91bbd2bb0..31cc9e040 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/model.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/model.py
@@ -9,25 +9,79 @@ engine and persistence layer consume these dataclasses; the ORM
from __future__ import annotations
+from collections.abc import Iterable
from dataclasses import dataclass, field
+from xml.etree import ElementTree as ET
@dataclass
class FileCoverage:
- """Per-file coverage extracted from a single report."""
+ """Per-file coverage extracted from a single report.
+
+ ``coverable_lines`` is the set of lines the report calls executable
+ (hit or not). It is what tells an uncovered changed line apart from a
+ changed comment or blank line, so patch coverage needs it. Empty means
+ the report did not say which lines are executable, not that none are.
+ """
file_path: str
line_coverage_pct: float
branch_coverage_pct: float | None
covered_lines: list[int] = field(default_factory=list)
total_coverable_lines: int = 0
+ coverable_lines: list[int] = field(default_factory=list)
+
+
+def file_coverage(
+ file_path: str,
+ covered: Iterable[int],
+ coverable: Iterable[int],
+ *,
+ branches_found: int = 0,
+ branches_hit: int = 0,
+ total: int | None = None,
+ hit: int | None = None,
+) -> FileCoverage:
+ """Build a :class:`FileCoverage` from line sets, the one place percentages are derived.
+
+ *total* / *hit* override the counts taken from the sets, for formats that
+ state their own summary (lcov ``LF``/``LH``). Branch coverage is ``None``
+ when the report named no branches, never 0%.
+ """
+ covered_set = set(covered)
+ coverable_set = set(coverable)
+ n_total = total if total is not None else len(coverable_set)
+ n_hit = hit if hit is not None else len(covered_set)
+ line_pct = n_hit / n_total * 100.0 if n_total else 0.0
+ branch_pct = branches_hit / branches_found * 100.0 if branches_found else None
+ return FileCoverage(
+ file_path=file_path,
+ line_coverage_pct=round(line_pct, 2),
+ branch_coverage_pct=round(branch_pct, 2) if branch_pct is not None else None,
+ covered_lines=sorted(covered_set),
+ total_coverable_lines=n_total,
+ coverable_lines=sorted(coverable_set),
+ )
+
+
+def parse_xml(text: str) -> ET.Element | None:
+ """Root element of an XML report, or ``None`` when it does not parse.
+
+ Parsers never raise on bad input; ``None`` becomes an empty report.
+ External DTDs (JaCoCo declares one) are never fetched by ``xml.etree``.
+ """
+ try:
+ return ET.fromstring(text)
+ except ET.ParseError:
+ return None
@dataclass
class CoverageReport:
"""Whole-report bundle returned by every parser.
- ``source_format`` is one of ``lcov`` / ``cobertura`` / ``clover``.
+ ``source_format`` is a key of ``detector.PARSERS`` (``lcov``,
+ ``cobertura``, ``clover``, ``repowise-json``, ...), or ``unknown``.
``commit_sha`` is best-effort: parsers leave it ``None``; the CLI
fills it in from ``git rev-parse HEAD`` when available.
"""
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/repowise_json.py b/packages/core/src/repowise/core/analysis/health/coverage/repowise_json.py
index ef4a2e320..7ab920576 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/repowise_json.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/repowise_json.py
@@ -1,10 +1,10 @@
"""Repowise normalized-JSON coverage parser.
-A small, explicit JSON schema so coverage produced by *any* runner
-(``pytest-cov``, ``c8``/``nyc``, ``cargo-llvm-cov``, ``go test
--coverprofile``, JaCoCo, coverlet, or a Codecov/Coveralls scrape) can be
-normalized once to a single shape and fed to ``repowise health
---coverage``. Keyed by **repo-relative POSIX path**.
+A small, explicit JSON schema so coverage from a runner with no native
+parser here (any runner or a custom export) can be normalized once to a
+single shape and fed to ``repowise health --coverage``. The other formats in
+:data:`~.detector.PARSERS` are read directly. Keyed by **repo-relative POSIX
+path**.
Schema (``format: "repowise-coverage-v1"``)::
@@ -16,6 +16,7 @@ Schema (``format: "repowise-coverage-v1"``)::
"line_coverage_pct": 87.5, # 0..100; derivable from covered/total
"branch_coverage_pct": 70.0, # optional, may be null
"covered_lines": [1, 2, 5], # optional explicit hit set
+ "coverable_lines": [1, 2, 3, 5], # optional executable set (patch coverage)
"total_coverable_lines": 40 # optional; derivable from pct+covered
},
...
@@ -77,11 +78,13 @@ def _parse_entry(key: str | None, entry: dict[str, Any]) -> FileCoverage | None:
return None
path = Path(str(path).replace("\\", "/")).as_posix()
- covered = entry.get("covered_lines")
- covered_lines = sorted({int(x) for x in covered}) if isinstance(covered, (list, tuple)) else []
+ covered_lines = _line_set(entry.get("covered_lines"))
+ coverable_lines = _line_set(entry.get("coverable_lines"))
total = entry.get("total_coverable_lines")
total = int(total) if isinstance(total, (int, float)) and total >= 0 else None
+ if total is None and coverable_lines:
+ total = len(coverable_lines)
pct = entry.get("line_coverage_pct")
pct = float(pct) if isinstance(pct, (int, float)) else None
@@ -112,4 +115,15 @@ def _parse_entry(key: str | None, entry: dict[str, Any]) -> FileCoverage | None:
branch_coverage_pct=round(branch_pct, 2) if branch_pct is not None else None,
covered_lines=covered_lines,
total_coverable_lines=int(total or 0),
+ coverable_lines=coverable_lines,
)
+
+
+def _line_set(raw: Any) -> list[int]:
+ """Sorted unique line numbers from a JSON list, ``[]`` when absent or malformed."""
+ if not isinstance(raw, (list, tuple)):
+ return []
+ try:
+ return sorted({int(x) for x in raw})
+ except (TypeError, ValueError):
+ return []
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py
new file mode 100644
index 000000000..83709f570
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py
@@ -0,0 +1,43 @@
+"""Patch coverage: the share of a change's executable lines the tests ran."""
+
+from __future__ import annotations
+
+from .compute import (
+ FilePatchCoverage,
+ FileStatus,
+ GateStatus,
+ PatchCoverage,
+ PatchScope,
+ compute_patch_coverage,
+ patch_coverage_from_resolved,
+)
+from .render import (
+ RANGE_LIMIT,
+ STATUS_TEXT,
+ attention_rows,
+ fmt_pct,
+ format_ranges,
+ github_annotations,
+ headline,
+ render_markdown,
+ scope_line,
+)
+
+__all__ = [
+ "RANGE_LIMIT",
+ "STATUS_TEXT",
+ "FilePatchCoverage",
+ "FileStatus",
+ "GateStatus",
+ "PatchCoverage",
+ "PatchScope",
+ "attention_rows",
+ "compute_patch_coverage",
+ "fmt_pct",
+ "format_ranges",
+ "github_annotations",
+ "headline",
+ "patch_coverage_from_resolved",
+ "render_markdown",
+ "scope_line",
+]
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
new file mode 100644
index 000000000..793438625
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
@@ -0,0 +1,228 @@
+"""Patch coverage: how much of a change's executable lines the tests ran.
+
+Pure: it takes the change as ``{path: changed new-side lines}`` and the
+coverage as ``{path: FileCoverage}``, both keyed by repo-relative POSIX path,
+and does no I/O. Built to be the one computation a CLI gate, an agent tool or
+a hosted pull-request check reads, so they cannot disagree.
+
+The denominator is changed lines the report calls executable. A changed
+comment or blank line is neither covered nor uncovered, which is why the
+report's ``coverable_lines`` is required: without it a file is
+``no_line_data``, never 0%.
+
+What counts is decided by the report. A changed file the report names is
+measured. One it does not name is ``not_in_report`` when it looks like code
+the report measures (its extension appears in the report), so a new,
+untested source file is surfaced rather than dropped; it is out of scope
+when it is a test file or a type the report never measures (docs, config).
+Ceiling: a not-in-report file is reported but excluded from the percentage,
+because its executable lines are unknown. A stricter gate can count it once a
+report format carries "file present, nothing executed".
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Iterable, Mapping, Sequence
+from dataclasses import dataclass, field
+from pathlib import PurePosixPath
+from typing import TYPE_CHECKING, Any, Literal, get_args
+
+from ...test_paths import is_test_related_path
+from ..changed_lines import line_ranges
+from ..health.coverage.model import FileCoverage
+
+if TYPE_CHECKING:
+ from ..health.coverage.discovery import ResolvedCoverage
+
+FileStatus = Literal["measured", "not_in_report", "no_line_data", "no_coverable_changes"]
+GateStatus = Literal["pass", "fail", "no_data", "not_set"]
+
+
+@dataclass(frozen=True)
+class FilePatchCoverage:
+ """One changed file's slice of the patch. Counts are line counts."""
+
+ file_path: str
+ status: FileStatus
+ changed_line_count: int
+ coverable_line_count: int = 0
+ covered_line_count: int = 0
+ # Inclusive (start, end) runs of changed, executable, unexecuted lines.
+ uncovered_ranges: tuple[tuple[int, int], ...] = ()
+
+ @property
+ def patch_coverage_pct(self) -> float | None:
+ return _pct(self.covered_line_count, self.coverable_line_count)
+
+ @property
+ def uncovered_line_count(self) -> int:
+ return self.coverable_line_count - self.covered_line_count
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "file_path": self.file_path,
+ "status": self.status,
+ "changed_line_count": self.changed_line_count,
+ "coverable_line_count": self.coverable_line_count,
+ "covered_line_count": self.covered_line_count,
+ "patch_coverage_pct": _round(self.patch_coverage_pct),
+ "uncovered_ranges": [list(r) for r in self.uncovered_ranges],
+ }
+
+
+@dataclass(frozen=True)
+class PatchScope:
+ """Where the numbers came from, carried so every renderer can say so."""
+
+ label: str = "" # the diff, e.g. "origin/main...HEAD"
+ source_formats: tuple[str, ...] = ()
+ reports: tuple[str, ...] = () # report files read, as the caller named them
+ report_path_count: int = 0 # file entries across those reports
+ # Report entries that did not map to a file in the repository.
+ unmatched_report_path_count: int = 0
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "label": self.label,
+ "source_formats": list(self.source_formats),
+ "reports": list(self.reports),
+ "report_path_count": self.report_path_count,
+ "unmatched_report_path_count": self.unmatched_report_path_count,
+ }
+
+
+@dataclass(frozen=True)
+class PatchCoverage:
+ """The patch-coverage verdict for one change."""
+
+ files: tuple[FilePatchCoverage, ...] = ()
+ threshold: float | None = None
+ # Changed files left out because the report does not measure their kind.
+ out_of_scope_count: int = 0
+ scope: PatchScope = field(default_factory=PatchScope)
+
+ @property
+ def changed_file_count(self) -> int:
+ return len(self.files) + self.out_of_scope_count
+
+ @property
+ def coverable_line_count(self) -> int:
+ return sum(f.coverable_line_count for f in self.with_status("measured"))
+
+ @property
+ def covered_line_count(self) -> int:
+ return sum(f.covered_line_count for f in self.with_status("measured"))
+
+ @property
+ def patch_coverage_pct(self) -> float | None:
+ return _pct(self.covered_line_count, self.coverable_line_count)
+
+ @property
+ def gate(self) -> GateStatus:
+ if self.threshold is None:
+ return "not_set"
+ pct = self.patch_coverage_pct
+ if pct is None:
+ return "no_data"
+ return "pass" if pct >= self.threshold else "fail"
+
+ def with_status(self, status: FileStatus) -> list[FilePatchCoverage]:
+ return [f for f in self.files if f.status == status]
+
+ def to_dict(self) -> dict[str, Any]:
+ counts = {status: len(self.with_status(status)) for status in get_args(FileStatus)}
+ counts["out_of_scope"] = self.out_of_scope_count
+ return {
+ "patch_coverage_pct": _round(self.patch_coverage_pct),
+ "covered_line_count": self.covered_line_count,
+ "coverable_line_count": self.coverable_line_count,
+ "threshold": self.threshold,
+ "gate": self.gate,
+ "file_counts": counts,
+ "files": [f.to_dict() for f in self.files],
+ "scope": self.scope.to_dict(),
+ }
+
+
+def compute_patch_coverage(
+ changed: Mapping[str, Iterable[int]],
+ coverage: Mapping[str, FileCoverage],
+ *,
+ threshold: float | None = None,
+ scope: PatchScope | None = None,
+) -> PatchCoverage:
+ """Intersect a change with a coverage report. See the module docstring."""
+ measured_suffixes = {PurePosixPath(p).suffix for p in coverage}
+ files: list[FilePatchCoverage] = []
+ out_of_scope = 0
+ for path in sorted(changed):
+ lines = set(changed[path])
+ if not lines:
+ continue
+ fc = coverage.get(path)
+ if fc is not None:
+ files.append(_file_patch(path, lines, fc))
+ elif is_test_related_path(path) or PurePosixPath(path).suffix not in measured_suffixes:
+ out_of_scope += 1
+ else:
+ files.append(FilePatchCoverage(path, "not_in_report", len(lines)))
+ return PatchCoverage(
+ files=tuple(files),
+ threshold=threshold,
+ out_of_scope_count=out_of_scope,
+ scope=scope or PatchScope(),
+ )
+
+
+def patch_coverage_from_resolved(
+ changed: Mapping[str, Iterable[int]],
+ resolved: ResolvedCoverage,
+ *,
+ threshold: float | None = None,
+ label: str = "",
+ reports: Sequence[str] = (),
+) -> PatchCoverage:
+ """:func:`compute_patch_coverage` over reports already resolved to repo keys."""
+ unmatched = len(resolved.unmatched) + len(resolved.ambiguous)
+ return compute_patch_coverage(
+ changed,
+ {fc.file_path: fc for fc in resolved.files},
+ threshold=threshold,
+ scope=PatchScope(
+ label=label,
+ source_formats=tuple(resolved.source_formats),
+ reports=tuple(reports),
+ report_path_count=resolved.matched + unmatched,
+ unmatched_report_path_count=unmatched,
+ ),
+ )
+
+
+def _file_patch(path: str, lines: set[int], fc: FileCoverage) -> FilePatchCoverage:
+ if not fc.coverable_lines:
+ return FilePatchCoverage(path, "no_line_data", len(lines))
+ coverable = lines.intersection(fc.coverable_lines)
+ if not coverable:
+ return FilePatchCoverage(path, "no_coverable_changes", len(lines))
+ covered = coverable.intersection(fc.covered_lines)
+ return FilePatchCoverage(
+ path,
+ "measured",
+ len(lines),
+ coverable_line_count=len(coverable),
+ covered_line_count=len(covered),
+ uncovered_ranges=line_ranges(coverable - covered),
+ )
+
+
+def _pct(covered: int, coverable: int) -> float | None:
+ # Unrounded, so a gate never passes on rounding (79.998% is below 80%).
+ # Rounding happens only where the number is shown or serialized.
+ # Multiply first: 57 / 100 * 100 is 56.99999999999999.
+ return covered * 100.0 / coverable if coverable else None
+
+
+def _round(pct: float | None) -> float | None:
+ # Floored like the display, so a serialized 80.0 never means 79.998.
+ return None if pct is None else math.floor(pct * 100) / 100
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/render.py b/packages/core/src/repowise/core/analysis/patch_coverage/render.py
new file mode 100644
index 000000000..21c59b113
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/render.py
@@ -0,0 +1,160 @@
+"""Human renderings of :class:`PatchCoverage`: markdown, plain text, CI annotations.
+
+Markdown is what a CI step summary or a pull-request comment shows, so it is
+written to be read once and acted on: the verdict in words on the first line
+with its denominator, the diff, report and file counts on the second, and
+detail only for what needs attention. A passing change with no gaps is two
+lines. A file the report never named reads "not in report", never 0%.
+
+Workflow-command and markdown mechanics (escaping, caps, collapsed lists)
+come from :mod:`repowise.core.ci`, shared with every other CI gate.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Sequence
+
+from ...ci import github
+from ...ci.markdown import ROW_LIMIT, cell, details, more_line
+from .compute import FilePatchCoverage, PatchCoverage
+
+#: Uncovered ranges shown per file before "+N more".
+RANGE_LIMIT = 8
+
+#: How a file that could not be measured reads, wherever it is listed.
+STATUS_TEXT = {
+ "not_in_report": "not in report",
+ "no_line_data": "report has no line data",
+ "no_coverable_changes": "no executable lines changed",
+}
+
+
+def headline(pc: PatchCoverage, *, markdown: bool = True) -> str:
+ """One-sentence verdict. Bold on the figure only in markdown."""
+ bold = "**" if markdown else ""
+ pct = pc.patch_coverage_pct
+ if pct is None:
+ text = f"{bold}Patch coverage: no measurable changed lines.{bold} {_no_data_reason(pc)}"
+ if pc.threshold is not None:
+ text += f" The {fmt_pct(pc.threshold)} gate was not applied."
+ return text
+ text = (
+ f"{bold}Patch coverage {fmt_pct(pct)}{bold} ({pc.covered_line_count} of "
+ f"{pc.coverable_line_count} changed executable lines covered)"
+ )
+ if pc.gate == "fail":
+ text += f" · below the {fmt_pct(pc.threshold)} gate"
+ elif pc.gate == "pass":
+ text += f" · meets the {fmt_pct(pc.threshold)} gate"
+ return text
+
+
+def scope_line(pc: PatchCoverage, *, markdown: bool = True) -> str:
+ """The diff, the reports and how many changed files were measured."""
+ scope = pc.scope
+ parts = []
+ if scope.label:
+ parts.append(f"`{scope.label}`" if markdown else scope.label)
+ if scope.source_formats:
+ parts.append(", ".join(scope.source_formats))
+ measured = len(pc.with_status("measured"))
+ files = f"{measured} of {pc.changed_file_count} changed files measured"
+ if pc.out_of_scope_count:
+ files += f", {pc.out_of_scope_count} out of scope"
+ parts.append(files)
+ if scope.unmatched_report_path_count:
+ parts.append(
+ f"{scope.unmatched_report_path_count} of {scope.report_path_count} report paths "
+ "did not match a file in this repository"
+ )
+ return " · ".join(parts)
+
+
+def attention_rows(pc: PatchCoverage) -> list[FilePatchCoverage]:
+ """Files a reader should look at: uncovered changes first, then unmeasurable ones."""
+ gaps = sorted(
+ (f for f in pc.with_status("measured") if f.uncovered_line_count),
+ key=lambda f: (-f.uncovered_line_count, f.file_path),
+ )
+ return gaps + pc.with_status("not_in_report") + pc.with_status("no_line_data")
+
+
+def render_markdown(pc: PatchCoverage) -> str:
+ """Markdown for a CI step summary or PR comment."""
+ out = [headline(pc), "", scope_line(pc)]
+ gaps = [f for f in attention_rows(pc) if f.status == "measured"]
+ if gaps:
+ out += ["", "| File | Uncovered changed lines | Covered |", "|---|---|---|"]
+ out += [
+ f"| `{cell(f.file_path)}` | {format_ranges(f.uncovered_ranges, RANGE_LIMIT)} | "
+ f"{f.covered_line_count} of {f.coverable_line_count} |"
+ for f in gaps[:ROW_LIMIT]
+ ]
+ if len(gaps) > ROW_LIMIT:
+ out += ["", more_line(len(gaps) - ROW_LIMIT, "files with uncovered changed lines")]
+ out += _details(pc.with_status("not_in_report"), "not in the coverage report")
+ out += _details(pc.with_status("no_line_data"), "in a report without line data")
+ return "\n".join(out) + "\n"
+
+
+def github_annotations(pc: PatchCoverage) -> list[str]:
+ """GitHub Actions workflow commands for a change's patch coverage.
+
+ A failed gate is an error. The largest uncovered ranges are marked, capped
+ at what GitHub displays, with a notice counting the rest.
+ """
+ ranges = sorted(
+ ((f.file_path, a, b) for f in pc.with_status("measured") for a, b in f.uncovered_ranges),
+ key=lambda r: (r[1] - r[2], r[0], r[1]),
+ )
+ warnings = [
+ github.annotation(
+ "warning",
+ f"Changed {_span(a, b)} not covered by tests",
+ file=path,
+ line=a,
+ end_line=b,
+ title="Uncovered change",
+ )
+ for path, a, b in ranges
+ ]
+ verdict = [github.error(headline(pc, markdown=False))] if pc.gate == "fail" else []
+ return verdict + github.cap_annotations(warnings, noun="uncovered changed ranges")
+
+
+def format_ranges(ranges: Sequence[tuple[int, int]], limit: int | None = None) -> str:
+ """``((1, 3), (7, 7))`` -> ``"1-3, 7"``, with ``+N more`` past *limit*."""
+ shown = ranges if limit is None else ranges[:limit]
+ text = ", ".join(str(a) if a == b else f"{a}-{b}" for a, b in shown)
+ rest = len(ranges) - len(shown)
+ return text + (f", +{rest} more" if rest else "")
+
+
+def fmt_pct(value: float | None) -> str:
+ """One decimal, floored, so a figure never reads as meeting a gate it missed."""
+ return "n/a" if value is None else f"{math.floor(value * 10) / 10:.1f}%"
+
+
+def _details(files: list[FilePatchCoverage], where: str) -> list[str]:
+ if not files:
+ return []
+ noun = "file is" if len(files) == 1 else "files are"
+ summary = f"{len(files)} changed {noun} {where}, so not counted"
+ return ["", *details(summary, [f"`{cell(f.file_path)}`" for f in files])]
+
+
+def _no_data_reason(pc: PatchCoverage) -> str:
+ if not pc.changed_file_count:
+ return "The change has no changed lines."
+ if pc.with_status("no_line_data"):
+ return "The report does not say which lines are executable."
+ if pc.with_status("not_in_report"):
+ return "The changed source files are not in the coverage report."
+ if pc.with_status("no_coverable_changes"):
+ return "The change touches no executable lines."
+ return "Only tests or files the report does not measure changed."
+
+
+def _span(a: int, b: int) -> str:
+ return f"line {a}" if a == b else f"lines {a}-{b}"
diff --git a/packages/core/src/repowise/core/ci/__init__.py b/packages/core/src/repowise/core/ci/__init__.py
new file mode 100644
index 000000000..e6f65ee0c
--- /dev/null
+++ b/packages/core/src/repowise/core/ci/__init__.py
@@ -0,0 +1,8 @@
+"""Shared CI plumbing: workflow commands, markdown pieces, the target branch.
+
+Every CI-facing feature (patch coverage, doc drift, ...) renders its own
+content and uses these for the parts CI systems define, so escaping, caps and
+base-branch rules are written once and a hosted check can reuse them.
+"""
+
+from __future__ import annotations
diff --git a/packages/core/src/repowise/core/ci/base.py b/packages/core/src/repowise/core/ci/base.py
new file mode 100644
index 000000000..6888be4bf
--- /dev/null
+++ b/packages/core/src/repowise/core/ci/base.py
@@ -0,0 +1,53 @@
+"""Which branch a CI change targets, read from the CI's own variables.
+
+CI checkouts are detached, rarely set ``origin/HEAD`` and have no local trunk
+branch, so the usual "default branch" lookup finds nothing and a gate that
+diffs ``HEAD...HEAD`` would pass having measured nothing. The pull-request
+variables name the target directly.
+"""
+
+from __future__ import annotations
+
+import os
+from collections.abc import Mapping
+
+from .. import git_refs
+
+#: Variables naming the branch a change will merge into, in the order they are
+#: consulted; each is read from the ``origin`` remote. A branch, not a base
+#: commit, so a pipeline that runs on a merge onto the target's tip (merged
+#: results) still diffs only the change's own lines.
+CI_BASE_VARS = (
+ "GITHUB_BASE_REF", # GitHub Actions pull_request
+ "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", # GitLab merge request
+ "CHANGE_TARGET", # Jenkins multibranch pull request
+ "BITBUCKET_PR_DESTINATION_BRANCH", # Bitbucket Pipelines
+)
+
+
+class BaseNotFoundError(ValueError):
+ """No target branch could be determined; the caller should ask for a revspec."""
+
+
+def default_revspec(repo_root: str, env: Mapping[str, str] | None = None) -> str:
+ """``<base>...HEAD`` for the change being checked.
+
+ The base comes from :data:`CI_BASE_VARS`, else the repository's default
+ branch, else ``origin/main`` / ``origin/master``. Raises
+ :class:`BaseNotFoundError` when none resolves.
+ """
+ env = os.environ if env is None else env
+ for var in CI_BASE_VARS:
+ if branch := env.get(var, "").strip():
+ return f"origin/{branch}...HEAD"
+ base = git_refs.default_base(repo_root)
+ if base == "HEAD":
+ base = next(
+ (b for b in ("origin/main", "origin/master") if git_refs.resolve(repo_root, b)), ""
+ )
+ if not base:
+ raise BaseNotFoundError(
+ "Could not tell which branch this change targets. Pass REVSPEC, "
+ "e.g. origin/main...HEAD."
+ )
+ return f"{base}...HEAD"
diff --git a/packages/core/src/repowise/core/ci/github.py b/packages/core/src/repowise/core/ci/github.py
new file mode 100644
index 000000000..a6e228d41
--- /dev/null
+++ b/packages/core/src/repowise/core/ci/github.py
@@ -0,0 +1,68 @@
+"""GitHub Actions workflow commands: the one place they are built and escaped.
+
+Pure string builders, so a CLI gate and a hosted check render identical
+annotations. GitHub shows at most 10 warning and 10 error annotations per
+step and drops the rest silently, which is why :func:`cap_annotations` counts
+what it cut instead of emitting it.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+#: Annotations GitHub displays per level per step.
+ANNOTATION_LIMIT = 10
+
+
+def escape_data(text: str) -> str:
+ """Escape a workflow-command message (``%``, CR, LF)."""
+ return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
+
+
+def escape_property(text: str) -> str:
+ """Escape a workflow-command property value (a message's escapes plus ``:`` and ``,``)."""
+ return escape_data(text).replace(":", "%3A").replace(",", "%2C")
+
+
+def annotation(
+ level: str,
+ message: str,
+ *,
+ file: str | None = None,
+ line: int | None = None,
+ end_line: int | None = None,
+ title: str | None = None,
+) -> str:
+ """``::level file=..,line=..,endLine=..,title=..::message``, omitting absent properties."""
+ props = [
+ f"{key}={value}"
+ for key, value in (
+ ("file", escape_property(file) if file is not None else None),
+ ("line", line),
+ ("endLine", end_line),
+ ("title", escape_property(title) if title is not None else None),
+ )
+ if value is not None
+ ]
+ head = f"::{level} {','.join(props)}" if props else f"::{level}"
+ return f"{head}::{escape_data(message)}"
+
+
+def error(message: str) -> str:
+ """A bare ``::error::`` line."""
+ return annotation("error", message)
+
+
+def notice(message: str) -> str:
+ """A bare ``::notice::`` line."""
+ return annotation("notice", message)
+
+
+def cap_annotations(
+ lines: Sequence[str], limit: int = ANNOTATION_LIMIT, *, noun: str = "findings"
+) -> list[str]:
+ """The first *limit* lines, plus one notice counting the rest."""
+ kept = list(lines[:limit])
+ if len(lines) > limit:
+ kept.append(notice(f"{len(lines) - limit} more {noun}, listed in the job summary"))
+ return kept
diff --git a/packages/core/src/repowise/core/ci/markdown.py b/packages/core/src/repowise/core/ci/markdown.py
new file mode 100644
index 000000000..d1e768fdd
--- /dev/null
+++ b/packages/core/src/repowise/core/ci/markdown.py
@@ -0,0 +1,37 @@
+"""Markdown pieces shared by CI step summaries and pull-request comments."""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Any
+
+#: Items listed in a section before the rest collapse into "and N more".
+ROW_LIMIT = 10
+
+
+def cell(value: Any) -> str:
+ """*value* made safe for a markdown table cell."""
+ text = str(value)
+ for char, escaped in (("\\", "\\\\"), ("|", "\\|"), ("`", "\\`"), ("<", "&lt;")):
+ text = text.replace(char, escaped)
+ return text
+
+
+def plural(n: int, word: str, many: str | None = None) -> str:
+ """``"1 file"`` / ``"3 files"``."""
+ return f"{n} {word if n == 1 else many or word + 's'}"
+
+
+def more_line(n: int, noun: str) -> str:
+ """``"and 4 more files."``, or ``""`` when nothing was cut."""
+ return f"and {n} more {noun}." if n > 0 else ""
+
+
+def details(summary: str, items: Sequence[str], limit: int = ROW_LIMIT) -> list[str]:
+ """A collapsed ``<details>`` list of *items* (already formatted), capped at *limit*."""
+ if not items:
+ return []
+ out = ["<details>", f"<summary>{summary}</summary>", "", *(f"- {i}" for i in items[:limit])]
+ if len(items) > limit:
+ out.append(f"- and {len(items) - limit} more")
+ return [*out, "", "</details>"]
diff --git a/packages/core/src/repowise/core/git_refs.py b/packages/core/src/repowise/core/git_refs.py
index e8d71b18b..0b1dcd25c 100644
--- a/packages/core/src/repowise/core/git_refs.py
+++ b/packages/core/src/repowise/core/git_refs.py
@@ -12,7 +12,7 @@ import subprocess
from collections.abc import Sequence
from dataclasses import dataclass
-from .analysis.change_risk.features import _git
+from .analysis.change_risk.features import _git, split_revspec
__all__ = [
"BranchRef",
@@ -28,6 +28,7 @@ __all__ = [
"refs_merged_into",
"resolve",
"toplevel",
+ "tracked_paths",
]
#: Subprocess failures that mean "no answer", not "bug": a wedged or missing
@@ -68,6 +69,11 @@ def toplevel(repo_path: str) -> str:
return _read(repo_path, ["rev-parse", "--show-toplevel"])
+def tracked_paths(repo_path: str) -> frozenset[str]:
+ """Every path git tracks, repo-relative POSIX, or empty when git cannot answer."""
+ return frozenset(p for p in _read(repo_path, ["ls-files", "-z"]).split("\0") if p)
+
+
def current_branch(repo_path: str) -> str | None:
"""The checked-out branch, or ``None`` when detached or unreadable."""
name = _read(repo_path, ["rev-parse", "--abbrev-ref", "HEAD"])
@@ -218,14 +224,12 @@ def commit_file_sets(repo_path: str, revspec: str | None) -> list[frozenset[str]
Only a range carries the information: a single revision names one commit,
and one commit says nothing about what moves with what.
"""
- if not revspec:
+ parts = split_revspec(revspec) if revspec else None
+ if parts is None:
return []
# The commits of "a...b" are "a..b"; three dots is diff syntax, not a range.
- if "..." in revspec:
- revspec = revspec.replace("...", "..")
- elif ".." not in revspec:
- return []
- out = _read(repo_path, ["log", "--reverse", "--format=%x00%H", "--name-only", revspec])
+ base, _sep, head = parts
+ out = _read(repo_path, ["log", "--reverse", "--format=%x00%H", "--name-only", f"{base}..{head}"])
sets: list[frozenset[str]] = []
for block in out.split("\x00"):
paths = {line.strip() for line in block.splitlines()[1:] if line.strip()}
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index d115eee1a..2102fb73d 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -958,18 +958,9 @@ def _git_tracked_paths(root: Path) -> frozenset[str]:
witness has nothing to say, and the caller treats silence as "no opinion"
rather than as "nothing is tracked".
"""
- import subprocess
+ from repowise.core.git_refs import tracked_paths
- try:
- out = subprocess.run(
- ["git", "-C", str(root), "ls-files", "-z"],
- capture_output=True,
- timeout=60,
- check=True,
- ).stdout
- except Exception:
- return frozenset()
- return frozenset(p for p in out.decode("utf-8", "replace").split("\0") if p)
+ return tracked_paths(str(root))
class _FileLiveness:
diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py
index 43ab34848..c92583bde 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -182,21 +182,12 @@ def _build_pipeline_coverage(
from repowise.core.analysis.health.coverage import (
CoverageConfig,
build_coverage_map,
- discover_artifacts,
)
from repowise.core.repo_config import load_repo_config
cfg = CoverageConfig.from_repo_config(load_repo_config(repo_path))
- if explicit_paths:
- report_paths = list(explicit_paths)
- elif cfg.paths:
- report_paths = [repo_path / p for p in cfg.paths if (repo_path / p).is_file()]
- elif cfg.auto_discover:
- report_paths = discover_artifacts(repo_path, globs=cfg.artifacts or None)
- else:
- return {}, [], None, False
-
+ report_paths = list(explicit_paths) if explicit_paths else cfg.report_paths(repo_path)
if not report_paths:
return {}, [], None, False
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 671c9e9d8..bb5407d8f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -486,22 +486,6 @@ async def _repository(ctx: Any) -> Any | None:
return None
-def _normalize_revspec(revspec: str | None) -> str:
- """Mirror ``score_live_change``'s three-dot handling for ``changed_lines``.
-
- ``changed_lines`` verifies each side of a ``base..head`` range as a ref, so a
- three-dot ``base...head`` (whose head parses as ``.head``) would fail its
- ref check. Strip the extra dot to the two-dot form the scorer already uses.
- """
- if revspec is None:
- return "HEAD"
- if ".." in revspec:
- base, _, head = revspec.partition("..")
- head = head.lstrip(".") or "HEAD"
- return f"{base}..{head}"
- return revspec
-
-
def _filter_changed(
changed: dict[str, set[int]],
extensions: tuple[str, ...],
@@ -769,7 +753,7 @@ async def _changed_in_scope(
partial(
changed_lines,
repo_path,
- _normalize_revspec(revspec),
+ revspec or "HEAD",
working_tree=working_tree,
)
)
@@ -941,7 +925,7 @@ async def _independent_changes_block(
return None
# Returns [] without a git call for anything that is not a range, so the
# range test lives in one place rather than here as well.
- sets = await asyncio.to_thread(commit_file_sets, str(ctx.path), _normalize_revspec(revspec))
+ sets = await asyncio.to_thread(commit_file_sets, str(ctx.path), revspec)
try:
async with get_session(session_factory) as session:
repo_id = (await _get_repo(session)).id
diff --git a/packages/ui/src/files/file-coverage-tab.tsx b/packages/ui/src/files/file-coverage-tab.tsx
index 9dfb3cfd8..72f5114f7 100644
--- a/packages/ui/src/files/file-coverage-tab.tsx
+++ b/packages/ui/src/files/file-coverage-tab.tsx
@@ -1,6 +1,7 @@
import type { ReactNode } from "react";
import { PageLede } from "../shared/page-lede";
import { coverageBand } from "../health/tokens";
+import { COVERAGE_REPORT_FORMATS } from "../health/coverage-formats";
import { formatNumber, formatRelativeTime } from "../lib/format";
import type { FileDetailCoverage } from "@repowise-dev/types/files";
import { FileSection, Fig } from "./file-section";
@@ -44,12 +45,12 @@ export function FileCoverageTab({
title="Line-level coverage"
description="What a report would add here: which lines of this file your tests actually executed, rather than which tests can reach it."
>
- <p className="max-w-[62ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ <p className="max-w-[62ch] text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
Run your suite with coverage on and hand us the report with{" "}
<span className="font-mono text-[var(--color-text-primary)]">
repowise coverage add &lt;report&gt;
</span>
- . LCOV, Cobertura and coverage.py output all work.
+ . Any of {COVERAGE_REPORT_FORMATS.join(", ")} works.
</p>
</FileSection>
</div>
diff --git a/packages/ui/src/health/coverage-formats.ts b/packages/ui/src/health/coverage-formats.ts
new file mode 100644
index 000000000..4ab5fe004
--- /dev/null
+++ b/packages/ui/src/health/coverage-formats.ts
@@ -0,0 +1,17 @@
+/**
+ * Curated display list of the coverage reports users produce, in display
+ * order. Not a mirror of the parsers: core's `PARSERS` registry in
+ * `analysis/health/coverage/detector.py` is authoritative, and repowise's own
+ * JSON is left out because nobody hand-produces it.
+ */
+export const COVERAGE_REPORT_FORMATS = [
+ "LCOV",
+ "Cobertura",
+ "Clover",
+ "Go coverprofile",
+ "JaCoCo",
+ "coverage.py",
+] as const;
+
+/** The micro-label form shown under the empty-state commands. */
+export const COVERAGE_REPORT_FORMATS_LABEL = COVERAGE_REPORT_FORMATS.join(" · ");
diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsx
index 501c2f9fc..af32bb691 100644
--- a/packages/ui/src/health/coverage-view.tsx
+++ b/packages/ui/src/health/coverage-view.tsx
@@ -51,6 +51,7 @@ import {
type CoverageFilePromptInput,
} from "./ai-prompt-builder";
import { scoreBadgeClass } from "./tokens";
+import { COVERAGE_REPORT_FORMATS_LABEL } from "./coverage-formats";
import type { CodeHealthAdapter } from "./code-health-adapter";
export function CoverageView({ adapter }: { adapter: CodeHealthAdapter }) {
@@ -591,7 +592,7 @@ function NoCoverageState() {
<h2 className="text-base font-semibold text-[var(--color-text-primary)]">
Nothing here can say whether your code is tested
</h2>
- <p className="text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ <p className="text-[15px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
No coverage report has been ingested, and the dependency graph found no
test files to trace either. Either would fill this tab: a report gives the
lines your tests executed, and the graph alone can name which tests reach
@@ -603,7 +604,7 @@ function NoCoverageState() {
repowise coverage add coverage.lcov
</pre>
<p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- LCOV · Cobertura · Clover
+ {COVERAGE_REPORT_FORMATS_LABEL}
</p>
</div>
);
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index d7de77b57..9812ff299 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -41,6 +41,7 @@ export * from "./file-opportunity";
export * from "./triage-view";
export * from "./findings-view";
export * from "./performance-view";
+export * from "./coverage-formats";
export * from "./coverage-view";
export * from "./inferred-tests-view";
export * from "./tests-reaching-list";
diff --git a/packages/ui/src/health/inferred-tests-view.tsx b/packages/ui/src/health/inferred-tests-view.tsx
index 2a922ae32..62d0e9765 100644
--- a/packages/ui/src/health/inferred-tests-view.tsx
+++ b/packages/ui/src/health/inferred-tests-view.tsx
@@ -44,6 +44,7 @@ import { formatNumber } from "../lib/format";
import { RiskCoverageScatter } from "./risk-coverage-scatter";
import { scoreBadgeClass } from "./tokens";
+import { COVERAGE_REPORT_FORMATS_LABEL } from "./coverage-formats";
/** Below this, a file nothing reaches is worth leading with. */
const AT_RISK_SCORE = 6;
@@ -246,7 +247,7 @@ function AddResolutionSection() {
description="Everything above is read from the dependency graph and needs no setup. A report adds what the graph structurally cannot see: which lines actually ran."
>
<div className="flex max-w-[62ch] flex-col gap-3 border-t border-[var(--color-border-default)] pt-4">
- <p className="text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ <p className="text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
Hand us a report and the two columns above become a continuous axis,
every file moves to its own coverage figure, and the untested-hotspot
list narrows from &ldquo;nothing calls this&rdquo; to the exact lines no
@@ -257,7 +258,7 @@ function AddResolutionSection() {
repowise coverage add coverage.lcov
</pre>
<p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- LCOV · Cobertura · Clover
+ {COVERAGE_REPORT_FORMATS_LABEL}
</p>
</div>
</OverviewSection>
diff --git a/plugins/claude-code/commands/coverage.md b/plugins/claude-code/commands/coverage.md
index c9c0ebf1f..3b11b35b6 100644
--- a/plugins/claude-code/commands/coverage.md
+++ b/plugins/claude-code/commands/coverage.md
@@ -1,5 +1,5 @@
---
-description: Ingest or inspect test-coverage reports — LCOV, Cobertura/Clover, or coverage.py .coverage (builds the per-test map when contexts are present).
+description: Ingest or inspect test-coverage reports (LCOV, Cobertura, Clover, Go cover profiles, JaCoCo, repowise JSON, or coverage.py .coverage; builds the per-test map when contexts are present), or gate a change on its patch coverage in CI.
allowed-tools: Bash, Read
---
@@ -25,13 +25,31 @@ repowise coverage status
Handle `$ARGUMENTS`:
- "status" / "show" → `repowise coverage status`
-- A report path (`coverage.lcov`, `lcov.info`, `coverage.xml`, `.coverage`, …)
- → `repowise coverage add <path>`
+- A report path (`coverage.lcov`, `lcov.info`, `coverage.xml`, `coverage.out`,
+ `jacoco.xml`, `.coverage`, …) → `repowise coverage add <path>`
- "add" with no path → `repowise coverage add` (auto-discover common report paths)
- Multiple paths → `repowise coverage add <a> <b>` (merged; hit wins)
+- "check" / "gate" / "patch coverage" → `repowise coverage check [REVSPEC]`
Useful flags on `add`: `--verbose` for ingestion debug logs; `--path <dir>`
-to point at a different repo.
+to point at a different repo; `--format <parser>` to force a parser instead
+of auto-detecting from content.
+
+## Gating a change in CI
+
+`repowise coverage check` reports patch coverage: the share of a change's
+executable lines the tests ran. It needs no index, so it runs in CI.
+REVSPEC is the change (`origin/main...HEAD`, `base..head`, or one commit;
+defaults to the default branch `...HEAD`).
+```
+repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80
+```
+- `--report FILE` (repeatable; discovered from the usual locations when omitted)
+- `--fail-under PCT` exits 1 below the threshold (defaults to
+ `coverage.fail_under` in `.repowise/config.yaml`)
+- `--report-format <parser>` forces a parser
+- `--format github` writes annotations plus a step summary in GitHub Actions;
+ `--format json|markdown` for other consumers
## Notes
diff --git a/plugins/shared/commands/coverage.md b/plugins/shared/commands/coverage.md
index b78d5238e..21add2029 100644
--- a/plugins/shared/commands/coverage.md
+++ b/plugins/shared/commands/coverage.md
@@ -1,6 +1,6 @@
---
frontmatter: |
- description: Ingest or inspect test-coverage reports — LCOV, Cobertura/Clover, or coverage.py .coverage (builds the per-test map when contexts are present).
+ description: Ingest or inspect test-coverage reports (LCOV, Cobertura, Clover, Go cover profiles, JaCoCo, repowise JSON, or coverage.py .coverage; builds the per-test map when contexts are present), or gate a change on its patch coverage in CI.
allowed-tools: Bash, Read
---
@@ -26,13 +26,31 @@ repowise coverage status
Handle `$ARGUMENTS`:
- "status" / "show" → `repowise coverage status`
-- A report path (`coverage.lcov`, `lcov.info`, `coverage.xml`, `.coverage`, …)
- → `repowise coverage add <path>`
+- A report path (`coverage.lcov`, `lcov.info`, `coverage.xml`, `coverage.out`,
+ `jacoco.xml`, `.coverage`, …) → `repowise coverage add <path>`
- "add" with no path → `repowise coverage add` (auto-discover common report paths)
- Multiple paths → `repowise coverage add <a> <b>` (merged; hit wins)
+- "check" / "gate" / "patch coverage" → `repowise coverage check [REVSPEC]`
Useful flags on `add`: `--verbose` for ingestion debug logs; `--path <dir>`
-to point at a different repo.
+to point at a different repo; `--format <parser>` to force a parser instead
+of auto-detecting from content.
+
+## Gating a change in CI
+
+`repowise coverage check` reports patch coverage: the share of a change's
+executable lines the tests ran. It needs no index, so it runs in CI.
+REVSPEC is the change (`origin/main...HEAD`, `base..head`, or one commit;
+defaults to the default branch `...HEAD`).
+```
+repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80
+```
+- `--report FILE` (repeatable; discovered from the usual locations when omitted)
+- `--fail-under PCT` exits 1 below the threshold (defaults to
+ `coverage.fail_under` in `.repowise/config.yaml`)
+- `--report-format <parser>` forces a parser
+- `--format github` writes annotations plus a step summary in GitHub Actions;
+ `--format json|markdown` for other consumers
## Notes
diff --git a/tests/fixtures/coverage/sample.coverprofile b/tests/fixtures/coverage/sample.coverprofile
new file mode 100644
index 000000000..480b9e565
--- /dev/null
+++ b/tests/fixtures/coverage/sample.coverprofile
@@ -0,0 +1,10 @@
+mode: set
+example.com/mod/pkg/calc.go:3.24,5.2 1 1
+example.com/mod/pkg/calc.go:7.30,8.14 1 0
+example.com/mod/pkg/calc.go:8.14,10.3 1 0
+example.com/mod/pkg/calc.go:10.3,11.1 0 0
+example.com/mod/pkg/calc.go:12.2,14.1 1 0
+example.com/mod/util/str.go:3.30,5.2 2 1
+mode: set
+example.com/mod/pkg/calc.go:7.30,8.14 1 1
+example.com/mod/util/str.go:3.30,5.2 2 0
diff --git a/tests/fixtures/coverage/sample.jacoco.xml b/tests/fixtures/coverage/sample.jacoco.xml
new file mode 100644
index 000000000..996941c44
--- /dev/null
+++ b/tests/fixtures/coverage/sample.jacoco.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?><!DOCTYPE report PUBLIC "-//JACOCO//DTD Report 1.1//EN" "report.dtd"><report name="sample">
+ <sessioninfo id="host-1" start="1700000000000" dump="1700000001000"/>
+ <group name="app">
+ <package name="com/foo">
+ <class name="com/foo/Bar" sourcefilename="Bar.java">
+ <method name="run" desc="()V" line="5">
+ <counter type="INSTRUCTION" missed="3" covered="6"/>
+ <counter type="LINE" missed="1" covered="2"/>
+ </method>
+ <counter type="LINE" missed="2" covered="2"/>
+ </class>
+ <sourcefile name="Bar.java">
+ <line nr="3" mi="0" ci="2" mb="0" cb="0"/>
+ <line nr="5" mi="0" ci="4" mb="1" cb="1"/>
+ <line nr="7" mi="3" ci="0" mb="2" cb="0"/>
+ <line nr="9" mi="1" ci="0" mb="0" cb="0"/>
+ <counter type="LINE" missed="2" covered="2"/>
+ </sourcefile>
+ <sourcefile name="Api.java">
+ <counter type="CLASS" missed="0" covered="1"/>
+ </sourcefile>
+ </package>
+ <package name="">
+ <class name="Main" sourcefilename="Main.java">
+ <counter type="LINE" missed="1" covered="1"/>
+ </class>
+ <sourcefile name="Main.java">
+ <line nr="1" mi="1" ci="0" mb="0" cb="0"/>
+ <line nr="2" mi="0" ci="1" mb="0" cb="0"/>
+ <line nr="4" mi="0" ci="0" mb="0" cb="0"/>
+ </sourcefile>
+ </package>
+ </group>
+ <group name="lib">
+ <package name="com/foo">
+ <sourcefile name="Bar.java">
+ <line nr="7" mi="0" ci="3" mb="1" cb="1"/>
+ </sourcefile>
+ </package>
+ </group>
+ <counter type="LINE" missed="3" covered="4"/>
+</report>
diff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.py
index 2db9daf9a..d5a68b922 100644
--- a/tests/unit/analysis/test_change_risk.py
+++ b/tests/unit/analysis/test_change_risk.py
@@ -336,11 +336,11 @@ def test_score_live_change_three_dot_range_is_valid(git_repo: Path) -> None:
["git", "rev-parse", "HEAD"], cwd=git_repo, check=True, capture_output=True, text=True
).stdout.strip()
_commit(git_repo, {"r/a.py": "a=1\n"}, "feat: a", author="Dev")
- # Three-dot syntax (base...HEAD) must degrade to a valid anchor rather than
- # leaving a leading dot that git rejects as a ref.
+ # Three-dot syntax (base...HEAD) resolves to valid refs and keeps its
+ # merge-base meaning in the label.
result = score_live_change(str(git_repo), f"{base}...HEAD", baseline=0)
assert result.features.nf == 1
- assert result.features.ref == f"{base}..HEAD"
+ assert result.features.ref == f"{base}...HEAD"
def test_score_live_change_below_min_baseline_yields_no_percentile(git_repo: Path) -> None:
diff --git a/tests/unit/analysis/test_changed_lines.py b/tests/unit/analysis/test_changed_lines.py
index 01d2f8f6d..eb3c2742e 100644
--- a/tests/unit/analysis/test_changed_lines.py
+++ b/tests/unit/analysis/test_changed_lines.py
@@ -112,3 +112,52 @@ def test_changed_lines_unknown_revision_raises(git_repo) -> None:
changed_lines(str(git_repo), "nope123..HEAD")
with pytest.raises(ValueError):
changed_lines(str(git_repo), "deadbeef")
+
+
+def test_changed_lines_three_dot_diffs_from_merge_base(git_repo) -> None:
+ # A branch edits line 2 while base moves on and edits line 3: the PR view
+ # (three dots) reports only the branch's own line.
+ _git(git_repo, "branch", "-M", "main")
+ _git(git_repo, "switch", "-qc", "feat")
+ (git_repo / "mod.py").write_text("a = 1\nb = 22\nc = 3\n", encoding="utf-8")
+ _git(git_repo, "commit", "-qam", "feat edit")
+ _git(git_repo, "switch", "-q", "main")
+ (git_repo / "mod.py").write_text("a = 1\nb = 2\nc = 33\n", encoding="utf-8")
+ _git(git_repo, "commit", "-qam", "base edit")
+
+ changed, label = changed_lines(str(git_repo), "main...feat")
+ assert label == "main...feat"
+ assert changed == {"mod.py": {2}}
+ # Two dots compares the tips, so base's own edit shows up too.
+ assert changed_lines(str(git_repo), "main..feat")[0] == {"mod.py": {2, 3}}
+
+
+def test_single_commit_at_a_shallow_boundary_raises(git_repo, tmp_path_factory) -> None:
+ # Its parents are cut off, so git would diff against the empty tree and
+ # report every line as changed.
+ (git_repo / "mod.py").write_text("a = 1\nb = 2\nc = 3\nd = 4\n", encoding="utf-8")
+ _git(git_repo, "commit", "-qam", "second")
+ clone = tmp_path_factory.mktemp("shallow") / "c"
+ _git(git_repo, "clone", "-q", "--depth", "1", git_repo.as_uri(), str(clone))
+
+ with pytest.raises(ValueError, match="shallow"):
+ changed_lines(str(clone), "HEAD")
+
+
+def test_range_without_merge_base_raises_value_error(git_repo) -> None:
+ _git(git_repo, "branch", "-M", "main")
+ _git(git_repo, "checkout", "-q", "--orphan", "lonely")
+ _git(git_repo, "commit", "-qm", "orphan")
+
+ with pytest.raises(ValueError):
+ changed_lines(str(git_repo), "main...lonely")
+
+
+def test_split_revspec() -> None:
+ from repowise.core.analysis.change_risk.features import split_revspec
+
+ assert split_revspec("a..b") == ("a", "..", "b")
+ assert split_revspec("a...b") == ("a", "...", "b")
+ assert split_revspec("HEAD~3..") == ("HEAD~3", "..", "HEAD")
+ assert split_revspec("..HEAD") == ("HEAD", "..", "HEAD")
+ assert split_revspec("HEAD") is None
diff --git a/tests/unit/analysis/test_patch_coverage.py b/tests/unit/analysis/test_patch_coverage.py
new file mode 100644
index 000000000..47c5a0f5b
--- /dev/null
+++ b/tests/unit/analysis/test_patch_coverage.py
@@ -0,0 +1,203 @@
+"""Patch coverage: the pure compute and its renderings."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.changed_lines import line_ranges
+from repowise.core.analysis.health.coverage import file_coverage
+from repowise.core.analysis.patch_coverage import (
+ PatchScope,
+ compute_patch_coverage,
+ fmt_pct,
+ github_annotations,
+ headline,
+ render_markdown,
+)
+
+
+def _cov(path: str, covered: list[int], coverable: list[int]):
+ return {path: file_coverage(path, covered, coverable)}
+
+
+def test_counts_only_changed_executable_lines() -> None:
+ # Lines 1-6 changed; 2 and 5 are comments (not coverable); 3 is unexecuted.
+ coverage = _cov("src/a.py", covered=[1, 4, 6, 9], coverable=[1, 3, 4, 6, 9])
+ pc = compute_patch_coverage({"src/a.py": {1, 2, 3, 4, 5, 6}}, coverage)
+
+ (f,) = pc.files
+ assert f.status == "measured"
+ assert (f.covered_line_count, f.coverable_line_count, f.changed_line_count) == (3, 4, 6)
+ assert f.uncovered_ranges == ((3, 3),)
+ assert pc.patch_coverage_pct == 75.0
+
+
+def test_file_absent_from_report_is_not_in_report_and_not_counted() -> None:
+ coverage = _cov("src/a.py", covered=[1], coverable=[1])
+ pc = compute_patch_coverage({"src/a.py": {1}, "src/new.py": {1, 2}}, coverage)
+
+ assert [f.status for f in pc.files] == ["measured", "not_in_report"]
+ assert pc.patch_coverage_pct == 100.0 # the unknown file is surfaced, not scored as 0%
+
+
+def test_tests_and_unmeasured_kinds_are_out_of_scope() -> None:
+ coverage = _cov("src/a.py", covered=[1], coverable=[1])
+ pc = compute_patch_coverage(
+ {"src/a.py": {1}, "tests/test_a.py": {3}, "README.md": {1}}, coverage
+ )
+
+ assert [f.file_path for f in pc.files] == ["src/a.py"]
+ assert pc.out_of_scope_count == 2
+
+
+def test_report_without_line_data_is_never_zero_percent() -> None:
+ fc = file_coverage("src/a.py", [1], [])
+ pc = compute_patch_coverage({"src/a.py": {1, 2}}, {"src/a.py": fc})
+
+ assert pc.files[0].status == "no_line_data"
+ assert pc.patch_coverage_pct is None
+ assert pc.gate == "not_set"
+
+
+def test_gate() -> None:
+ coverage = _cov("a.py", covered=[1], coverable=[1, 2])
+ changed = {"a.py": {1, 2}}
+ assert compute_patch_coverage(changed, coverage, threshold=50).gate == "pass"
+ assert compute_patch_coverage(changed, coverage, threshold=60).gate == "fail"
+ # Only comments changed: nothing to judge, so the gate does not fail.
+ assert compute_patch_coverage({"a.py": {9}}, coverage, threshold=90).gate == "no_data"
+
+
+def test_line_ranges() -> None:
+ assert line_ranges([5, 1, 2, 3, 7, 8]) == ((1, 3), (5, 5), (7, 8))
+ assert line_ranges([]) == ()
+
+
+def test_to_dict_shape() -> None:
+ coverage = _cov("a.py", covered=[1], coverable=[1, 2])
+ d = compute_patch_coverage(
+ {"a.py": {1, 2}}, coverage, threshold=80, scope=PatchScope(label="main...HEAD")
+ ).to_dict()
+
+ assert d["patch_coverage_pct"] == 50.0
+ assert d["gate"] == "fail"
+ assert d["file_counts"]["measured"] == 1
+ assert d["files"][0]["uncovered_ranges"] == [[2, 2]]
+ assert d["files"][0]["file_path"] == "a.py"
+ assert d["covered_line_count"] == 1
+ assert d["scope"]["label"] == "main...HEAD"
+
+
+def test_markdown_passing_change_is_quiet() -> None:
+ coverage = _cov("a.py", covered=[1, 2], coverable=[1, 2])
+ md = render_markdown(
+ compute_patch_coverage(
+ {"a.py": {1, 2}},
+ coverage,
+ threshold=80,
+ scope=PatchScope(label="main...HEAD", source_formats=("lcov",)),
+ )
+ )
+
+ assert md.splitlines() == [
+ "**Patch coverage 100.0%** (2 of 2 changed executable lines covered) "
+ "· meets the 80.0% gate",
+ "",
+ "`main...HEAD` · lcov · 1 of 1 changed files measured",
+ ]
+
+
+def test_markdown_lists_gaps_and_files_missing_from_report() -> None:
+ coverage = _cov("a.py", covered=[1], coverable=[1, 2, 3, 5])
+ md = render_markdown(
+ compute_patch_coverage({"a.py": {1, 2, 3, 5}, "b.py": {1}}, coverage, threshold=90)
+ )
+
+ assert "below the 90.0% gate" in md
+ assert "| `a.py` | 2-3, 5 | 1 of 4 |" in md
+ assert "1 changed file is not in the coverage report" in md
+ assert "`b.py`" in md
+ assert "0%" not in md.split("<details>")[1]
+
+
+def test_headline_without_data_explains_why() -> None:
+ fc = file_coverage("a.py", [1], [])
+ text = headline(compute_patch_coverage({"a.py": {1}}, {"a.py": fc}))
+ assert "does not say which lines are executable" in text
+
+
+def test_github_annotations_escape_and_span() -> None:
+ coverage = _cov("dir,x/a:b.py", covered=[], coverable=[4, 5, 9])
+ lines = github_annotations(compute_patch_coverage({"dir,x/a:b.py": {4, 5, 9}}, coverage))
+
+ assert lines == [
+ "::warning file=dir%2Cx/a%3Ab.py,line=4,endLine=5,title=Uncovered change::"
+ "Changed lines 4-5 not covered by tests",
+ "::warning file=dir%2Cx/a%3Ab.py,line=9,endLine=9,title=Uncovered change::"
+ "Changed line 9 not covered by tests",
+ ]
+
+
+def test_gate_compares_unrounded_and_display_never_rounds_up() -> None:
+ # 79.9975% rounds to 80.0 but must still fail an 80% gate, and say so.
+ coverable = list(range(1, 40001))
+ coverage = _cov("a.py", covered=coverable[:31999], coverable=coverable)
+ pc = compute_patch_coverage({"a.py": set(coverable)}, coverage, threshold=80)
+
+ assert pc.gate == "fail"
+ assert "79.9%" in headline(pc)
+ assert fmt_pct(79.96) == "79.9%"
+ assert fmt_pct(None) == "n/a"
+
+
+def test_no_data_headline_names_the_reason_and_the_skipped_gate() -> None:
+ coverage = _cov("a.py", covered=[1], coverable=[1])
+ empty = headline(compute_patch_coverage({}, coverage, threshold=80))
+ assert "no changed lines" in empty
+ assert "80.0% gate was not applied" in empty
+ docs_only = headline(compute_patch_coverage({"README.md": {1}}, coverage))
+ assert "Only tests or files the report does not measure changed" in docs_only
+
+
+def test_annotations_mark_largest_ranges_first_and_count_the_rest() -> None:
+ coverable = list(range(1, 100))
+ # Twelve single uncovered lines plus one 5-line run.
+ uncovered = {*range(1, 24, 2), 50, 51, 52, 53, 54}
+ covered = [n for n in coverable if n not in uncovered]
+ pc = compute_patch_coverage(
+ {"a.py": set(coverable)}, _cov("a.py", covered, coverable), threshold=99
+ )
+ lines = github_annotations(pc)
+
+ warnings = [line for line in lines if line.startswith("::warning")]
+ assert len(warnings) == 10
+ assert "line=50,endLine=54" in warnings[0]
+ assert lines[0].startswith("::error::Patch coverage")
+ assert lines[-1].startswith("::notice::3 more uncovered changed ranges")
+
+
+def test_markdown_lists_files_without_line_data() -> None:
+ fc = file_coverage("b.py", [1], [])
+ md = render_markdown(
+ compute_patch_coverage(
+ {"a.py": {1}, "b.py": {1}}, {**_cov("a.py", [1], [1]), "b.py": fc}
+ )
+ )
+ assert "1 changed file is in a report without line data" in md
+
+
+def test_exact_threshold_passes_and_reads_exactly() -> None:
+ # 57 / 100 * 100 is 56.99999999999999 in floating point.
+ coverable = list(range(1, 101))
+ pc = compute_patch_coverage(
+ {"a.py": set(coverable)}, _cov("a.py", coverable[:57], coverable), threshold=57
+ )
+ assert pc.gate == "pass"
+ assert "57.0%" in headline(pc)
+ assert pc.to_dict()["patch_coverage_pct"] == 57.0
+
+
+def test_serialized_percentage_is_floored_not_rounded() -> None:
+ coverable = list(range(1, 40001))
+ pc = compute_patch_coverage(
+ {"a.py": set(coverable)}, _cov("a.py", coverable[:31999], coverable), threshold=80
+ )
+ assert pc.to_dict()["patch_coverage_pct"] == 79.99
diff --git a/tests/unit/cli/test_ci.py b/tests/unit/cli/test_ci.py
new file mode 100644
index 000000000..f9b465420
--- /dev/null
+++ b/tests/unit/cli/test_ci.py
@@ -0,0 +1,50 @@
+"""The CLI side of CI gates: exit codes, output channels, the step summary."""
+
+from __future__ import annotations
+
+import json
+
+import click
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.ci import (
+ EXIT_CANNOT_EVALUATE,
+ append_step_summary,
+ cannot_evaluate,
+)
+
+
+def _invoke(fmt: str):
+ @click.command()
+ def cmd() -> None:
+ cannot_evaluate(fmt, "no_report", "No report: 5%")
+
+ return CliRunner().invoke(cmd)
+
+
+def test_cannot_evaluate_json_is_one_document() -> None:
+ result = _invoke("json")
+ assert result.exit_code == EXIT_CANNOT_EVALUATE
+ assert json.loads(result.stdout) == {"error": "no_report", "message": "No report: 5%"}
+
+
+def test_cannot_evaluate_github_emits_an_error_command() -> None:
+ result = _invoke("github")
+ assert result.exit_code == EXIT_CANNOT_EVALUATE
+ assert "::error::No report: 5%25" in result.stdout
+
+
[email protected]("fmt", ["table", "markdown"])
+def test_cannot_evaluate_other_formats_exit_2(fmt: str) -> None:
+ assert _invoke(fmt).exit_code == EXIT_CANNOT_EVALUATE
+
+
+def test_append_step_summary(tmp_path) -> None:
+ target = tmp_path / "summary.md"
+ assert append_step_summary("# a", env={"GITHUB_STEP_SUMMARY": str(target)}) is True
+ assert append_step_summary("b\n\n", env={"GITHUB_STEP_SUMMARY": str(target)}) is True
+ assert target.read_text(encoding="utf-8") == "# a\nb\n"
+ assert append_step_summary("x", env={}) is False
+ missing = tmp_path / "no" / "dir.md"
+ assert append_step_summary("x", env={"GITHUB_STEP_SUMMARY": str(missing)}) is False
diff --git a/tests/unit/cli/test_coverage_check_cmd.py b/tests/unit/cli/test_coverage_check_cmd.py
new file mode 100644
index 000000000..62e19e0c0
--- /dev/null
+++ b/tests/unit/cli/test_coverage_check_cmd.py
@@ -0,0 +1,191 @@
+"""``repowise coverage check``: patch coverage of a change against a real git repo."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.main import cli
+from repowise.core.ci.base import CI_BASE_VARS
+
+
+def _git(cwd, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)
+
+
+def repo(tmp_path):
+ """``main`` has src/app.py; branch ``feat`` edits lines 2-3 and adds src/new.py."""
+ _git(tmp_path, "init", "-q", "-b", "main")
+ _git(tmp_path, "config", "user.email", "[email protected]")
+ _git(tmp_path, "config", "user.name", "t")
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "app.py").write_text("a = 1\nb = 2\nc = 3\n", encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "commit", "-qm", "init")
+ _git(tmp_path, "switch", "-qc", "feat")
+ (tmp_path / "src" / "app.py").write_text("a = 1\nb = 22\nc = 33\n", encoding="utf-8")
+ (tmp_path / "src" / "new.py").write_text("x = 1\n", encoding="utf-8")
+ (tmp_path / "README.md").write_text("docs\n", encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "commit", "-qm", "feat")
+ return tmp_path
+
+
+def _lcov(repo, covered: dict[int, int]) -> str:
+ """An lcov report for src/app.py with absolute paths, as runners write them."""
+ body = "".join(f"DA:{line},{hits}\n" for line, hits in covered.items())
+ path = repo / "coverage.lcov"
+ path.write_text(f"SF:{repo / 'src' / 'app.py'}\n{body}end_of_record\n", encoding="utf-8")
+ return str(path)
+
+
+def _run(repo, *args: str, env: dict[str, str] | None = None):
+ # Unset the CI variables the default base reads, so the host CI cannot leak in.
+ base_env = dict.fromkeys(CI_BASE_VARS, "")
+ return CliRunner(env={**base_env, **(env or {})}).invoke(
+ cli, ["coverage", "check", "--path", str(repo), *args]
+ )
+
+
+def test_json_reports_patch_coverage_without_an_index(repo) -> None:
+ report = _lcov(repo, {1: 1, 2: 1, 3: 0})
+ result = _run(repo, "main...feat", "--report", report, "--format", "json")
+
+ assert result.exit_code == 0, result.output
+ data = json.loads(result.stdout)
+ assert data["patch_coverage_pct"] == 50.0
+ assert (data["covered_line_count"], data["coverable_line_count"]) == (1, 2)
+ assert data["gate"] == "not_set"
+ statuses = {f["file_path"]: f["status"] for f in data["files"]}
+ # The new file resolves from git (no index) and is surfaced, README is out of scope.
+ assert statuses == {"src/app.py": "measured", "src/new.py": "not_in_report"}
+ assert data["file_counts"]["out_of_scope"] == 1
+ assert data["scope"]["label"] == "main...feat"
+ assert data["scope"]["reports"] == [report]
+
+
+def test_gate_fails_below_threshold(repo) -> None:
+ report = _lcov(repo, {1: 1, 2: 1, 3: 0})
+
+ assert _run(repo, "main...feat", "--report", report, "--fail-under", "50").exit_code == 0
+ failed = _run(repo, "main...feat", "--report", report, "--fail-under", "80")
+ assert failed.exit_code == 1
+ assert "below the 80.0% gate" in failed.output
+
+
+def test_threshold_defaults_to_repo_config(repo) -> None:
+ (repo / ".repowise").mkdir()
+ (repo / ".repowise" / "config.yaml").write_text(
+ "coverage:\n fail_under: 90\n", encoding="utf-8"
+ )
+ report = _lcov(repo, {2: 1, 3: 0})
+
+ assert _run(repo, "main...feat", "--report", report).exit_code == 1
+
+
+def test_github_format_writes_annotations_and_step_summary(repo, tmp_path_factory) -> None:
+ report = _lcov(repo, {2: 1, 3: 0})
+ summary = tmp_path_factory.mktemp("gh") / "summary.md"
+
+ result = _run(
+ repo,
+ "main...feat",
+ "--report",
+ report,
+ "--format",
+ "github",
+ env={"GITHUB_STEP_SUMMARY": str(summary)},
+ )
+
+ assert result.exit_code == 0, result.output
+ assert "::warning file=src/app.py,line=3,endLine=3" in result.stdout
+ assert summary.read_text(encoding="utf-8").startswith("**Patch coverage 50.0%**")
+
+
+def test_default_base_comes_from_ci_variables(repo) -> None:
+ # A CI checkout: detached, no local trunk, the base only as a remote branch.
+ _git(repo, "update-ref", "refs/remotes/origin/main", "main")
+ _git(repo, "checkout", "-q", "--detach", "feat")
+ _git(repo, "branch", "-D", "main")
+ report = _lcov(repo, {2: 1, 3: 0})
+
+ via_ci = _run(repo, "--report", report, "--format", "json", env={"GITHUB_BASE_REF": "main"})
+ assert via_ci.exit_code == 0, via_ci.output
+ assert json.loads(via_ci.stdout)["scope"]["label"] == "origin/main...HEAD"
+ # Without the variable, origin/main is found even though origin/HEAD is unset.
+ fallback = _run(repo, "--report", report, "--format", "json")
+ assert json.loads(fallback.stdout)["patch_coverage_pct"] == 50.0
+
+
+def test_undeterminable_base_exits_2_instead_of_passing(repo) -> None:
+ _git(repo, "checkout", "-q", "--detach", "feat")
+ _git(repo, "branch", "-D", "main")
+ report = _lcov(repo, {2: 1, 3: 0})
+
+ result = _run(repo, "--report", report, "--fail-under", "90")
+ assert result.exit_code == 2
+ assert "Pass REVSPEC" in result.output
+
+
+def test_bad_fail_under_in_config_exits_2(repo) -> None:
+ (repo / ".repowise").mkdir()
+ (repo / ".repowise" / "config.yaml").write_text(
+ "coverage:\n fail_under: 80%\n", encoding="utf-8"
+ )
+ assert _run(repo, "main...feat", "--report", _lcov(repo, {2: 1})).exit_code == 2
+
+
+def test_reports_come_from_config_paths(repo) -> None:
+ out = repo / "out"
+ out.mkdir()
+ (out / "cov.info").write_text(
+ f"SF:{repo / 'src' / 'app.py'}\nDA:2,1\nDA:3,1\nend_of_record\n", encoding="utf-8"
+ )
+ (repo / ".repowise").mkdir()
+ (repo / ".repowise" / "config.yaml").write_text(
+ "coverage:\n paths: [out/cov.info]\n", encoding="utf-8"
+ )
+ result = _run(repo, "main...feat", "--format", "json")
+ assert result.exit_code == 0, result.output
+ assert json.loads(result.stdout)["patch_coverage_pct"] == 100.0
+
+
+def test_cannot_evaluate_exits_2(repo, tmp_path) -> None:
+ # No report given and none discoverable.
+ assert _run(repo, "main...feat").exit_code == 2
+ report = _lcov(repo, {1: 1})
+ assert _run(repo, "nope...feat", "--report", report).exit_code == 2
+ # A report whose paths match nothing in the repository.
+ other = tmp_path / "other.lcov"
+ other.write_text("SF:/elsewhere/zzz.py\nDA:1,1\nend_of_record\n", encoding="utf-8")
+ assert _run(repo, "main...feat", "--report", str(other)).exit_code == 2
+
+
+def test_not_a_git_repository_exits_2(tmp_path) -> None:
+ lcov = tmp_path / "c.lcov"
+ lcov.write_text("SF:a.py\nDA:1,1\nend_of_record\n", encoding="utf-8")
+ assert _run(tmp_path, "--report", str(lcov)).exit_code == 2
+
+
+def test_no_merge_base_exits_2_not_1(repo) -> None:
+ # An unrelated history stands in for a shallow clone that lacks the merge-base.
+ _git(repo, "checkout", "-q", "--orphan", "lonely")
+ _git(repo, "commit", "-qm", "orphan")
+ report = _lcov(repo, {1: 1})
+
+ result = _run(repo, "main...lonely", "--report", report)
+ assert result.exit_code == 2
+ assert "merge-base" in result.output
+
+
+def test_flag_overrides_a_bad_config_threshold(repo) -> None:
+ (repo / ".repowise").mkdir()
+ (repo / ".repowise" / "config.yaml").write_text(
+ "coverage:\n fail_under: 80%\n", encoding="utf-8"
+ )
+ report = _lcov(repo, {2: 1, 3: 1})
+ assert _run(repo, "main...feat", "--report", report, "--fail-under", "50").exit_code == 0
diff --git a/tests/unit/cli/test_update_persist_reliability.py b/tests/unit/cli/test_update_persist_reliability.py
index 4421e4934..13d72ab15 100644
--- a/tests/unit/cli/test_update_persist_reliability.py
+++ b/tests/unit/cli/test_update_persist_reliability.py
@@ -247,7 +247,7 @@ def test_missing_reingested_coverage_is_authoritative_empty(tmp_path: Path, monk
lambda _path: {"coverage": {"reingest_on_update": True}},
)
monkeypatch.setattr(
- "repowise.core.analysis.health.coverage.discover_artifacts",
+ "repowise.core.analysis.health.coverage.discovery.discover_artifacts",
lambda *_args, **_kwargs: [],
)
@@ -261,6 +261,26 @@ def test_missing_reingested_coverage_is_authoritative_empty(tmp_path: Path, monk
assert authoritative is True
+def test_reingest_with_nothing_to_read_keeps_stored_coverage(tmp_path: Path, monkeypatch) -> None:
+ # No paths and discovery off: coverage added by hand must survive an update.
+ from repowise.cli.commands.update_cmd import persistence
+
+ monkeypatch.setattr(
+ "repowise.core.repo_config.load_repo_config",
+ lambda _path: {"coverage": {"reingest_on_update": True, "auto_discover": False}},
+ )
+
+ async def _stored(_session, _repo_id):
+ return []
+
+ monkeypatch.setattr("repowise.core.persistence.crud.load_coverage_for_repo", _stored)
+
+ *_, authoritative = asyncio.run(
+ persistence._coverage_for_rescore(object(), "repo", tmp_path, [])
+ )
+ assert authoritative is False
+
+
# ---------------------------------------------------------------------------
# A retirement has to reach an index nobody re-indexes
# ---------------------------------------------------------------------------
diff --git a/tests/unit/health/test_coverage_discovery.py b/tests/unit/health/test_coverage_discovery.py
index 0641375ca..481c386b8 100644
--- a/tests/unit/health/test_coverage_discovery.py
+++ b/tests/unit/health/test_coverage_discovery.py
@@ -163,6 +163,33 @@ def test_discover_recursive_patterns_reach_deep_files(tmp_path: Path) -> None:
assert {deep_cob, deep_lcov, rust} <= found
+def test_discover_finds_go_and_jacoco_defaults(tmp_path: Path) -> None:
+ """A literally spelled ``build/`` is searched even though ``build`` is pruned."""
+ go = tmp_path / "coverage.out"
+ go.write_text("mode: set\n")
+ maven = tmp_path / "target" / "site" / "jacoco" / "jacoco.xml"
+ maven.parent.mkdir(parents=True)
+ maven.write_text("<report/>")
+ gradle = tmp_path / "build" / "reports" / "jacoco" / "test" / "jacocoTestReport.xml"
+ gradle.parent.mkdir(parents=True)
+ gradle.write_text("<report/>")
+ # ``build`` reached only through ``**`` stays pruned.
+ nested = tmp_path / "lib" / "build" / "reports" / "jacoco" / "jacocoTestReport.xml"
+ nested.parent.mkdir(parents=True)
+ nested.write_text("<report/>")
+ below = tmp_path / "build" / "reports" / "jacoco" / "node_modules" / "x.xml"
+ below.parent.mkdir(parents=True)
+ below.write_text("<report/>")
+ module = tmp_path / "svc" / "target" / "site" / "jacoco-aggregate" / "jacoco.xml"
+ module.parent.mkdir(parents=True)
+ module.write_text("<report/>")
+
+ found = set(discover_artifacts(tmp_path))
+ assert {go, maven, gradle, module} <= found
+ assert nested not in found
+ assert below not in found
+
+
def test_discover_root_only_patterns_stay_root_only(tmp_path: Path) -> None:
"""Literal patterns must NOT gain match-anywhere semantics: a checked-in
fixture named ``lcov.info``/``coverage.xml`` deep in the tree is not a
diff --git a/tests/unit/health/test_coverage_parsers.py b/tests/unit/health/test_coverage_parsers.py
index b886c3806..5adcdb195 100644
--- a/tests/unit/health/test_coverage_parsers.py
+++ b/tests/unit/health/test_coverage_parsers.py
@@ -14,8 +14,11 @@ from repowise.core.analysis.health.coverage import (
parse,
parse_clover,
parse_cobertura,
+ parse_go_coverprofile,
+ parse_jacoco,
parse_lcov,
parse_repowise_json,
+ resolve_reports,
)
FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "coverage"
@@ -146,16 +149,103 @@ def test_repowise_json_bad_input_is_empty() -> None:
assert parse_repowise_json("[1,2,3]").files == []
+def test_go_coverprofile_expands_blocks_to_lines() -> None:
+ report = parse_go_coverprofile(_read("sample.coverprofile"))
+ assert report.source_format == "go-coverprofile"
+ paths = {f.file_path: f for f in report.files}
+ assert set(paths) == {"example.com/mod/pkg/calc.go", "example.com/mod/util/str.go"}
+
+ calc = paths["example.com/mod/pkg/calc.go"]
+ # The zero-statement block adds no line 11; the ``14.1`` end adds no line 14.
+ assert calc.coverable_lines == [3, 4, 5, 7, 8, 9, 10, 12, 13]
+ # 7-8 is hit in the second profile section; line 8 is hit-wins over 8-10.
+ assert calc.covered_lines == [3, 4, 5, 7, 8]
+ assert calc.total_coverable_lines == 9
+ assert calc.line_coverage_pct == 55.56
+ assert calc.branch_coverage_pct is None
+
+ # A later zero count never un-covers a block.
+ assert paths["example.com/mod/util/str.go"].line_coverage_pct == 100.0
+
+
+def test_go_coverprofile_skips_malformed_lines() -> None:
+ text = (
+ "mode: count\n"
+ "garbage\n"
+ "a.go:1.1,2.2 x 1\n"
+ "a.go:nope 1 1\n"
+ "a.go:3.1,2.1 1 1\n"
+ ":1.1,1.9 1 1\n"
+ "dir with space/b:c.go:4.2,4.9 1 3\n"
+ )
+ report = parse_go_coverprofile(text)
+ assert [(f.file_path, f.covered_lines) for f in report.files] == [
+ ("dir with space/b:c.go", [4])
+ ]
+ assert parse_go_coverprofile("").files == []
+ assert parse_go_coverprofile("mode: set\n").files == []
+
+
+def test_jacoco_parses_lines_branches_and_merges_groups() -> None:
+ report = parse_jacoco(_read("sample.jacoco.xml"))
+ assert report.source_format == "jacoco"
+ paths = {f.file_path: f for f in report.files}
+ # Api.java has no line data, so it is unmeasured rather than 0%.
+ assert set(paths) == {"com/foo/Bar.java", "Main.java"}
+
+ bar = paths["com/foo/Bar.java"]
+ assert bar.coverable_lines == [3, 5, 7, 9]
+ # Line 7 is missed in one group and covered in the other: hit wins.
+ assert bar.covered_lines == [3, 5, 7]
+ assert bar.line_coverage_pct == 75.0
+ # Line 5: 1/2, line 7: max over both groups 1/2.
+ assert bar.branch_coverage_pct == 50.0
+
+ main = paths["Main.java"]
+ assert main.coverable_lines == [1, 2]
+ assert main.covered_lines == [2]
+ assert main.branch_coverage_pct is None
+
+
+def test_jacoco_returns_empty_on_bad_xml() -> None:
+ assert parse_jacoco("<report><package").files == []
+
+
@pytest.mark.parametrize(
"name, expected",
[
("sample.lcov", "lcov"),
("sample.cobertura.xml", "cobertura"),
("sample.clover.xml", "clover"),
+ ("sample.coverprofile", "go-coverprofile"),
+ ("sample.jacoco.xml", "jacoco"),
],
)
def test_detect_format(name: str, expected: str) -> None:
assert detect_format(_read(name)) == expected
+ # Some Windows tools prepend a UTF-8 BOM.
+ assert detect_format("" + _read(name)) == expected
+
+
+def test_detect_jacoco_without_doctype() -> None:
+ assert detect_format('<?xml version="1.0"?>\n<report name="x"><group/></report>') == "jacoco"
+
+
+def test_bom_prefixed_reports_parse() -> None:
+ assert parse("" + _read("sample.coverprofile")).source_format == "go-coverprofile"
+ assert len(parse("" + _read("sample.jacoco.xml")).files) == 2
+
+
+def test_go_and_jacoco_paths_resolve_to_repo_keys() -> None:
+ keys = {"pkg/f.go", "src/main/java/com/foo/Bar.java", "src/main/java/com/other/Bar.java"}
+ go = parse_go_coverprofile("mode: set\nexample.com/mod/pkg/f.go:1.1,2.9 1 1\n")
+ jacoco = parse_jacoco(
+ '<report name="r"><package name="com/foo"><sourcefile name="Bar.java">'
+ '<line nr="1" mi="0" ci="1"/></sourcefile></package></report>'
+ )
+ res = resolve_reports([go, jacoco], keys)
+ assert set(res.coverage_map) == {"pkg/f.go", "src/main/java/com/foo/Bar.java"}
+ assert res.unmatched == [] and res.ambiguous == []
def test_detect_and_dispatch_repowise_json() -> None:
@@ -180,6 +270,8 @@ def test_parse_dispatches_via_detect() -> None:
assert parse(_read("sample.lcov")).source_format == "lcov"
assert parse(_read("sample.cobertura.xml")).source_format == "cobertura"
assert parse(_read("sample.clover.xml")).source_format == "clover"
+ assert parse(_read("sample.coverprofile")).source_format == "go-coverprofile"
+ assert parse(_read("sample.jacoco.xml")).source_format == "jacoco"
def test_parse_with_explicit_format_override() -> None:
diff --git a/tests/unit/test_ci.py b/tests/unit/test_ci.py
new file mode 100644
index 000000000..c731ffbc5
--- /dev/null
+++ b/tests/unit/test_ci.py
@@ -0,0 +1,76 @@
+"""Shared CI plumbing: workflow commands, markdown pieces, the target branch."""
+
+from __future__ import annotations
+
+import subprocess
+
+import pytest
+
+from repowise.core.ci import github
+from repowise.core.ci.base import BaseNotFoundError, default_revspec
+from repowise.core.ci.markdown import cell, details, more_line, plural
+
+
+def test_annotation_escapes_properties_and_message() -> None:
+ line = github.annotation(
+ "warning", "50% done\nnext", file="a,b:c.py", line=3, end_line=4, title="T: x"
+ )
+ assert line == "::warning file=a%2Cb%3Ac.py,line=3,endLine=4,title=T%3A x::50%25 done%0Anext"
+
+
+def test_bare_commands_share_the_builder() -> None:
+ assert github.error("boom: 5%") == "::error::boom: 5%25"
+ assert github.notice("hi") == "::notice::hi"
+
+
+def test_cap_annotations_counts_what_it_cut() -> None:
+ lines = [f"::warning::{n}" for n in range(13)]
+ capped = github.cap_annotations(lines, noun="ranges")
+ assert capped[:10] == lines[:10]
+ assert capped[10] == "::notice::3 more ranges, listed in the job summary"
+ assert github.cap_annotations(lines[:4]) == lines[:4]
+
+
+def test_markdown_pieces() -> None:
+ assert cell("a|b`c<d") == "a\\|b\\`c&lt;d"
+ assert plural(1, "file") == "1 file"
+ assert plural(2, "file") == "2 files"
+ assert more_line(0, "files") == ""
+ assert more_line(3, "files") == "and 3 more files."
+ out = details("S", [str(n) for n in range(12)], limit=10)
+ assert out[:3] == ["<details>", "<summary>S</summary>", ""]
+ assert out[-3:] == ["- and 2 more", "", "</details>"]
+ assert details("S", []) == []
+
+
+def _git(cwd, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)
+
+
+def detached_repo(tmp_path):
+ """A CI-shaped checkout: detached, no local trunk, no origin/HEAD."""
+ _git(tmp_path, "init", "-q", "-b", "work")
+ _git(tmp_path, "config", "user.email", "[email protected]")
+ _git(tmp_path, "config", "user.name", "t")
+ (tmp_path / "f").write_text("x", encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "commit", "-qm", "init")
+ _git(tmp_path, "checkout", "-q", "--detach")
+ _git(tmp_path, "branch", "-D", "work")
+ return tmp_path
+
+
+def test_default_revspec_prefers_ci_variables(detached_repo) -> None:
+ env = {"CHANGE_TARGET": "release", "GITHUB_BASE_REF": ""}
+ assert default_revspec(str(detached_repo), env) == "origin/release...HEAD"
+
+
+def test_default_revspec_falls_back_to_remote_trunk(detached_repo) -> None:
+ _git(detached_repo, "update-ref", "refs/remotes/origin/main", "HEAD")
+ assert default_revspec(str(detached_repo), {}) == "origin/main...HEAD"
+
+
+def test_default_revspec_raises_when_nothing_names_a_base(detached_repo) -> None:
+ with pytest.raises(BaseNotFoundError):
+ default_revspec(str(detached_repo), {})