Files
codeberg-to-gitea-migrator/src/codeberg_to_gitea_migrator/refs.py
T
AlexKucera 8ec9ce49db
CI / test (push) Canceled after 0s
refactor(migrator): own _pr/N PR-head contract
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
2026-08-11 17:26:46 +02:00

129 lines
4.6 KiB
Python

"""Reference-namespace knowledge: branch-name patterns and cross-reference
rewriting between source and target forges.
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.
"""
from __future__ import annotations
import re
# A standalone ``#123`` reference — not part of a URL, not a markdown heading.
# Preceded by start-of-string or a non-``#``/non-word char so ``## 2`` (heading)
# and ``foo#123`` (anchor) are left alone; followed by a word boundary so
# ``#1234`` isn't matched as ``#123``.
HASH_REF = re.compile(r"(?<![#\w])#(\d+)\b")
# ``…/issues/123`` or ``…/pulls/123`` (Forgejo/Gitea share both path shapes).
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."""
def __init__(self) -> None:
self._map: dict[int, int] = {}
def add(self, source: int, target: int) -> None:
self._map[source] = target
def get(self, source: int) -> int | None:
return self._map.get(source)
def has(self, source: int) -> bool:
return source in self._map
@property
def any_mismatch(self) -> bool:
return any(s != t for s, t in self._map.items())
def __len__(self) -> int:
return len(self._map)
def __repr__(self) -> str: # pragma: no cover - debugging aid
return f"NumberMap({len(self._map)} entries, mismatch={self.any_mismatch})"
def rewrite(
text: str | None,
numbers: NumberMap,
*,
source_web_root: str,
target_web_root: str,
) -> str | None:
"""Rewrite ``#NNN`` refs and source URLs in ``text`` to target numbers.
Only numbers known to ``numbers`` are rewritten; unknown references are
left untouched. ``#NNN`` is rewritten to the new number (or left alone if
it maps to itself, to keep diffs clean). Source web URLs are repointed at
the target web root.
"""
if not text:
return text
src_root = source_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
tgt_root = target_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
def rewrite_hash(match: re.Match[str]) -> str:
old = int(match.group(1))
new = numbers.get(old)
if new is None or new == old:
return match.group(0)
return f"#{new}"
def rewrite_url(match: re.Match[str]) -> str:
base = match.group("base")
old = int(match.group("num"))
new = numbers.get(old)
# Repoint any source URL at the target host; keep its number in sync
# when we know the mapping, else leave the number as-is.
out_base = base.replace(src_root, tgt_root, 1) if base.startswith(src_root) else base
out_num = new if new is not None else old
return f"{out_base}/issues/{out_num}"
out = URL_REF.sub(rewrite_url, text)
out = HASH_REF.sub(rewrite_hash, out)
return out
if __name__ == "__main__": # self-check
nm = NumberMap()
nm.add(289, 2)
nm.add(290, 3)
sample = (
"Fixes #289 and see #999 (unknown). Also https://codeberg.org/AlexKucera/helm/issues/290."
)
result = rewrite(
sample,
nm,
source_web_root="https://codeberg.org",
target_web_root="https://git.babylondreams.de",
)
assert result == (
"Fixes #2 and see #999 (unknown). "
"Also https://git.babylondreams.de/AlexKucera/helm/issues/3."
), result
print("refs self-check ok:", result)