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
This commit is contained in:
1 parent
1613ec72b8
commit
9d585f601a
12 files changed
+654
-124
No files matched your search
@@ -23,13 +23,14 @@ Console script: `codeberg-to-gitea`.
|
||||
|
||||
## Module map
|
||||
|
||||
- `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.
|
||||
- `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; `parallel(items, fn, workers=, executor=)` lives here.
|
||||
- `git.py` — the git-op seam (`GitRunner`): the *only* way git is invoked. Owns subprocess execution, per-op timeout (`DEFAULT_GIT_TIMEOUT`), error redaction (`redact` — known-secret first, legacy `oauth2:` fallback), and auth delivery (`Forge`, a frozen value type binding a token-free URL + token). Auth is a non-persisted per-op `git -c http.<scheme>://<host>.extraHeader=Authorization: token <T>`, so the token never enters a remote URL, the command line, or `.git/config` (closes audit HIGH A09 + MEDIUM A02 at the root). `run`/`capture`/`ok` verbs; an injectable exec callable is the test seam (recording fake).
|
||||
- `mirror.py` — the git-mirror *procedure*: drives a `GitRunner` (clone/fetch → capture `refs/pull/<n>/head` → prune forge-internal refs → `push --mirror` → recreate deleted-branch PR heads as `refs/heads/_pr/<n>` → LFS fetch+push). Owns the workdir lifecycle (per-user `0700`); its value is the ordering invariants, which its tests lock. `DEFAULT_GIT_TIMEOUT`/`GitError` are re-exported here so `cli.py`/`migrate.py` import them unchanged.
|
||||
- `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. 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.
|
||||
- `migration.py` — `Migration`: the bound context for one repo's transfer (source + target `ApiClient`, `owner`, `name`, `NumberMap`). Pure context — no I/O, no phase logic; two accessors only (`.path(suffix)` repo-scoped API path, `.rewrite(text)` delegating to the pure refs rewriter via the bound clients' web roots). The four phase functions take this handle instead of the old five loose params; it is also the phase layer's test surface (two mock-transport clients + a number map).
|
||||
- `issues.py` — labels, milestones, issues + PRs + comments. Each phase is a free function taking the `Migration` handle (`migrate_labels`/`migrate_milestones` return old-id→new-id maps; `migrate_issues_and_prs` mutates `m.numbers`). 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` — `migrate_releases` (takes the `Migration` handle): 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, builds one `Migration` once both clients are open, drives the entity phases with it (threading the label/milestone maps between them), returns a report.
|
||||
- `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
|
||||
@@ -42,10 +43,11 @@ Console script: `codeberg-to-gitea`.
|
||||
- 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: git auth goes through the `git.GitRunner` seam as a non-persisted `http.<host>.extraHeader`, so tokens never reach logs, exceptions, the command line, or the persisted `/tmp/cb2gitea-<uid>/.git/config`. Don't reintroduce bare tokens into error messages or stored URLs, and don't invoke git outside `GitRunner` (an AST regression guard fails the suite otherwise).
|
||||
- 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.
|
||||
- Bound context: the entity phases (`migrate_labels`/`migrate_milestones`/`migrate_issues_and_prs`/`migrate_releases`) take one `Migration` handle, not five loose params. `Migration` is pure context — no REST I/O, no entity branching, no phase logic lives on it; anything doing I/O belongs in a phase module. Per-phase outputs (label/milestone maps, the report) stay threaded by the orchestrator, not on the handle. `concurrency` is a per-call keyword (run-tuning, not identity).
|
||||
|
||||
## Verification
|
||||
|
||||
- `pytest` (testpaths = `tests`) — refs rewriting, number map, client pagination (mock transport); the `GitRunner` seam (recording exec fake) + mirror-procedure ordering invariants; an AST guard that git is invoked only through `GitRunner`. No network.
|
||||
- `pytest` (testpaths = `tests`) — refs rewriting, number map, client pagination (mock transport); the `GitRunner` seam (recording exec fake) + mirror-procedure ordering invariants; an AST guard that git is invoked only through `GitRunner`; `test_phases.py` drives all four entity phases through the `Migration` seam (two mock-transport clients + a number map, asserting paths/bodies received and number-map state). No network.
|
||||
- `ruff check .` and `ruff format --check .`.
|
||||
- End-to-end: `CODEBERG_TOKEN=… GITEA_TOKEN=… codeberg-to-gitea migrate owner/name`.
|
||||
- CI installs from the committed, hash-verified `uv.lock` (`uv sync --frozen --extra dev`) with Gitea Actions pinned to commit SHAs; run `uv lock` then `uv lock --check` when changing dependencies.
|
||||
|
||||
@@ -52,11 +52,6 @@ class CircuitOpenError(RuntimeError):
|
||||
"""
|
||||
|
||||
|
||||
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``)."""
|
||||
|
||||
|
||||
@@ -27,41 +27,18 @@ assignees/reactions.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from .clients import ApiClient, ApiError, _path, parallel
|
||||
from .refs import NumberMap, rewrite
|
||||
from .clients import ApiError, parallel
|
||||
from .migration import Migration
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
# -- labels ---------------------------------------------------------------
|
||||
def migrate_labels(
|
||||
src: ApiClient,
|
||||
tgt: ApiClient,
|
||||
owner: str,
|
||||
repo: str,
|
||||
*,
|
||||
concurrency: int = 1,
|
||||
) -> dict[int, int]:
|
||||
def migrate_labels(m: Migration, *, concurrency: int = 1) -> dict[int, int]:
|
||||
"""Recreate labels on target. Returns old_id→new_id."""
|
||||
labels = src.get_all(_path(owner, repo, "/labels"))
|
||||
labels = m.src.get_all(m.path("/labels"))
|
||||
|
||||
def make(label: dict) -> tuple[dict, dict]:
|
||||
body = {
|
||||
@@ -71,7 +48,7 @@ def migrate_labels(
|
||||
"exclusive": bool(label.get("exclusive", False)),
|
||||
"is_archived": bool(label.get("is_archived", False)),
|
||||
}
|
||||
created = tgt.post(_path(owner, repo, "/labels"), body=body)
|
||||
created = m.tgt.post(m.path("/labels"), body=body)
|
||||
log.info("label %s → #%s", label["name"], created["id"])
|
||||
return label, created
|
||||
|
||||
@@ -80,11 +57,9 @@ def migrate_labels(
|
||||
|
||||
|
||||
# -- milestones -----------------------------------------------------------
|
||||
def migrate_milestones(
|
||||
src: ApiClient, tgt: ApiClient, owner: str, repo: str, *, concurrency: int = 1
|
||||
) -> dict[int, int]:
|
||||
def migrate_milestones(m: Migration, *, concurrency: int = 1) -> dict[int, int]:
|
||||
"""Recreate milestones on target. Returns old_id→new_id."""
|
||||
milestones = src.get_all(_path(owner, repo, "/milestones"), state="all")
|
||||
milestones = m.src.get_all(m.path("/milestones"), state="all")
|
||||
|
||||
def make(ms: dict) -> tuple[dict, dict]:
|
||||
body: dict[str, Any] = {
|
||||
@@ -94,7 +69,7 @@ def migrate_milestones(
|
||||
}
|
||||
if ms.get("due_on"):
|
||||
body["due_on"] = ms["due_on"]
|
||||
created = tgt.post(_path(owner, repo, "/milestones"), body=body)
|
||||
created = m.tgt.post(m.path("/milestones"), body=body)
|
||||
log.info("milestone %s → #%s", ms["title"], created["id"])
|
||||
return ms, created
|
||||
|
||||
@@ -103,33 +78,26 @@ def migrate_milestones(
|
||||
|
||||
|
||||
# -- issues + PRs ---------------------------------------------------------
|
||||
def _collect(src: ApiClient, owner: str, repo: str) -> list[dict]:
|
||||
def _collect(m: Migration) -> 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"):
|
||||
for issue in m.src.get_all(m.path("/issues"), state="all", type="issues"):
|
||||
issue["_kind"] = "issue"
|
||||
items.append(issue)
|
||||
for pull in src.get_all(_path(owner, repo, "/pulls"), state="all"):
|
||||
for pull in m.src.get_all(m.path("/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:
|
||||
def _set_state(m: Migration, number: int, state: str) -> None:
|
||||
if state != "closed":
|
||||
return
|
||||
tgt.patch(_path(owner, repo, f"/issues/{number}"), body={"state": "closed"})
|
||||
m.tgt.patch(m.path(f"/issues/{number}"), body={"state": "closed"})
|
||||
|
||||
|
||||
def _merge_pr(
|
||||
src: ApiClient,
|
||||
tgt: ApiClient,
|
||||
owner: str,
|
||||
repo: str,
|
||||
number: int,
|
||||
source_pull: dict,
|
||||
) -> None:
|
||||
def _merge_pr(m: Migration, 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
|
||||
@@ -139,8 +107,8 @@ def _merge_pr(
|
||||
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"),
|
||||
m.tgt.post(
|
||||
m.path(f"/pulls/{number}/merge"),
|
||||
body={"Do": "merge"},
|
||||
)
|
||||
except ApiError as exc: # already merged / not mergeable — expected
|
||||
@@ -148,9 +116,7 @@ def _merge_pr(
|
||||
|
||||
|
||||
def _create_entity(
|
||||
tgt: ApiClient,
|
||||
owner: str,
|
||||
repo: str,
|
||||
m: Migration,
|
||||
item: dict,
|
||||
milestone_map: dict[int, int],
|
||||
) -> int:
|
||||
@@ -169,7 +135,7 @@ def _create_entity(
|
||||
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)
|
||||
created = m.tgt.post(m.path("/issues"), body=body)
|
||||
else:
|
||||
head = item.get("head", {}) or {}
|
||||
base = (item.get("base", {}) or {}).get("ref", "main")
|
||||
@@ -178,8 +144,8 @@ def _create_entity(
|
||||
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"),
|
||||
created = m.tgt.post(
|
||||
m.path("/pulls"),
|
||||
body={
|
||||
"title": item["title"],
|
||||
"body": item.get("body") or "",
|
||||
@@ -188,30 +154,27 @@ def _create_entity(
|
||||
},
|
||||
)
|
||||
if ms_id is not None:
|
||||
tgt.patch(_path(owner, repo, f"/issues/{created['number']}"), body={"milestone": ms_id})
|
||||
m.tgt.patch(m.path(f"/issues/{created['number']}"), body={"milestone": ms_id})
|
||||
return created["number"]
|
||||
|
||||
|
||||
def migrate_issues_and_prs(
|
||||
src: ApiClient,
|
||||
tgt: ApiClient,
|
||||
owner: str,
|
||||
repo: str,
|
||||
m: Migration,
|
||||
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
|
||||
items = _collect(src, owner, repo)
|
||||
) -> None:
|
||||
"""Migrate issues + PRs + comments, recording the source→target number map
|
||||
on ``m.numbers`` (mutated in place)."""
|
||||
numbers = m.numbers
|
||||
items = _collect(m)
|
||||
|
||||
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)
|
||||
new_number = _create_entity(m, item, milestone_map)
|
||||
except ApiError as exc:
|
||||
log.warning("skipped %s #%s (%s): %s", kind, item["number"], item["title"], exc.status)
|
||||
continue
|
||||
@@ -224,14 +187,14 @@ def migrate_issues_and_prs(
|
||||
if label.get("id") in label_id_map
|
||||
]
|
||||
if label_ids:
|
||||
tgt.post(
|
||||
_path(owner, repo, f"/issues/{new_number}/labels"),
|
||||
m.tgt.post(
|
||||
m.path(f"/issues/{new_number}/labels"),
|
||||
body={"labels": label_ids},
|
||||
)
|
||||
|
||||
_set_state(tgt, owner, repo, new_number, item.get("state", "open"))
|
||||
_set_state(m, new_number, item.get("state", "open"))
|
||||
if kind == "pull":
|
||||
_merge_pr(src, tgt, owner, repo, new_number, item)
|
||||
_merge_pr(m, new_number, item)
|
||||
|
||||
created.append((item, new_number))
|
||||
log.info("%s #%s → #%s (%s)", kind, item["number"], new_number, item["title"])
|
||||
@@ -241,17 +204,16 @@ def migrate_issues_and_prs(
|
||||
# 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(
|
||||
_path(owner, repo, f"/issues/{new_number}"),
|
||||
new_title = m.rewrite(item.get("title"))
|
||||
new_body = m.rewrite(item.get("body"))
|
||||
m.tgt.patch(
|
||||
m.path(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"))},
|
||||
for comment in m.src.get_all(m.path(f"/issues/{item['number']}/comments")):
|
||||
m.tgt.post(
|
||||
m.path(f"/issues/{new_number}/comments"),
|
||||
body={"body": m.rewrite(comment.get("body"))},
|
||||
)
|
||||
|
||||
parallel(created, pass_b, workers=concurrency)
|
||||
return numbers
|
||||
@@ -14,9 +14,9 @@ import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from .clients import ApiClient, ApiError
|
||||
from .issues import RefCtx, migrate_issues_and_prs, migrate_labels, migrate_milestones
|
||||
from .issues import migrate_issues_and_prs, migrate_labels, migrate_milestones
|
||||
from .migration import Migration
|
||||
from .mirror import DEFAULT_GIT_TIMEOUT, mirror_repo
|
||||
from .refs import NumberMap
|
||||
from .releases import migrate_releases
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -131,7 +131,6 @@ def migrate_repo(
|
||||
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 (
|
||||
@@ -141,11 +140,7 @@ def migrate_repo(
|
||||
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,
|
||||
)
|
||||
migration = Migration(src, tgt, owner, name)
|
||||
|
||||
if not skip_git:
|
||||
workdir = workdir or Path(tempfile.gettempdir()) / f"cb2gitea-{os.getuid()}"
|
||||
@@ -161,19 +156,15 @@ def migrate_repo(
|
||||
log.info("git mirror done: %s", git_report)
|
||||
|
||||
if not skip_issues:
|
||||
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
|
||||
)
|
||||
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(numbers)
|
||||
report["issues_prs"] = len(migration.numbers)
|
||||
|
||||
if not skip_releases:
|
||||
report["releases"] = migrate_releases(
|
||||
src, tgt, owner, name, ref, concurrency=concurrency
|
||||
)
|
||||
report["releases"] = migrate_releases(migration, concurrency=concurrency)
|
||||
|
||||
log.info("migration complete: %s", report)
|
||||
return report
|
||||
@@ -0,0 +1,74 @@
|
||||
"""The bound context for one repository's transfer.
|
||||
|
||||
``Migration`` binds exactly the identity quintet that every entity-migration
|
||||
phase needs: the source client, the target client, the ``owner`` and ``name``
|
||||
of the repo, and the source→target ``NumberMap``. Those five are conceptually
|
||||
one thing — the repo being transferred — so binding them once makes the
|
||||
source/target clients and the owner/name impossible to drift between phases.
|
||||
|
||||
It is **pure context**: it holds no phase logic and performs no I/O. The two
|
||||
derived accessors only build a path string and delegate to the existing pure
|
||||
reference rewriter (sourcing the web roots from the bound clients). Anything
|
||||
doing REST I/O or entity-specific branching belongs in a phase module, never
|
||||
here — ``Migration`` must not accrete into a god-object.
|
||||
|
||||
The handle is also the phase layer's test surface: construct one from two
|
||||
mock-transport clients and a number map, and the previously-untested two-pass
|
||||
core, mappings, and merge logic become reachable without any network.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .clients import ApiClient
|
||||
from .refs import NumberMap, rewrite
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Migration:
|
||||
"""One repo's transfer in progress: bound identity, no phase logic.
|
||||
|
||||
``numbers`` defaults to empty (an orchestrator always starts a migration
|
||||
with no mappings yet). It is mutated in place by the issue/PR phase (which
|
||||
appends mappings as it creates entities); ``frozen`` forbids rebinding the
|
||||
fields, not mutating the mutable ``NumberMap``.
|
||||
"""
|
||||
|
||||
src: ApiClient
|
||||
tgt: ApiClient
|
||||
owner: str
|
||||
name: str
|
||||
numbers: NumberMap = field(default_factory=NumberMap)
|
||||
|
||||
def path(self, suffix: str = "") -> str:
|
||||
"""Repo-scoped API path: ``/repos/{owner}/{name}{suffix}``."""
|
||||
return f"/repos/{self.owner}/{self.name}{suffix}"
|
||||
|
||||
def rewrite(self, text: str | None) -> str | None:
|
||||
"""Rewrite ``#NNN`` refs / source URLs to the target number space.
|
||||
|
||||
Delegates to the pure :func:`codeberg_to_gitea_migrator.refs.rewrite`,
|
||||
sourcing the two web roots from the bound clients.
|
||||
"""
|
||||
return rewrite(
|
||||
text,
|
||||
self.numbers,
|
||||
source_web_root=self.src.web_root,
|
||||
target_web_root=self.tgt.web_root,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__": # self-check
|
||||
src = ApiClient("https://codeberg.org", "tok")
|
||||
tgt = ApiClient("https://git.babylondreams.de", "tok")
|
||||
m = Migration(src, tgt, "AlexKucera", "helm")
|
||||
assert m.path() == "/repos/AlexKucera/helm"
|
||||
assert m.path("/issues") == "/repos/AlexKucera/helm/issues"
|
||||
m.numbers.add(289, 2)
|
||||
assert m.rewrite("Fixes #289") == "Fixes #2"
|
||||
fresh = Migration(src, tgt, "o", "r")
|
||||
assert len(fresh.numbers) == 0
|
||||
src.close()
|
||||
tgt.close()
|
||||
print("migration self-check ok")
|
||||
@@ -17,24 +17,16 @@ from __future__ import annotations
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from .clients import ApiClient, ApiError, _path, parallel
|
||||
from .issues import RefCtx
|
||||
from .clients import ApiError, parallel
|
||||
from .migration import Migration
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def migrate_releases(
|
||||
src: ApiClient,
|
||||
tgt: ApiClient,
|
||||
owner: str,
|
||||
repo: str,
|
||||
ref: RefCtx,
|
||||
*,
|
||||
concurrency: int = 1,
|
||||
) -> int:
|
||||
def migrate_releases(m: Migration, *, concurrency: int = 1) -> int:
|
||||
"""Recreate non-draft releases + assets on target. Returns count migrated."""
|
||||
try:
|
||||
releases = src.get_all(_path(owner, repo, "/releases"))
|
||||
releases = m.src.get_all(m.path("/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.
|
||||
@@ -54,12 +46,12 @@ def migrate_releases(
|
||||
body = {
|
||||
"tag_name": rel["tag_name"],
|
||||
"name": rel.get("name") or rel["tag_name"],
|
||||
"body": ref(rel.get("body")),
|
||||
"body": m.rewrite(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)
|
||||
created = m.tgt.post(m.path("/releases"), body=body)
|
||||
new_id = created["id"]
|
||||
|
||||
assets = rel.get("assets", []) or []
|
||||
@@ -67,11 +59,11 @@ def migrate_releases(
|
||||
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']}")
|
||||
with m.src.raw_get_stream(
|
||||
m.path(f"/releases/{rel['id']}/assets/{asset['id']}")
|
||||
) as data:
|
||||
tgt.post_multipart(
|
||||
_path(owner, repo, f"/releases/{new_id}/assets"),
|
||||
m.tgt.post_multipart(
|
||||
m.path(f"/releases/{new_id}/assets"),
|
||||
files={"attachment": (asset["name"], data)},
|
||||
name=asset["name"],
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user