|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import re |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +import pygit2 |
| 7 | + |
| 8 | +from treemapper.diffctx.git import GitError, _parse_hunk_header, _parse_path_line |
| 9 | +from treemapper.diffctx.types import DiffHunk |
| 10 | + |
| 11 | +_HUNK_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") |
| 12 | + |
| 13 | +_repo_cache: dict[str, pygit2.Repository] = {} |
| 14 | + |
| 15 | +_SIGNATURE = pygit2.Signature("Test", "test@test.com") |
| 16 | + |
| 17 | + |
| 18 | +def _get_repo(repo_root: Path) -> pygit2.Repository: |
| 19 | + key = str(repo_root) |
| 20 | + if key not in _repo_cache: |
| 21 | + _repo_cache[key] = pygit2.Repository(str(repo_root)) |
| 22 | + return _repo_cache[key] |
| 23 | + |
| 24 | + |
| 25 | +def clear_repo_cache() -> None: |
| 26 | + _repo_cache.clear() |
| 27 | + |
| 28 | + |
| 29 | +def _resolve_commit(repo: pygit2.Repository, rev: str) -> pygit2.Commit: |
| 30 | + obj = repo.revparse_single(rev) |
| 31 | + if isinstance(obj, pygit2.Tag): |
| 32 | + obj = obj.peel(pygit2.Commit) |
| 33 | + if isinstance(obj, pygit2.Commit): |
| 34 | + return obj |
| 35 | + raise GitError(f"Cannot resolve {rev} to a commit") |
| 36 | + |
| 37 | + |
| 38 | +def _is_working_tree_diff(diff_range: str) -> bool: |
| 39 | + return ".." not in diff_range |
| 40 | + |
| 41 | + |
| 42 | +def _resolve_range(repo: pygit2.Repository, diff_range: str) -> tuple[pygit2.Commit, pygit2.Commit | None]: |
| 43 | + if _is_working_tree_diff(diff_range): |
| 44 | + return _resolve_commit(repo, diff_range), None |
| 45 | + |
| 46 | + parts = diff_range.split("...") |
| 47 | + if len(parts) == 2: |
| 48 | + base = _resolve_commit(repo, parts[0]) |
| 49 | + head = _resolve_commit(repo, parts[1]) |
| 50 | + return base, head |
| 51 | + |
| 52 | + parts = diff_range.split("..") |
| 53 | + if len(parts) == 2: |
| 54 | + base = _resolve_commit(repo, parts[0]) |
| 55 | + head = _resolve_commit(repo, parts[1]) |
| 56 | + return base, head |
| 57 | + |
| 58 | + raise GitError(f"Cannot parse diff range: {diff_range}") |
| 59 | + |
| 60 | + |
| 61 | +def _get_diff(repo: pygit2.Repository, diff_range: str, context_lines: int = 3) -> pygit2.Diff: |
| 62 | + base, head = _resolve_range(repo, diff_range) |
| 63 | + flags = pygit2.GIT_DIFF_PATIENCE |
| 64 | + if _is_working_tree_diff(diff_range): |
| 65 | + repo.index.read() |
| 66 | + diff_index = repo.index.diff_to_tree(base.tree) |
| 67 | + diff_workdir = repo.diff(a=base.tree, flags=flags, context_lines=context_lines) |
| 68 | + diff_index.merge(diff_workdir) |
| 69 | + diff_index.find_similar() |
| 70 | + return diff_index |
| 71 | + else: |
| 72 | + diff = repo.diff(a=base.tree, b=head.tree, flags=flags, context_lines=context_lines) # type: ignore[arg-type] |
| 73 | + diff.find_similar() |
| 74 | + return diff |
| 75 | + |
| 76 | + |
| 77 | +def parse_diff(repo_root: Path, diff_range: str) -> list[DiffHunk]: |
| 78 | + repo = _get_repo(repo_root) |
| 79 | + diff = _get_diff(repo, diff_range, context_lines=0) |
| 80 | + patch_text = diff.patch or "" |
| 81 | + |
| 82 | + hunks: list[DiffHunk] = [] |
| 83 | + old_path: Path | None = None |
| 84 | + new_path: Path | None = None |
| 85 | + |
| 86 | + for line in patch_text.splitlines(): |
| 87 | + path_type, path = _parse_path_line(line, repo_root) |
| 88 | + if path_type == "old": |
| 89 | + old_path = path |
| 90 | + continue |
| 91 | + if path_type == "new": |
| 92 | + new_path = path |
| 93 | + continue |
| 94 | + |
| 95 | + match = _HUNK_RE.match(line) |
| 96 | + if match: |
| 97 | + current_path = new_path if new_path else old_path |
| 98 | + if current_path: |
| 99 | + hunks.append(_parse_hunk_header(match, current_path)) |
| 100 | + |
| 101 | + return hunks |
| 102 | + |
| 103 | + |
| 104 | +def get_diff_text(repo_root: Path, diff_range: str) -> str: |
| 105 | + repo = _get_repo(repo_root) |
| 106 | + diff = _get_diff(repo, diff_range) |
| 107 | + return diff.patch or "" |
| 108 | + |
| 109 | + |
| 110 | +def get_changed_files(repo_root: Path, diff_range: str) -> list[Path]: |
| 111 | + repo = _get_repo(repo_root) |
| 112 | + diff = _get_diff(repo, diff_range) |
| 113 | + paths: list[Path] = [] |
| 114 | + for patch in diff: |
| 115 | + delta = patch.delta |
| 116 | + if delta.new_file.path: |
| 117 | + paths.append(repo_root / delta.new_file.path) |
| 118 | + return paths |
| 119 | + |
| 120 | + |
| 121 | +def get_deleted_files(repo_root: Path, diff_range: str) -> set[Path]: |
| 122 | + repo = _get_repo(repo_root) |
| 123 | + diff = _get_diff(repo, diff_range) |
| 124 | + result: set[Path] = set() |
| 125 | + for patch in diff: |
| 126 | + delta = patch.delta |
| 127 | + if delta.status == pygit2.GIT_DELTA_DELETED: |
| 128 | + result.add((repo_root / delta.old_file.path).resolve()) |
| 129 | + return result |
| 130 | + |
| 131 | + |
| 132 | +def get_renamed_old_paths(repo_root: Path, diff_range: str) -> set[Path]: |
| 133 | + repo = _get_repo(repo_root) |
| 134 | + diff = _get_diff(repo, diff_range) |
| 135 | + result: set[Path] = set() |
| 136 | + for patch in diff: |
| 137 | + delta = patch.delta |
| 138 | + if delta.status == pygit2.GIT_DELTA_RENAMED: |
| 139 | + result.add((repo_root / delta.old_file.path).resolve()) |
| 140 | + return result |
| 141 | + |
| 142 | + |
| 143 | +def get_untracked_files(repo_root: Path) -> list[Path]: |
| 144 | + repo = _get_repo(repo_root) |
| 145 | + result: list[Path] = [] |
| 146 | + for filepath, flags in repo.status().items(): |
| 147 | + if flags & pygit2.GIT_STATUS_WT_NEW: |
| 148 | + result.append(repo_root / filepath) |
| 149 | + return result |
| 150 | + |
| 151 | + |
| 152 | +def show_file_at_revision(repo_root: Path, rev: str, rel_path: Path) -> str: |
| 153 | + repo = _get_repo(repo_root) |
| 154 | + commit = _resolve_commit(repo, rev) |
| 155 | + try: |
| 156 | + entry = commit.tree[rel_path.as_posix()] |
| 157 | + except KeyError: |
| 158 | + raise GitError(f"Path {rel_path} not found at revision {rev}") |
| 159 | + blob = repo.get(entry.id) |
| 160 | + if blob is None or not isinstance(blob, pygit2.Blob): |
| 161 | + raise GitError(f"Not a blob: {rel_path} at {rev}") |
| 162 | + return blob.data.decode("utf-8", errors="replace") |
| 163 | + |
| 164 | + |
| 165 | +def is_git_repo(path: Path) -> bool: |
| 166 | + try: |
| 167 | + pygit2.Repository(str(path)) |
| 168 | + return True |
| 169 | + except pygit2.GitError: |
| 170 | + return False |
| 171 | + |
| 172 | + |
| 173 | +def run_git(repo_root: Path, args: list[str]) -> str: |
| 174 | + raise GitError( |
| 175 | + f"run_git called with args {args} — all git operations should be handled by pygit2 backend. " |
| 176 | + "This indicates a missing pygit2 replacement." |
| 177 | + ) |
| 178 | + |
| 179 | + |
| 180 | +class Pygit2Repo: |
| 181 | + def __init__(self, path: Path) -> None: |
| 182 | + self.path = path |
| 183 | + path.mkdir(parents=True, exist_ok=True) |
| 184 | + self._repo = pygit2.init_repository(str(path)) |
| 185 | + self._repo.config["user.name"] = "Test" |
| 186 | + self._repo.config["user.email"] = "test@test.com" |
| 187 | + _repo_cache[str(path)] = self._repo |
| 188 | + |
| 189 | + def add_file(self, rel_path: str, content: str) -> Path: |
| 190 | + file_path = self.path / rel_path |
| 191 | + file_path.parent.mkdir(parents=True, exist_ok=True) |
| 192 | + file_path.write_text(content, encoding="utf-8") |
| 193 | + return file_path |
| 194 | + |
| 195 | + def add_file_binary(self, rel_path: str, data: bytes) -> Path: |
| 196 | + file_path = self.path / rel_path |
| 197 | + file_path.parent.mkdir(parents=True, exist_ok=True) |
| 198 | + file_path.write_bytes(data) |
| 199 | + return file_path |
| 200 | + |
| 201 | + def remove_file(self, rel_path: str) -> None: |
| 202 | + file_path = self.path / rel_path |
| 203 | + if file_path.exists(): |
| 204 | + file_path.unlink() |
| 205 | + |
| 206 | + def stage_file(self, rel_path: str) -> None: |
| 207 | + self._repo.index.read() |
| 208 | + self._repo.index.add(rel_path) |
| 209 | + self._repo.index.write() |
| 210 | + |
| 211 | + def commit(self, message: str) -> str: |
| 212 | + self._repo.index.read() |
| 213 | + self._repo.index.add_all() |
| 214 | + self._repo.index.write() |
| 215 | + tree_oid = self._repo.index.write_tree() |
| 216 | + |
| 217 | + try: |
| 218 | + parent = self._repo.head.peel(pygit2.Commit) |
| 219 | + parents = [parent.id] |
| 220 | + except pygit2.GitError: |
| 221 | + parents = [] |
| 222 | + |
| 223 | + oid = self._repo.create_commit( |
| 224 | + "refs/heads/main" if not parents else "HEAD", |
| 225 | + _SIGNATURE, |
| 226 | + _SIGNATURE, |
| 227 | + message, |
| 228 | + tree_oid, |
| 229 | + parents, |
| 230 | + ) |
| 231 | + |
| 232 | + if not parents: |
| 233 | + self._repo.set_head(self._repo.references["refs/heads/main"].target) |
| 234 | + |
| 235 | + return str(oid) |
0 commit comments