"""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/`` 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"(?https?://[^\s/]+/[^\s]+?)/(?:issues|pulls)/(?P\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/`` namespace. The git-mirror layer (mirror.py) pushes ``refs/heads/`` for each PR whose source head is gone; the REST layer (issues.py) sends ```` 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)