"""commit_runtime with the frozen local adapter installed. Three hooks, all infrastructure, none touching pipeline logic: 1. `_start_validation_sandbox` returns a LocalSandbox over the repository's prepared checkout (commit_runtime.py line 518 is the only construction site). 2. The commit walk's clone is redirected from the GitHub URL to the pinned local mirror (`_shallow_clone_at_ref` at commit_runtime.py line 284). The task keeps `repo = owner/name` and real commit references. 3. Issue enrichment is disabled: `capabilities_for` returns no ISSUES capability, so the pipeline uses the commit message (its documented fallback for sources without an issue API). There is no network. """ from __future__ import annotations import json import shutil import subprocess from dataclasses import fields from pathlib import Path from repo2rlenv.bootstrap.spec import BootstrapResult, LanguageHint from repo2rlenv.pipelines import commit_runtime as _cr from repo2rlenv.pipelines.commit_runtime import CommitRuntimePipeline from .sandbox import LocalSandbox def load_bootstrap(path: Path) -> BootstrapResult: """Load a prebaked bootstrap.json exactly as bootstrap/cache.py line 117 does.""" data = json.loads(Path(path).read_text()) if isinstance(data.get("language"), str): try: data["language"] = LanguageHint(data["language"]) except ValueError: data["language"] = LanguageHint.UNKNOWN if isinstance(data.get("transcript_path"), str): data["transcript_path"] = Path(data["transcript_path"]) known = {f.name for f in fields(BootstrapResult)} return BootstrapResult(**{k: v for k, v in data.items() if k in known}) def _mirror_for(repo_url: str, mirrors: dict[str, Path]) -> Path: key = repo_url.rstrip("/").removesuffix(".git").lower() if key not in mirrors: raise RuntimeError(f"no local mirror registered for {repo_url}") return mirrors[key] def install_hooks(mirrors: dict[str, Path]) -> None: """Redirect clones to local mirrors and disable issue lookups. Idempotent.""" normalized = {k.rstrip("/").removesuffix(".git").lower(): Path(v) for k, v in mirrors.items()} def _local_clone(repo_url, ref, token, dest, *, depth=1, on_progress=None): del token, on_progress mirror = _mirror_for(repo_url, normalized) dest = Path(dest) if dest.exists(): shutil.rmtree(dest, ignore_errors=True) # --shared: no object copy; the mirror outlives every temp clone. subprocess.run( ["git", "clone", "-q", "--shared", "--no-checkout", f"file://{mirror}", str(dest)], check=True, capture_output=True, text=True, timeout=300, ) subprocess.run( ["git", "-C", str(dest), "checkout", "-q", "--detach", ref], check=True, capture_output=True, text=True, timeout=120, ) _ = depth # history is complete; the depth limit is honored by list_commits' -n _cr._shallow_clone_at_ref = _local_clone _cr.capabilities_for = lambda kind: frozenset() # git_local.show_diff decodes `git show` strictly as UTF-8 and a single # commit carrying latin-1 bytes aborts the whole repository walk. Surface # it as the GitError the run loop already handles (diff_fetch_failed skip). _orig_show_diff = _cr.show_diff def _show_diff(clone_dir, commit_sha): try: return _orig_show_diff(clone_dir, commit_sha) except UnicodeDecodeError as exc: raise _cr.GitError(f"non-UTF-8 diff for {commit_sha[:12]}: {exc}") from exc _cr.show_diff = _show_diff class LocalCommitRuntimePipeline(CommitRuntimePipeline): """CommitRuntimePipeline whose validation sandbox is a LocalSandbox.""" def __init__(self, input, options, bootstrap=None, *, sandbox_dir: Path): super().__init__(input, options, bootstrap) self.sandbox_dir = Path(sandbox_dir) def _start_validation_sandbox(self): return LocalSandbox.start( sandbox_dir=self.sandbox_dir, post_clean_cmds=list(self.bootstrap.rebuild_cmds or []), )