feat: implement Codeberg → Gitea repo migrator

Replay git (mirror + LFS), labels, milestones, issues & PRs (with
comments), and releases (with assets) entity-by-entity over the shared
Forgejo/Gitea REST API. Two-pass issue/PR creation rewrites #NNN and
URL cross-references to the target number space; deleted-branch PR
heads are recreated as refs/heads/_pr/<n>.

CLI: codeberg-to-gitea migrate owner/name  (CODEBERG_TOKEN/GITEA_TOKEN)
Verified end-to-end on AlexKucera/helm: 283 issues, 1 PR, 19 labels,
219 comments, git history, with cross-refs correctly rewritten.
This commit is contained in:
AlexKucera committed 2026-08-11 11:12:06 +02:00
1 parent 601cf4c41e
commit ab43b0311e
14 files changed
+1240 -23

No files matched your search

+183
View File
@@ -0,0 +1,183 @@
"""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.
"""
from __future__ import annotations
import shutil
import subprocess
from pathlib import Path
from urllib.parse import quote, urlsplit, urlunsplit
LFS_MARKERS = (".gitattributes",) # presence hints at possible LFS rules
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}"))
def _run(cmd: list[str], cwd: Path | None = None) -> None:
proc = subprocess.run( # noqa: S603 - argv list, no shell
cmd, cwd=cwd, capture_output=True, text=True
)
if proc.returncode != 0:
raise GitError(f"git failed ({proc.returncode}): {' '.join(cmd)}\n{proc.stderr.strip()}")
def _run_capture(cmd: list[str], cwd: Path | None = None) -> str:
"""Run git, return stdout; raise on non-zero (errors carry stderr)."""
proc = subprocess.run( # noqa: S603 - argv list, no shell
cmd, cwd=cwd, capture_output=True, text=True
)
if proc.returncode != 0:
raise GitError(f"git failed ({proc.returncode}): {' '.join(cmd)}\n{proc.stderr.strip()}")
return proc.stdout
def _prune_internal_refs(bare: Path) -> None:
"""Delete forge-managed refs (refs/pull/*) that the target won't accept."""
listing = _run_capture(
["git", "--git-dir", str(bare), "for-each-ref", "--format=%(refname)", "refs/pull/"]
)
for ref in listing.split():
_run(["git", "--git-dir", str(bare), "update-ref", "-d", ref])
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):
continue
heads[number] = sha
return heads
def has_lfs(source_url: str, token: str, workdir: Path) -> bool:
"""Quick check for LFS rules via the contents API is unreliable cross-forge,
so we treat LFS as present whenever ``git lfs`` is installed and the clone
yields LFS objects. Cheap heuristic: this always returns True when
``git lfs`` is available (fetch/push become no-ops without objects)."""
return shutil.which("git") is not None and _lfs_installed()
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,
) -> 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)
bare = workdir / (Path(source_url).name.removesuffix(".git") + ".git")
src = _authed(source_url, source_token)
tgt = _authed(target_url, target_token)
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])
_run(["git", "--git-dir", str(bare), "fetch", "--prune", "origin", "*:*"])
else:
_run(["git", "clone", "--mirror", src, str(bare)])
# 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])
# 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.)
for pr_number, sha in pull_heads.items():
_run(
[
"git",
"--git-dir",
str(bare),
"push",
tgt,
f"{sha}:refs/heads/_pr/{pr_number}",
]
)
lfs_pushed = False
if _lfs_installed():
# Fetch every LFS object the source history references.
_run(["git", "--git-dir", str(bare), "lfs", "fetch", "--all", "origin"])
# 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"])
lfs_pushed = True
return {"bare": str(bare), "lfs_pushed": lfs_pushed, "pr_head_branches": len(pull_heads)}
if __name__ == "__main__": # self-check — URL auth only, 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"
print("mirror self-check ok:", url)