perf(migrator): parallelize and harden migration
CI / test (push) Canceled after 0s

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.
This commit is contained in:
AlexKucera committed 2026-08-11 13:36:11 +02:00
1 parent 867d982786
commit 137734673d
14 files changed
+1372 -299

No files matched your search

+7 -6
View File
@@ -18,18 +18,18 @@ Console script: `codeberg-to-gitea`.
- `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 (root `pyproject.toml`): `httpx` (HTTP), `typer` (CLI). Dev: `pytest`, `ruff`.
- Runtime deps (root `pyproject.toml`): `httpx` (HTTP). CLI is stdlib `argparse` (no CLI dep). 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. Tokens are masked in any `GitError` and scrubbed from the on-disk remote config after each run; the mirror workdir is per-user `0700`.
- `clients.py` — `ApiClient`: bearer auth, transparent pagination (`page`/`limit`), retry on 429/5xx with full jitter, `get/post/patch/delete`, `raw_get_stream` (binary download streamed to a spooled temp file), `post_multipart` (asset upload). Thread-safe (one underlying `httpx.Client` per thread via a thread-local), so a single client serves concurrent requests; circuit breaker (`CircuitOpenError`) trips after N consecutive exhausted-retry failures; `_path` helper + `parallel(items, fn, workers=, executor=)` live here.
- `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. Tokens are masked in any `GitError` and scrubbed from the on-disk remote config after each run; the mirror workdir is per-user `0700`. Every network git op runs under a per-op timeout (`DEFAULT_GIT_TIMEOUT`, `--git-timeout`); PR-head pushes and `refs/pull/*` pruning are batched into a single `git push` / `update-ref --stdin`.
- `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".
- `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. Pass A (creation) is serial (ordered); labels/milestones and Pass B (ref rewrite + comments) overlap via `parallel`. Issues carry their milestone in the create body; PRs still PATCH it (pull-create has no milestone field).
- `releases.py` — non-draft releases + asset re-upload. Assets stream through `raw_get_stream` (bounded memory) and upload concurrently within a release. 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`).
- `cli.py` — `codeberg-to-gitea migrate` argparse entrypoint (`app()`). Tokens via `CODEBERG_TOKEN` / `GITEA_TOKEN` env or flags. `--repo owner/name` (or bare `name`). `--concurrency` (parallel independent writes, default 8), `--git-timeout` (per-op git timeout, default 1800s); catches `CircuitOpenError`.
## Work Guidance
@@ -40,6 +40,7 @@ Console script: `codeberg-to-gitea`.
- 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).
- Migration is intentionally one-shot per repo (cutover model): populate a fresh target once, then freeze the source. There is no incremental/delta sync; re-running on a populated target refuses unless `--delete-existing`, which wipes and redoes everything with fresh numbers. Incremental `--update` was considered and deliberately not built.
- Forge API tokens are secrets: the mirror path never lets them reach logs, exceptions, or the persisted `/tmp/cb2gitea-<uid>/.git/config`. Don't reintroduce bare tokens into error messages or stored URLs.
- Execution model: a single `ApiClient` is thread-safe (per-thread underlying `httpx.Client`), so the migration overlaps independent writes via `parallel(..., workers=concurrency)`. Pass A issue/PR creation stays serial — entities are created in source-number order so the number map can rewrite forward cross-references. `--concurrency` sizes the pool (default 8); `--git-timeout` bounds network git ops (default 1800s). Tune `--concurrency` down if the target forge rate-limits hard — the jittered 429 backoff + circuit breaker handle it, but lower concurrency is gentler.
## Verification
+93 -61
View File
@@ -7,92 +7,124 @@ 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).
Uses stdlib ``argparse`` (no CLI dependency).
"""
from __future__ import annotations
import argparse
import logging
import typer
import os
import sys
from . import __version__
from .clients import ApiClient, ApiError
from .clients import ApiClient, ApiError, CircuitOpenError
from .migrate import DEFAULT_SOURCE, DEFAULT_TARGET, MigrationError, migrate_repo
from .mirror import GitError
from .mirror import DEFAULT_GIT_TIMEOUT, GitError
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,
)
PROG = "codeberg-to-gitea"
@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."""
def _die(msg: str, code: int = 1) -> None:
print(f"{PROG}: {msg}", file=sys.stderr)
raise SystemExit(code)
def app(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(
prog=PROG,
description="Migrate a Codeberg (Forgejo) repo to a self-hosted Gitea instance.",
)
sub = parser.add_subparsers(dest="command", metavar="<command>")
m = sub.add_parser("migrate", help="Migrate a single repository from source to target forge.")
m.add_argument(
"repo",
help="Source repo as 'owner/name', or just 'name' (owner defaults to your user).",
)
m.add_argument("--source-url", default=DEFAULT_SOURCE, help="Source forge base URL.")
m.add_argument("--target-url", default=DEFAULT_TARGET, help="Target Gitea base URL.")
m.add_argument(
"--source-token",
default=os.environ.get("CODEBERG_TOKEN", ""),
help="Source forge API token (or CODEBERG_TOKEN env).",
)
m.add_argument(
"--target-token",
default=os.environ.get("GITEA_TOKEN", ""),
help="Target Gitea API token (or GITEA_TOKEN env).",
)
m.add_argument(
"--delete-existing",
action="store_true",
help="Delete the target repo first (one-shot re-run).",
)
m.add_argument("--skip-git", action="store_true", help="Skip the git mirror.")
m.add_argument("--skip-issues", action="store_true", help="Skip issues/PRs/labels/milestones.")
m.add_argument("--skip-releases", action="store_true", help="Skip releases + assets.")
m.add_argument(
"--concurrency",
type=int,
default=8,
help="Parallel requests for independent writes (labels, comments, assets).",
)
m.add_argument(
"--git-timeout",
type=int,
default=int(DEFAULT_GIT_TIMEOUT),
help="Per-op timeout (seconds) for network git ops (clone/fetch/push).",
)
m.add_argument("-v", "--verbose", action="store_true", help="Verbose logging.")
sub.add_parser("version", help="Print the migrator version.")
args = parser.parse_args(argv)
if args.command is None:
parser.print_help()
return
if args.command == "version":
print(__version__)
return
_migrate(args)
def _migrate(args: argparse.Namespace) -> None:
logging.basicConfig(
level=logging.DEBUG if verbose else logging.INFO,
level=logging.DEBUG if args.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)."
)
if not args.source_token or not args.target_token:
_die("both tokens are required (flags or CODEBERG_TOKEN/GITEA_TOKEN env).", code=2)
owner, name = _parse_repo(repo, source_url, source_token)
owner, name = _parse_repo(args.repo, args.source_url, args.source_token)
try:
report = migrate_repo(
source_url=source_url,
target_url=target_url,
source_url=args.source_url,
target_url=args.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,
source_token=args.source_token,
target_token=args.target_token,
delete_existing=args.delete_existing,
skip_git=args.skip_git,
skip_issues=args.skip_issues,
skip_releases=args.skip_releases,
concurrency=args.concurrency,
git_timeout=args.git_timeout,
)
except MigrationError as exc:
raise typer.BadParameter(str(exc)) from exc
_die(str(exc), code=2)
except CircuitOpenError as exc:
_die(f"aborting: {exc}")
except ApiError as exc:
typer.echo(f"API error: {exc}", err=True)
raise typer.Exit(1) from exc
_die(f"API error: {exc}")
except GitError as exc:
typer.echo(f"git error: {exc}", err=True)
raise typer.Exit(1) from exc
_die(f"git error: {exc}")
typer.echo(f"✓ migrated {owner}/{name}: {report}")
@app.command()
def version() -> None:
"""Print the migrator version."""
typer.echo(__version__)
print(f"✓ migrated {owner}/{name}: {report}")
def _parse_repo(repo: str, source_url: str, source_token: str) -> tuple[str, str]:
@@ -104,7 +136,7 @@ def _parse_repo(repo: str, source_url: str, source_token: str) -> tuple[str, str
me = src.get("/user")
login = me.get("login")
if not login:
raise typer.BadParameter("could not resolve source user to default the owner")
_die("could not resolve source user to default the owner.", code=2)
return login, repo
+159 -16
View File
@@ -4,17 +4,33 @@ 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.
A single :class:`ApiClient` is safe to drive from multiple threads: each thread
transparently gets its own underlying ``httpx.Client`` (and thus its own
connection pool) via a thread-local. This lets the migration overlap independent
requests through :func:`parallel` without per-worker client plumbing.
"""
from __future__ import annotations
import random
import tempfile
import threading
import time
from collections.abc import Iterator
from collections.abc import Callable, Iterator
from concurrent.futures import ThreadPoolExecutor
from typing import Any
import httpx
PAGE_SIZE = 50
#: Per-op ceiling for bulk binary transfers (release assets). Metadata calls
#: stay on the snappier default ``timeout``; this only gates ``raw_get_stream`` /
#: ``post_multipart`` so large assets don't trip a read/write timeout mid-stream.
DEFAULT_BULK_TIMEOUT = 600.0
#: Aborts once this many requests exhaust their retries in a row with no success
#: in between (a sustained 5xx/429 storm → the target looks down). 0 disables.
DEFAULT_FAIL_FAST = 5
class ApiError(RuntimeError):
@@ -27,6 +43,20 @@ class ApiError(RuntimeError):
self.body = body
class CircuitOpenError(RuntimeError):
"""Raised once consecutive exhausted-retry failures exceed the fail-fast cap.
A degraded target forge otherwise turns the run into hours of per-item retry
churn; tripping aborts early so the operator learns the target (not the data)
is the problem.
"""
def _path(owner: str, repo: str, suffix: str = "") -> str:
"""Shared repo-scoped API path (used by every migration module)."""
return f"/repos/{owner}/{repo}{suffix}"
class ApiClient:
"""Bearer-auth client over the Forgejo/Gitea REST API (``/api/v1``)."""
@@ -37,21 +67,66 @@ class ApiClient:
*,
timeout: float = 30.0,
max_retries: int = 4,
bulk_timeout: float = DEFAULT_BULK_TIMEOUT,
fail_fast: int = DEFAULT_FAIL_FAST,
transport: httpx.BaseTransport | None = None,
) -> 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._token = token
self._timeout = timeout
self.max_retries = max_retries
self._bulk_timeout = httpx.Timeout(timeout, read=bulk_timeout, write=bulk_timeout)
self._fail_fast = fail_fast
self._transport = transport
# One underlying httpx.Client per thread (httpx.Client is not itself
# concurrency-safe); a single ApiClient is then safe across threads.
self._tls = threading.local()
self._all_clients: list[httpx.Client] = []
self._clients_lock = threading.Lock()
self._fail_lock = threading.Lock()
self._consecutive_failures = 0
self._circuit_open = False
@property
def _client(self) -> httpx.Client:
c = getattr(self._tls, "client", None)
if c is None:
c = httpx.Client(
base_url=self.api_root,
headers={"Authorization": f"token {self._token}"},
timeout=self._timeout,
follow_redirects=True,
transport=self._transport,
)
self._tls.client = c
with self._clients_lock:
self._all_clients.append(c)
return c
# -- low level ---------------------------------------------------------
def _on_success(self) -> None:
if self._consecutive_failures:
with self._fail_lock:
self._consecutive_failures = 0
def _on_failure(self) -> None:
if self._fail_fast <= 0:
return
with self._fail_lock:
self._consecutive_failures += 1
if self._consecutive_failures >= self._fail_fast:
self._circuit_open = True
raise CircuitOpenError(
f"target {self.web_root} appears down: {self._consecutive_failures} "
f"consecutive requests exhausted retries — aborting"
)
def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
if self._circuit_open:
raise CircuitOpenError(f"target {self.web_root} circuit open — aborting")
path = path.lstrip("/")
url = f"{self.api_root}/{path}"
last_err: Exception | None = None
@@ -64,9 +139,11 @@ class ApiClient:
if resp.status_code in (429, 502, 503, 504):
last_err = ApiError(resp.status_code, url, resp.text)
else:
self._on_success()
return resp # caller decides on 4xx/5xx
# backoff: 0.5, 1, 2, 4, 8 …
time.sleep(0.5 * (2**attempt))
# backoff with full jitter: 0.5, 1, 2, 4, 8 … × [0.5, 1.0)
time.sleep((0.5 * (2**attempt)) * (0.5 + random.random()))
self._on_failure()
raise last_err if last_err else ApiError(0, url, "exhausted retries")
def request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
@@ -91,14 +168,48 @@ class ApiClient:
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))
def post_multipart(self, path: str, files: dict[str, Any], **params: Any) -> Any:
# Bulk path: large asset uploads need a generous read/write window so a
# multi-hundred-MB file over a slow link doesn't time out mid-upload and
# trigger a wasteful full re-send.
resp = self.request(
"POST", path, files=files, params=_clean(params), timeout=self._bulk_timeout
)
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
def raw_get_stream(self, path: str, **params: Any) -> Any:
"""Stream a raw download into a spooled temp file; caller closes it.
The *download* is streamed to a spooled ~1 MiB temp file (vs. buffering
the whole body), so download peak memory is bounded regardless of asset
size. The subsequent *upload* (:meth:`post_multipart`) still buffers the
full asset — httpx materializes the multipart body — so overall peak
memory is ~one asset, not two. Honors the circuit breaker (aborts if
already open; counts transient 429/5xx + transport errors toward it) but
does NOT per-attempt retry a streamed download — a transient error on an
asset aborts the release phase; re-run the migration. Returns an open
``SpooledTemporaryFile`` positioned at 0.
"""
if self._circuit_open:
raise CircuitOpenError(f"target {self.web_root} circuit open — aborting")
tmp: Any = tempfile.SpooledTemporaryFile(max_size=1 << 20) # 1 MiB in-RAM threshold
try:
with self._client.stream(
"GET", path.lstrip("/"), params=_clean(params), timeout=self._bulk_timeout
) as resp:
if resp.status_code >= 400:
body = resp.read().decode(errors="replace")
if resp.status_code in (429, 502, 503, 504):
self._on_failure()
raise ApiError(resp.status_code, str(resp.url), body)
for chunk in resp.iter_bytes():
tmp.write(chunk)
self._on_success()
except httpx.TransportError as exc:
self._on_failure()
raise ApiError(0, f"{self.api_root}/{path.lstrip('/')}", str(exc)) from exc
tmp.seek(0)
return tmp
# -- pagination --------------------------------------------------------
def paged(self, path: str, **params: Any) -> Iterator[Any]:
@@ -118,7 +229,10 @@ class ApiClient:
return list(self.paged(path, **params))
def close(self) -> None:
self._client.close()
with self._clients_lock:
for c in self._all_clients:
c.close()
self._all_clients.clear()
def __enter__(self) -> ApiClient:
return self
@@ -127,6 +241,35 @@ class ApiClient:
self.close()
def parallel(
items: list[Any],
fn: Callable[[Any], Any],
*,
workers: int = 1,
executor: ThreadPoolExecutor | None = None,
) -> list[Any]:
"""Run ``fn(item)`` over ``items`` via a thread pool sized to ``workers``.
A single :class:`ApiClient` is thread-safe (each worker transparently gets
its own underlying ``httpx.Client``), so ``fn`` can close over the shared
source/target clients. Results are returned in input order. ``workers <= 1``
(or a single item) runs serially.
Pass a shared ``executor`` when calling in a loop (e.g. once per release) so
the same worker threads — and their thread-local clients — are reused
instead of accumulating a fresh pool per call. The first task failure
propagates via ``map`` but does NOT cancel already-running or queued
siblings (they drain on exit); the open-circuit fast-abort in ``_request``
makes the rest fail cheaply when the target is down.
"""
if workers <= 1 or len(items) <= 1:
return [fn(it) for it in items]
if executor is not None:
return list(executor.map(fn, items))
with ThreadPoolExecutor(max_workers=workers) as ex:
return list(ex.map(fn, items))
def _clean(params: dict[str, Any]) -> dict[str, Any]:
"""Drop ``None`` values and stringify booleans the Forgejo way."""
out: dict[str, Any] = {}
+56 -36
View File
@@ -14,6 +14,11 @@ 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.
Pass A is inherently serial (entities must be created in source-number order so
the number map resolves forward references). Pass B, plus label/milestone
creation, are independent across items and overlap through
:func:`codeberg_to_gitea_migrator.clients.parallel`.
Known fidelity limits (the public Gitea API stamps these server-side): original
author (attributed to the migration token user), original timestamps, and
assignees/reactions.
@@ -25,7 +30,7 @@ import logging
from dataclasses import dataclass
from typing import Any
from .clients import ApiClient, ApiError
from .clients import ApiClient, ApiError, _path, parallel
from .refs import NumberMap, rewrite
log = logging.getLogger(__name__)
@@ -46,18 +51,19 @@ class RefCtx:
)
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")):
src: ApiClient,
tgt: ApiClient,
owner: str,
repo: str,
*,
concurrency: int = 1,
) -> dict[int, int]:
"""Recreate labels on target. Returns old_id→new_id."""
labels = src.get_all(_path(owner, repo, "/labels"))
def make(label: dict) -> tuple[dict, dict]:
body = {
"name": label["name"],
"color": label.get("color", "ededed"),
@@ -66,18 +72,21 @@ def migrate_labels(
"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
log.info("label %s → #%s", label["name"], created["id"])
return label, created
results = parallel(labels, make, workers=concurrency)
return {lab["id"]: created["id"] for lab, created in results}
# -- milestones -----------------------------------------------------------
def migrate_milestones(src: ApiClient, tgt: ApiClient, owner: str, repo: str) -> dict[int, int]:
def migrate_milestones(
src: ApiClient, tgt: ApiClient, owner: str, repo: str, *, concurrency: int = 1
) -> 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"):
milestones = src.get_all(_path(owner, repo, "/milestones"), state="all")
def make(ms: dict) -> tuple[dict, dict]:
body: dict[str, Any] = {
"title": ms["title"],
"description": ms.get("description") or "",
@@ -86,9 +95,11 @@ def migrate_milestones(src: ApiClient, tgt: ApiClient, owner: str, repo: str) ->
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
return ms, created
results = parallel(milestones, make, workers=concurrency)
return {ms["id"]: created["id"] for ms, created in results}
# -- issues + PRs ---------------------------------------------------------
@@ -144,13 +155,21 @@ def _create_entity(
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."""
(e.g. head branch gone) so the caller can skip cleanly.
Issues carry their milestone in the create body (one request); PRs can't
(the pull-create endpoint has no milestone field), so they still take a
follow-up PATCH.
"""
kind = item["_kind"]
ms = item.get("milestone")
ms_id = milestone_map[ms["id"]] if ms and ms.get("id") in milestone_map else None
if kind == "issue":
created = tgt.post(
_path(owner, repo, "/issues"),
body={"title": item["title"], "body": item.get("body") or ""},
)
body: dict[str, Any] = {"title": item["title"], "body": item.get("body") or ""}
if ms_id is not None:
body["milestone"] = ms_id
created = tgt.post(_path(owner, repo, "/issues"), body=body)
else:
head = item.get("head", {}) or {}
base = (item.get("base", {}) or {}).get("ref", "main")
@@ -168,14 +187,9 @@ def _create_entity(
"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
if ms_id is not None:
tgt.patch(_path(owner, repo, f"/issues/{created['number']}"), body={"milestone": ms_id})
return created["number"]
def migrate_issues_and_prs(
@@ -186,6 +200,8 @@ def migrate_issues_and_prs(
label_id_map: dict[int, int],
milestone_map: dict[int, int],
ref: RefCtx,
*,
concurrency: int = 1,
) -> NumberMap:
"""Migrate issues + PRs + comments, returning the source→target number map."""
numbers = ref.numbers
@@ -220,8 +236,11 @@ def migrate_issues_and_prs(
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:
# Pass B: rewrite refs in title+body, then stream comments. Items are
# independent of each other (the number map is already complete), so they
# overlap; each item's comments stay sequential to preserve their order.
def pass_b(pair: tuple[dict, int]) -> None:
item, new_number = pair
new_title = ref(item.get("title"))
new_body = ref(item.get("body"))
tgt.patch(
@@ -234,4 +253,5 @@ def migrate_issues_and_prs(
body={"body": ref(comment.get("body"))},
)
parallel(created, pass_b, workers=concurrency)
return numbers
+12 -5
View File
@@ -15,7 +15,7 @@ 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 .mirror import DEFAULT_GIT_TIMEOUT, mirror_repo
from .refs import NumberMap
from .releases import migrate_releases
@@ -124,6 +124,8 @@ def migrate_repo(
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:
@@ -153,20 +155,25 @@ def migrate_repo(
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, _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)
label_id_map = migrate_labels(src, tgt, owner, name, concurrency=concurrency)
milestone_map = migrate_milestones(src, tgt, owner, name, concurrency=concurrency)
migrate_issues_and_prs(
src, tgt, owner, name, label_id_map, milestone_map, ref, concurrency=concurrency
)
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)
report["releases"] = migrate_releases(
src, tgt, owner, name, ref, concurrency=concurrency
)
log.info("migration complete: %s", report)
return report
+100 -68
View File
@@ -5,17 +5,25 @@ Mirrors the source repository's git data to the target with
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 shutil
import subprocess
from pathlib import Path
from urllib.parse import quote, urlsplit, urlunsplit
LFS_MARKERS = (".gitattributes",) # presence hints at possible LFS rules
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):
@@ -67,22 +75,24 @@ def _scrub_remote_tokens(bare: Path) -> None:
)
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(_redact(a) for a in cmd)}"
f"\n{_redact(proc.stderr.strip())}"
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
)
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
)
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)}"
@@ -91,13 +101,31 @@ def _run_capture(cmd: list[str], cwd: Path | None = None) -> str:
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."""
"""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/"]
)
for ref in listing.split():
_run(["git", "--git-dir", str(bare), "update-ref", "-d", ref])
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]:
@@ -124,19 +152,12 @@ def _capture_pull_heads(bare: Path) -> dict[int, str]:
try:
number = int(ref.split("/")[2])
except (IndexError, ValueError):
log.warning("ignoring unparseable pull ref: %s", ref)
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
@@ -161,6 +182,8 @@ def mirror_repo(
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.
@@ -177,50 +200,59 @@ def mirror_repo(
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)])
# 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)
# 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])
# 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.)
for pr_number, sha in pull_heads.items():
_run(
[
"git",
"--git-dir",
str(bare),
"push",
tgt,
f"{sha}:refs/heads/_pr/{pr_number}",
]
)
# 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"])
# 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
_scrub_remote_tokens(bare)
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)}
-1
View File
@@ -56,7 +56,6 @@ def rewrite(
*,
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.
+41 -26
View File
@@ -4,28 +4,33 @@ 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.
Asset *downloads* stream through a spooled temp file (``raw_get_stream``) so
download memory is bounded regardless of asset size; the *upload* still
buffers the full asset (httpx materializes the multipart body), so overall peak
memory is ~one asset per in-flight worker, not two. A single executor spans all
releases so worker threads (and their thread-local clients) are reused.
"""
from __future__ import annotations
import logging
from concurrent.futures import ThreadPoolExecutor
from .clients import ApiClient, ApiError
from .clients import ApiClient, ApiError, _path, parallel
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,
*,
concurrency: int = 1,
) -> int:
"""Recreate non-draft releases + assets on target. Returns count migrated."""
try:
@@ -42,26 +47,36 @@ def migrate_releases(
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"]
# One executor spans all releases so worker threads (and their thread-local
# clients) are reused, not re-created per release.
with ThreadPoolExecutor(max_workers=max(concurrency, 1)) as ex:
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
assets = rel.get("assets", []) or []
def upload_asset(asset: dict) -> None:
# Stream the download to a spooled temp file (bounded download
# memory); the upload still buffers the full asset.
with src.raw_get_stream(
_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}")
) as data:
tgt.post_multipart(
_path(owner, repo, f"/releases/{new_id}/assets"),
files={"attachment": (asset["name"], data)},
name=asset["name"],
)
parallel(assets, upload_asset, workers=concurrency, executor=ex)
log.info("release %s → #%s (%d assets)", rel["tag_name"], new_id, len(assets))
count += 1
return count