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

+5
View File
@@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. The format
## [Unreleased]
### feat
- **migrator:** working Codeberg → Gitea migration via `codeberg-to-gitea migrate`. Mirrors git (code, history, tags, LFS) and replays 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 with `#NNN`/URL cross-reference rewriting to the target's number space; deleted-branch PR heads recreated as `refs/heads/_pr/<n>`. Tokens via `CODEBERG_TOKEN`/`GITEA_TOKEN`; `--repo owner/name` (or bare name). `--delete-existing` for clean re-runs.
### chore
- **project:** bootstrap scaffold — Python package (`src/` layout, hatchling, ruff, pytest), GPL-3.0-or-later license, Gitea Actions CI, CITATION.cff, README, ADRs, and DOX-structured AGENTS.md.
- **deps:** add `httpx`, `typer`; add `codeberg-to-gitea` console script.
+54 -13
View File
@@ -1,28 +1,69 @@
# codeberg-to-gitea-migrator
Migrate repositories (code, issues & PRs, releases & assets, labels & milestones)
from [Codeberg](https://codeberg.org) (Forgejo) to a self-hosted
[Gitea](https://about.gitea.com) instance.
Migrate a repository from [Codeberg](https://codeberg.org) (Forgejo) to a
self-hosted [Gitea](https://about.gitea.com) instance — code, full git history,
issues & PRs (with comments), releases & assets, labels, milestones, and LFS
objects.
Gitea ships its own `POST /repos/migrate` importer, but it failed on the target
repo across several settings, so this tool replays every entity directly via the
shared Forgejo/Gitea REST API for full control.
## What it migrates
- **Code** — `git clone --mirror` + push (branches, tags).
- **Issues & PRs** — via the Forgejo → Gitea migration APIs (comments, labels, assignees).
- **Releases & assets** — releases plus attached binaries.
- **Labels & milestones** — recreated in the target repo first.
- **Code & history** — `git clone --mirror` + `push --mirror` (branches, tags, notes).
- **LFS** — objects fetched and pushed alongside the mirror (no-op when absent).
- **Labels** — recreated with colour, description, exclusive/archived flags.
- **Milestones** — title, description, state, due date.
- **Issues & PRs** — created in source-number order with comments; `#NNN`
references and source URLs are rewritten to the target's number space.
- **Pull-request heads** — when the source branch was deleted (common for
merged/closed PRs), the head commits are recreated on the target as
`refs/heads/_pr/<n>` so the PR can be rebuilt.
- **Releases & assets** — non-draft releases with binary assets re-uploaded.
## Requirements
- Python ≥ 3.11
- `git` on `PATH`
- `git` on `PATH` (`git-lfs` optional — used automatically when present)
- A **Codeberg** API token (`read:issue`, `read:repository`)
- A **Gitea** API token (`write:issue`, `write:repository`; `write:user` if you
want the tool to create the target repo for you)
## Getting started
## Usage
```sh
python -m pip install -e ".[dev]" # install (editable, with dev extras)
pytest # test
ruff check . # lint
ruff format --check . # format check
python -m pip install -e ".[dev]"
export CODEBERG_TOKEN=*** # source (read)
export GITEA_TOKEN=*** # target (write)
codeberg-to-gitea migrate AlexKucera/helm # owner defaults to your user
codeberg-to-gitea migrate AlexKucera/helm -v # verbose
codeberg-to-gitea migrate someorg/somerepo --delete-existing # clean re-run
```
Options: `--source-url` (default `https://codeberg.org`), `--target-url`
(default `https://git.babylondreams.de`), `--skip-git` / `--skip-issues` /
`--skip-releases`, `--delete-existing`, `-v`.
If the target token lacks `write:user`, create the empty target repo by hand
(via the web UI) first; the migrator then populates it.
## Fidelity notes
The public Gitea API stamps author and timestamp server-side, so migrated
issues/PRs/comments are attributed to the migration token user with migration
timestamps — original authors and dates are not preserved. Assignees and
reactions are not migrated. Cross-references (`#NNN`, issue/PR URLs) **are**
rewritten to stay correct.
## Development
```sh
pytest # tests (network-free)
ruff check . # lint
ruff format --check . # format check
```
## License
+4 -1
View File
@@ -12,11 +12,14 @@ license = "GPL-3.0-or-later"
license-files = ["LICENSE"]
authors = [{ name = "Alexander Kucera", email = "a.kucera@babylondreams.de" }]
keywords = ["migration", "codeberg", "gitea", "forgejo", "repository-migration"]
dependencies = []
dependencies = ["httpx>=0.27", "typer>=0.12"]
[project.optional-dependencies]
dev = ["pytest", "ruff"]
[project.scripts]
codeberg-to-gitea = "codeberg_to_gitea_migrator.cli:app"
[tool.hatch.build.targets.wheel]
packages = ["src/codeberg_to_gitea_migrator"]
+22 -5
View File
@@ -3,30 +3,47 @@
## Purpose
Python package implementing the Codeberg → self-hosted Gitea migration: git
mirror push plus issues/PRs, releases/assets, and labels/milestones via the
respective REST/migration APIs. Currently a stub — migration modules land here.
mirror (code, history, tags, LFS) plus labels, milestones, issues & PRs (with
comments), and releases (with assets), written entity-by-entity via the shared
Forgejo/Gitea REST API. Gitea's own `POST /repos/migrate` migrator failed on
the target repo, so this replays entities directly.
## Ownership
Project maintainer (Alexander Kucera). Import path: `codeberg_to_gitea_migrator`.
Console script: `codeberg-to-gitea`.
## Local Contracts
- `src/` layout; wheel `packages = ["src/codeberg_to_gitea_migrator"]` (root `pyproject.toml`).
- `__init__.py` holds the single `__version__` string — the version source of truth for the build.
- Distribution name `codeberg-to-gitea-migrator`; import name `codeberg_to_gitea_migrator` (dashes → underscores).
- Runtime deps are declared in root `pyproject.toml` `[project] dependencies` and added when a feature first needs them (none yet).
- Runtime deps (root `pyproject.toml`): `httpx` (HTTP), `typer` (CLI). Dev: `pytest`, `ruff`.
- Forgejo and Gitea share one REST API; `clients.ApiClient` is instantiated twice — once for source (read), once for target (write).
## Module map
- `clients.py` — `ApiClient`: bearer auth, transparent pagination (`page`/`limit`), retry on 429/5xx, `get/post/patch/delete`, `raw_get` (binary), `post_multipart` (asset upload).
- `mirror.py` — `git clone --mirror` + `push --mirror`; captures `refs/pull/<n>/head` SHAs and recreates them as target branches `refs/heads/_pr/<n>` (so deleted-branch PRs survive), prunes Forgejo-internal `refs/pull/*` before push, mirrors LFS objects.
- `refs.py` — `NumberMap` + `rewrite`: rewrites `#NNN` refs and source issue/PR URLs to the target's fresh number space (source numbers are sparse after deletions).
- `issues.py` — labels, milestones, issues + PRs + comments. Two-pass: create in source-number order (build number map), then rewrite title/body refs + stream comments. PR head falls back to `_pr/<n>` when the source branch is gone.
- `releases.py` — non-draft releases + asset re-upload. Treats a 404 releases endpoint (feature disabled) as "none".
- `migrate.py` — `migrate_repo` orchestrator: creates/validates the target repo, runs the pipeline, returns a report.
- `cli.py` — `codeberg-to-gitea migrate` Typer entrypoint. Tokens via `CODEBERG_TOKEN` / `GITEA_TOKEN` env or flags. `--repo owner/name` (or bare `name`).
## Work Guidance
- ADR-0001 records the Python stack; ADR-0003 records the Gitea forge + CI.
- Prefer one module per migration concern (mirror, issues, releases, labels) over a monolith.
- Prefer one module per migration concern over a monolith.
- Target Python ≥ 3.11; ruff line-length 100.
- Fidelity is intentionally bounded: the public Gitea API stamps issue/PR/comment author (→ migration token user) and timestamps server-side; assignees and reactions are not migrated. Cross-references ARE rewritten to stay correct.
- Repo creation needs the target token to have `write:user` scope; otherwise create the empty repo by hand first (the migrator then populates a fresh target).
## Verification
- `pytest` (testpaths = `tests`) from the repo root.
- `pytest` (testpaths = `tests`) — refs rewriting, number map, client pagination (mock transport, no network).
- `ruff check .` and `ruff format --check .`.
- End-to-end: `CODEBERG_TOKEN=… GITEA_TOKEN=… codeberg-to-gitea migrate owner/name`.
## Child DOX Index
+108
View File
@@ -0,0 +1,108 @@
"""Command-line entrypoint.
```
CODEBERG_TOKEN=*** GITEA_TOKEN=*** codeberg-to-gitea migrate AlexKucera/helm
```
Both tokens may be passed as flags or via the ``CODEBERG_TOKEN`` / ``GITEA_TOKEN``
env vars. ``--repo`` accepts ``owner/name`` or a bare ``name`` (owner defaults
to the source-forge authenticated user).
"""
from __future__ import annotations
import logging
import typer
from . import __version__
from .clients import ApiClient, ApiError
from .migrate import DEFAULT_SOURCE, DEFAULT_TARGET, MigrationError, migrate_repo
app = typer.Typer(
name="codeberg-to-gitea",
help="Migrate a Codeberg (Forgejo) repo to a self-hosted Gitea instance.",
no_args_is_help=True,
add_completion=False,
)
@app.command()
def migrate(
repo: str = typer.Argument(
..., help="Source repo as 'owner/name', or just 'name' (owner defaults to your user)."
),
source_url: str = typer.Option(DEFAULT_SOURCE, "--source-url", help="Source forge base URL."),
target_url: str = typer.Option(DEFAULT_TARGET, "--target-url", help="Target Gitea base URL."),
source_token: str = typer.Option(
"", "--source-token", envvar="CODEBERG_TOKEN", help="Source forge API token."
),
target_token: str = typer.Option(
"", "--target-token", envvar="GITEA_TOKEN", help="Target Gitea API token."
),
delete_existing: bool = typer.Option(
False, "--delete-existing", help="Delete the target repo first (one-shot re-run)."
),
skip_git: bool = typer.Option(False, "--skip-git", help="Skip the git mirror."),
skip_issues: bool = typer.Option(
False, "--skip-issues", help="Skip issues/PRs/labels/milestones."
),
skip_releases: bool = typer.Option(False, "--skip-releases", help="Skip releases + assets."),
verbose: bool = typer.Option(False, "-v", "--verbose", help="Verbose logging."),
) -> None:
"""Migrate a single repository from source to target forge."""
logging.basicConfig(
level=logging.DEBUG if verbose else logging.INFO,
format="%(levelname)s %(name)s: %(message)s",
)
if not source_token or not target_token:
raise typer.BadParameter(
"Both tokens are required (flags or CODEBERG_TOKEN/GITEA_TOKEN env)."
)
owner, name = _parse_repo(repo, source_url, source_token)
try:
report = migrate_repo(
source_url=source_url,
target_url=target_url,
owner=owner,
name=name,
source_token=source_token,
target_token=target_token,
delete_existing=delete_existing,
skip_git=skip_git,
skip_issues=skip_issues,
skip_releases=skip_releases,
)
except MigrationError as exc:
raise typer.BadParameter(str(exc)) from exc
except ApiError as exc:
typer.echo(f"API error: {exc}", err=True)
raise typer.Exit(1) from exc
typer.echo(f"✓ migrated {owner}/{name}: {report}")
@app.command()
def version() -> None:
"""Print the migrator version."""
typer.echo(__version__)
def _parse_repo(repo: str, source_url: str, source_token: str) -> tuple[str, str]:
if "/" in repo:
owner, name = repo.split("/", 1)
return owner, name
# Bare name: owner defaults to the source-forge authenticated user.
with ApiClient(source_url, source_token) as src:
me = src.get("/user")
login = me.get("login")
if not login:
raise typer.BadParameter("could not resolve source user to default the owner")
return login, repo
if __name__ == "__main__":
app()
+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
+237
View File
@@ -0,0 +1,237 @@
"""Migrate labels, milestones, issues, pull requests, and comments.
Two-pass design for issues + PRs:
* **Pass A** creates every issue/PR in ascending source-number order, sets its
state (and attempts to merge closed-and-merged PRs), and records the
source→target number mapping. Bodies are stored *unrewritten* here because
forward cross-references aren't resolvable yet.
* **Pass B** runs once the full number map is known: it rewrites
``#NNN`` refs / source URLs in each title+body (PATCH) and creates every
comment (rewritten), preserving comment order.
Issue/PR numbers share one sequence on both forges, and source numbers are
sparse (deleted issues leave gaps), so the rewrite pass is what keeps migrated
cross-references honest.
Known fidelity limits (the public Gitea API stamps these server-side): original
author (attributed to the migration token user), original timestamps, and
assignees/reactions.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Any
from .clients import ApiClient, ApiError
from .refs import NumberMap, rewrite
log = logging.getLogger(__name__)
@dataclass
class RefCtx:
numbers: NumberMap
source_web_root: str
target_web_root: str
def __call__(self, text: str | None) -> str | None:
return rewrite(
text,
self.numbers,
source_web_root=self.source_web_root,
target_web_root=self.target_web_root,
)
def _path(owner: str, repo: str, suffix: str = "") -> str:
return f"/repos/{owner}/{repo}{suffix}"
# -- labels ---------------------------------------------------------------
def migrate_labels(
src: ApiClient, tgt: ApiClient, owner: str, repo: str
) -> tuple[dict[int, int], dict[str, int]]:
"""Recreate labels on target. Returns (old_id→new_id, name→new_id)."""
id_map: dict[int, int] = {}
name_map: dict[str, int] = {}
for label in src.get_all(_path(owner, repo, "/labels")):
body = {
"name": label["name"],
"color": label.get("color", "ededed"),
"description": label.get("description") or "",
"exclusive": bool(label.get("exclusive", False)),
"is_archived": bool(label.get("is_archived", False)),
}
created = tgt.post(_path(owner, repo, "/labels"), body=body)
new_id = created["id"]
id_map[label["id"]] = new_id
name_map[label["name"]] = new_id
log.info("label %s → #%s", label["name"], new_id)
return id_map, name_map
# -- milestones -----------------------------------------------------------
def migrate_milestones(src: ApiClient, tgt: ApiClient, owner: str, repo: str) -> dict[int, int]:
"""Recreate milestones on target. Returns old_id→new_id."""
id_map: dict[int, int] = {}
for ms in src.get_all(_path(owner, repo, "/milestones"), state="all"):
body: dict[str, Any] = {
"title": ms["title"],
"description": ms.get("description") or "",
"state": ms.get("state", "open"),
}
if ms.get("due_on"):
body["due_on"] = ms["due_on"]
created = tgt.post(_path(owner, repo, "/milestones"), body=body)
id_map[ms["id"]] = created["id"]
log.info("milestone %s → #%s", ms["title"], created["id"])
return id_map
# -- issues + PRs ---------------------------------------------------------
def _collect(src: ApiClient, owner: str, repo: str) -> list[dict]:
"""All source issues and PRs, tagged with kind, sorted by number."""
items: list[dict] = []
for issue in src.get_all(_path(owner, repo, "/issues"), state="all", type="issues"):
issue["_kind"] = "issue"
items.append(issue)
for pull in src.get_all(_path(owner, repo, "/pulls"), state="all"):
pull["_kind"] = "pull"
items.append(pull)
items.sort(key=lambda it: it["number"])
return items
def _set_state(tgt: ApiClient, owner: str, repo: str, number: int, state: str) -> None:
if state != "closed":
return
tgt.patch(_path(owner, repo, f"/issues/{number}"), body={"state": "closed"})
def _merge_pr(
src: ApiClient,
tgt: ApiClient,
owner: str,
repo: str,
number: int,
source_pull: dict,
) -> None:
"""Best-effort: recreate a merged PR's merged state. Gitea will only merge
if the head is cleanly mergeable into base at current history; for a
historical merge the commits are usually already in base, so this often
no-ops or 409s — either way the PR ends up closed, which is the fidelity
floor we can reach without time-travel."""
if not source_pull.get("merged"):
return
# The original merge style isn't exposed by the API; default to a merge commit.
try:
tgt.post(
_path(owner, repo, f"/pulls/{number}/merge"),
body={"Do": "merge"},
)
except ApiError as exc: # already merged / not mergeable — expected
log.debug("merge attempt for #%s: %s (ignored)", number, exc.status)
def _create_entity(
tgt: ApiClient,
owner: str,
repo: str,
item: dict,
milestone_map: dict[int, int],
) -> int:
"""Create an issue or PR; return its new number. Raises on PR-create failure
(e.g. head branch gone) so the caller can skip cleanly."""
kind = item["_kind"]
if kind == "issue":
created = tgt.post(
_path(owner, repo, "/issues"),
body={"title": item["title"], "body": item.get("body") or ""},
)
else:
head = item.get("head", {}) or {}
base = (item.get("base", {}) or {}).get("ref", "main")
# Source reports a deleted-branch PR's head as "refs/pull/<n>/head";
# the mirror recreated its commits on the target as branch _pr/<n>.
head_ref = head.get("ref", "")
if not head_ref or head_ref.startswith("refs/pull/"):
head_ref = f"_pr/{item['number']}"
created = tgt.post(
_path(owner, repo, "/pulls"),
body={
"title": item["title"],
"body": item.get("body") or "",
"head": head_ref,
"base": base,
},
)
new_number = created["number"]
ms = item.get("milestone")
if ms and ms.get("id") in milestone_map:
tgt.patch(
_path(owner, repo, f"/issues/{new_number}"),
body={"milestone": milestone_map[ms["id"]]},
)
return new_number
def migrate_issues_and_prs(
src: ApiClient,
tgt: ApiClient,
owner: str,
repo: str,
label_id_map: dict[int, int],
milestone_map: dict[int, int],
ref: RefCtx,
) -> NumberMap:
"""Migrate issues + PRs + comments, returning the source→target number map."""
numbers = ref.numbers
items = _collect(src, owner, repo)
created: list[tuple[dict, int]] = [] # (source_item, new_number)
for item in items:
kind = item["_kind"]
try:
new_number = _create_entity(tgt, owner, repo, item, milestone_map)
except ApiError as exc:
log.warning("skipped %s #%s (%s): %s", kind, item["number"], item["title"], exc.status)
continue
numbers.add(item["number"], new_number)
# Labels (works for both issues and PRs via the shared issue path).
label_ids = [
label_id_map[label["id"]]
for label in item.get("labels", [])
if label.get("id") in label_id_map
]
if label_ids:
tgt.post(
_path(owner, repo, f"/issues/{new_number}/labels"),
body={"labels": label_ids},
)
_set_state(tgt, owner, repo, new_number, item.get("state", "open"))
if kind == "pull":
_merge_pr(src, tgt, owner, repo, new_number, item)
created.append((item, new_number))
log.info("%s #%s → #%s (%s)", kind, item["number"], new_number, item["title"])
# Pass B: rewrite refs in title+body, then stream comments.
for item, new_number in created:
new_title = ref(item.get("title"))
new_body = ref(item.get("body"))
tgt.patch(
_path(owner, repo, f"/issues/{new_number}"),
body={"title": new_title, "body": new_body},
)
for comment in src.get_all(_path(owner, repo, f"/issues/{item['number']}/comments")):
tgt.post(
_path(owner, repo, f"/issues/{new_number}/comments"),
body={"body": ref(comment.get("body"))},
)
return numbers
+171
View File
@@ -0,0 +1,171 @@
"""End-to-end migration orchestration.
``migrate_repo`` ties the pieces together: open both forge clients, (re)create
the target repository, mirror git data, then replay labels, milestones,
issues+PRs (+comments), and releases (+assets). Cross-references are rewritten
to the target's fresh number space.
"""
from __future__ import annotations
import logging
import tempfile
from pathlib import Path
from .clients import ApiClient, ApiError
from .issues import RefCtx, migrate_issues_and_prs, migrate_labels, migrate_milestones
from .mirror import mirror_repo
from .refs import NumberMap
from .releases import migrate_releases
log = logging.getLogger(__name__)
DEFAULT_SOURCE = "https://codeberg.org"
DEFAULT_TARGET = "https://git.babylondreams.de"
class MigrationError(RuntimeError):
pass
def _git_url(web_root: str, owner: str, name: str) -> str:
return f"{web_root.rstrip('/')}/{owner}/{name}.git"
def _target_exists(tgt: ApiClient, owner: str, name: str) -> dict | None:
"""Return the target repo metadata, or None if it doesn't exist."""
try:
return tgt.get(f"/repos/{owner}/{name}")
except ApiError as exc:
if exc.status == 404:
return None
raise
def _is_fresh(tgt: ApiClient, owner: str, name: str) -> bool:
"""A repo counts as fresh (safe to populate) when it has no issues/PRs yet."""
issues = tgt.get_all(f"/repos/{owner}/{name}/issues", state="all", type="issues")
pulls = tgt.get_all(f"/repos/{owner}/{name}/pulls", state="all")
return not issues and not pulls
def _ensure_target_repo(
tgt: ApiClient, owner: str, name: str, source_meta: dict, *, delete_existing: bool
) -> None:
"""Ensure a fresh target repo exists to populate.
Repo creation is a privileged step: Gitea's ``POST /user/repos`` needs the
``write:user`` scope, which migration tokens often lack. So the repo may be
pre-created by hand (web UI) — we then just populate it. If the target
already exists *and* isn't fresh, we refuse unless ``--delete-existing``
(re-running would duplicate issues/PRs, which the API can't upsert).
"""
existing = _target_exists(tgt, owner, name)
if existing is not None:
if delete_existing:
log.warning("deleting existing target repo %s/%s", owner, name)
try:
tgt.delete(f"/repos/{owner}/{name}")
except ApiError as exc:
raise MigrationError(
f"could not delete {owner}/{name} (token needs admin scope): {exc}"
) from exc
existing = None
elif not _is_fresh(tgt, owner, name):
raise MigrationError(
f"target repo {owner}/{name} already exists and isn't empty "
"(has issues/PRs); re-running would duplicate them. "
"Delete it first, then re-run."
)
else:
log.info("target repo %s/%s already exists (fresh) — populating", owner, name)
if existing is not None:
return
body = {
"name": name,
"description": source_meta.get("description") or "",
"private": bool(source_meta.get("private")),
"default_branch": source_meta.get("default_branch") or "main",
"has_issues": True,
"has_pull_requests": True,
"has_wiki": bool(source_meta.get("has_wiki", False)),
"has_projects": bool(source_meta.get("has_projects", False)),
"auto_init": False,
}
me = tgt.get("/user")
endpoint = "/user/repos" if me.get("login") == owner else f"/orgs/{owner}/repos"
try:
tgt.post(endpoint, body=body)
except ApiError as exc:
if exc.status in (401, 403):
raise MigrationError(
f"cannot create target repo {owner}/{name}: token lacks the needed "
f"scope ({exc.status}). Create the empty repo on Gitea first "
"(web UI), then re-run — the migrator will populate it."
) from exc
raise
log.info("created target repo %s/%s", owner, name)
def migrate_repo(
*,
source_url: str,
target_url: str,
owner: str,
name: str,
source_token: str,
target_token: str,
delete_existing: bool = False,
workdir: Path | None = None,
skip_git: bool = False,
skip_issues: bool = False,
skip_releases: bool = False,
) -> dict:
"""Migrate one repo from source forge to target forge. Returns a report."""
if not source_token or not target_token:
raise MigrationError("both source and target tokens are required")
numbers = NumberMap()
report: dict = {"owner": owner, "name": name}
with (
ApiClient(source_url, source_token) as src,
ApiClient(target_url, target_token) as tgt,
):
source_meta = src.get(f"/repos/{owner}/{name}")
_ensure_target_repo(tgt, owner, name, source_meta, delete_existing=delete_existing)
ref = RefCtx(
numbers=numbers,
source_web_root=src.web_root,
target_web_root=tgt.web_root,
)
if not skip_git:
workdir = workdir or Path(tempfile.gettempdir()) / "cb2gitea"
git_report = mirror_repo(
source_url=_git_url(src.web_root, owner, name),
target_url=_git_url(tgt.web_root, owner, name),
source_token=source_token,
target_token=target_token,
workdir=workdir,
)
report["git"] = git_report
log.info("git mirror done: %s", git_report)
if not skip_issues:
label_id_map, _name_map = migrate_labels(src, tgt, owner, name)
milestone_map = migrate_milestones(src, tgt, owner, name)
migrate_issues_and_prs(src, tgt, owner, name, label_id_map, milestone_map, ref)
report["labels"] = len(label_id_map)
report["milestones"] = len(milestone_map)
report["issues_prs"] = len(numbers)
if not skip_releases:
report["releases"] = migrate_releases(src, tgt, owner, name, ref)
log.info("migration complete: %s", report)
return report
+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)
+112
View File
@@ -0,0 +1,112 @@
"""Cross-reference rewriting between source and target forges.
Source issue/PR numbers rarely line up with target numbers after migration
(deleted source issues leave gaps; the target assigns fresh dense numbers).
Rewriting ``#NNN`` references and full issue/PR URLs in migrated text keeps
cross-references pointing at the *right* target entities instead of dangling
or pointing at the wrong one.
Usage: build a :class:`NumberMap` as entities are created, then call
:func:`rewrite` on every title, body, and comment before it lands on target.
"""
from __future__ import annotations
import re
# A standalone ``#123`` reference — not part of a URL, not a markdown heading.
# Preceded by start-of-string or a non-``#``/non-word char so ``## 2`` (heading)
# and ``foo#123`` (anchor) are left alone; followed by a word boundary so
# ``#1234`` isn't matched as ``#123``.
HASH_REF = re.compile(r"(?<![#\w])#(\d+)\b")
# ``…/issues/123`` or ``…/pulls/123`` (Forgejo/Gitea share both path shapes).
URL_REF = re.compile(r"(?P<base>https?://[^\s/]+/[^\s]+?)/(?:issues|pulls)/(?P<num>\d+)")
class NumberMap:
"""source issue/PR number → target issue/PR number."""
def __init__(self) -> None:
self._map: dict[int, int] = {}
def add(self, source: int, target: int) -> None:
self._map[source] = target
def get(self, source: int) -> int | None:
return self._map.get(source)
def has(self, source: int) -> bool:
return source in self._map
@property
def any_mismatch(self) -> bool:
return any(s != t for s, t in self._map.items())
def __len__(self) -> int:
return len(self._map)
def __repr__(self) -> str: # pragma: no cover - debugging aid
return f"NumberMap({len(self._map)} entries, mismatch={self.any_mismatch})"
def rewrite(
text: str | None,
numbers: NumberMap,
*,
source_web_root: str,
target_web_root: str,
owner_repo: str | None = None,
) -> str | None:
"""Rewrite ``#NNN`` refs and source URLs in ``text`` to target numbers.
Only numbers known to ``numbers`` are rewritten; unknown references are
left untouched. ``#NNN`` is rewritten to the new number (or left alone if
it maps to itself, to keep diffs clean). Source web URLs are repointed at
the target web root.
"""
if not text:
return text
src_root = source_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
tgt_root = target_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
def rewrite_hash(match: re.Match[str]) -> str:
old = int(match.group(1))
new = numbers.get(old)
if new is None or new == old:
return match.group(0)
return f"#{new}"
def rewrite_url(match: re.Match[str]) -> str:
base = match.group("base")
old = int(match.group("num"))
new = numbers.get(old)
# Repoint any source URL at the target host; keep its number in sync
# when we know the mapping, else leave the number as-is.
out_base = base.replace(src_root, tgt_root, 1) if base.startswith(src_root) else base
out_num = new if new is not None else old
return f"{out_base}/issues/{out_num}"
out = URL_REF.sub(rewrite_url, text)
out = HASH_REF.sub(rewrite_hash, out)
return out
if __name__ == "__main__": # self-check
nm = NumberMap()
nm.add(289, 2)
nm.add(290, 3)
sample = (
"Fixes #289 and see #999 (unknown). Also https://codeberg.org/AlexKucera/helm/issues/290."
)
result = rewrite(
sample,
nm,
source_web_root="https://codeberg.org",
target_web_root="https://git.babylondreams.de",
)
assert result == (
"Fixes #2 and see #999 (unknown). "
"Also https://git.babylondreams.de/AlexKucera/helm/issues/3."
), result
print("refs self-check ok:", result)
@@ -0,0 +1,67 @@
"""Migrate releases and their attached binary assets.
Git tags (which releases hang off) already arrived via the git mirror, so this
module only needs to (re)create each release record on the target and re-upload
its assets. Drafts are skipped — the target forge can't recreate a draft under
its true author, and a draft published under the token user would mislead.
"""
from __future__ import annotations
import logging
from .clients import ApiClient, ApiError
from .issues import RefCtx
log = logging.getLogger(__name__)
def _path(owner: str, repo: str, suffix: str = "") -> str:
return f"/repos/{owner}/{repo}{suffix}"
def migrate_releases(
src: ApiClient,
tgt: ApiClient,
owner: str,
repo: str,
ref: RefCtx,
) -> int:
"""Recreate non-draft releases + assets on target. Returns count migrated."""
try:
releases = src.get_all(_path(owner, repo, "/releases"))
except ApiError as exc:
# Forgejo 404s the releases endpoint when the feature is off for the
# repo (or it simply has none) — nothing to migrate.
if exc.status == 404:
log.info("source has no releases endpoint (disabled/empty); skipping")
return 0
raise
# Oldest first so a chronological viewer matches the source; skip drafts.
releases = [r for r in releases if not r.get("draft")]
releases.sort(key=lambda r: r.get("created_at", ""))
count = 0
for rel in releases:
body = {
"tag_name": rel["tag_name"],
"name": rel.get("name") or rel["tag_name"],
"body": ref(rel.get("body")),
"draft": False,
"prerelease": bool(rel.get("prerelease")),
"target_commitish": (rel.get("target_commitish") or "main"),
}
created = tgt.post(_path(owner, repo, "/releases"), body=body)
new_id = created["id"]
for asset in rel.get("assets", []) or []:
data = src.raw_get(_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}"))
tgt.post_multipart(
_path(owner, repo, f"/releases/{new_id}/assets"),
files={"attachment": (asset["name"], data)},
name=asset["name"],
)
n_assets = len(rel.get("assets", []) or [])
log.info("release %s → #%s (%d assets)", rel["tag_name"], new_id, n_assets)
count += 1
return count
+5 -4
View File
@@ -2,8 +2,7 @@
## Purpose
Pytest suite for `codeberg_to_gitea_migrator`. Currently a smoke test asserting
the package imports and reports its version.
Pytest suite for `codeberg_to_gitea_migrator`.
## Ownership
@@ -16,8 +15,10 @@ Project maintainer (Alexander Kucera).
## Work Guidance
- Add focused tests alongside each migration module.
- Keep network calls behind a fake/recorded client — do not hit live Codeberg/Gitea from tests.
- `test_smoke.py` — package imports + version.
- `test_refs.py` — `#NNN`/URL cross-reference rewrite + `NumberMap`.
- `test_clients.py` — `ApiClient` pagination, param cleaning, 4xx handling, JSON POST, all via `httpx.MockTransport` (no network).
- Keep tests network-free: never hit live Codeberg/Gitea from the suite. The end-to-end run is a manual CLI invocation, not a test.
## Verification
+73
View File
@@ -0,0 +1,73 @@
"""Tests for the API client (pagination + helpers) using a mock transport.
No network: httpx.MockTransport answers all requests deterministically.
"""
import httpx
import pytest
from codeberg_to_gitea_migrator.clients import ApiClient, ApiError
def _client(handler) -> ApiClient:
transport = httpx.MockTransport(handler)
real = ApiClient("https://example.com", "tok")
# Swap in the mock transport but keep the auth header.
real._client = httpx.Client(
base_url=real.api_root,
headers={"Authorization": "token tok"},
transport=transport,
)
return real
def test_paged_follows_pages_until_short_batch() -> None:
pages = {
1: [{"id": i} for i in range(50)],
2: [{"id": i} for i in range(50, 70)], # < limit → stop
}
def handler(request: httpx.Request) -> httpx.Response:
page = int(request.url.params["page"])
return httpx.Response(200, json=pages.get(page, []))
with _client(handler) as c:
items = c.get_all("/repos/o/r/labels")
assert len(items) == 70
assert items[0]["id"] == 0
assert items[-1]["id"] == 69
def test_get_drops_none_params_and_stringifies_bools() -> None:
seen = {}
def handler(request: httpx.Request) -> httpx.Response:
seen["params"] = dict(request.url.params)
return httpx.Response(200, json={"ok": True})
with _client(handler) as c:
c.get("/repos/o/r", state=None, private=True, draft=False, name="x")
assert seen["params"] == {"private": "true", "draft": "false", "name": "x"}
def test_raises_on_4xx() -> None:
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(404, text="not found")
with _client(handler) as c:
with pytest.raises(ApiError) as exc_info:
c.get("/repos/o/r/missing")
assert exc_info.value.status == 404
def test_post_sends_json_body() -> None:
seen = {}
def handler(request: httpx.Request) -> httpx.Response:
seen["body"] = request.read().decode()
return httpx.Response(201, json={"id": 7})
with _client(handler) as c:
result = c.post("/repos/o/r/issues", body={"title": "x"})
assert result == {"id": 7}
assert '"title":"x"' in seen["body"]
+59
View File
@@ -0,0 +1,59 @@
"""Tests for cross-reference rewriting (no network)."""
from codeberg_to_gitea_migrator.refs import NumberMap, rewrite
def _ref(numbers: dict[int, int], text: str) -> str:
nm = NumberMap()
for src, tgt in numbers.items():
nm.add(src, tgt)
return rewrite(
text,
nm,
source_web_root="https://codeberg.org",
target_web_root="https://git.babylondreams.de",
)
def test_hash_ref_rewritten_when_mapped() -> None:
assert _ref({289: 2}, "Fixes #289 and more") == "Fixes #2 and more"
def test_unknown_hash_ref_left_alone() -> None:
assert _ref({289: 2}, "see #999 here") == "see #999 here"
def test_self_mapping_left_unchanged() -> None:
# Numbers that map to themselves aren't rewritten (keeps diffs clean).
assert _ref({5: 5}, "ref #5") == "ref #5"
def test_markdown_heading_not_matched() -> None:
assert _ref({}, "## 2 Section") == "## 2 Section"
def test_anchor_not_matched() -> None:
# `C#123` — the '#' is glued to a word char, so not a ref.
assert _ref({123: 1}, "use C#123 framework") == "use C#123 framework"
def test_url_repointed_and_renumbered() -> None:
out = _ref({290: 3}, "see https://codeberg.org/AlexKucera/helm/issues/290")
assert out == "see https://git.babylondreams.de/AlexKucera/helm/issues/3"
def test_url_host_only_when_number_unknown() -> None:
out = _ref({}, "see https://codeberg.org/AlexKucera/helm/issues/42")
assert out == "see https://git.babylondreams.de/AlexKucera/helm/issues/42"
def test_number_map_any_mismatch() -> None:
nm = NumberMap()
assert nm.any_mismatch is False
nm.add(1, 1)
assert nm.any_mismatch is False
nm.add(2, 5)
assert nm.any_mismatch is True
assert len(nm) == 2
assert nm.get(2) == 5
assert nm.get(99) is None