"""Git mirror procedure: code, full history, branches, tags, and LFS objects. Drives git exclusively through :class:`git.GitRunner` — the sole git-op seam — so per-op timeout, error redaction, and auth delivery are properties of running git, not a per-call bolt-on. The token never reaches a remote URL or ``.git/config``: auth is delivered per op via a non-persisted git config override (see :mod:`git`). This module's value is the *ordering* of the procedure (capture pull-heads → prune forge-internal refs → mirror push → recreate deleted-branch PR heads → LFS), which is what its tests lock. Every network git op runs under ``DEFAULT_GIT_TIMEOUT`` (``--git-timeout``) so a stalled connection aborts with a clear :class:`GitError` instead of hanging. """ from __future__ import annotations import logging from pathlib import Path from .git import DEFAULT_GIT_TIMEOUT, Forge, GitError, GitRunner, _real_exec # Re-exported so cli.py / migrate.py keep importing these from here — the seam # owns them now, but the orchestration + CLI layers stay untouched by this # refactor (a bare re-export, not a re-implementation). __all__ = ["DEFAULT_GIT_TIMEOUT", "GitError", "mirror_repo"] log = logging.getLogger(__name__) def _capture_pull_heads(runner: GitRunner, bare: Path) -> dict[int, str]: """Map PR number → head SHA from refs/pull//head before they're pruned.""" listing = runner.capture( [ "git", "--git-dir", str(bare), "for-each-ref", "--format=%(refname) %(objectname)", "refs/pull/", ] ) heads: dict[int, str] = {} for line in listing.splitlines(): parts = line.split() if len(parts) != 2: continue ref, sha = parts if not ref.endswith("/head"): # skip refs/pull//merge test refs continue try: number = int(ref.split("/")[2]) except (IndexError, ValueError): log.warning("ignoring unparseable pull ref: %s", ref) continue heads[number] = sha return heads def _prune_internal_refs(runner: GitRunner, bare: Path) -> None: """Delete forge-managed refs (refs/pull/*) the target won't accept. One ``update-ref --stdin`` prunes them all instead of a git process per ref. """ listing = runner.capture( ["git", "--git-dir", str(bare), "for-each-ref", "--format=%(refname)", "refs/pull/"] ) refs = listing.split() if not refs: return runner.run( ["git", "--git-dir", str(bare), "update-ref", "--stdin"], stdin="".join(f"delete {r}\n" for r in refs), ) def mirror_repo( source_url: str, target_url: str, source_token: str, target_token: str, workdir: Path, *, git_timeout: float = DEFAULT_GIT_TIMEOUT, git_exec=_real_exec, ) -> dict[str, object]: """Mirror a repo's git data (and LFS) from source to target. Returns a small report dict. ``workdir`` is created if missing; the bare clone is left there (useful for inspection / re-push). ``git_exec`` is the test seam — production leaves it at the real subprocess adapter. """ workdir.mkdir(parents=True, exist_ok=True) try: workdir.chmod(0o700) # private even on a shared /tmp except OSError: pass bare = workdir / (Path(source_url).name.removesuffix(".git") + ".git") source = Forge(source_url, source_token) target = Forge(target_url, target_token) runner = GitRunner(timeout=git_timeout, exec=git_exec) if bare.exists(): # Re-fetch source refs into an existing mirror (idempotent re-run). runner.run(["git", "--git-dir", str(bare), "remote", "set-url", "origin", source.url]) runner.run( ["git", "--git-dir", str(bare), "fetch", "--prune", "origin", "*:*"], auth=source ) else: runner.run(["git", "clone", "--mirror", source.url, str(bare)], auth=source) # clone --mirror grabs refs/pull//head, but the target declines pushes to # refs/pull/* (it manages those). Capture each PR's head first so a # deleted-branch PR can be recreated, then drop the namespace so the mirror # push doesn't trip on it. pull_heads = _capture_pull_heads(runner, bare) _prune_internal_refs(runner, bare) # push --mirror replaces all target refs with source refs. runner.run(["git", "--git-dir", str(bare), "push", "--mirror", target.url], auth=target) # Recreate each PR head on the target as refs/heads/_pr/ (used as the PR's # head when the original branch is gone). Pushed after the mirror so --mirror # doesn't wipe them; batched into one push. if pull_heads: refspecs = [f"{sha}:refs/heads/_pr/{n}" for n, sha in pull_heads.items()] runner.run(["git", "--git-dir", str(bare), "push", target.url, *refspecs], auth=target) lfs_pushed = False if runner.ok(["git", "lfs", "version"]): # Fetch every LFS object the source history references, then push them. # A bare mirror has `origin` → source; LFS needs the target URL reachable # as a named remote. # ponytail: assumes git-lfs honours http..extraHeader. If a forge # proves it does not, swap to a credential helper scoped to LFS behind # this same seam — an internal knob, not an architectural change. runner.run(["git", "--git-dir", str(bare), "lfs", "fetch", "--all", "origin"], auth=source) # Ensure the target remote exists (add-or-set-url): the bare mirror is # left on disk across idempotent re-runs, so `remote add target` fails if # it's already registered — fall back to set-url rather than crash. if not runner.ok(["git", "--git-dir", str(bare), "remote", "add", "target", target.url]): runner.run(["git", "--git-dir", str(bare), "remote", "set-url", "target", target.url]) runner.run(["git", "--git-dir", str(bare), "lfs", "push", "--all", "target"], auth=target) lfs_pushed = True return {"bare": str(bare), "lfs_pushed": lfs_pushed, "pr_head_branches": len(pull_heads)}