CI / test (push) Canceled after 0s
Introduce a frozen Migration handle binding the identity quintet (src/tgt clients, owner, name, NumberMap) the four entity phases previously received as five loose params. The phases now take the handle; migrate_repo builds one and drives all phases with it. Retire RefCtx and the shared _path helper (absorbed into the handle's .path()/.rewrite() accessors), deleting code rather than leaving dead types. migrate_issues_and_prs mutates m.numbers in place (returns None). Add tests/test_phases.py: the previously-untested entity layer is now reachable through the Migration seam (two mock-transport clients + a number map, no network), covering the two-pass issue/PR flow, label/milestone mappings, state-setting, best-effort PR merge, the deleted-branch head fallback, and release+asset re-upload. Closes #2
171 lines
6.1 KiB
Python
171 lines
6.1 KiB
Python
"""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 os
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
from .clients import ApiClient, ApiError
|
|
from .issues import migrate_issues_and_prs, migrate_labels, migrate_milestones
|
|
from .migration import Migration
|
|
from .mirror import DEFAULT_GIT_TIMEOUT, mirror_repo
|
|
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,
|
|
concurrency: int = 8,
|
|
git_timeout: float = DEFAULT_GIT_TIMEOUT,
|
|
) -> 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")
|
|
|
|
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)
|
|
|
|
migration = Migration(src, tgt, owner, name)
|
|
|
|
if not skip_git:
|
|
workdir = workdir or Path(tempfile.gettempdir()) / f"cb2gitea-{os.getuid()}"
|
|
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,
|
|
git_timeout=git_timeout,
|
|
)
|
|
report["git"] = git_report
|
|
log.info("git mirror done: %s", git_report)
|
|
|
|
if not skip_issues:
|
|
label_id_map = migrate_labels(migration, concurrency=concurrency)
|
|
milestone_map = migrate_milestones(migration, concurrency=concurrency)
|
|
migrate_issues_and_prs(migration, label_id_map, milestone_map, concurrency=concurrency)
|
|
report["labels"] = len(label_id_map)
|
|
report["milestones"] = len(milestone_map)
|
|
report["issues_prs"] = len(migration.numbers)
|
|
|
|
if not skip_releases:
|
|
report["releases"] = migrate_releases(migration, concurrency=concurrency)
|
|
|
|
log.info("migration complete: %s", report)
|
|
return report
|