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 -1
View File
@@ -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** (434 symbols, 884 relationships, 31 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** (444 symbols, 901 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,6 +154,7 @@ 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-issue3-pr-head-branch-helper-in-refs_log.md](docs/devlog/20260811-issue3-pr-head-branch-helper-in-refs_log.md) | Extract the duplicated `_pr/<n>` deleted-branch PR-head name into one shared pure helper `refs.pr_head_branch`; `mirror.py` + `issues.py` route through it instead of spelling the literal. Closes #3. |
| 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 -->
+3 -1
View File
@@ -19,7 +19,9 @@ shared Forgejo/Gitea REST API for full control.
references and source URLs are rewritten to the target's number space.
- **Pull-request heads** — when the source branch was deleted (common for
merged/closed PRs), the head commits are recreated on the target as
`refs/heads/_pr/<n>` so the PR can be rebuilt.
`refs/heads/_pr/<n>` so the PR can be rebuilt. That `_pr/<n>` branch name is
owned by one symbol — `refs.pr_head_branch` — shared by the mirror and the
issue/PR phase, so the two layers cannot diverge.
- **Releases & assets** — non-draft releases with binary assets re-uploaded.
## Requirements
@@ -0,0 +1,70 @@
# Own the _pr/<n> deleted-branch PR-head contract (shared pr_head_branch helper in refs.py)
> **Date:** 2026-08-11
> **Type:** issue
> **Reference:** [#3](https://git.babylondreams.de/AlexKucera/codeberg-to-gitea-migrator/issues/3)
## Goal
Eliminate the duplicated `_pr/<n>` branch-name literal that the deleted-branch
PR survival feature rested on. The git-transport layer (`mirror.py`) *created*
`refs/heads/_pr/<n>`; the REST/entity layer (`issues.py`) *referenced* the same
branch as a PR's head when the source branch was gone. Both spelled
`f"_pr/{n}"` with no shared symbol binding them — editing one side silently
broke the other, and the failure was narrow and late (404/500 on PR create for
deleted-branch PRs only). Own the contract as one shared, importable helper so
the two cannot diverge.
## What Was Done
- Added `pr_head_branch(n: int) -> str` to `refs.py` (returns `f"_pr/{n}"`);
pure, no I/O. The single source of truth for the `_pr/<n>` namespace.
- `mirror.py` (producer): added `from .refs import pr_head_branch`; refspec now
`f"{sha}:refs/heads/{pr_head_branch(n)}"` (refspec syntax stays local).
- `issues.py` (consumer): added `from .refs import pr_head_branch`; PR head now
`pr_head_branch(item["number"])` instead of the inline literal.
- Widened `refs.py`'s module docstring from "cross-reference rewriting" to
"reference-namespace knowledge" (branch-name patterns + cross-ref rewriting);
still pure stdlib (`re` only).
- Docs closeout: `src/.../AGENTS.md` module-map (`refs.py` + `issues.py`
entries) and `README.md` "Pull-request heads" bullet now name
`refs.pr_head_branch` as the single source of truth.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Free function, not a `Migration` method | The producer (`mirror.py`, git layer) holds no `Migration` handle, so both layers reach a neutral pure module instead of one depending on the other's internals. |
| House it in `refs.py` | A branch-name pattern *is* reference-namespace knowledge; broadens `refs.py` coherently. Pure stdlib, so the git layer importing it drags in no REST coupling. |
| Shared kernel = bare branch name only | The producer prefixes refspec syntax (`refs/heads/`, the `sha:` source) locally — those are refspec concerns, not part of the shared contract. |
| `n` stays `int` on both sides | The mirror parses `int(ref.split("/")[2])`; the consumer reads the source PR number — no int/str bridge needed. |
| No change-specific test | A shared symbol prevents divergence by construction; a test asserting "the two literals agree" tests the absence of duplication (issue #3 testing decision). The deleted-branch round-trip stays covered by the existing phase test seam. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| PRD claimed `refs.py` was "already imported" in `issues.py` | It wasn't — `issues.py` imported `.clients` + `.migration` only (`m.rewrite` reaches refs via the `Migration` handle) | Added `from .refs import pr_head_branch` to `issues.py`. Minimal deviation from the PRD; intent unchanged. |
| First cut added a `__main__` self-check `assert pr_head_branch(42) == "_pr/42"` | That asserts "the literal agrees" — exactly the redundant test the spec's testing decision warns against, and a trivial one-liner under ponytail | Removed it after the fresh-context review fanout confirmed it was redundant. |
## Files Changed
| File | Change Summary |
|------|----------------|
| `src/codeberg_to_gitea_migrator/refs.py` | Add `pr_head_branch(n)`; widen module docstring to reference-namespace knowledge. |
| `src/codeberg_to_gitea_migrator/mirror.py` | Import + route the PR-head refspec through `pr_head_branch`. |
| `src/codeberg_to_gitea_migrator/issues.py` | Import + route the deleted-branch PR head through `pr_head_branch`. |
| `src/codeberg_to_gitea_migrator/AGENTS.md` | Module map: `refs.py` and `issues.py` entries note the shared symbol. |
| `README.md` | "Pull-request heads" bullet notes `refs.pr_head_branch` as the single source of truth. |
| `AGENTS.md` (root) | GitNexus symbol count auto-bump (434→444) from re-index. |
## Open Items & Next Steps
- [ ] **Untracked `CONTEXT.md`** — predates this session, not gitignored, but
referenced by `AGENTS.md` as the DOX "single-context" core doc. Track-vs-ignore
intent undecided; left out of this commit intentionally. Not in #3's scope.
- [ ] None for #3 itself — all 13 user stories met; behaviour unchanged.
---
*Log written by write-log skill*
+1
View File
@@ -5,5 +5,6 @@ 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-issue3-pr-head-branch-helper-in-refs_log.md](20260811-issue3-pr-head-branch-helper-in-refs_log.md) | Extract the duplicated `_pr/<n>` deleted-branch PR-head name into one shared pure helper `refs.pr_head_branch`; `mirror.py` + `issues.py` route through it instead of spelling the literal. Closes #3. |
| 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. |
+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."""