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

+140
View File
@@ -0,0 +1,140 @@
"""Thin, shared REST client for Forgejo (Codeberg) and Gitea.
The two forges share one REST API lineage, so one client serves both: a source
instance (read) and a target instance (write). Handles bearer-token auth,
transparent pagination (``page``/``limit`` query params), and a small retry on
transient errors / rate limiting.
"""
from __future__ import annotations
import time
from collections.abc import Iterator
from typing import Any
import httpx
PAGE_SIZE = 50
class ApiError(RuntimeError):
"""A non-2xx response from the forge API."""
def __init__(self, status: int, url: str, body: str) -> None:
super().__init__(f"{status} {url}: {body[:300]}")
self.status = status
self.url = url
self.body = body
class ApiClient:
"""Bearer-auth client over the Forgejo/Gitea REST API (``/api/v1``)."""
def __init__(
self,
base_url: str,
token: str,
*,
timeout: float = 30.0,
max_retries: int = 4,
) -> None:
# api/v1 path normalised onto the host root.
root = base_url.rstrip("/").removesuffix("/api/v1")
self.api_root = root + "/api/v1"
self.web_root = root
self._client = httpx.Client(
base_url=self.api_root,
headers={"Authorization": f"token {token}"},
timeout=timeout,
follow_redirects=True,
)
self.max_retries = max_retries
# -- low level ---------------------------------------------------------
def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
path = path.lstrip("/")
url = f"{self.api_root}/{path}"
last_err: Exception | None = None
for attempt in range(self.max_retries + 1):
try:
resp = self._client.request(method, path, **kwargs)
except httpx.TransportError as exc:
last_err = exc
else:
if resp.status_code in (429, 502, 503, 504):
last_err = ApiError(resp.status_code, url, resp.text)
else:
return resp # caller decides on 4xx/5xx
# backoff: 0.5, 1, 2, 4, 8 …
time.sleep(0.5 * (2**attempt))
raise last_err if last_err else ApiError(0, url, "exhausted retries")
def request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
resp = self._request(method, path, **kwargs)
if resp.status_code >= 400:
raise ApiError(resp.status_code, str(resp.url), resp.text)
return resp
# -- verbs -------------------------------------------------------------
def get(self, path: str, **params: Any) -> Any:
resp = self.request("GET", path, params=_clean(params))
return resp.json() if resp.content else None
def post(self, path: str, body: Any | None = None, **kwargs: Any) -> Any:
resp = self.request("POST", path, json=body, **kwargs)
return resp.json() if resp.content else None
def patch(self, path: str, body: Any | None = None, **kwargs: Any) -> Any:
resp = self.request("PATCH", path, json=body, **kwargs)
return resp.json() if resp.content else None
def delete(self, path: str, **kwargs: Any) -> None:
self.request("DELETE", path, **kwargs)
def post_multipart(self, path: str, files: dict[str, tuple[str, bytes]], **params: Any) -> Any:
resp = self.request("POST", path, files=files, params=_clean(params))
return resp.json() if resp.content else None
def raw_get(self, path: str, **params: Any) -> bytes:
"""Fetch a path as raw bytes (binary downloads like release assets)."""
resp = self.request("GET", path, params=_clean(params))
return resp.content
# -- pagination --------------------------------------------------------
def paged(self, path: str, **params: Any) -> Iterator[Any]:
"""Yield every item across all pages of a list endpoint."""
page = int(params.pop("page", 1))
limit = int(params.pop("limit", PAGE_SIZE))
while True:
batch = self.get(path, page=page, limit=limit, **params) or []
if not isinstance(batch, list):
raise ApiError(200, path, f"expected list, got {type(batch).__name__}")
yield from batch
if len(batch) < limit:
return
page += 1
def get_all(self, path: str, **params: Any) -> list[Any]:
return list(self.paged(path, **params))
def close(self) -> None:
self._client.close()
def __enter__(self) -> ApiClient:
return self
def __exit__(self, *exc: object) -> None:
self.close()
def _clean(params: dict[str, Any]) -> dict[str, Any]:
"""Drop ``None`` values and stringify booleans the Forgejo way."""
out: dict[str, Any] = {}
for key, value in params.items():
if value is None:
continue
if isinstance(value, bool):
out[key] = "true" if value else "false"
else:
out[key] = value
return out