"""Local git access for the node projection. The ground truth records each candidate node against a concrete ``(base, after)`` diff of a repository. To lift a predicted line to the same node, CoReDD needs the source at those commits. It reads them from a **local clone** of each benchmark repository via pygit2 -- no network, no cloud. The caller supplies the directory the clones live under. ``GitRepository`` exposes exactly the three operations the projection needs (``parents``/``diff``/``blob``), copied from the pipeline's ``VersionControl`` so the lift is byte-for-byte the one that built the labels. ``RepositorySet`` maps a ``owner/repo`` name to its clone and hands out one warm projection per repository. """ from __future__ import annotations from pathlib import Path import pygit2 from coredd.projection import NodeProjection class GitRepository: """The git operations :class:`~coredd.projection.NodeProjection` needs, on a clone.""" def __init__(self, repository: pygit2.Repository) -> None: self._repository = repository @classmethod def open(cls, path: str | Path) -> "GitRepository": """Open a local clone (working tree or bare) at *path*.""" return cls(pygit2.Repository(str(path))) def parents(self, commit: str) -> list[str]: """Return parent SHAs of *commit*.""" obj = self._repository.get(commit) if obj is None: raise ValueError(f"Commit {commit} not found in repository") c = obj.peel(pygit2.Commit) return [str(pid) for pid in c.parent_ids] def diff(self, base: str, after: str, *, context: int = 0) -> pygit2.Diff: """Return the libgit2 diff between *base* and *after* trees.""" base_obj = self._repository.get(base) if base_obj is None: raise ValueError(f"Commit {base} not found") after_obj = self._repository.get(after) if after_obj is None: raise ValueError(f"Commit {after} not found") base_commit = base_obj.peel(pygit2.Commit) after_commit = after_obj.peel(pygit2.Commit) diff = self._repository.diff( base_commit.tree, after_commit.tree, context_lines=context, interhunk_lines=0, ) diff.find_similar( flags=( pygit2.enums.DiffFind.FIND_COPIES | pygit2.enums.DiffFind.FIND_COPIES_FROM_UNMODIFIED | pygit2.enums.DiffFind.FIND_RENAMES | pygit2.enums.DiffFind.FIND_RENAMES_FROM_REWRITES ), copy_threshold=50, rename_threshold=50, rename_from_rewrite_threshold=50, rename_limit=1000, ) return diff def blob(self, commit: str, path: str) -> bytes: """Return the raw bytes of *path* at *commit*.""" obj = self._repository.get(commit) if obj is None: raise ValueError(f"Commit {commit} not found") commit_obj = obj.peel(pygit2.Commit) try: entry = commit_obj.tree[path] except KeyError: raise FileNotFoundError(f"{path} not found in commit {commit}") blob = self._repository.get(entry.id) if not isinstance(blob, pygit2.Blob): raise ValueError(f"{path} is not a blob in commit {commit}") return blob.data class RepositorySet: """Resolve ``owner/repo`` names to local clones and their warm projections.""" def __init__(self, root: str | Path) -> None: self._root = Path(root) self._repositories: dict[str, GitRepository] = {} self._projections: dict[str, NodeProjection] = {} def repository(self, name: str) -> GitRepository: """Return the git handle for ``owner/repo``, opening its clone lazily. The clone is looked up at ``root/owner/repo``, then ``root/repo`` and ``root/repo.git``. A missing clone raises so the failure names the repository. """ if name not in self._repositories: self._repositories[name] = GitRepository.open(self._locate(name)) return self._repositories[name] def projection(self, name: str) -> NodeProjection: """Return one node projection per repository, sharing its warm caches.""" if name not in self._projections: self._projections[name] = NodeProjection(self.repository(name)) return self._projections[name] def _locate(self, name: str) -> Path: owner, _, repo = name.partition("/") candidates = [ self._root / owner / repo, self._root / repo, self._root / f"{repo}.git", self._root / name, ] for candidate in candidates: if (candidate / ".git").exists() or (candidate / "HEAD").exists(): return candidate raise FileNotFoundError( f"No local clone of {name!r} under {self._root} " f"(looked for {', '.join(str(c) for c in candidates)}). " f"Clone the benchmark repositories there first." )