Files
codeberg-to-gitea-migrator/src/codeberg_to_gitea_migrator/mirror.py
T
AlexKucera 137734673d
CI / test (push) Canceled after 0s
perf(migrator): parallelize and harden migration
The migrator was fully synchronous — every HTTP round-trip and git
op serialized over one blocking client, and a stalled git push could
hang it forever. Overlap the independent phases and bound the slow /
memory-heavy paths.

- clients: ApiClient is now thread-safe (per-thread httpx.Client) so
  labels, milestones, Pass-B comments, and release assets overlap via
  parallel(); --concurrency sizes it (default 8). Pass A issue/PR
  creation stays serial — entities are created in source-number order
  so the number map resolves forward cross-references.
- releases: stream assets through a spooled temp file instead of
  buffering each whole into memory; upload them concurrently.
- reliability: per-op --git-timeout (was unbounded hangs), a circuit
  breaker that aborts on a degraded target, jittered retry backoff,
  and a bulk timeout for large asset transfers.
- round-trips: set an issue's milestone in the create body; batch the
  deleted-branch PR-head git push and refs/pull/* pruning.
- fix: raw_get_stream 4xx/5xx raised AttributeError (resp.read().text
  on bytes) instead of ApiError — now decodes. Wrap mirror git ops in
  try/finally so tokenized remote URLs are scrubbed even on timeout.
- refactor: drop the typer dependency — the CLI is now stdlib argparse
  (same subcommands, flags, and env vars); remove dead code surfaced by
  a whole-repo audit (has_lfs, name_map, unused owner_repo param,
  stored-but-unread _base_url).
- ci: enable the uv download cache.

Tests cover parallel ordering, the circuit breaker, and the streamed
4xx path. CHANGELOG updated; the runtime dependency is now just httpx.
2026-08-11 13:36:11 +02:00

266 lines
9.6 KiB
Python

"""Git mirror: code, full history, branches, tags, and LFS objects.
Mirrors the source repository's git data to the target with
``git clone --mirror`` + ``git push --mirror``. LFS objects (if any) are
fetched and pushed separately — mirror push does not carry them. Both steps are
no-ops when there's nothing LFS in the source, so this is safe to run on any
repo.
Every network-bound git op runs under a timeout (``DEFAULT_GIT_TIMEOUT``,
overridable via ``--git-timeout``) so a stalled TCP connection aborts with a
clear :class:`GitError` instead of hanging the migration forever.
"""
from __future__ import annotations
import logging
import re
import subprocess
from pathlib import Path
from urllib.parse import quote, urlsplit, urlunsplit
log = logging.getLogger(__name__)
#: Per-op ceiling for network git ops (clone/fetch/push). Generous so a legit
#: large clone completes; small enough that a stalled connection is caught.
DEFAULT_GIT_TIMEOUT = 1800.0
class GitError(RuntimeError):
pass
def _authed(url: str, token: str) -> str:
"""Inject ``oauth2:<token>`` into an https git URL for private-repo access."""
parts = urlsplit(url)
if parts.scheme != "https" or not token:
return url
userinfo = f"oauth2:{quote(token, safe='')}"
return urlunsplit(parts._replace(netloc=f"{userinfo}@{parts.netloc}"))
_TOKEN_RE = re.compile(r"(oauth2:)[^@]+(@)")
def _redact(text: str) -> str:
"""Mask any embedded ``oauth2:<token>`` so secrets never reach logs/exceptions."""
return _TOKEN_RE.sub(r"\1***\2", text)
def _bare(url: str) -> str:
"""Strip an ``oauth2:<token>@`` userinfo, returning the bare URL."""
return _TOKEN_RE.sub("", url)
def _scrub_remote_tokens(bare: Path) -> None:
"""Rewrite token-bearing remote URLs in the bare config to bare form.
The mirror is left on disk for inspection / re-push; strip the embedded
``oauth2:<token>`` so it isn't persisted in plaintext in ``.git/config``.
A re-run re-injects auth via :func:`_authed`, so scrubbing is safe. Best-effort.
"""
listing = subprocess.run( # noqa: S603 - argv list, no shell
["git", "--git-dir", str(bare), "remote", "-v"], capture_output=True, text=True
)
for line in listing.stdout.splitlines():
parts = line.split("\t")
if len(parts) < 2:
continue
name = parts[0]
url = parts[1].split(" ")[0]
if "oauth2:" in url:
subprocess.run( # noqa: S603 - argv list, no shell
["git", "--git-dir", str(bare), "remote", "set-url", name, _bare(url)],
capture_output=True,
)
def _run_capture(
cmd: list[str],
cwd: Path | None = None,
*,
timeout: float = DEFAULT_GIT_TIMEOUT,
input: str | None = None,
) -> str:
"""Run git, return stdout; raise on non-zero or timeout (errors carry stderr).
The error message redacts any ``oauth2:<token>`` embedded in the command or
stderr so forge secrets never reach logs or tracebacks.
"""
try:
proc = subprocess.run( # noqa: S603 - argv list, no shell
cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout, input=input
)
except subprocess.TimeoutExpired as exc:
raise GitError(f"git timed out after {timeout}s: {_redact(' '.join(cmd))}") from exc
if proc.returncode != 0:
raise GitError(
f"git failed ({proc.returncode}): {' '.join(_redact(a) for a in cmd)}"
f"\n{_redact(proc.stderr.strip())}"
)
return proc.stdout
def _run(
cmd: list[str],
cwd: Path | None = None,
*,
timeout: float = DEFAULT_GIT_TIMEOUT,
input: str | None = None,
) -> None:
"""Run git, raising on non-zero/timeout. Thin wrapper over :func:`_run_capture`."""
_run_capture(cmd, cwd, timeout=timeout, input=input)
def _prune_internal_refs(bare: Path) -> None:
"""Delete forge-managed refs (refs/pull/*) that the target won't accept.
Batched into a single ``update-ref --stdin`` so one process prunes them all,
instead of spawning a git process per ref.
"""
listing = _run_capture(
["git", "--git-dir", str(bare), "for-each-ref", "--format=%(refname)", "refs/pull/"]
)
refs = listing.split()
if not refs:
return
stdin = "".join(f"delete {r}\n" for r in refs)
_run(["git", "--git-dir", str(bare), "update-ref", "--stdin"], input=stdin)
def _capture_pull_heads(bare: Path) -> dict[int, str]:
"""Map PR number → head SHA from refs/pull/<n>/head before they're pruned."""
listing = _run_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
# refs/pull/<n>/head only — skip /merge test refs.
if not ref.endswith("/head"):
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 _lfs_installed() -> bool:
proc = subprocess.run( # noqa: S603
["git", "lfs", "version"], capture_output=True, text=True
)
return proc.returncode == 0
def _ensure_remote(bare: Path, name: str, url: str) -> None:
"""Create or update a git remote in a bare mirror."""
add = subprocess.run( # noqa: S603
["git", "--git-dir", str(bare), "remote", "add", name, url],
capture_output=True,
text=True,
)
if add.returncode != 0:
_run(["git", "--git-dir", str(bare), "remote", "set-url", name, url])
def mirror_repo(
source_url: str,
target_url: str,
source_token: str,
target_token: str,
workdir: Path,
*,
git_timeout: float = DEFAULT_GIT_TIMEOUT,
) -> 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).
"""
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")
src = _authed(source_url, source_token)
tgt = _authed(target_url, target_token)
# All git ops run under try/finally so the tokenized remote URLs git writes
# into .git/config are always scrubbed — even on a timeout/failure (the
# timeout this diff added makes early abort more frequent, so this matters).
try:
if bare.exists():
# Re-fetch source refs into an existing mirror (idempotent re-run).
_run(
["git", "--git-dir", str(bare), "remote", "set-url", "origin", src],
timeout=git_timeout,
)
_run(
["git", "--git-dir", str(bare), "fetch", "--prune", "origin", "*:*"],
timeout=git_timeout,
)
else:
_run(["git", "clone", "--mirror", src, str(bare)], timeout=git_timeout)
# Forgejo/Gitea expose refs/pull/<n>/head (and /merge) as fetchable refs;
# `clone --mirror` grabs them, but the target declines pushes to refs/pull/*
# (it manages those itself). First capture each PR's head SHA so we can
# recreate the PR on the target (a deleted-branch PR has no other branch),
# then drop the namespace so the mirror push doesn't trip on it.
pull_heads = _capture_pull_heads(bare)
_prune_internal_refs(bare)
# push --mirror replaces all target refs with source refs.
_run(["git", "--git-dir", str(bare), "push", "--mirror", tgt], timeout=git_timeout)
# Recreate each PR head on the target as a real branch refs/heads/_pr/<n>,
# 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 so one
# process + one connection handles all deleted-branch PRs.
if pull_heads:
refspecs = [f"{sha}:refs/heads/_pr/{n}" for n, sha in pull_heads.items()]
_run(["git", "--git-dir", str(bare), "push", tgt, *refspecs], timeout=git_timeout)
lfs_pushed = False
if _lfs_installed():
# Fetch every LFS object the source history references.
_run(
["git", "--git-dir", str(bare), "lfs", "fetch", "--all", "origin"],
timeout=git_timeout,
)
# Push LFS objects to the target via a named remote (a bare mirror has
# `origin` → source; LFS needs the target URL reachable as a remote).
_ensure_remote(bare, "target", tgt)
_run(
["git", "--git-dir", str(bare), "lfs", "push", "--all", "target"],
timeout=git_timeout,
)
lfs_pushed = True
finally:
_scrub_remote_tokens(bare)
return {"bare": str(bare), "lfs_pushed": lfs_pushed, "pr_head_branches": len(pull_heads)}
if __name__ == "__main__": # self-check — URL auth + redaction, no network
url = _authed("https://codeberg.org/AlexKucera/helm.git", "t ok@en")
assert url == "https://oauth2:t%20ok%40en@codeberg.org/AlexKucera/helm.git", url
assert _authed("https://x/o.git", "") == "https://x/o.git"
assert _redact(url) == "https://oauth2:***@codeberg.org/AlexKucera/helm.git", _redact(url)
assert _bare(url) == "https://codeberg.org/AlexKucera/helm.git", _bare(url)
print("mirror self-check ok:", url)