Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(core): read change-request numbers from commit messages per forge (#3367)

Raghav Chamadiya6cc9bae13122
diff --git a/packages/core/src/repowise/core/forges/__init__.py b/packages/core/src/repowise/core/forges/__init__.py
index 82d765ead..5cc0a2ab0 100644
--- a/packages/core/src/repowise/core/forges/__init__.py
+++ b/packages/core/src/repowise/core/forges/__init__.py
@@ -12,11 +12,13 @@ from __future__ import annotations
# disjoint, so the order does not matter; generic claims none and is the fallback.
from . import azure, bitbucket, generic, github, gitlab # noqa: F401
from .base import BaseForge, CiSystem, Forge, ForgeKind, RemoteRef
+from .changes import CHANGE_BODY_MARKERS, change_number, change_refs
from .detect import detect_forge, read_remote_url
from .registry import HOSTS_ENV_VAR, all_forges, forge_hosts, get_forge, register
from .remote import canonical_key, parse_remote, strip_credentials
__all__ = [
+ "CHANGE_BODY_MARKERS",
"HOSTS_ENV_VAR",
"BaseForge",
"CiSystem",
@@ -25,6 +27,8 @@ __all__ = [
"RemoteRef",
"all_forges",
"canonical_key",
+ "change_number",
+ "change_refs",
"detect_forge",
"forge_hosts",
"get_forge",
diff --git a/packages/core/src/repowise/core/forges/azure.py b/packages/core/src/repowise/core/forges/azure.py
index c1055128a..b4b5018a4 100644
--- a/packages/core/src/repowise/core/forges/azure.py
+++ b/packages/core/src/repowise/core/forges/azure.py
@@ -9,6 +9,7 @@ sits before ``_git``.
from __future__ import annotations
+import re
from dataclasses import dataclass
from urllib.parse import quote
@@ -18,6 +19,7 @@ from .base import (
ForgeKind,
RemoteParts,
RemoteRef,
+ collect_refs,
join_url,
looks_like_sha,
quote_path,
@@ -31,6 +33,14 @@ _SSH_HOSTS = frozenset({"ssh.dev.azure.com", "vs-ssh.visualstudio.com"})
_LEGACY_SUFFIX = ".visualstudio.com"
_GIT = "_git"
+# Squash and merge completions write ``Merged PR 12: title``; older Server
+# merges write ``Merge pull request 12 from x into main``.
+_SUBJECT_REF_RES = (
+ re.compile(r"^Merged PR (\d{1,9}):"),
+ re.compile(r"^Merge pull request (\d{1,9}) from "),
+)
+_URL_REF_RE = re.compile(r"/pullrequest/(\d{1,9})\b", re.IGNORECASE)
+
def _project_repo(rest: tuple[str, ...]) -> tuple[str, str] | None:
"""``(project, repo)`` from ``project/_git/repo``, or ``_git/repo`` when they share a name."""
@@ -109,6 +119,9 @@ class Azure(BaseForge):
def format_change_ref(self, number: int) -> str:
return f"PR {number}"
+ def parse_change_refs(self, subject: str, body: str = "", *, native: bool = True) -> list[int]:
+ return collect_refs(subject, body, _SUBJECT_REF_RES, (_URL_REF_RE,))
+
register(
Azure(
@@ -137,5 +150,6 @@ register(
("bitbucket", ForgeKind.BITBUCKET),
),
),
+ merge_subject_res=_SUBJECT_REF_RES,
)
)
diff --git a/packages/core/src/repowise/core/forges/base.py b/packages/core/src/repowise/core/forges/base.py
index 571f6cb32..f9ba1362e 100644
--- a/packages/core/src/repowise/core/forges/base.py
+++ b/packages/core/src/repowise/core/forges/base.py
@@ -62,7 +62,9 @@ class Forge(Protocol):
def blob_url(self, ref: RemoteRef, rev: str, path: str, line: int | None = None) -> str: ...
def compare_url(self, ref: RemoteRef, base: str, head: str) -> str: ...
def format_change_ref(self, number: int) -> str: ...
- def parse_change_refs(self, subject: str, body: str = "") -> list[int]: ...
+ def parse_change_refs(
+ self, subject: str, body: str = "", *, native: bool = True
+ ) -> list[int]: ...
def normalize_identity(self, email: str, name: str) -> tuple[str, bool]: ...
@@ -142,6 +144,36 @@ class CiSystem:
return any(env_flag(env.get(var)) for var in self.markers)
+def unique_ints(groups: list[str]) -> list[int]:
+ """First-seen order, no repeats: the order refs appear in the message."""
+ seen: dict[int, None] = {}
+ for g in groups:
+ if g:
+ seen.setdefault(int(g), None)
+ return list(seen)
+
+
+def collect_refs(
+ subject: str,
+ body: str,
+ subject_res: tuple[re.Pattern[str], ...],
+ anywhere_res: tuple[re.Pattern[str], ...],
+) -> list[int]:
+ """Numbers captured by *subject_res* in the subject and *anywhere_res* in both.
+
+ Merge and squash conventions only hold on the subject line; a body can
+ quote other commits' subjects. Each pattern has one capture group of at
+ most nine digits: a huge run of digits is no change number and would hit
+ int()'s digit limit.
+ """
+ found = [m.group(1) for p in subject_res for m in p.finditer(subject or "")]
+ for text in (subject, body):
+ if text:
+ for p in anywhere_res:
+ found.extend(m.group(1) for m in p.finditer(text))
+ return unique_ints(found)
+
+
@dataclass(frozen=True, slots=True)
class BaseForge:
"""Shared defaults; a forge module subclasses this and calls ``register``."""
@@ -154,6 +186,16 @@ class BaseForge:
#: Path segments that start a web route on this forge and never name a
#: group or repo, so they are cut from a URL on any host.
route_markers: frozenset[str] = frozenset()
+ #: Forms that say a commit *is* one change (a merge or squash message),
+ #: read on the subject and on the body. A mention of another change, such
+ #: as a link, is not one; those are ``parse_change_refs``.
+ merge_subject_res: tuple[re.Pattern[str], ...] = ()
+ merge_body_res: tuple[re.Pattern[str], ...] = ()
+ #: Merge forms that only mean a change when the repo is on this forge.
+ native_merge_subject_res: tuple[re.Pattern[str], ...] = ()
+ #: On this forge the body's merge trailer outranks a subject suffix (a
+ #: cherry-picked ``(#7)`` merged through MR ``!3`` is MR 3).
+ merge_body_first: bool = False
# -- registry hooks -------------------------------------------------
@@ -186,8 +228,11 @@ class BaseForge:
def format_change_ref(self, number: int) -> str:
return f"#{number}"
- def parse_change_refs(self, subject: str, body: str = "") -> list[int]:
- """No convention known: no refs."""
+ def parse_change_refs(self, subject: str, body: str = "", *, native: bool = True) -> list[int]:
+ """Every change the message mentions. ``native=False`` reads it for a
+ repo on another forge, dropping forms that only hold on this one.
+
+ No convention known: no refs."""
return []
def normalize_identity(self, email: str, name: str) -> tuple[str, bool]:
diff --git a/packages/core/src/repowise/core/forges/bitbucket.py b/packages/core/src/repowise/core/forges/bitbucket.py
index cec78479a..96cd33930 100644
--- a/packages/core/src/repowise/core/forges/bitbucket.py
+++ b/packages/core/src/repowise/core/forges/bitbucket.py
@@ -7,6 +7,7 @@ The two share a name and little else: Cloud is ``workspace/repo`` with
from __future__ import annotations
+import re
from dataclasses import dataclass
from urllib.parse import quote
@@ -16,6 +17,7 @@ from .base import (
ForgeKind,
RemoteParts,
RemoteRef,
+ collect_refs,
join_url,
quote_path,
quote_segment,
@@ -26,6 +28,19 @@ PUBLIC_HOST = "bitbucket.org"
_PUBLIC_ORIGIN = f"https://{PUBLIC_HOST}"
_HOST_ALIASES = frozenset({PUBLIC_HOST, "www.bitbucket.org", "altssh.bitbucket.org"})
+# Cloud merges write ``Merged in branch (pull request #12)``; Data Center
+# writes ``Merge pull request #12 in PROJ/repo from branch to main``.
+_SUBJECT_REF_RES = (
+ re.compile(r"\(pull request #(\d{1,9})\)"),
+ re.compile(r"^Merge pull request #(\d{1,9}) in "),
+)
+_URL_REF_RE = re.compile(r"/pull-requests/(\d{1,9})\b")
+# Cloud's suffix closes the subject it merged; anywhere else it is quoted.
+_MERGE_SUBJECT_RES = (
+ re.compile(r"\(pull request #(\d{1,9})\)\s*$"),
+ _SUBJECT_REF_RES[1],
+)
+
def _data_center(parts: RemoteParts) -> tuple[tuple[str, ...], str, str] | None:
"""``(context path, project, repo)`` from a Data Center clone or browse URL."""
@@ -100,6 +115,9 @@ class Bitbucket(BaseForge):
# Cloud joins the two revs with a CR, head first.
return f"{ref.web_base}/branches/compare/{quote_path(head)}%0D{quote_path(base)}"
+ def parse_change_refs(self, subject: str, body: str = "", *, native: bool = True) -> list[int]:
+ return collect_refs(subject, body, _SUBJECT_REF_RES, (_URL_REF_RE,))
+
register(
Bitbucket(
@@ -113,5 +131,6 @@ register(
change_number=("BITBUCKET_PR_ID",),
repo_url=(("BITBUCKET_GIT_HTTP_ORIGIN",),),
),
+ merge_subject_res=_MERGE_SUBJECT_RES,
)
)
diff --git a/packages/core/src/repowise/core/forges/changes.py b/packages/core/src/repowise/core/forges/changes.py
new file mode 100644
index 000000000..1f3218f8b
--- /dev/null
+++ b/packages/core/src/repowise/core/forges/changes.py
@@ -0,0 +1,148 @@
+"""Change-request numbers (PRs, MRs) in commit messages, read across forges.
+
+Two questions, kept apart:
+
+- ``change_number``: the one change a commit *is*, from its merge or squash
+ message. A wrong number is worse than none, so a mention never counts: a
+ bare ``#12`` names an issue as often as a PR, and a link names another change.
+- ``change_refs``: every change a message mentions, for matching a revert to
+ what it undid.
+
+Both read every forge's conventions with the repo's own forge first, since
+history can predate a move between forges. A form that only means a change on
+one forge (GitLab's ``!12``) counts only when the repo is on that forge.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable
+from dataclasses import dataclass
+from functools import cache
+
+from .base import ForgeKind
+from .registry import all_forges, get_forge
+
+#: Lowercase markers that make a commit body read like a PR or MR description
+#: worth mining for decisions, rather than an incidental multi-line message.
+CHANGE_BODY_MARKERS: tuple[str, ...] = (
+ "## why",
+ "## motivation",
+ "## what",
+ "## changes",
+ "## context",
+ "## summary",
+ "closes #",
+ "fixes #",
+ "resolves #",
+ "before:",
+ "after:",
+)
+
+
+#: The literal text a pattern opens with (``^`` aside), escapes still in.
+_LEAD_RE = re.compile(r"\^?((?:[^\\.^$*+?{}\[\]|()]|\\[^\w])*)")
+
+
+def lead_of(p: re.Pattern[str]) -> str:
+ """The text *p* cannot match without, from its literal opening.
+
+ Raises for a pattern with none (or a case-blind one): every merge form
+ must have a lead, so a message is rejected by string tests alone.
+ """
+ m = _LEAD_RE.match(p.pattern)
+ raw = m.group(1) if m else ""
+ # A quantifier right after the lead makes its last character optional.
+ if raw and p.pattern[m.end() : m.end() + 1] in ("*", "?", "{"):
+ raw = raw[:-2] if raw.endswith("\\", 0, len(raw) - 1) else raw[:-1]
+ lead = re.sub(r"\\(.)", r"\1", raw)
+ if not lead or p.flags & re.IGNORECASE or p.groups != 1:
+ raise ValueError(f"a merge form needs a literal lead and one group: {p.pattern!r}")
+ return lead
+
+
+@dataclass(frozen=True, slots=True)
+class _Forms:
+ """One side's merge forms, each behind a string test it cannot match without.
+
+ Most messages fail every form, and one ``str.startswith`` or ``in`` rejects
+ them several times faster than a regex call. Forms anchored to the start
+ are tried first, then the rest, each group in the order given.
+ """
+
+ starts: tuple[str, ...]
+ anchored: tuple[tuple[str, re.Pattern[str]], ...]
+ floating: tuple[tuple[str, re.Pattern[str]], ...]
+ #: Take a floating form's last match: a body's own trailer closes it, and
+ #: one quoted above it (a description, a squashed log) names another change.
+ last: bool = False
+
+ @classmethod
+ def of(cls, patterns: Iterable[re.Pattern[str]], *, last: bool = False) -> _Forms:
+ pairs = [(lead_of(p), p) for p in dict.fromkeys(patterns)]
+ anchored = tuple(x for x in pairs if x[1].pattern.startswith("^"))
+ floating = tuple(x for x in pairs if not x[1].pattern.startswith("^"))
+ return cls(tuple(dict.fromkeys(lead for lead, _ in anchored)), anchored, floating, last)
+
+ def first(self, text: str) -> int | None:
+ if text.startswith(self.starts):
+ for lead, p in self.anchored:
+ if text.startswith(lead) and (m := p.match(text)):
+ return int(m.group(1))
+ for lead, p in self.floating:
+ if lead not in text:
+ continue
+ m = None
+ if self.last:
+ for m in p.finditer(text): # noqa: B007 - the last one is wanted
+ pass
+ else:
+ m = p.search(text)
+ if m:
+ return int(m.group(1))
+ return None
+
+
+# Forges register on package import, before any message is read, so the
+# forms per forge are fixed once built.
+@cache
+def _merge_forms(forge: ForgeKind | str) -> tuple[_Forms, _Forms, bool]:
+ """``(subject forms, body forms, body first)`` for a repo on *forge*.
+
+ Keyed by the caller's value as given: a ``ForgeKind`` and its string are
+ one key, so the hot path skips converting it per commit.
+ """
+ first = get_forge(forge)
+ order = [first, *(f for f in all_forges() if f is not first)]
+ subject = [*first.native_merge_subject_res, *(p for f in order for p in f.merge_subject_res)]
+ body = _Forms.of((p for f in order for p in f.merge_body_res), last=True)
+ return _Forms.of(subject), body, first.merge_body_first
+
+
+def change_number(
+ subject: str, body: str = "", forge: ForgeKind | str = ForgeKind.GENERIC
+) -> int | None:
+ """The PR or MR this commit merged, or ``None`` when its message does not say."""
+ subject_forms, body_forms, body_first = _merge_forms(forge)
+ if body_first and body and (found := body_forms.first(body)) is not None:
+ return found
+ found = subject_forms.first(subject) if subject else None
+ if found is None and body and not body_first:
+ found = body_forms.first(body)
+ return found
+
+
+def change_refs(
+ subject: str, body: str = "", forge: ForgeKind | str = ForgeKind.GENERIC
+) -> list[int]:
+ """Every PR or MR the message mentions: the repo's forge's first, then in order."""
+ kind = ForgeKind(forge)
+ first = get_forge(kind)
+ found: dict[int, None] = {}
+ for f in (first, *(f for f in all_forges() if f.kind is not kind)):
+ for n in f.parse_change_refs(subject, body, native=f is first):
+ found.setdefault(n, None)
+ return list(found)
+
+
+__all__ = ["CHANGE_BODY_MARKERS", "change_number", "change_refs"]
diff --git a/packages/core/src/repowise/core/forges/generic.py b/packages/core/src/repowise/core/forges/generic.py
index 8a4828cc7..e9ce6dc6b 100644
--- a/packages/core/src/repowise/core/forges/generic.py
+++ b/packages/core/src/repowise/core/forges/generic.py
@@ -1,13 +1,15 @@
"""Any other git host: Gitea, cgit, a bare ssh server, or a forge with no override.
Nothing is known about its web pages, so every URL builder returns ``""`` and
-callers render plain text.
+callers render plain text. Commit messages are read the GitHub way, the
+convention most other hosts and mirrors follow.
"""
from __future__ import annotations
from dataclasses import dataclass
+from . import github
from .base import BaseForge, ForgeKind, RemoteParts, RemoteRef, join_url
from .registry import register
@@ -33,5 +35,10 @@ class Generic(BaseForge):
def compare_url(self, ref: RemoteRef, base: str, head: str) -> str:
return ""
+ def parse_change_refs(self, subject: str, body: str = "", *, native: bool = True) -> list[int]:
+ return github.change_refs(subject, body)
-register(Generic(kind=ForgeKind.GENERIC, label="Git"))
+
+register(
+ Generic(kind=ForgeKind.GENERIC, label="Git", merge_subject_res=github.MERGE_SUBJECT_RES)
+)
diff --git a/packages/core/src/repowise/core/forges/github.py b/packages/core/src/repowise/core/forges/github.py
index cbdfcf4ee..6f15e362d 100644
--- a/packages/core/src/repowise/core/forges/github.py
+++ b/packages/core/src/repowise/core/forges/github.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import re
from dataclasses import dataclass
from .base import (
@@ -10,6 +11,7 @@ from .base import (
ForgeKind,
RemoteParts,
RemoteRef,
+ collect_refs,
join_url,
quote_path,
quote_segment,
@@ -21,6 +23,28 @@ _PUBLIC_ORIGIN = f"https://{PUBLIC_HOST}"
# ssh.github.com serves ssh over port 443; both aliases are github.com.
_HOST_ALIASES = frozenset({PUBLIC_HOST, "www.github.com", "ssh.github.com"})
+# Squash merges end the subject with ``(#12)`` (``(gh-12)`` in some projects);
+# merge commits open with ``Merge pull request #12``. A bare ``#12`` is an
+# issue reference as often as a PR, so it is not read as one.
+_SUBJECT_REF_RES = (
+ re.compile(r"\((?:#|gh-)(\d{1,9})\)", re.IGNORECASE),
+ re.compile(r"^Merge pull request #(\d{1,9})\b"),
+)
+_URL_REF_RE = re.compile(r"/pull/(\d{1,9})\b")
+
+# What says a commit *is* one PR: a merge commit's subject, or the squash
+# suffix closing the subject. ``Revert "x (#5)"`` merged no PR 5, so the
+# suffix must end the subject, give or take a full stop or a ``[skip ci]``.
+MERGE_SUBJECT_RES = (
+ _SUBJECT_REF_RES[1],
+ re.compile(r"\((?:#|[Gg][Hh]-)(\d{1,9})\)[\s.]*(?:\[[^\]\n]{0,40}\][\s.]*)?$"),
+)
+
+
+def change_refs(subject: str, body: str = "") -> list[int]:
+ """PR numbers in a GitHub commit message, in order of appearance."""
+ return collect_refs(subject, body, _SUBJECT_REF_RES, (_URL_REF_RE,))
+
@dataclass(frozen=True, slots=True)
class GitHub(BaseForge):
@@ -51,6 +75,9 @@ class GitHub(BaseForge):
def compare_url(self, ref: RemoteRef, base: str, head: str) -> str:
return f"{ref.web_base}/compare/{quote_path(base)}...{quote_path(head)}"
+ def parse_change_refs(self, subject: str, body: str = "", *, native: bool = True) -> list[int]:
+ return change_refs(subject, body)
+
register(
GitHub(
@@ -64,5 +91,6 @@ register(
change_number=("GITHUB_REF",), # refs/pull/N/merge on a pull request
repo_url=(("GITHUB_SERVER_URL", "GITHUB_REPOSITORY"),),
),
+ merge_subject_res=MERGE_SUBJECT_RES,
)
)
diff --git a/packages/core/src/repowise/core/forges/gitlab.py b/packages/core/src/repowise/core/forges/gitlab.py
index 30572b5fd..ef1961423 100644
--- a/packages/core/src/repowise/core/forges/gitlab.py
+++ b/packages/core/src/repowise/core/forges/gitlab.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import re
from dataclasses import dataclass
from .base import (
@@ -10,6 +11,7 @@ from .base import (
ForgeKind,
RemoteParts,
RemoteRef,
+ collect_refs,
join_url,
quote_path,
quote_segment,
@@ -18,6 +20,25 @@ from .registry import register
PUBLIC_HOST = "gitlab.com"
+# ``See merge request group/proj!12`` closes a merge commit's body; ``!12``
+# alone is GitLab's shorthand, never preceded by a word char or another ``!``.
+# The ``!`` leads, ahead of the lookbehind, so the scan jumps from ``!`` to
+# ``!`` instead of trying every position (about 17x faster on a real history).
+# Newer GitLab writes the trailer's reference as the MR's full URL. The path
+# is bounded so a run of trailers over long tokens stays linear.
+_MERGE_TRAILER_RE = re.compile(
+ r"See merge request \S{0,512}?(?:!|/-/merge_requests/)(\d{1,9})\b"
+)
+_SHORTHAND_RE = re.compile(r"!(?<![\w!]!)(\d{1,9})\b")
+_URL_REF_RE = re.compile(r"/-/merge_requests/(\d{1,9})\b")
+_REF_RES = (_MERGE_TRAILER_RE, _SHORTHAND_RE, _URL_REF_RE)
+# Off GitLab, ``!12`` is as likely an exclamation as a reference: only the
+# explicit trailer and links count there.
+_FOREIGN_REF_RES = (_MERGE_TRAILER_RE, _URL_REF_RE)
+# A squash subject closed with ``(!12)`` is that MR, as ``(#12)`` is on
+# GitHub; a bare ``!12`` elsewhere in a subject only mentions one.
+_NATIVE_MERGE_SUBJECT_RES = (re.compile(r"\(!(\d{1,9})\)\s*$"),)
+
@dataclass(frozen=True, slots=True)
class GitLab(BaseForge):
@@ -54,6 +75,9 @@ class GitLab(BaseForge):
def format_change_ref(self, number: int) -> str:
return f"!{number}"
+ def parse_change_refs(self, subject: str, body: str = "", *, native: bool = True) -> list[int]:
+ return collect_refs(subject, body, (), _REF_RES if native else _FOREIGN_REF_RES)
+
register(
GitLab(
@@ -70,6 +94,9 @@ register(
change_number=("CI_MERGE_REQUEST_IID",),
repo_url=(("CI_PROJECT_URL",),),
),
+ merge_body_res=(_MERGE_TRAILER_RE,),
+ merge_body_first=True,
+ native_merge_subject_res=_NATIVE_MERGE_SUBJECT_RES,
route_markers=frozenset({"-"}),
)
)
diff --git a/tests/unit/core/test_forges_change_refs.py b/tests/unit/core/test_forges_change_refs.py
new file mode 100644
index 000000000..13681a4aa
--- /dev/null
+++ b/tests/unit/core/test_forges_change_refs.py
@@ -0,0 +1,184 @@
+"""Change-request numbers read out of commit messages, per forge."""
+
+from __future__ import annotations
+
+import re
+
+import pytest
+
+from repowise.core.forges import ForgeKind, change_number, change_refs, get_forge
+from repowise.core.forges.changes import _merge_forms, lead_of
+
+GH, GL, AZ, BB, GEN = (
+ ForgeKind.GITHUB,
+ ForgeKind.GITLAB,
+ ForgeKind.AZURE,
+ ForgeKind.BITBUCKET,
+ ForgeKind.GENERIC,
+)
+
+
+ ("kind", "subject", "body", "expected"),
+ [
+ # GitHub: squash suffix, merge commit, PR links. A bare #N is an issue.
+ (GH, "feat: add x (#123)", "", [123]),
+ (GH, "fix: y (gh-45)", "", [45]),
+ (GH, "Merge pull request #456 from org/branch", "Some title", [456]),
+ (GH, "fix: z", "See https://github.com/o/r/pull/77 for context", [77]),
+ (GH, "fix: closes #9", "Fixes #10", []),
+ (GH, "feat: x (#12) (#12)", "https://github.com/o/r/pull/12", [12]),
+ (GH, "Revert \"feat: a (#5)\" (#6)", "", [5, 6]),
+ (GH, "chore: wow!12", "", []),
+ # GitLab: merge-commit trailer, !N shorthand, MR links.
+ (GL, "Merge branch 'feat' into 'main'", "Title\n\nSee merge request group/sub/proj!42", [42]),
+ (GL, "feat: thing (!17)", "", [17]),
+ (GL, "fix: a", "Related to !3 and !4", [3, 4]),
+ (GL, "fix: a", "https://gitlab.com/g/p/-/merge_requests/88", [88]),
+ (GL, "chore: wow!!1 and word!2", "", []),
+ (GL, "fix: issue #12", "", []),
+ # Azure: completion message and PR links.
+ (AZ, "Merged PR 1234: Add the thing", "", [1234]),
+ (AZ, "Merge pull request 77 from feat into main", "", [77]),
+ (AZ, "fix: a", "https://dev.azure.com/o/p/_git/r/pullrequest/55", [55]),
+ (AZ, "fix: a (#12)", "", []),
+ # Bitbucket: Cloud and Data Center merge messages, PR links.
+ (BB, "Merged in feature/x (pull request #12)", "Approved-by: someone", [12]),
+ (BB, "Merge pull request #34 in PROJ/repo from feat to master", "", [34]),
+ (BB, "fix: a", "https://bitbucket.org/ws/repo/pull-requests/9", [9]),
+ (BB, "fix: a (#12)", "", []),
+ # Generic reads the GitHub way.
+ (GEN, "feat: add x (#123)", "", [123]),
+ (GEN, "Merged PR 12: a", "", []),
+ (GH, "", "", []),
+ ],
+)
+def test_parse_change_refs(kind: ForgeKind, subject: str, body: str, expected: list[int]) -> None:
+ assert get_forge(kind).parse_change_refs(subject, body) == expected
+
+
[email protected]("kind", list(ForgeKind))
+def test_a_huge_number_is_not_a_change_ref(kind: ForgeKind) -> None:
+ """``int()`` refuses 4300+ digits; a run that long names no change."""
+ digits = "9" * 50_000
+ subject = f"Merged PR {digits}: x (#{digits}) Merge pull request #{digits} from a !{digits}"
+ body = f"/pull/{digits} /-/merge_requests/{digits} /pullrequest/{digits} /pull-requests/{digits}"
+ assert get_forge(kind).parse_change_refs(subject, body) == []
+ assert change_number(subject, f"See merge request g/p!{digits}", kind) is None
+ assert change_refs(subject, body, kind) == []
+
+
+ ("forge", "subject", "body", "expected"),
+ [
+ # GitHub: the squash suffix closing the subject, or a merge subject.
+ (GH, "feat: add x (#123)", "", 123),
+ (GH, "feat: add x (gh-45) ", "", 45),
+ (GH, "Merge pull request #456 from org/branch", "", 456),
+ # Only the suffix is the PR; an issue named before it is not.
+ (GH, "fix(x): y (#881) (#911)", "", 911),
+ (GH, "Fix #2379: classify dotfiles (#2381)", "", 2381),
+ # A bare #N is an issue as often as a PR, and a link is a mention.
+ (GH, "fix: closes #12", "", None),
+ (GH, "feat: add JVM PKCS#12 helper", "", None),
+ (GH, "fix: a", "Follow-up to https://github.com/o/r/pull/77", None),
+ (GH, "fix: a", "* feat: squashed (#5)", None),
+ # A direct revert merged no PR; a revert that went through one did.
+ (GH, 'Revert "feat: a (#5)"', "", None),
+ (GH, 'Revert "feat: a (#5)" (#6)', "", 6),
+ # GitLab: the merge trailer, in either form, on any forge.
+ (GL, "Merge branch 'f' into 'main'", "Title\n\nSee merge request g/sub/p!42", 42),
+ (
+ GH,
+ "Merge branch 'f' into 'main'",
+ "See merge request https://gitlab.com/g/p/-/merge_requests/4009\n",
+ 4009,
+ ),
+ # The body's own trailer is its last; on GitLab it outranks a suffix.
+ (GL, "Add x", "See merge request g/p!5 for context\nSee merge request g/p!9", 9),
+ (GL, "Backport (#7)", "(cherry picked from commit abc)\nSee merge request g/p!3", 3),
+ (GH, "Backport (#7)", "See merge request g/p!3", 7),
+ # A suffix followed by a full stop or a CI tag still closes the subject.
+ (GH, "fix foo (#12) [skip ci]", "", 12),
+ (GH, "fix foo (#12).", "", 12),
+ # GitLab's (!N) suffix counts on GitLab only; a bare !N is a mention.
+ (GL, "feat: thing (!17)", "", 17),
+ (GH, "feat: thing (!17)", "", None),
+ (GL, "fix(orbit): address review nits from !3269", "", None),
+ (GL, "fix: issue #12", "", None),
+ # Azure DevOps and Bitbucket merge messages, read on any forge.
+ (AZ, "Merged PR 1234: Add the thing", "", 1234),
+ (GH, "Merged PR 1234: Add the thing", "", 1234),
+ (AZ, "Merge pull request 77 from feat into main", "", 77),
+ (BB, "Merged in feature/x (pull request #12)", "Approved-by: a", 12),
+ (GL, "Merge pull request #34 in PROJ/repo from feat to master", "", 34),
+ (BB, "fix: see (pull request #12) for why", "", None),
+ # Azure's AB#N links a work item, never a PR.
+ (AZ, "fix: a AB#123", "", None),
+ (GEN, "", "", None),
+ ],
+)
+def test_change_number(forge: ForgeKind, subject: str, body: str, expected: int | None) -> None:
+ assert change_number(subject, body, forge) == expected
+
+
+ ("forge", "subject", "body", "expected"),
+ [
+ (GH, "revert: x", "Reverts https://github.com/o/r/pull/7", [7]),
+ (GL, "revert: x", "Reverts !7", [7]),
+ # Off GitLab, !7 is punctuation; the explicit forms still count.
+ (GH, "revert: x", "Reverts !7", []),
+ (GH, "revert: x", "See https://gitlab.com/g/p/-/merge_requests/8", [8]),
+ (GH, "revert: x (#3)", "https://dev.azure.com/o/p/_git/r/pullrequest/9", [3, 9]),
+ (AZ, "fix: a AB#123", "", []),
+ ],
+)
+def test_change_refs_reads_every_forge_with_the_repos_first(
+ forge: ForgeKind, subject: str, body: str, expected: list[int]
+) -> None:
+ assert change_refs(subject, body, forge) == expected
+
+
[email protected]("kind", list(ForgeKind))
+def test_the_string_gates_never_hide_a_match(kind: ForgeKind) -> None:
+ """Each merge form's lead is text it cannot match without."""
+ subject_forms, body_forms, _ = _merge_forms(kind)
+ samples = [
+ "feat: x (#1)",
+ "feat: x (GH-2) ",
+ "feat: x (!3)",
+ "Merged PR 4: x",
+ "Merge pull request 5 from a into b",
+ "Merge pull request #6 in P/r from a",
+ "Merged in b (pull request #7)",
+ "x\nSee merge request g/p!8",
+ ]
+ hidden = [
+ (pattern.pattern, text)
+ for forms in (subject_forms, body_forms)
+ for _, pattern in (*forms.anchored, *forms.floating)
+ for text in samples
+ if pattern.search(text) and forms.first(text) is None
+ ]
+ assert hidden == []
+
+
+ ("pattern", "lead"),
+ [
+ (r"^Merged PR (\d+):", "Merged PR "),
+ (r"\(!(\d+)\)\s*$", "(!"),
+ (r"See merge request \S*?!(\d+)", "See merge request "),
+ (r"ab?c(\d)", "a"),
+ (r"\(x*(\d)", "("),
+ ],
+)
+def test_lead_of(pattern: str, lead: str) -> None:
+ assert lead_of(re.compile(pattern)) == lead
+
+
[email protected]("pattern", [r"(\d+)", r"(?i)abc(\d)", r"abc(\d)(\d)"])
+def test_a_merge_form_without_a_lead_is_refused(pattern: str) -> None:
+ with pytest.raises(ValueError):
+ lead_of(re.compile(pattern))