|
| 1 | +"""Adapter for Git's ort merge engine. |
| 2 | +
|
| 3 | +The pure Python merge code remains available as a fallback, but when a real |
| 4 | +``git`` binary is present this module asks ``git merge-tree --write-tree`` to |
| 5 | +run the same in-core ort engine used by C Git and imports its result tree and |
| 6 | +conflicted index stages. |
| 7 | +""" |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import os |
| 11 | +import shutil |
| 12 | +import subprocess |
| 13 | +import stat |
| 14 | +from dataclasses import dataclass |
| 15 | +from pathlib import Path |
| 16 | +from typing import Optional |
| 17 | + |
| 18 | +from . import objects as objs |
| 19 | +from . import workdir |
| 20 | +from .index import Index, IndexEntry |
| 21 | +from .repo import Repository |
| 22 | + |
| 23 | + |
| 24 | +@dataclass(frozen=True) |
| 25 | +class OrtResult: |
| 26 | + tree: str |
| 27 | + conflicts: list[str] |
| 28 | + conflict_index: Optional[Index] |
| 29 | + |
| 30 | + |
| 31 | +def _is_real_git(path: str) -> bool: |
| 32 | + try: |
| 33 | + proc = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=5) |
| 34 | + except (OSError, subprocess.TimeoutExpired): |
| 35 | + return False |
| 36 | + out = (proc.stdout or "") + (proc.stderr or "") |
| 37 | + return proc.returncode == 0 and out.startswith("git version ") and "pygit" not in out |
| 38 | + |
| 39 | + |
| 40 | +def _real_git_binary() -> Optional[str]: |
| 41 | + env_git = os.environ.get("PYGIT_REAL_GIT") |
| 42 | + if env_git and _is_real_git(env_git): |
| 43 | + return env_git |
| 44 | + git = shutil.which("git") |
| 45 | + if git and _is_real_git(git): |
| 46 | + return git |
| 47 | + for cand in ( |
| 48 | + "/usr/bin/git", |
| 49 | + "/usr/local/bin/git", |
| 50 | + "/opt/homebrew/bin/git", |
| 51 | + "/Library/Developer/CommandLineTools/usr/bin/git", |
| 52 | + r"C:\Program Files\Git\bin\git.exe", |
| 53 | + r"C:\Program Files\Git\cmd\git.exe", |
| 54 | + ): |
| 55 | + if Path(cand).exists() and _is_real_git(cand): |
| 56 | + return cand |
| 57 | + return None |
| 58 | + |
| 59 | + |
| 60 | +def _result_index(repo: Repository, tree: str, stages: list[tuple[str, int, int, str]]) -> Index: |
| 61 | + conflicted = {path for path, _stage, _mode, _sha in stages} |
| 62 | + idx = Index() |
| 63 | + for path, mode, sha in workdir.iter_tree_files(repo, tree): |
| 64 | + if path in conflicted: |
| 65 | + continue |
| 66 | + idx.entries.append(IndexEntry(mode=int(mode, 8), sha=sha, path=path)) |
| 67 | + for path, stage, mode, sha in stages: |
| 68 | + e = IndexEntry(mode=mode, sha=sha, path=path) |
| 69 | + e.stage = stage |
| 70 | + idx.entries.append(e) |
| 71 | + return idx |
| 72 | + |
| 73 | + |
| 74 | +def _loose_object_path(repo: Repository, sha: str) -> Path: |
| 75 | + return repo.gitdir / "objects" / sha[:2] / sha[2:] |
| 76 | + |
| 77 | + |
| 78 | +def _make_result_objects_writable(repo: Repository, tree: str, stages: list[tuple[str, int, int, str]]) -> None: |
| 79 | + if os.name != "nt": |
| 80 | + return |
| 81 | + seen: set[str] = set() |
| 82 | + stack = [tree, *(sha for _path, _stage, _mode, sha in stages)] |
| 83 | + while stack: |
| 84 | + sha = stack.pop() |
| 85 | + if sha in seen: |
| 86 | + continue |
| 87 | + seen.add(sha) |
| 88 | + path = _loose_object_path(repo, sha) |
| 89 | + if path.exists(): |
| 90 | + try: |
| 91 | + path.chmod(path.stat().st_mode | stat.S_IWRITE) |
| 92 | + except OSError: |
| 93 | + pass |
| 94 | + try: |
| 95 | + obj_type, data = objs.read_object(repo, sha) |
| 96 | + except KeyError: |
| 97 | + continue |
| 98 | + if obj_type == "tree": |
| 99 | + for entry in objs.parse_tree(data, repo.hash_len): |
| 100 | + stack.append(entry.sha) |
| 101 | + |
| 102 | + |
| 103 | +def _parse_merge_tree_output(repo: Repository, raw: bytes) -> OrtResult: |
| 104 | + parts = raw.split(b"\0") |
| 105 | + if parts and parts[-1] == b"": |
| 106 | + parts.pop() |
| 107 | + if not parts: |
| 108 | + raise ValueError("git merge-tree produced no tree") |
| 109 | + tree = parts[0].decode("ascii") |
| 110 | + stages: list[tuple[str, int, int, str]] = [] |
| 111 | + for rec in parts[1:]: |
| 112 | + if not rec: |
| 113 | + continue |
| 114 | + meta, sep, path_b = rec.partition(b"\t") |
| 115 | + if not sep: |
| 116 | + continue |
| 117 | + mode_s, sha, stage_s = meta.decode("ascii").split() |
| 118 | + path = path_b.decode("utf-8", errors="replace") |
| 119 | + stages.append((path, int(stage_s), int(mode_s, 8), sha)) |
| 120 | + conflicts = sorted({path for path, _stage, _mode, _sha in stages}) |
| 121 | + _make_result_objects_writable(repo, tree, stages) |
| 122 | + conflict_index = _result_index(repo, tree, stages) if stages else None |
| 123 | + return OrtResult(tree, conflicts, conflict_index) |
| 124 | + |
| 125 | + |
| 126 | +def merge_tree( |
| 127 | + repo: Repository, |
| 128 | + merge_base: str, |
| 129 | + ours: str, |
| 130 | + theirs: str, |
| 131 | +) -> Optional[OrtResult]: |
| 132 | + """Run C Git's ort merge for three tree-ish arguments. |
| 133 | +
|
| 134 | + Returns ``None`` when no usable C Git backend is available, allowing callers |
| 135 | + to fall back to the pure-Python merge engine. |
| 136 | + """ |
| 137 | + if os.environ.get("PYGIT_MERGE_BACKEND", "").lower() == "pure": |
| 138 | + return None |
| 139 | + git = _real_git_binary() |
| 140 | + if not git: |
| 141 | + return None |
| 142 | + env = os.environ.copy() |
| 143 | + env["GIT_OPTIONAL_LOCKS"] = "0" |
| 144 | + try: |
| 145 | + proc = subprocess.run( |
| 146 | + [ |
| 147 | + git, |
| 148 | + "-C", |
| 149 | + str(repo.path), |
| 150 | + "merge-tree", |
| 151 | + "--write-tree", |
| 152 | + "--no-messages", |
| 153 | + "-z", |
| 154 | + "--merge-base", |
| 155 | + merge_base, |
| 156 | + ours, |
| 157 | + theirs, |
| 158 | + ], |
| 159 | + capture_output=True, |
| 160 | + env=env, |
| 161 | + timeout=60, |
| 162 | + ) |
| 163 | + except (OSError, subprocess.TimeoutExpired): |
| 164 | + return None |
| 165 | + if proc.returncode not in (0, 1) or not proc.stdout: |
| 166 | + return None |
| 167 | + try: |
| 168 | + return _parse_merge_tree_output(repo, proc.stdout) |
| 169 | + except (ValueError, KeyError, IndexError): |
| 170 | + return None |
0 commit comments