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.

fix(analysis): unify git cat-file --batch reader across analysis consumers (#3332) (#3702)

Rishabh Mishra5651c2979ff1
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 aca5c54e1..4dc50c2a5 100644
--- a/packages/core/src/repowise/core/analysis/change_health/sources.py
+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py
@@ -15,6 +15,7 @@ from pathlib import Path
from typing import Protocol
from ..changed_lines import FileDiff, is_shallow_root, parse_unified_diff, untracked_diffs
+from ..git_cat_file import cat_file_batch
from ..git_cli import path_filter, split_revspec, untracked_paths
GIT_TIMEOUT_SECONDS = 120
@@ -390,34 +391,8 @@ def read_blobs(repo_path: str, specs: list[tuple[str, str]]) -> dict[tuple[str,
An object missing at its revision, or one that is not a file (a submodule),
is omitted instead of raising.
"""
- request = "\n".join(f"{rev}:{path}" for rev, path in specs) + "\n"
- proc = subprocess.run(
- ["git", "-C", repo_path, "cat-file", "--batch"],
- input=request.encode("utf-8"),
- capture_output=True,
- timeout=GIT_TIMEOUT_SECONDS,
- )
- if proc.returncode != 0:
+ req_specs = [f"{rev}:{path}" for rev, path in specs]
+ read = cat_file_batch(repo_path, req_specs, on_missing="omit", timeout=GIT_TIMEOUT_SECONDS)
+ if read is None:
return None
- out: dict[tuple[str, str], bytes] = {}
- data, cursor = proc.stdout, 0
- for spec in specs:
- newline = data.find(b"\n", cursor)
- if newline == -1:
- break
- header = data[cursor:newline]
- # A missing object echoes the whole spec back: "<sha>:<path> missing".
- # Match the suffix, not the field count, because a path may hold spaces.
- # A submodule whose commit this repository lacks: "<sha> submodule", no body.
- fields = header.decode("utf-8", "replace").split()
- if header.endswith(b" missing") or fields[1:] == ["submodule"]:
- cursor = newline + 1
- continue
- if len(fields) < 3 or not fields[2].isdigit():
- break # unparseable header: stop rather than misread the stream
- size = int(fields[2])
- start = newline + 1
- if fields[1] == "blob": # a submodule whose commit is here reads as that commit
- out[spec] = data[start : start + size]
- cursor = start + size + 1 # trailing newline
- return out
+ return {spec: blob for spec, (_, blob) in zip(specs, read, strict=True) if blob is not None}
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/symbols.py b/packages/core/src/repowise/core/analysis/doc_drift/symbols.py
index ada04df34..dfd60d3f8 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/symbols.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/symbols.py
@@ -31,6 +31,7 @@ from difflib import SequenceMatcher
from pathlib import Path
from typing import Any
+from repowise.core.analysis.git_cat_file import cat_file_batch
from repowise.core.ingestion.change_detector import ChangeDetector
from repowise.core.ingestion.languages.registry import REGISTRY
from repowise.core.ingestion.models import ParsedFile
@@ -451,21 +452,15 @@ def _parse_at(
"""Each ``(commit, path)`` parsed, from one ``cat-file --batch``."""
if not files:
return {}
- request = "".join(f"{sha}:./{path}\n" for sha, path in files).encode("utf-8")
- ran = git_run(root, "cat-file", "--batch", stdin=request, timeout=_GIT_TIMEOUT_SECONDS)
- if ran is None or ran[0] != 0:
+ req_specs = [f"{sha}:./{path}" for sha, path in files]
+ read = cat_file_batch(str(root), req_specs, on_missing="omit", timeout=_GIT_TIMEOUT_SECONDS)
+ if read is None:
return None
- data, pos, out = ran[1], 0, {}
- # Each object is ``<oid> blob <size>\n<bytes>\n``, or one ``missing`` line.
- for key in files:
- end = data.find(b"\n", pos)
- header = data[pos:end].split(b" ")
- pos = end + 1
- if len(header) != 3 or header[1] != b"blob":
+ out = {}
+ for key, (_, blob) in zip(files, read, strict=True):
+ if blob is None:
continue
- size = int(header[2])
- parsed = detector.parse_bytes(data[pos : pos + size], key[1])
- pos += size + 1
+ parsed = detector.parse_bytes(blob, key[1])
if parsed is not None:
out[key] = parsed
return out
diff --git a/packages/core/src/repowise/core/analysis/git_cat_file.py b/packages/core/src/repowise/core/analysis/git_cat_file.py
new file mode 100644
index 000000000..c7b61b523
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/git_cat_file.py
@@ -0,0 +1,111 @@
+"""Unified `git cat-file --batch` stream reader.
+
+Parses git's batch stdout stream:
+- `<oid> <type> <size>\\n<body bytes>\\n` for objects present in the repository
+- `<sha> submodule\\n` for submodules whose commit is not in this repository
+- `<spec> missing\\n` for missing objects
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+from collections.abc import Sequence
+
+GIT_TIMEOUT_SECONDS = 60
+
+
+def cat_file_batch(
+ repo_path: str,
+ specs: Sequence[str],
+ *,
+ on_missing: str = "omit",
+ timeout: float = GIT_TIMEOUT_SECONDS,
+ check: bool = False,
+) -> list[tuple[str, bytes | None]] | None:
+ """Read a batch of git specs in one subprocess invocation.
+
+ Returns a list of `(spec, blob_bytes)` pairs matching the order of `specs`.
+ If an object is not a blob (a directory tree or a submodule commit), its
+ bytes value is `None`, and its stream body is safely consumed so subsequent
+ objects stay aligned.
+
+ - `on_missing='omit'`: Missing objects or non-blobs have `None` bytes.
+ - `on_missing='raise'`: Raises `ValueError` on missing object line.
+ - `check=True`: Raises `subprocess.CalledProcessError` if git exits non-zero.
+ - `check=False`: Returns `None` if git exits non-zero.
+ """
+ if not specs:
+ return []
+ request = "\n".join(specs) + "\n"
+ env = {**os.environ, "GIT_NO_LAZY_FETCH": "1", "GIT_LITERAL_PATHSPECS": "1"}
+ try:
+ proc = subprocess.run(
+ ["git", "cat-file", "--batch"],
+ cwd=repo_path,
+ input=request.encode("utf-8"),
+ capture_output=True,
+ timeout=timeout,
+ env=env,
+ )
+ except (OSError, subprocess.SubprocessError):
+ if check:
+ raise
+ return None
+ if check and proc.returncode != 0:
+ raise subprocess.CalledProcessError(
+ proc.returncode, proc.args, output=proc.stdout, stderr=proc.stderr
+ )
+ if proc.returncode != 0:
+ return None
+
+ data, pos = proc.stdout, 0
+ out: list[tuple[str, bytes | None]] = []
+ for spec in specs:
+ nl = data.find(b"\n", pos)
+ if nl == -1:
+ if on_missing == "raise":
+ raise ValueError(f"git cat-file stream ended unexpectedly for {spec!r}")
+ break
+ header = data[pos:nl]
+ fields = header.decode("utf-8", "replace").split()
+ if header.endswith(b" missing"):
+ pos = nl + 1
+ if on_missing == "raise":
+ is_submodule = False
+ if ":" in spec:
+ rev, path = spec.split(":", 1)
+ if rev and path:
+ try:
+ chk = subprocess.run(
+ ["git", "ls-tree", rev, path],
+ cwd=repo_path,
+ capture_output=True,
+ timeout=5.0,
+ text=True,
+ )
+ if chk.returncode == 0 and chk.stdout.startswith("160000 commit "):
+ is_submodule = True
+ except (OSError, subprocess.SubprocessError):
+ pass
+ if not is_submodule:
+ raise ValueError(f"git has no object for {spec!r}")
+ out.append((spec, None))
+ continue
+ if fields[1:] == ["submodule"]:
+ pos = nl + 1
+ out.append((spec, None))
+ continue
+ if len(fields) < 3 or not fields[2].isdigit():
+ if on_missing == "raise":
+ raise ValueError(
+ f"git cat-file unparseable header for {spec!r}: {header.decode('utf-8', 'replace')}"
+ )
+ break # unparseable header: stop rather than misread the stream
+ obj_type = fields[1]
+ size = int(fields[2])
+ start = nl + 1
+ pos = start + size + 1
+ blob = data[start : start + size] if obj_type == "blob" else None
+ out.append((spec, blob))
+ return out
diff --git a/packages/core/src/repowise/core/analysis/history_scan.py b/packages/core/src/repowise/core/analysis/history_scan.py
index 760e0180c..aae3d9ef8 100644
--- a/packages/core/src/repowise/core/analysis/history_scan.py
+++ b/packages/core/src/repowise/core/analysis/history_scan.py
@@ -40,6 +40,7 @@ from datetime import UTC, datetime
from pathlib import Path
from typing import Any
+from repowise.core.analysis.git_cat_file import cat_file_batch
from repowise.core.analysis.secret_allowlist import secret_path_allowlist
from repowise.core.analysis.security_scan import (
SECRET_KINDS,
@@ -90,32 +91,6 @@ def _parse_author_date(iso: str) -> datetime | None:
return None
-def _parse_cat_file_batch(data: bytes) -> dict[str, str]:
- """Parse ``git cat-file --batch`` stdout into ``{blob_sha: content}``."""
- contents: dict[str, str] = {}
- pos = 0
- while pos < len(data):
- nl = data.find(b"\n", pos)
- if nl == -1:
- break
- header = data[pos:nl].decode("ascii", errors="replace")
- pos = nl + 1
- parts = header.split()
- if len(parts) < 3:
- continue
- sha = parts[0]
- try:
- size = int(parts[2])
- except ValueError:
- continue
- chunk = data[pos : pos + size]
- pos += size
- if pos < len(data) and data[pos : pos + 1] == b"\n":
- pos += 1
- contents[sha] = chunk.decode("utf-8", errors="replace")
- return contents
-
-
@dataclass
class HistoryScanSummary:
"""Aggregate result of a full-history scan, for CLI/JSON output."""
@@ -267,19 +242,14 @@ class HistorySecurityScanner:
"""Return ``{blob_sha: content}`` via a single ``git cat-file --batch``."""
if not blob_shas:
return {}
- try:
- result = subprocess.run(
- ["git", "cat-file", "--batch"],
- cwd=str(repo_path),
- input=("\n".join(blob_shas) + "\n").encode(),
- capture_output=True,
- timeout=120.0,
- )
- except (OSError, subprocess.SubprocessError):
- return {}
- if result.returncode != 0:
- return {}
- return _parse_cat_file_batch(result.stdout)
+ read = cat_file_batch(
+ str(repo_path), blob_shas, on_missing="omit", timeout=120.0, check=True
+ )
+ return {
+ sha: blob.decode("utf-8", errors="replace")
+ for sha, blob in (read or [])
+ if blob is not None
+ }
@staticmethod
def _is_source(path: str) -> bool:
diff --git a/packages/core/src/repowise/core/analysis/security_gate.py b/packages/core/src/repowise/core/analysis/security_gate.py
index f41da8cfe..65921df99 100644
--- a/packages/core/src/repowise/core/analysis/security_gate.py
+++ b/packages/core/src/repowise/core/analysis/security_gate.py
@@ -30,7 +30,6 @@ from __future__ import annotations
import hashlib
import re
import string
-import subprocess
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
@@ -43,6 +42,7 @@ from repowise.core.support_paths import DOC_EXTENSIONS
from .change_risk.features import GIT_TIMEOUT_SECONDS, _git, revspec_head, split_revspec
from .changed_lines import DIFF_ARGS, parse_unified_diff
+from .git_cat_file import cat_file_batch
from .secret_allowlist import secret_path_allowlist
from .security_scan import (
SECRET_KINDS,
@@ -364,31 +364,17 @@ def _read_blobs(root: str, specs: Sequence[str]) -> list[str | None]:
"""
if not specs:
return []
- proc = subprocess.run(
- ["git", "cat-file", "--batch"],
- cwd=root,
- input=("\n".join(specs) + "\n").encode("utf-8"),
- capture_output=True,
- timeout=GIT_TIMEOUT_SECONDS,
- check=True,
- )
- out, pos, texts = proc.stdout, 0, []
- for spec in specs:
- nl = out.index(b"\n", pos)
- header = out[pos:nl].split()
- pos = nl + 1
- # "<sha> <type> <size>", "<sha> submodule" for a gitlink, else
- # "<spec> missing" (the spec may hold spaces).
- if len(header) == 2 and header[1] == b"submodule":
- texts.append(None)
- continue
- if len(header) != 3 or not header[2].isdigit():
- raise MissingObjectError(f"git has no object for {spec!r}")
- size = int(header[2])
- body = out[pos : pos + size]
- pos += size + 1
- texts.append(_text(body) if header[1] == b"blob" else None)
- return texts
+ try:
+ read = cat_file_batch(
+ root, specs, on_missing="raise", timeout=GIT_TIMEOUT_SECONDS, check=True
+ )
+ except ValueError as exc:
+ raise MissingObjectError(str(exc)) from exc
+ if read is None or len(read) != len(specs):
+ raise MissingObjectError(
+ f"git cat-file returned incomplete batch for {len(specs)} specs"
+ )
+ return [_text(blob) if blob is not None else None for _, blob in read]
def _custom_spans(
diff --git a/tests/unit/analysis/test_cat_file_batch.py b/tests/unit/analysis/test_cat_file_batch.py
new file mode 100644
index 000000000..90fec23a9
--- /dev/null
+++ b/tests/unit/analysis/test_cat_file_batch.py
@@ -0,0 +1,202 @@
+"""Unit tests for the unified cat_file_batch reader."""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.git_cat_file import cat_file_batch
+
+
+def _run_git(cwd: Path, *args: str) -> str:
+ proc = subprocess.run(
+ ["git", *args],
+ cwd=cwd,
+ capture_output=True,
+ check=True,
+ text=True,
+ )
+ return proc.stdout.strip()
+
+
+def sample_repo(tmp_path: Path) -> Path:
+ """Create a test repository containing files, directories, and commits."""
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _run_git(repo, "init", "-b", "main")
+ _run_git(repo, "config", "user.name", "Test User")
+ _run_git(repo, "config", "user.email", "[email protected]")
+
+ # Create root files and a subdirectory with a file
+ (repo / "file1.txt").write_text("hello from file1\n")
+ (repo / "file with spaces.txt").write_text("hello spaces\n")
+ sub = repo / "subdir"
+ sub.mkdir()
+ (sub / "nested.txt").write_text("hello nested\n")
+
+ _run_git(repo, "add", ".")
+ _run_git(repo, "commit", "-m", "Initial commit")
+ return repo
+
+
+def test_cat_file_batch_empty_specs(sample_repo: Path) -> None:
+ res = cat_file_batch(str(sample_repo), [])
+ assert res == []
+
+
+def test_cat_file_batch_reads_blobs_and_preserves_order(sample_repo: Path) -> None:
+ specs = [
+ "HEAD:file1.txt",
+ "HEAD:subdir/nested.txt",
+ "HEAD:file with spaces.txt",
+ ]
+ res = cat_file_batch(str(sample_repo), specs)
+ assert res is not None
+ assert len(res) == 3
+
+ assert res[0] == ("HEAD:file1.txt", b"hello from file1\n")
+ assert res[1] == ("HEAD:subdir/nested.txt", b"hello nested\n")
+ assert res[2] == ("HEAD:file with spaces.txt", b"hello spaces\n")
+
+
+def test_cat_file_batch_handles_directory_tree_without_stream_desync(sample_repo: Path) -> None:
+ """When a spec resolves to a tree object (e.g. HEAD:subdir), its body is consumed
+
+ and subsequent items in the stream must remain perfectly aligned.
+ """
+ specs = [
+ "HEAD:file1.txt",
+ "HEAD:subdir", # directory -> tree object
+ "HEAD:file with spaces.txt",
+ ]
+ res = cat_file_batch(str(sample_repo), specs)
+ assert res is not None
+ assert len(res) == 3
+
+ assert res[0] == ("HEAD:file1.txt", b"hello from file1\n")
+ assert res[1] == ("HEAD:subdir", None)
+ assert res[2] == ("HEAD:file with spaces.txt", b"hello spaces\n")
+
+
+def test_cat_file_batch_on_missing_omit(sample_repo: Path) -> None:
+ specs = [
+ "HEAD:file1.txt",
+ "HEAD:non_existent.txt",
+ "HEAD:subdir/nested.txt",
+ ]
+ res = cat_file_batch(str(sample_repo), specs, on_missing="omit")
+ assert res is not None
+ assert len(res) == 3
+ assert res[0] == ("HEAD:file1.txt", b"hello from file1\n")
+ assert res[1] == ("HEAD:non_existent.txt", None)
+ assert res[2] == ("HEAD:subdir/nested.txt", b"hello nested\n")
+
+
+def test_cat_file_batch_on_missing_raise(sample_repo: Path) -> None:
+ specs = [
+ "HEAD:file1.txt",
+ "HEAD:non_existent.txt",
+ ]
+ with pytest.raises(ValueError, match=r"git has no object for 'HEAD:non_existent\.txt'"):
+ cat_file_batch(str(sample_repo), specs, on_missing="raise")
+
+
+def test_cat_file_batch_submodule_gitlink(sample_repo: Path, tmp_path: Path) -> None:
+ """Submodule whose commit is missing or present in repo is parsed as None."""
+ # Create another repo to be added as submodule
+ sub_repo = tmp_path / "sub_repo"
+ sub_repo.mkdir()
+ _run_git(sub_repo, "init", "-b", "main")
+ _run_git(sub_repo, "config", "user.name", "Test User")
+ _run_git(sub_repo, "config", "user.email", "[email protected]")
+ (sub_repo / "subfile.txt").write_text("sub\n")
+ _run_git(sub_repo, "add", ".")
+ _run_git(sub_repo, "commit", "-m", "Sub init")
+
+ # Add submodule to sample_repo
+ _run_git(
+ sample_repo,
+ "-c",
+ "protocol.file.allow=always",
+ "submodule",
+ "add",
+ str(sub_repo),
+ "sub_mod",
+ )
+ _run_git(sample_repo, "commit", "-m", "Add submodule")
+
+ specs = [
+ "HEAD:file1.txt",
+ "HEAD:sub_mod",
+ "HEAD:subdir/nested.txt",
+ ]
+ res = cat_file_batch(str(sample_repo), specs)
+ assert res is not None
+ assert len(res) == 3
+ assert res[0] == ("HEAD:file1.txt", b"hello from file1\n")
+ assert res[1] == ("HEAD:sub_mod", None)
+ assert res[2] == ("HEAD:subdir/nested.txt", b"hello nested\n")
+
+
+def test_cat_file_batch_check_flag(sample_repo: Path, tmp_path: Path) -> None:
+ not_a_repo = tmp_path / "not_a_repo"
+ not_a_repo.mkdir()
+
+ # check=False returns None on git failure
+ res = cat_file_batch(str(not_a_repo), ["HEAD:file1.txt"], check=False)
+ assert res is None
+
+ # check=True raises CalledProcessError
+ with pytest.raises(subprocess.CalledProcessError):
+ cat_file_batch(str(not_a_repo), ["HEAD:file1.txt"], check=True)
+
+
+def test_cat_file_batch_timeout_handling(sample_repo: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ def _mock_run(*args, **kwargs):
+ raise subprocess.TimeoutExpired(cmd=["git", "cat-file", "--batch"], timeout=1.0)
+
+ monkeypatch.setattr(subprocess, "run", _mock_run)
+
+ # When check=False, timeout returns None
+ assert cat_file_batch(str(sample_repo), ["HEAD:file1.txt"], check=False) is None
+
+ # When check=True, timeout raises TimeoutExpired
+ with pytest.raises(subprocess.TimeoutExpired):
+ cat_file_batch(str(sample_repo), ["HEAD:file1.txt"], check=True)
+
+
+def test_cat_file_batch_sets_env_vars(sample_repo: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ captured_env: dict | None = None
+ real_run = subprocess.run
+
+ def _mock_run(*args, **kwargs):
+ nonlocal captured_env
+ captured_env = kwargs.get("env")
+ return real_run(*args, **kwargs)
+
+ monkeypatch.setattr(subprocess, "run", _mock_run)
+ res = cat_file_batch(str(sample_repo), ["HEAD:file1.txt"])
+ assert res is not None
+ assert captured_env is not None
+ assert captured_env.get("GIT_NO_LAZY_FETCH") == "1"
+ assert captured_env.get("GIT_LITERAL_PATHSPECS") == "1"
+
+
+def test_cat_file_batch_ambiguous_header(sample_repo: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ def _mock_run(*args, **kwargs):
+ return subprocess.CompletedProcess(
+ args=args[0],
+ returncode=0,
+ stdout=b"deadbeef ambiguous\n",
+ stderr=b"",
+ )
+
+ monkeypatch.setattr(subprocess, "run", _mock_run)
+ assert cat_file_batch(str(sample_repo), ["deadbeef"], on_missing="omit") == []
+ with pytest.raises(ValueError, match=r"unparseable header"):
+ cat_file_batch(str(sample_repo), ["deadbeef"], on_missing="raise")
+
+
diff --git a/tests/unit/analysis/test_security_gate.py b/tests/unit/analysis/test_security_gate.py
index 88719e389..b0464e2f9 100644
--- a/tests/unit/analysis/test_security_gate.py
+++ b/tests/unit/analysis/test_security_gate.py
@@ -439,6 +439,28 @@ def test_a_path_git_does_not_have_raises():
security_gate._read_blobs(".", ["HEAD:no/such/file-anywhere.py"])
+def test_read_blobs_missing_object_raises():
+ """security_gate._read_blobs fails closed with MissingObjectError on a missing object."""
+ with pytest.raises(security_gate.MissingObjectError, match=r"git has no object for 'HEAD:nope\.py'"):
+ security_gate._read_blobs(".", ["HEAD:nope.py"])
+
+
+def test_read_blobs_ambiguous_object_raises(monkeypatch: pytest.MonkeyPatch):
+ """security_gate._read_blobs fails closed with MissingObjectError on an ambiguous object."""
+ def _mock_run(*args, **kwargs):
+ return subprocess.CompletedProcess(
+ args=args[0],
+ returncode=0,
+ stdout=b"deadbeef ambiguous\n",
+ stderr=b"",
+ )
+
+ monkeypatch.setattr(subprocess, "run", _mock_run)
+ with pytest.raises(security_gate.MissingObjectError, match=r"unparseable header"):
+ security_gate._read_blobs(".", ["deadbeef"])
+
+
+
def test_sarif_suppresses_the_baseline_and_drops_history_lines():
head = _row()
old = _row("aws_access_key", snippet="AWS = 'AKIA****'", commit="a" * 40)
diff --git a/tests/unit/analysis/test_security_scan_history.py b/tests/unit/analysis/test_security_scan_history.py
index f0d061fd6..6930b8f9e 100644
--- a/tests/unit/analysis/test_security_scan_history.py
+++ b/tests/unit/analysis/test_security_scan_history.py
@@ -12,6 +12,7 @@ Covers the maintainer's review points for issue #818:
from __future__ import annotations
import os
+import subprocess
import tempfile
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
@@ -512,3 +513,13 @@ async def test_blob_introductions_resolves_real_blobs(secret_repo: Path) -> None
for sha in source:
assert sha in intro, f"blob {sha} has no introducing commit (SHA width mismatch?)"
assert dates.get(intro[sha]), "introducing commit has no author date"
+
+
+def test_read_blobs_batch_git_failure_raises(tmp_path: Path) -> None:
+ """A git failure in history scan must raise rather than silently returning {}."""
+ scanner = HistorySecurityScanner.__new__(HistorySecurityScanner)
+ not_a_repo = tmp_path / "not_a_repo"
+ not_a_repo.mkdir()
+ with pytest.raises(subprocess.CalledProcessError):
+ scanner._read_blobs_batch(not_a_repo, ["abc1234"])
+
diff --git a/tests/unit/doc_drift/test_symbols.py b/tests/unit/doc_drift/test_symbols.py
index 0a684d1e5..17d22f92d 100644
--- a/tests/unit/doc_drift/test_symbols.py
+++ b/tests/unit/doc_drift/test_symbols.py
@@ -369,3 +369,33 @@ def test_a_call_only_candidate_looks_up_its_name(tmp_path: Path):
assert ref.target == "load"
((res, _),) = resolve_symbols([ref], root=tmp_path, symbol_names={"load"})
assert res.verdict is DriftVerdict.RESOLVED
+
+
+def test_parse_at_handles_tree_entry_without_desync(tmp_path: Path):
+ """If a candidate path names a directory tree, it must not desync subsequent files."""
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ subprocess.run(["git", "init", "-q", "-b", "main", str(repo)], check=True)
+ subprocess.run(["git", "-C", str(repo), "config", "user.name", "Test"], check=True)
+ subprocess.run(["git", "-C", str(repo), "config", "user.email", "[email protected]"], check=True)
+
+ pkg = repo / "pkg"
+ pkg.mkdir()
+ (pkg / "mod.py").write_text("def foo(): pass\n")
+ (repo / "app.py").write_text("def bar(): pass\n")
+ subprocess.run(["git", "-C", str(repo), "add", "."], check=True)
+ subprocess.run(["git", "-C", str(repo), "commit", "-qm", "init"], check=True)
+ sha = subprocess.run(
+ ["git", "-C", str(repo), "rev-parse", "HEAD"], capture_output=True, text=True
+ ).stdout.strip()
+
+ from repowise.core.ingestion.change_detector import ChangeDetector
+
+ detector = ChangeDetector(repo)
+ # Request pkg (a tree), then app.py (a blob)
+ files = [(sha, "pkg"), (sha, "app.py")]
+ parsed = symbols_mod._parse_at(repo, detector, files)
+ assert parsed is not None
+ assert (sha, "pkg") not in parsed
+ assert (sha, "app.py") in parsed
+ assert [s.name for s in parsed[(sha, "app.py")].symbols] == ["bar"]