refactor(migrator): own _pr/N PR-head contract
CI / test (push) Canceled after 0s

Extract the duplicated `_pr/<n>` deleted-branch PR-head branch name
into a single pure helper `refs.pr_head_branch(n)`, now the only
definition. The git-mirror layer (mirror.py) and the REST/entity
layer (issues.py) both call it instead of spelling the pattern, so
the two can no longer diverge — editing one side previously broke
the other silently and late (404/500 on PR create for deleted-branch
PRs only).

Behavior-preserving string round-trip. refs.py widens from
"cross-reference rewriting" to "reference-namespace knowledge"
(branch-name patterns + cross-ref rewriting), still pure stdlib. No
new test — a shared symbol prevents divergence by construction
(issue #3 testing decision); the deleted-branch round-trip stays
covered by the existing phase test seam.

Closes #3
This commit is contained in:
AlexKucera committed 2026-08-11 17:26:46 +02:00
1 parent 9d585f601a
commit 8ec9ce49db
8 files changed
+107 -13

No files matched your search

+2 -2
View File
@@ -26,9 +26,9 @@ Console script: `codeberg-to-gitea`.
- `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).
- `refs.py` — reference-namespace knowledge: `pr_head_branch` (the single source of truth for the `_pr/<n>` deleted-branch PR-head branch, shared by the git-mirror and REST layers so they cannot diverge) plus `NumberMap` + `rewrite` (rewrites `#NNN` refs and source issue/PR URLs to the target's fresh number space — source numbers are sparse after deletions). Pure stdlib (`re` only).
- `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).
- `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>` (via `refs.pr_head_branch`, shared with the mirror) 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`.
+4 -2
View File
@@ -31,6 +31,7 @@ from typing import Any
from .clients import ApiError, parallel
from .migration import Migration
from .refs import pr_head_branch
log = logging.getLogger(__name__)
@@ -140,10 +141,11 @@ def _create_entity(
head = item.get("head", {}) or {}
base = (item.get("base", {}) or {}).get("ref", "main")
# Source reports a deleted-branch PR's head as "refs/pull/<n>/head";
# the mirror recreated its commits on the target as branch _pr/<n>.
# the mirror recreated its commits on the target as branch _pr/<n>
# (shared branch name — see refs.pr_head_branch, the single source of truth).
head_ref = head.get("ref", "")
if not head_ref or head_ref.startswith("refs/pull/"):
head_ref = f"_pr/{item['number']}"
head_ref = pr_head_branch(item["number"])
created = m.tgt.post(
m.path("/pulls"),
body={
+2 -1
View File
@@ -18,6 +18,7 @@ import logging
from pathlib import Path
from .git import DEFAULT_GIT_TIMEOUT, Forge, GitError, GitRunner, _real_exec
from .refs import pr_head_branch
# Re-exported so cli.py / migrate.py keep importing these from here — the seam
# owns them now, but the orchestration + CLI layers stay untouched by this
@@ -123,7 +124,7 @@ def mirror_repo(
# head when the original branch is gone). Pushed after the mirror so --mirror
# doesn't wipe them; batched into one push.
if pull_heads:
refspecs = [f"{sha}:refs/heads/_pr/{n}" for n, sha in pull_heads.items()]
refspecs = [f"{sha}:refs/heads/{pr_head_branch(n)}" for n, sha in pull_heads.items()]
runner.run(["git", "--git-dir", str(bare), "push", target.url, *refspecs], auth=target)
lfs_pushed = False
+23 -6
View File
@@ -1,10 +1,15 @@
"""Cross-reference rewriting between source and target forges.
"""Reference-namespace knowledge: branch-name patterns and cross-reference
rewriting between source and target forges.
Source issue/PR numbers rarely line up with target numbers after migration
(deleted source issues leave gaps; the target assigns fresh dense numbers).
Rewriting ``#NNN`` references and full issue/PR URLs in migrated text keeps
cross-references pointing at the *right* target entities instead of dangling
or pointing at the wrong one.
Two concerns share this module because both are reference-namespace knowledge:
* :func:`pr_head_branch` names the ``_pr/<n>`` branch a deleted-branch PR's head
is recreated under — the single source of truth shared by the git-mirror layer
(mirror.py) and the REST/entity layer (issues.py).
* :class:`NumberMap` + :func:`rewrite` rewrite ``#NNN`` references and full
issue/PR URLs in migrated text, keeping cross-references pointing at the
*right* target entities. Source numbers are sparse after deletions; the target
assigns fresh dense numbers.
Usage: build a :class:`NumberMap` as entities are created, then call
:func:`rewrite` on every title, body, and comment before it lands on target.
@@ -24,6 +29,18 @@ HASH_REF = re.compile(r"(?<![#\w])#(\d+)\b")
URL_REF = re.compile(r"(?P<base>https?://[^\s/]+/[^\s]+?)/(?:issues|pulls)/(?P<num>\d+)")
# -- branch-name patterns ------------------------------------------------
def pr_head_branch(n: int) -> str:
"""Branch name a deleted-branch PR's head is recreated under, e.g. ``_pr/42``.
Single source of truth for the ``_pr/<n>`` namespace. The git-mirror layer
(mirror.py) pushes ``refs/heads/<this>`` for each PR whose source head is
gone; the REST layer (issues.py) sends ``<this>`` as that PR's head. Both
call this so the two cannot diverge on the prefix or the format.
"""
return f"_pr/{n}"
class NumberMap:
"""source issue/PR number → target issue/PR number."""