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
@@ -106,7 +106,7 @@ When the user requests a durable behavior change, record it here or in the relev
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **codeberg-to-gitea-migrator** (392 symbols, 767 relationships, 30 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
This project is indexed by GitNexus as **codeberg-to-gitea-migrator** (434 symbols, 884 relationships, 31 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
|
||||
|
||||
@@ -154,5 +154,6 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
<!-- write-log: window-start -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-08-11 | issue | [20260811-issue2-bind-migration-context-retire-refctx-path_log.md](docs/devlog/20260811-issue2-bind-migration-context-retire-refctx-path_log.md) | Introduce frozen `Migration` bound context; rewrite the four entity phases to take the handle; retire `RefCtx`/`_path`; add the phase test seam (`test_phases.py`). Closes #2. |
|
||||
| 2026-08-11 | issue | [20260811-issue1-gitrunner-sole-git-op-seam_log.md](docs/devlog/20260811-issue1-gitrunner-sole-git-op-seam_log.md) | Introduce `git.GitRunner` as the sole git-op seam; rewrite mirror to drive it; retire URL-token helpers; closes audit HIGH A09 + MEDIUM A02 at the root. |
|
||||
<!-- write-log: window-end -->
|
||||
@@ -26,6 +26,7 @@ All notable changes to this project will be documented in this file. The format
|
||||
|
||||
### refactor
|
||||
|
||||
- **migrator:** bind the repo-transfer context in a frozen `Migration` handle (source + target `ApiClient`s, `owner`, `name`, `NumberMap`). The four entity phases (`migrate_labels`/`migrate_milestones`/`migrate_issues_and_prs`/`migrate_releases`) take the handle instead of five loose params, so the source/target clients and owner/name can no longer drift between phases (an owner↔name transposition is now impossible to express); `migrate_repo` builds one and drives all phases with it. Retires `RefCtx` and the shared `_path` helper — absorbed into the handle's `.path()`/`.rewrite()` accessors (`rewrite` delegates to the existing pure rewriter via the bound clients' web roots). `migrate_issues_and_prs` now mutates `m.numbers` in place (returns `None`). Adds `tests/test_phases.py`: the previously-untested entity layer is reachable through the seam (two mock-transport clients + a number map, no network). Behavior unchanged. Closes #2.
|
||||
- **cli:** drop the `typer` dependency; the CLI now uses stdlib `argparse` (same `migrate`/`version` subcommands, flags, and `CODEBERG_TOKEN`/`GITEA_TOKEN` env vars). Removes `typer` and its transitive `rich`/`shellingham` from the install (3 fewer packages).
|
||||
- **migrator:** introduce `git.GitRunner` as the sole git-op seam — the only place git is invoked. The mirror procedure (`mirror.py`) is rewritten to drive it (`run`/`capture`/`ok` verbs; `Forge` value type for per-op auth), retiring the URL-tokenization, token-stripping, and on-exit config-scrub helpers (their reason to exist vanishes). The procedure's ordering invariants (pull-head capture → prune → mirror push → deleted-branch PR-head restore → LFS) are now locked by a recording-fake test; an AST guard fails the suite if any git op bypasses the seam.
|
||||
- **migrator:** remove dead code surfaced by a whole-repo over-engineering audit — `has_lfs`/`LFS_MARKERS` (uncalled), the `name_map` return of `migrate_labels` (sole caller discarded it), the unused `owner_repo` rewrite param, and a stored-but-unread `_base_url`.
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
# Migration: bind the repo-transfer context (slim phase interfaces, retire RefCtx/_path)
|
||||
|
||||
> **Date:** 2026-08-11
|
||||
> **Type:** issue
|
||||
> **Reference:** [Gitea issue #2](https://git.babylondreams.de/AlexKucera/codeberg-to-gitea-migrator/issues/2)
|
||||
|
||||
## Goal
|
||||
|
||||
Implement issue #2: introduce a single bound-context type — `Migration` — that
|
||||
holds the identity quintet (source client, target client, owner, name, number
|
||||
map) the four entity-migration phases previously received as five loose params.
|
||||
Rewrite the phases to take the handle; retire `RefCtx` and the shared `_path`
|
||||
helper (their reason to exist is absorbed); and give the entity layer its first
|
||||
test surface — construct a `Migration` from two mock-transport clients and call
|
||||
a phase, with no network. Behavior must be unchanged.
|
||||
|
||||
## What Was Done
|
||||
|
||||
- **New `src/codeberg_to_gitea_migrator/migration.py`** — frozen dataclass
|
||||
`Migration(src, tgt, owner, name, numbers=NumberMap())` with exactly two
|
||||
derived accessors: `.path(suffix)` → `/repos/{owner}/{name}{suffix}`, and
|
||||
`.rewrite(text)` delegating to the pure `refs.rewrite` via the bound clients'
|
||||
`web_root`s. Pure context — no I/O, no phase logic (god-object guard in the
|
||||
module docstring). Includes a `__main__` self-check.
|
||||
- **Four phases take the handle** (`issues.py`, `releases.py`):
|
||||
`migrate_labels(m, *, concurrency)`, `migrate_milestones(m, *, concurrency)`,
|
||||
`migrate_issues_and_prs(m, label_map, ms_map, *, concurrency) -> None`
|
||||
(mutates `m.numbers` in place), `migrate_releases(m, *, concurrency) -> int`.
|
||||
Internal helpers (`_collect`/`_set_state`/`_merge_pr`/`_create_entity`) take
|
||||
`m` too, so owner/name stay bound throughout. Dropped the unused `src` param
|
||||
from `_merge_pr`.
|
||||
- **`migrate_repo`** builds one `Migration` once both clients are open and the
|
||||
target repo is ensured, then drives all phases with it, threading the
|
||||
label/milestone maps between them; report reads `len(migration.numbers)`.
|
||||
- **Retired `RefCtx`** (was `issues.py`) and **`_path`** (was `clients.py`) —
|
||||
fully deleted, zero remaining references in `src/`. Dead imports cleaned
|
||||
(`ApiClient`/`_path`/`NumberMap`/`rewrite`/`dataclass` where now unused).
|
||||
- **`tests/test_phases.py`** (new, 10 tests) — the one seam: two
|
||||
`httpx.MockTransport` clients + a `NumberMap`. Asserts wire paths/bodies the
|
||||
target received + number-map state. Covers identity binding + fresh-map
|
||||
default, label/milestone id maps + bodies, two-pass ref rewrite + comment
|
||||
streaming, closed-state PATCH, best-effort merge tolerating 409, deleted-branch
|
||||
`_pr/<n>` head fallback, label-attachment + PR-milestone follow-up PATCH,
|
||||
release+asset re-upload with rewritten body, and the 404-endpoint clean skip.
|
||||
- **DOX closeout** — updated `src/…/AGENTS.md` (module map: added `migration.py`,
|
||||
removed `_path`, noted the handle on the phase/orchestrator lines; added a
|
||||
bound-context Work Guidance bullet; added `test_phases.py` to Verification)
|
||||
and `tests/AGENTS.md` (+`test_phases.py`).
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Drove the refactor in-context (not parallel subagents) | The change is atomic — phase signatures, the orchestrator, and the `RefCtx`/`_path` retirement are mutually dependent; intermediate states don't even import. Parallel subagents would produce broken intermediates + merge churn exceeding any context-isolation benefit. Honored `/implement`'s scenario-first / TDD-at-the-seam / verify / review parts instead. |
|
||||
| `.path()`/`.rewrite()` are the only two accessors | They are the two things every phase needs that aren't already on a client. Keeps `Migration` pure context; a future per-phase input type (if cross-phase outputs ever grow beyond two maps) is an additive change. |
|
||||
| `concurrency` stays a per-call keyword, not a handle field | It is run-tuning, not identity; the handle binds exactly the quintet (per the issue's explicit rejection of folding concurrency on). |
|
||||
| `migrate_issues_and_prs` returns `None` and mutates `m.numbers` | The number map already lives on the handle; returning it duplicated the source of truth. The sole caller reads `len(migration.numbers)`. |
|
||||
| Internal helpers take `m`, not loose owner/repo | Keeps owner/name bound once (the whole point) and routes every path through `m.path()` — retiring `_path` without reintroducing f-string paths inside helpers. |
|
||||
| Mock harness splits source (reads) vs target (records writes) | Source only reads, target only writes, so two clients with separate handlers is a clean split. `_wire_path` strips the client's `/api/v1` prefix so phase tests assert repo-scoped paths (a transposition fails) without coupling to the client's api-root convention. |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|------------|-----|
|
||||
| Recorded wire path was `/api/v1/repos/o/r/labels`, not repo-scoped | `ApiClient` prepends `/api/v1` as `base_url`; `req.url.path` carries it | `_wire_path(req)` strips the prefix; recorders/assertions use repo-scoped paths |
|
||||
| Multipart asset uploads crashed the recorder's `json.loads` | Asset upload body is multipart bytes, not JSON | Recorder falls back to `{"_raw": …}` on `ValueError`; tests assert the upload *path*, not its body |
|
||||
| Orphan `return`/duplicate `report`/duplicate import/lost `fresh` assertion/duplicate try-block during edits | Several `edit` operations left strays when replace ranges collided with shifted anchors | Each caught immediately by `ruff`/`pytest` and removed; re-read for fresh anchors before re-editing |
|
||||
| `_path` flagged CRITICAL by impact analysis | Count artifact — all 11 direct callers live inside the refactored `issues.py`/`releases.py`; `migrate.py` uses raw f-strings, tests don't import it | Confirmed fully internal via grep; retirement left no external caller broken |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|----------------|
|
||||
| `src/codeberg_to_gitea_migrator/migration.py` | **New** — frozen `Migration` bound context + `.path()`/`.rewrite()` accessors + self-check |
|
||||
| `tests/test_phases.py` | **New** — 10 phase tests through the Migration seam (two mock clients + number map) |
|
||||
| `src/codeberg_to_gitea_migrator/issues.py` | Phases + helpers take `m`; `migrate_issues_and_prs` → `None` mutating `m.numbers`; deleted `RefCtx`; cleaned imports |
|
||||
| `src/codeberg_to_gitea_migrator/releases.py` | `migrate_releases(m, *, concurrency)`; dropped `ApiClient`/`_path` imports |
|
||||
| `src/codeberg_to_gitea_migrator/migrate.py` | Builds one `Migration`, drives all phases; dropped `RefCtx`/`NumberMap` + standalone `numbers` |
|
||||
| `src/codeberg_to_gitea_migrator/clients.py` | Deleted the `_path` helper |
|
||||
| `src/codeberg_to_gitea_migrator/AGENTS.md` | Module map (+`migration.py`, −`_path`, handle notes), bound-context guidance, Verification (+`test_phases.py`) |
|
||||
| `tests/AGENTS.md` | Added `test_phases.py` to Work Guidance |
|
||||
|
||||
## Verification
|
||||
|
||||
- `uv run pytest -q` → **54 passed** (was 44; +10 phase tests).
|
||||
- `uv run ruff check .` → clean. `uv run ruff format --check .` → clean.
|
||||
- Independent review fanout (ponytail-review / security-review STRIDE / general
|
||||
review): **no blocker/major/minor**; one accepted fix (label-attachment +
|
||||
PR-milestone PATCH coverage gap) → added a test. Ponytail verdict: net
|
||||
**−124/+67** lines, a deletion of complexity. Security: behavior-preserving,
|
||||
marginally improves integrity (owner/name bound once). Token-leak invariant
|
||||
unchanged (AST guard passes; `migration.py` has no subprocess).
|
||||
- `node .gitnexus/run.cjs analyze` → index rebuilt (434 nodes / 884 edges).
|
||||
- `detect_changes`: blast radius confined to the entity-migration layer; git
|
||||
mirror, pure rewriter, REST-client internals, and CLI untouched.
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] Issue #2 itself is closed by this commit (`Closes #2`); confirm on Gitea.
|
||||
- [ ] `CONTEXT.md` is untracked and pre-existing — already documents `Migration`
|
||||
accurately; left as-is (out of scope, not introduced here).
|
||||
- [ ] No known tech debt introduced; the bound-context seam is the additive
|
||||
surface for any future per-phase input type.
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
@@ -5,4 +5,5 @@ Complete history of session logs in this directory, newest first. One-line summa
|
||||
<!-- write-log: full-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-08-11 | issue | [20260811-issue2-bind-migration-context-retire-refctx-path_log.md](20260811-issue2-bind-migration-context-retire-refctx-path_log.md) | Introduce frozen `Migration` bound context; rewrite the four entity phases to take the handle; retire `RefCtx`/`_path`; add the phase test seam (`test_phases.py`). Closes #2. |
|
||||
| 2026-08-11 | issue | [20260811-issue1-gitrunner-sole-git-op-seam_log.md](20260811-issue1-gitrunner-sole-git-op-seam_log.md) | Introduce `git.GitRunner` as the sole git-op seam; rewrite mirror to drive it; retire URL-token helpers; closes audit HIGH A09 + MEDIUM A02 at the root. |
|
||||
@@ -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"],
|
||||
)
|
||||
|
||||
@@ -20,6 +20,7 @@ Project maintainer (Alexander Kucera).
|
||||
- `test_clients.py` — `ApiClient` pagination, param cleaning, 4xx handling, JSON POST, all via `httpx.MockTransport` (no network).
|
||||
- `test_git.py` — the `GitRunner` seam (auth delivery via non-persisted `extraHeader`, known-secret redaction, timeout/error contract, `ok` never raises) + an AST guard that git is invoked only through `GitRunner`. Driven by a recording exec fake; no git binary, no network.
|
||||
- `test_mirror.py` — the mirror procedure's ordering invariants (capture → prune → mirror push → PR-head push; LFS gated on the probe) and per-op auth wiring (fetch=source, push=target, local ref ops=none), via a recording exec fake that captures command intent only — never the token.
|
||||
- `test_phases.py` — all four entity phases (labels, milestones, issues+PRs two-pass, releases) driven through the `Migration` seam: two `httpx.MockTransport`-backed clients + a `NumberMap`, asserting the paths/bodies the target received and the resulting number-map state. Covers ref rewriting, state-setting, best-effort PR merge (409 tolerated), the deleted-branch `_pr/<n>` head fallback, and the 404-releases skip. 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
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
"""Phase tests through the Migration seam — no network.
|
||||
|
||||
Two ``httpx.MockTransport``-backed clients feed a :class:`Migration`, then a
|
||||
phase is called. Tests assert external behaviour — the paths and bodies the
|
||||
target client received, and the resulting number-map state — never phase
|
||||
internals, so they survive an internal refactor of a phase.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import httpx
|
||||
|
||||
from codeberg_to_gitea_migrator.clients import ApiClient
|
||||
from codeberg_to_gitea_migrator.issues import (
|
||||
migrate_issues_and_prs,
|
||||
migrate_labels,
|
||||
migrate_milestones,
|
||||
)
|
||||
from codeberg_to_gitea_migrator.migration import Migration
|
||||
from codeberg_to_gitea_migrator.releases import migrate_releases
|
||||
|
||||
|
||||
# -- shared mock-transport harness ----------------------------------------
|
||||
def _client(handler, base: str = "https://src.example") -> ApiClient:
|
||||
return ApiClient(base, "tok", transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
def _wire_path(req: httpx.Request) -> str:
|
||||
"""Repo-scoped path the wire saw, minus the client's ``/api/v1`` root.
|
||||
|
||||
Phase tests assert repo-scoped paths (so an owner↔name transposition fails)
|
||||
without coupling to the client's api-root prefix.
|
||||
"""
|
||||
return req.url.path.removeprefix("/api/v1")
|
||||
|
||||
|
||||
def _src(routes: dict[str, object]) -> ApiClient:
|
||||
"""Source client serving canned payloads keyed by exact repo-scoped path.
|
||||
|
||||
A ``bytes`` route is returned as raw content (for streamed asset downloads);
|
||||
anything else is returned as JSON (lists/dicts). Unknown paths → empty list.
|
||||
"""
|
||||
|
||||
def h(req: httpx.Request) -> httpx.Response:
|
||||
payload = routes.get(_wire_path(req), [])
|
||||
if isinstance(payload, (bytes, bytearray)):
|
||||
return httpx.Response(200, content=payload)
|
||||
return httpx.Response(200, json=payload)
|
||||
|
||||
return _client(h, base="https://codeberg.org")
|
||||
|
||||
|
||||
def _recording_target(overrides: dict | None = None) -> tuple[ApiClient, list[dict]]:
|
||||
"""Target client that records every write and returns canned created objects.
|
||||
|
||||
``overrides`` maps ``(method, path)`` → ``(status, json)`` for special cases
|
||||
(e.g. a 409 on PR merge). Recorded entries are ``{method, path, body}`` with
|
||||
repo-scoped paths. Creation POSTs return ascending ids/numbers.
|
||||
"""
|
||||
overrides = overrides or {}
|
||||
recorded: list[dict] = []
|
||||
counters = {"number": 100, "id": 1000}
|
||||
|
||||
def h(req: httpx.Request) -> httpx.Response:
|
||||
method, path = req.method, _wire_path(req)
|
||||
raw = req.read()
|
||||
try:
|
||||
body: object = json.loads(raw or "null")
|
||||
except ValueError: # multipart asset upload — not JSON
|
||||
body = {"_raw": raw.decode("utf-8", "replace")}
|
||||
recorded.append({"method": method, "path": path, "body": body})
|
||||
if (method, path) in overrides:
|
||||
status, payload = overrides[(method, path)]
|
||||
return httpx.Response(status, json=payload)
|
||||
if method == "POST" and path in ("/repos/o/r/issues", "/repos/o/r/pulls"):
|
||||
counters["number"] += 1
|
||||
return httpx.Response(201, json={"number": counters["number"]})
|
||||
if method == "POST" and path in (
|
||||
"/repos/o/r/labels",
|
||||
"/repos/o/r/milestones",
|
||||
"/repos/o/r/releases",
|
||||
):
|
||||
counters["id"] += 1
|
||||
return httpx.Response(201, json={"id": counters["id"]})
|
||||
return httpx.Response(200, json={})
|
||||
|
||||
return _client(h, base="https://git.babylondreams.de"), recorded
|
||||
|
||||
|
||||
def _find(recorded: list[dict], method: str, path: str) -> list[dict]:
|
||||
return [r for r in recorded if r["method"] == method and r["path"] == path]
|
||||
|
||||
|
||||
def test_migration_path_and_rewrite_bind_identity_without_io() -> None:
|
||||
src = _client(lambda r: httpx.Response(200, json={}), base="https://codeberg.org")
|
||||
tgt = _client(lambda r: httpx.Response(200, json={}), base="https://git.babylondreams.de")
|
||||
|
||||
m = Migration(src, tgt, "AlexKucera", "helm")
|
||||
assert m.path() == "/repos/AlexKucera/helm"
|
||||
assert m.path("/issues/5/comments") == "/repos/AlexKucera/helm/issues/5/comments"
|
||||
|
||||
# rewrite sources the web roots from the bound clients + the bound number map
|
||||
m.numbers.add(289, 2)
|
||||
assert m.rewrite("Fixes #289") == "Fixes #2"
|
||||
assert m.rewrite(None) is None
|
||||
|
||||
# a fresh migration starts with an empty number map (frozen field, mutable value)
|
||||
fresh = Migration(src, tgt, "o", "r")
|
||||
assert len(fresh.numbers) == 0
|
||||
|
||||
|
||||
# -- labels / milestones ------------------------------------------------
|
||||
def test_migrate_labels_maps_ids_and_posts_bodies() -> None:
|
||||
labels = [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "bug",
|
||||
"color": "#cc0000",
|
||||
"description": "defect",
|
||||
"exclusive": False,
|
||||
"is_archived": False,
|
||||
}
|
||||
]
|
||||
src = _client(lambda r: httpx.Response(200, json=labels), base="https://codeberg.org")
|
||||
recorded: list[tuple[str, str, dict]] = []
|
||||
|
||||
def tgt_h(req: httpx.Request) -> httpx.Response:
|
||||
recorded.append((req.method, _wire_path(req), json.loads(req.read() or "null")))
|
||||
return httpx.Response(201, json={"id": 101})
|
||||
|
||||
tgt = _client(tgt_h, base="https://git.babylondreams.de")
|
||||
m = Migration(src, tgt, "o", "r")
|
||||
|
||||
out = migrate_labels(m, concurrency=1)
|
||||
assert out == {1: 101}
|
||||
assert len(recorded) == 1
|
||||
method, path, body = recorded[0]
|
||||
assert (method, path) == ("POST", "/repos/o/r/labels")
|
||||
assert body == {
|
||||
"name": "bug",
|
||||
"color": "#cc0000",
|
||||
"description": "defect",
|
||||
"exclusive": False,
|
||||
"is_archived": False,
|
||||
}
|
||||
|
||||
|
||||
def test_migrate_milestones_maps_ids_and_passes_due_on() -> None:
|
||||
milestones = [
|
||||
{
|
||||
"id": 5,
|
||||
"title": "v1",
|
||||
"description": "first",
|
||||
"state": "open",
|
||||
"due_on": "2026-12-31T00:00:00Z",
|
||||
}
|
||||
]
|
||||
src = _client(lambda r: httpx.Response(200, json=milestones), base="https://codeberg.org")
|
||||
recorded: list[tuple[str, str, dict]] = []
|
||||
|
||||
def tgt_h(req: httpx.Request) -> httpx.Response:
|
||||
recorded.append((req.method, _wire_path(req), json.loads(req.read() or "null")))
|
||||
return httpx.Response(201, json={"id": 51})
|
||||
|
||||
tgt = _client(tgt_h, base="https://git.babylondreams.de")
|
||||
m = Migration(src, tgt, "o", "r")
|
||||
|
||||
out = migrate_milestones(m, concurrency=1)
|
||||
assert out == {5: 51}
|
||||
method, path, body = recorded[0]
|
||||
assert (method, path) == ("POST", "/repos/o/r/milestones")
|
||||
assert body == {
|
||||
"title": "v1",
|
||||
"description": "first",
|
||||
"state": "open",
|
||||
"due_on": "2026-12-31T00:00:00Z",
|
||||
}
|
||||
|
||||
|
||||
# -- issues + PRs (two-pass) --------------------------------------------
|
||||
def test_migrate_issues_and_prs_two_pass_rewrites_refs_and_maps_numbers() -> None:
|
||||
# Source #1 (issue, body refs forward #2) and #2 (open PR); #1 has a comment.
|
||||
src = _src(
|
||||
{
|
||||
"/repos/o/r/issues": [
|
||||
{"number": 1, "title": "first", "body": "depends on #2", "state": "open"}
|
||||
],
|
||||
"/repos/o/r/pulls": [
|
||||
{
|
||||
"number": 2,
|
||||
"title": "second",
|
||||
"body": "",
|
||||
"state": "open",
|
||||
"merged": False,
|
||||
"base": {"ref": "main"},
|
||||
"head": {"ref": "feature"},
|
||||
}
|
||||
],
|
||||
"/repos/o/r/issues/1/comments": [{"body": "also see #2"}],
|
||||
}
|
||||
)
|
||||
tgt, recorded = _recording_target()
|
||||
m = Migration(src, tgt, "o", "r")
|
||||
|
||||
migrate_issues_and_prs(m, {}, {}, concurrency=1)
|
||||
|
||||
# number map built in source-number order during Pass A
|
||||
assert len(m.numbers) == 2
|
||||
assert m.numbers.get(1) == 101
|
||||
assert m.numbers.get(2) == 102
|
||||
|
||||
# Pass B rewrites #2 → #102 in the issue body and streams the rewritten comment
|
||||
issue_patch = _find(recorded, "PATCH", "/repos/o/r/issues/101")
|
||||
assert any(r["body"]["body"] == "depends on #102" for r in issue_patch)
|
||||
comment_posts = _find(recorded, "POST", "/repos/o/r/issues/101/comments")
|
||||
assert comment_posts and comment_posts[0]["body"]["body"] == "also see #102"
|
||||
|
||||
|
||||
def test_migrate_issues_and_prs_sets_closed_state_in_pass_a() -> None:
|
||||
src = _src(
|
||||
{
|
||||
"/repos/o/r/issues": [
|
||||
{"number": 1, "title": "closed one", "body": "", "state": "closed"}
|
||||
],
|
||||
"/repos/o/r/pulls": [],
|
||||
"/repos/o/r/issues/1/comments": [],
|
||||
}
|
||||
)
|
||||
tgt, recorded = _recording_target()
|
||||
m = Migration(src, tgt, "o", "r")
|
||||
|
||||
migrate_issues_and_prs(m, {}, {}, concurrency=1)
|
||||
|
||||
# a closed source issue → a state=closed PATCH on the target issue
|
||||
state_patches = [
|
||||
r
|
||||
for r in _find(recorded, "PATCH", "/repos/o/r/issues/101")
|
||||
if r["body"] == {"state": "closed"}
|
||||
]
|
||||
assert state_patches
|
||||
|
||||
|
||||
def test_migrate_issues_and_prs_merged_pr_attempts_merge_and_tolerates_conflict() -> None:
|
||||
src = _src(
|
||||
{
|
||||
"/repos/o/r/issues": [],
|
||||
"/repos/o/r/pulls": [
|
||||
{
|
||||
"number": 1,
|
||||
"title": "merged",
|
||||
"body": "",
|
||||
"state": "closed",
|
||||
"merged": True,
|
||||
"base": {"ref": "main"},
|
||||
"head": {"ref": "feature"},
|
||||
}
|
||||
],
|
||||
"/repos/o/r/issues/1/comments": [],
|
||||
}
|
||||
)
|
||||
# Gitea 409s a historical merge (already in base) — best-effort must tolerate it.
|
||||
tgt, recorded = _recording_target(
|
||||
overrides={("POST", "/repos/o/r/pulls/101/merge"): (409, {"message": "conflict"})}
|
||||
)
|
||||
m = Migration(src, tgt, "o", "r")
|
||||
|
||||
migrate_issues_and_prs(m, {}, {}, concurrency=1) # must not raise
|
||||
|
||||
# the merge was attempted (recorded before the 409 raised), and #1 still mapped
|
||||
assert _find(recorded, "POST", "/repos/o/r/pulls/101/merge")
|
||||
assert m.numbers.get(1) == 101
|
||||
|
||||
|
||||
def test_migrate_issues_and_prs_deleted_branch_head_falls_back_to_pr_ref() -> None:
|
||||
src = _src(
|
||||
{
|
||||
"/repos/o/r/issues": [],
|
||||
"/repos/o/r/pulls": [
|
||||
{
|
||||
"number": 1,
|
||||
"title": "gone head",
|
||||
"body": "",
|
||||
"state": "open",
|
||||
"merged": False,
|
||||
"base": {"ref": "main"},
|
||||
"head": {"ref": "refs/pull/1/head"},
|
||||
}
|
||||
],
|
||||
"/repos/o/r/issues/1/comments": [],
|
||||
}
|
||||
)
|
||||
tgt, recorded = _recording_target()
|
||||
m = Migration(src, tgt, "o", "r")
|
||||
|
||||
migrate_issues_and_prs(m, {}, {}, concurrency=1)
|
||||
|
||||
pr_creates = _find(recorded, "POST", "/repos/o/r/pulls")
|
||||
assert pr_creates and pr_creates[0]["body"]["head"] == "_pr/1"
|
||||
|
||||
|
||||
def test_migrate_issues_and_prs_attaches_mapped_labels_and_pr_milestone() -> None:
|
||||
# an issue carrying a source label, and a PR carrying a milestone — both
|
||||
# per-phase maps (produced by the prior phases) are threaded through the
|
||||
# phase interface, not bound on the handle.
|
||||
src = _src(
|
||||
{
|
||||
"/repos/o/r/issues": [
|
||||
{
|
||||
"number": 1,
|
||||
"title": "with-label",
|
||||
"body": "",
|
||||
"state": "open",
|
||||
"labels": [{"id": 7, "name": "bug"}],
|
||||
}
|
||||
],
|
||||
"/repos/o/r/pulls": [
|
||||
{
|
||||
"number": 2,
|
||||
"title": "with-ms",
|
||||
"body": "",
|
||||
"state": "open",
|
||||
"merged": False,
|
||||
"milestone": {"id": 3},
|
||||
"base": {"ref": "main"},
|
||||
"head": {"ref": "feature"},
|
||||
}
|
||||
],
|
||||
"/repos/o/r/issues/1/comments": [],
|
||||
}
|
||||
)
|
||||
tgt, recorded = _recording_target()
|
||||
m = Migration(src, tgt, "o", "r")
|
||||
|
||||
migrate_issues_and_prs(m, {7: 77}, {3: 33}, concurrency=1)
|
||||
|
||||
# the source label id 7 is mapped to the target id 77 and attached to issue 101
|
||||
label_posts = _find(recorded, "POST", "/repos/o/r/issues/101/labels")
|
||||
assert label_posts and label_posts[0]["body"] == {"labels": [77]}
|
||||
# a PR can't carry its milestone in the create body, so it takes a follow-up PATCH
|
||||
pr_ms_patches = [
|
||||
r
|
||||
for r in _find(recorded, "PATCH", "/repos/o/r/issues/102")
|
||||
if r["body"] == {"milestone": 33}
|
||||
]
|
||||
assert pr_ms_patches
|
||||
|
||||
|
||||
# -- releases (+ assets) ------------------------------------------------
|
||||
def test_migrate_releases_recreates_rewrites_body_and_reuploads_assets() -> None:
|
||||
src = _src(
|
||||
{
|
||||
"/repos/o/r/releases": [
|
||||
{
|
||||
"id": 1,
|
||||
"tag_name": "v1",
|
||||
"name": "v1",
|
||||
"body": "see #5",
|
||||
"draft": False,
|
||||
"prerelease": False,
|
||||
"target_commitish": "main",
|
||||
"created_at": "2026-01-01T00:00:00Z",
|
||||
"assets": [{"id": 9, "name": "bin.tar.gz"}],
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"tag_name": "v0-d",
|
||||
"name": "draft",
|
||||
"body": "",
|
||||
"draft": True,
|
||||
"assets": [],
|
||||
},
|
||||
],
|
||||
"/repos/o/r/releases/1/assets/9": b"asset-bytes",
|
||||
}
|
||||
)
|
||||
tgt, recorded = _recording_target()
|
||||
m = Migration(src, tgt, "o", "r")
|
||||
m.numbers.add(5, 50) # rewrite "see #5" → "see #50"
|
||||
|
||||
count = migrate_releases(m, concurrency=1)
|
||||
|
||||
assert count == 1 # the draft is skipped
|
||||
rel_posts = _find(recorded, "POST", "/repos/o/r/releases")
|
||||
assert len(rel_posts) == 1
|
||||
assert rel_posts[0]["body"]["body"] == "see #50"
|
||||
assert rel_posts[0]["body"]["tag_name"] == "v1"
|
||||
assert rel_posts[0]["body"]["prerelease"] is False
|
||||
# the asset is re-uploaded under the new release id (1001 from the counter)
|
||||
assert _find(recorded, "POST", "/repos/o/r/releases/1001/assets")
|
||||
|
||||
|
||||
def test_migrate_releases_404_endpoint_skips_cleanly() -> None:
|
||||
def src_h(req: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(404, text="releases disabled")
|
||||
|
||||
src = _client(src_h, base="https://codeberg.org")
|
||||
tgt, recorded = _recording_target()
|
||||
m = Migration(src, tgt, "o", "r")
|
||||
|
||||
assert migrate_releases(m, concurrency=1) == 0
|
||||
assert recorded == []
|
||||
Reference in new issue
Block a user