Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(cli): make `coverage add` exit non-zero when it stores nothing (#1751)
Ngo Quoc Viet3433e55258a2
diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.pyindex 52a677849..49cb1f2cb 100644--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py@@ -67,6 +67,12 @@ def coverage_group() -> None:default=None,help="Force a parser instead of auto-detecting from content.",)+ "--strict",+ is_flag=True,+ default=False,+ help="Also fail when some report files did not map to the repo tree.",+)@click.option("--verbose","-v",@@ -78,6 +84,7 @@ def coverage_add(paths: tuple[str, ...],repo: str | None,coverage_format: str | None,+ strict: bool,verbose: bool,) -> None:"""Ingest coverage (auto-discovers reports when none are given).@@ -94,6 +101,10 @@ def coverage_add(repowise coverage add coverage/lcov.inforepowise coverage add .coverage # per-test map from coverage.pyrepowise coverage add web.lcov api.lcov # merged hit-wins++ Exits non-zero when nothing was stored, so `coverage add ... || exit 1`+ tells a complete ingest from a no-op. With --strict it also exits+ non-zero when some report files did not map to the repo tree."""configure_cli_logging(verbose=verbose)@@ -125,7 +136,7 @@ def coverage_add("then re-run, or pass a path:\n"" [cyan]repowise coverage add path/to/report[/cyan]")- return+ raise click.exceptions.Exit(1)console.print(f"Discovered {len(report_paths)} report(s): "+ ", ".join(p.name for p in report_paths[:5])@@ -136,7 +147,7 @@ def coverage_add(# text-parsing path (its binary bytes would not decode as UTF-8).agg_paths = [p for p in report_paths if not _is_sqlite(p)]- async def _do() -> None:+ async def _do() -> bool:from repowise.core.persistence import (create_engine,create_session_factory,@@ -157,18 +168,19 @@ def coverage_add("[yellow]No index yet — run `repowise init` once before ""adding coverage.[/yellow]")- return+ return Falserepo_keys = await _repo_file_keys(session, repo_row.id)if not repo_keys:console.print("[yellow]No indexed files found — run `repowise init` first.[/yellow]")- return+ return Falsehead_sha = getattr(repo_row, "head_commit", None)# --- Per-file aggregate coverage (lcov / cobertura / clover / json).agg_matched = 0+ unmapped = 0if agg_paths:resolved, errors = build_coverage_map(repo_path,@@ -180,6 +192,12 @@ def coverage_add()for path, err in errors:console.print(f"[yellow] {path.name}: {err}[/yellow]")+ # Counted from `resolved`, not from inside the `resolved.files`+ # branch below: total mapping loss leaves `files` empty, so+ # reading the count in there reported 0 report files unmapped+ # for the one run where every single one of them was.+ skipped = resolved.unmatched + resolved.ambiguous+ unmapped = len(skipped)if resolved.files:await save_coverage_files(session,@@ -193,7 +211,6 @@ def coverage_add(f"[green]Ingested coverage for {resolved.matched} file(s)[/green] "f"({resolved.matched_exact} exact, {resolved.matched_suffix} resolved).")- skipped = resolved.unmatched + resolved.ambiguousif skipped:sample = ", ".join(skipped[:5])console.print(@@ -250,13 +267,23 @@ def coverage_add("If paths look prefixed (e.g. build/…), set ""[cyan]coverage.strip_prefix[/cyan] in .repowise/config.yaml.")- return+ return False+ if strict and unmapped:+ console.print(+ f"[red]--strict: {unmapped} report file(s) did not map to the repo tree.[/red]"+ )+ return Falseconsole.print("Run [cyan]repowise health[/cyan] to fold coverage into the defect ""scores, or [cyan]repowise coverage status[/cyan] to review it.")+ return True- run_async(_do())+ # A refresh is commonly scripted as `coverage add ... || exit 1`, so a run+ # that stored nothing has to be distinguishable from a complete one by its+ # exit status alone.+ if not run_async(_do()):+ raise click.exceptions.Exit(1)_SQLITE_MAGIC = b"SQLite format 3\x00"diff --git a/tests/unit/cli/test_coverage_cmd.py b/tests/unit/cli/test_coverage_cmd.pyindex ee5ff3996..967f954e6 100644--- a/tests/unit/cli/test_coverage_cmd.py+++ b/tests/unit/cli/test_coverage_cmd.py@@ -43,3 +43,94 @@ def test_coverage_add_help_lists_verbose() -> None:assert result.exit_code == 0assert "--verbose" in result.output+++def _no_discovered_reports(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:+ """Point the command at an empty repo so auto-discovery finds nothing."""+ monkeypatch.setattr(coverage_cmd, "_resolve_coverage_repo", lambda _p: tmp_path)+ monkeypatch.setattr(coverage_cmd, "ensure_repowise_dir", lambda _p: None)+ monkeypatch.setattr(coverage_cmd, "_discover_context_reports", lambda _p: [])+++def test_coverage_add_exits_non_zero_when_it_discovers_nothing(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """+ A refresh is scripted as `coverage add ... || exit 1`, so a run that stored+ nothing has to be distinguishable from a complete one by its exit status.+ """+ _no_discovered_reports(monkeypatch, tmp_path)++ result = CliRunner().invoke(cli, ["coverage", "add"])++ assert result.exit_code == 1+ assert "No coverage report found" in result.output++[email protected](("stored", "expected_exit"), [(True, 0), (False, 1)])+def test_coverage_add_exit_status_follows_whether_anything_was_stored(+ monkeypatch: pytest.MonkeyPatch, tmp_path, stored: bool, expected_exit: int+) -> None:+ """+ Every no-op branch inside the ingest returns False -- no index, no indexed+ files, nothing mapped, or --strict with unmapped report files. This pins+ the wiring that turns that answer into the process exit status.+ """+ monkeypatch.setattr(coverage_cmd, "_resolve_coverage_repo", lambda _p: tmp_path)+ monkeypatch.setattr(coverage_cmd, "ensure_repowise_dir", lambda _p: None)++ def fake_run_async(coro):+ coro.close() # never awaited; the DB is not part of this test+ return stored++ monkeypatch.setattr(coverage_cmd, "run_async", fake_run_async)++ report = tmp_path / "lcov.info"+ report.write_text("TN:", encoding="utf-8")++ result = CliRunner().invoke(cli, ["coverage", "add", str(report)])++ assert result.exit_code == expected_exit+++def _coverage_add_source() -> str:+ """Source of the `coverage add` callback (Click wraps it in a Command)."""+ import inspect++ return inspect.getsource(coverage_cmd.coverage_add.callback)+++def test_strict_counts_unmapped_before_the_resolved_files_branch() -> None:+ """Total mapping loss on the aggregate leg must still be able to trip --strict.++ The count used to be read inside `if resolved.files:`, so the one run where+ every report file failed to map was also the run that saw zero unmapped+ files. With a per-test map present, `map_records` is non-empty, the+ "nothing mapped" branch is skipped, and a --strict run exited 0 having+ stored no per-file coverage at all.++ This is a structural guard, not a behavioural one: the branch lives in the+ async closure that needs a DB session, so this pins the ordering that makes+ the branch reachable rather than the branch itself.+ """+ source = _coverage_add_source()++ assert source.index("unmapped = len(skipped)") < source.index("if resolved.files:"), (+ "the unmapped count must be computed before the resolved.files branch"+ )+++def test_strict_failure_is_reported_before_the_success_guidance() -> None:+ """A failing --strict run must not first advise running `repowise health`."""+ source = _coverage_add_source()++ assert source.index("if strict and unmapped:") < source.index(+ "to fold coverage into the defect "+ )+++def test_coverage_add_help_documents_strict() -> None:+ result = CliRunner().invoke(cli, ["coverage", "add", "--help"])++ assert result.exit_code == 0+ assert "--strict" in result.output