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(coverage): name changed files from the indexed checkout in a nested repository (#4340)
Raghav Chamadiyae251d3bbe82c
diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.pyindex df00ba0c8..4aac96bde 100644--- a/packages/core/src/repowise/core/analysis/changed_lines.py+++ b/packages/core/src/repowise/core/analysis/changed_lines.py@@ -23,10 +23,10 @@ from __future__ import annotationsimport reimport subprocessfrom collections.abc import Iterable-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom pathlib import Path-from .git_cli import _git, path_filter, split_revspec, untracked_paths+from .git_cli import _git, checkout_relative, path_filter, split_revspec, untracked_paths# ``@@ -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).@@ -241,16 +241,19 @@ def changed_lines(of this branch would bring. A *base* that does not resolve, or sharesno merge-base, falls back to the plain working-tree diff and its label.*skip_untracked* (gitignore-style) names untracked files not to read; the- caller still filters tracked paths. *label* is a human string naming what- was diffed. Raises ``ValueError`` on an unknown revision so the caller can- fail loudly rather than silently reporting "no changes".+ caller still filters tracked paths. Paths are relative to *repo_path*, as+ the index names them (see :func:`~.git_cli.checkout_relative`).+ *label* is a human string naming what was diffed.+ Raises ``ValueError`` on an unknown revision so the caller can fail loudly+ rather than silently reporting "no changes"."""if working_tree:- return _working_tree_lines(repo_path, base, skip_untracked)-- command, revisions, label = _change_command(repo_path, revspec, staged=staged)- diff = _diff(repo_path, [*command, "--unified=0", *DIFF_ARGS, *revisions])- return _parse_unified_diff(diff), label+ changed, label = _working_tree_lines(repo_path, base, skip_untracked)+ else:+ command, revisions, label = _change_command(repo_path, revspec, staged=staged)+ diff = _diff(repo_path, [*command, "--unified=0", *DIFF_ARGS, *revisions])+ changed = _parse_unified_diff(diff)+ return checkout_relative(repo_path, changed), labeldef _change_command(@@ -312,7 +315,8 @@ def change_set(*working_tree* reads what ``HEAD`` does not have, staged or not, untrackedfiles included; its base is ``HEAD``. *exclude_patterns* (gitignore-style)drops paths that are not part of the change at all, such as repowise's own- output. Raises ``ValueError`` on an unknown revision, as :func:`changed_lines` does.+ output. Paths are relative to *repo_path*, as :func:`changed_lines` names+ them. Raises ``ValueError`` on an unknown revision, as :func:`changed_lines` does."""if working_tree:command, revisions, label = ["diff"], ["HEAD"], working_tree_label()@@ -334,6 +338,10 @@ def change_set(files[path] = diffs.get(path) or FileDiff(path=path)if working_tree:files.update(untracked_diffs(repo_path, exclude_patterns))+ # One re-keying for both sides: each relative path maps back to git's.+ named = checkout_relative(repo_path, {p: p for p in [*files, *deleted]})+ deleted = {rel for rel, top in named.items() if top in deleted}+ files = {rel: replace(files[top], path=rel) for rel, top in named.items() if top in files}base, head = _change_ends(repo_path, revspec, staged=staged or working_tree)return ChangeSet(files, deleted, label, base, head)@@ -395,8 +403,10 @@ def untracked_diffs(repo_path: str, exclude_patterns: tuple[str, ...] = ()) -> d*exclude_patterns* is never read."""out: dict[str, FileDiff] = {}+ # Listed from the git top level, so read from there too.+ root = _git(["rev-parse", "--show-toplevel"], repo_path, check=False).strip() or repo_pathfor path in untracked_paths(repo_path, exclude_patterns):- target = Path(repo_path) / path+ target = Path(root) / pathtry:data = b"" if target.stat().st_size > _UNTRACKED_READ_LIMIT else target.read_bytes()except OSError:@@ -430,10 +440,12 @@ def diff_since(What moves a line number read at one commit (an index's symbol spans) tothe code being asked about (:func:`map_old_line` over ``FileDiff.hunks``).+ *paths* and the keys are relative to *repo_path*, as the index names them."""tail = [until] if until else []args = ["diff", "--unified=0", *DIFF_ARGS, since, *tail, "--", *paths]- return parse_unified_diff(_diff(repo_path, args))+ diffs = checkout_relative(repo_path, parse_unified_diff(_diff(repo_path, args)))+ return {p: replace(d, path=p) for p, d in diffs.items()}def change_diff(@@ -508,4 +520,5 @@ def index_gap(repo_path: str, indexed_commit: str | None, change: ChangeSet) ->except (subprocess.SubprocessError, OSError):return Nonetouched = set(change.files) | change.deleted- return [p for p in listing.split("\0") if p.strip() and p not in touched]+ gap = checkout_relative(repo_path, dict.fromkeys(p for p in listing.split("\0") if p.strip()))+ return [p for p in gap if p not in touched]diff --git a/packages/core/src/repowise/core/analysis/git_cli.py b/packages/core/src/repowise/core/analysis/git_cli.pyindex 926446002..eabb1972f 100644--- a/packages/core/src/repowise/core/analysis/git_cli.py+++ b/packages/core/src/repowise/core/analysis/git_cli.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport subprocessfrom collections.abc import Callable, Mapping, Sequencefrom pathlib import Path+from typing import TypeVarimport pathspec@@ -104,6 +105,27 @@ def _git(args: list[str], cwd: str, *, check: bool = True) -> str:return proc.stdout+_V = TypeVar("_V")+++def checkout_relative(repo_path: str, by_path: Mapping[str, _V]) -> dict[str, _V]:+ """*by_path*, keyed by git's top-level paths, re-keyed relative to *repo_path*.++ The index names files from the checkout it was built in, which can sit+ below the git top level. A path outside that checkout keeps a ``../`` form+ no index path has, so a reader that must not miss a change still sees one+ it cannot place. Raises as :func:`_git` does when *repo_path* is not in a+ repository.+ """+ prefix = _git(["rev-parse", "--show-prefix"], repo_path).strip()+ if not prefix:+ return dict(by_path)+ up = "../" * prefix.count("/")+ return {+ p[len(prefix) :] if p.startswith(prefix) else up + p: v for p, v in by_path.items()+ }++def untracked_paths(repo_path: str,exclude_patterns: tuple[str, ...] = (),diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py b/packages/core/src/repowise/core/analysis/patch_coverage/stored.pyindex 98fb8c8e8..0b3b40b4e 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/stored.py@@ -16,7 +16,7 @@ from typing import TYPE_CHECKING, Anyfrom sqlalchemy.ext.asyncio import AsyncSession-from ..git_cli import _git, untracked_paths+from ..git_cli import _git, checkout_relative, untracked_pathsfrom ..health.coverage.discovery import CoverageScopefrom ..health.coverage.freshness import (FreshnessStatus,@@ -156,17 +156,15 @@ def _changed_since(tail = [until] if until else []spec = [f":(literal){p}" for p in paths]try:- prefix = _git(["rev-parse", "--show-prefix"], repo_path).strip()listing = _git(["diff", "--name-only", "-z", "--no-renames", since, *tail, "--", *spec], repo_path)+ changed = {p for p in listing.split("\0") if p}+ if until is None:+ changed |= set(untracked_paths(repo_path, pathspecs=spec or (":/",)))+ return set(checkout_relative(repo_path, dict.fromkeys(changed)))except (subprocess.SubprocessError, OSError):return None- # git names paths from its top level; the prefix is where *repo_path* sits.- changed = {p for p in listing.split("\0") if p}- if until is None:- changed |= set(untracked_paths(repo_path, pathspecs=spec or (":/",)))- return {p[len(prefix) :] for p in changed if p.startswith(prefix)}async def _stored_branch_data(diff --git a/packages/core/src/repowise/core/analysis/test_collection.py b/packages/core/src/repowise/core/analysis/test_collection.pyindex fd8a2e553..d5d40fd8b 100644--- a/packages/core/src/repowise/core/analysis/test_collection.py+++ b/packages/core/src/repowise/core/analysis/test_collection.py@@ -354,7 +354,9 @@ def _gap_routes(repo_path, change, config, repo_keys: set[str], out: dict) -> liplan = plan_gap(gap, config, [*change.files, *change.deleted])if plan.candidates:old, new = out["indexed_commit"], change.base- specs = [(rev, p) for p in plan.candidates for rev in (old, new)]+ # ``rev:./path`` reads from the checkout, which can sit below the git+ # top level; plain ``rev:path`` would miss and read as absent.+ specs = [(rev, f"./{p}") for p in plan.candidates for rev in (old, new)]blobs = read_blobs(str(repo_path), specs)# Unreadable means nothing was compared, so every candidate may have moved.unread = _unread(repo_path, specs, blobs)@@ -362,8 +364,8 @@ def _gap_routes(repo_path, change, config, repo_keys: set[str], out: dict) -> lipfor p in plan.candidatesif blobs is None- or p in unread- or edges_may_differ(p, blobs.get((old, p)), blobs.get((new, p)))+ or f"./{p}" in unread+ or edges_may_differ(p, blobs.get((old, f"./{p}")), blobs.get((new, f"./{p}")))]plan = with_rewired(plan, rewired, repo_keys)out["gap"] = plandiff --git a/tests/unit/analysis/test_changed_lines.py b/tests/unit/analysis/test_changed_lines.pyindex c39876d91..47a16a3a4 100644--- a/tests/unit/analysis/test_changed_lines.py+++ b/tests/unit/analysis/test_changed_lines.py@@ -11,7 +11,12 @@ import subprocessimport pytest-from repowise.core.analysis.changed_lines import _parse_unified_diff, changed_lines+from repowise.core.analysis.changed_lines import (+ _parse_unified_diff,+ change_set,+ changed_lines,+ diff_since,+)def test_parse_single_hunk_new_side_lines() -> None:@@ -405,3 +410,42 @@ def test_index_gap_on_a_sibling_branch_counts_only_the_base_side(git_repo) -> Nochange = change_set(str(git_repo), "HEAD~1..HEAD")assert index_gap(str(git_repo), indexed, change) == ["base_only.py"]+++def test_changed_lines_name_files_from_a_checkout_below_the_git_top_level(git_repo) -> None:+ # The index is built in ``svc/``; its file paths start there, git's at the top.+ (git_repo / "svc").mkdir()+ (git_repo / "svc" / "a.py").write_text("x = 1\n", encoding="utf-8")+ _git(git_repo, "add", "-A")+ _git(git_repo, "commit", "-qm", "svc")+ (git_repo / "svc" / "a.py").write_text("x = 1\ny = 2\n", encoding="utf-8")+ (git_repo / "mod.py").write_text("a = 1\nb = 2\nc = 3\nd = 4\n", encoding="utf-8")+ _git(git_repo, "commit", "-qam", "edit both")++ changed, _ = changed_lines(str(git_repo / "svc"), "HEAD~1..HEAD")+ # A file outside the checkout keeps a path no index file has.+ assert changed == {"a.py": {2}, "../mod.py": {4}}+ # Read from the top level, nothing moves.+ assert changed_lines(str(git_repo), "HEAD~1..HEAD")[0] == {"svc/a.py": {2}, "mod.py": {4}}+++def test_change_set_and_diff_since_name_files_from_a_nested_checkout(git_repo) -> None:+ svc = git_repo / "svc"+ svc.mkdir()+ for name in ("a.py", "gone.py"):+ (svc / name).write_text("x = 1\n", encoding="utf-8")+ _git(git_repo, "add", "-A")+ _git(git_repo, "commit", "-qm", "svc")+ (svc / "a.py").write_text("x = 1\ny = 2\n", encoding="utf-8")+ (svc / "gone.py").unlink()+ (svc / "new.py").write_text("z = 3\n", encoding="utf-8")+ (git_repo / "mod.py").write_text("a = 0\n", encoding="utf-8")++ change = change_set(str(svc), working_tree=True)+ assert set(change.files) == {"a.py", "new.py", "../mod.py"}+ assert change.deleted == {"gone.py"}+ assert change.files["new.py"].new_lines == {1} # read from where git listed it+ assert all(diff.path == path for path, diff in change.files.items())++ diffs = diff_since(str(svc), "HEAD", None, ["a.py"])+ assert set(diffs) == {"a.py"} and diffs["a.py"].new_lines == {2}diff --git a/tests/unit/cli/test_impacted_tests_cmd.py b/tests/unit/cli/test_impacted_tests_cmd.pyindex 3cfb9b3ed..79b408ce5 100644--- a/tests/unit/cli/test_impacted_tests_cmd.py+++ b/tests/unit/cli/test_impacted_tests_cmd.py@@ -592,3 +592,49 @@ def test_prioritize_needs_a_machine_format(repo) -> None:result = _run(repo, "main...feat", "--prioritize")assert result.exit_code != 0assert "--prioritize needs --format args, list or json" in result.output + result.stderr+++def nested_repo(tmp_path):+ """The ``repo`` layout indexed in ``svc/``, below the git top level, beside ``lib/``."""+ top = tmp_path / "mono"+ svc = top / "svc"+ svc.mkdir(parents=True)+ _git(top, "init", "-q", "-b", "main")+ _git(top, "config", "user.email", "[email protected]")+ _git(top, "config", "user.name", "t")+ _write(+ svc,+ {+ "src/a.py": "A = 1\n",+ "src/b.py": "B = 1\n",+ "tests/test_a.py": "from src.a import A\n\ndef test_a():\n assert A\n",+ "README.md": "docs\n",+ ".gitignore": ".repowise/\n",+ },+ )+ _write(top, {"lib/x.py": "X = 1\n"})+ _git(top, "add", "-A")+ _git(top, "commit", "-qm", "init")+ asyncio.run(_index(svc, _git(top, "rev-parse", "HEAD")))+ _git(top, "switch", "-qc", "feat")+ _write(svc, {"src/a.py": "A = 2\n", "README.md": "more docs\n"})+ _git(top, "commit", "-qam", "feat")+ return svc+++def test_a_checkout_below_the_git_top_level_selects_as_the_top_level_does(nested_repo) -> None:+ result = _run(nested_repo, "main...feat", "--format", "args")+ assert result.exit_code == 0, result.output+ assert result.stdout == "tests/test_a.py\n"+ assert "documentation: no tests needed" in _err(result)+++def test_a_change_outside_the_checkout_runs_every_test(nested_repo) -> None:+ # A path the index cannot place pushes toward more tests, never fewer.+ _write(nested_repo.parent, {"lib/x.py": "X = 2\n"})+ _git(nested_repo.parent, "commit", "-qam", "lib")+ result = _run(nested_repo, "feat~1...feat", "--format", "json", "--runner", "files")+ assert result.exit_code == 0, result.output+ data = json.loads(result.stdout)+ assert data["run_all"] is True and data["args"] == [":all"], datadiff --git a/tests/unit/server/test_patch_coverage_nested_checkout.py b/tests/unit/server/test_patch_coverage_nested_checkout.pynew file mode 100644index 000000000..5cf5d1bd1--- /dev/null+++ b/tests/unit/server/test_patch_coverage_nested_checkout.py@@ -0,0 +1,58 @@+"""``/health/coverage/patch`` for an index built below the git top level.++The index names files from its own checkout (``src/a.py``) while git names+them from the top level (``svc/src/a.py``); a changed covered file must still+match its stored coverage.+"""++from __future__ import annotations++import subprocess+from pathlib import Path++import pytest+from httpx import AsyncClient++from repowise.core.analysis.health.coverage import file_coverage+from repowise.core.persistence.crud import save_coverage_files, upsert_repository+++def _git(cwd: Path, *args: str) -> str:+ return subprocess.run(+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True+ ).stdout.strip()+++async def test_changed_covered_file_reads_measured(+ client: AsyncClient, session, tmp_path: Path+) -> None:+ top = tmp_path / "mono"+ (top / "svc" / "src").mkdir(parents=True)+ _git(top, "init", "-q")+ _git(top, "config", "user.email", "[email protected]")+ _git(top, "config", "user.name", "t")+ (top / "svc" / "src" / "a.py").write_text("x = 1\n", encoding="utf-8")+ _git(top, "add", "-A")+ _git(top, "commit", "-qm", "base")+ base = _git(top, "rev-parse", "HEAD")+ (top / "svc" / "src" / "a.py").write_text("x = 1\ny = 2\nz = 3\n", encoding="utf-8")+ _git(top, "commit", "-qam", "grow a")+ head = _git(top, "rev-parse", "HEAD")++ repo = await upsert_repository(session, name="svc", local_path=str(top / "svc"))+ await save_coverage_files(+ session,+ repo.id,+ [file_coverage("src/a.py", [1, 2], [1, 2, 3])],+ source_format="lcov",+ ingested_commit_sha=head,+ )+ await session.commit()++ resp = await client.get(f"/api/repos/{repo.id}/health/coverage/patch", params={"base": base})++ assert resp.status_code == 200+ data = resp.json()+ assert [(f["file_path"], f["status"]) for f in data["files"]] == [("src/a.py", "measured")]+ assert data["files"][0]["uncovered_ranges"] == [[3, 3]]