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(git): read a commit's PR or MR number through the forges package (#3368)

Raghav Chamadiya18593da13bfc
diff --git a/packages/core/src/repowise/core/analysis/decisions/commit_mining.py b/packages/core/src/repowise/core/analysis/decisions/commit_mining.py
index e9774a0a3..bb2716d32 100644
--- a/packages/core/src/repowise/core/analysis/decisions/commit_mining.py
+++ b/packages/core/src/repowise/core/analysis/decisions/commit_mining.py
@@ -11,6 +11,7 @@ from repowise.core.analysis.decisions.scope import (
commit_scope_files,
selected_scope_files,
)
+from repowise.core.forges import CHANGE_BODY_MARKERS, Forge
from .commit_signals import count_decision_signals
from .records import ExtractedDecision
@@ -24,21 +25,6 @@ _BATCH_MAX_TOKENS = 8000
#: truncating, so the files offered depend on the commit, not on map order.
_MAX_PROMPT_FILES = 20
-# PR/squash body markers: a body containing any of these reads like a PR
-# description worth mining (vs an incidental multi-line commit message).
-_PR_BODY_MARKERS = (
- "## why",
- "## motivation",
- "## what",
- "## changes",
- "## context",
- "## summary",
- "closes #",
- "fixes #",
- "resolves #",
- "before:",
- "after:",
-)
_MAX_PR_BODIES = 25
@@ -162,7 +148,7 @@ def signal_commits(
def _pr_candidate(commit: dict, body: str) -> dict | None:
"""The prompt-ready record of a PR-shaped body with decision signals, else None."""
low = body.lower()
- is_prish = commit.get("pr_number") is not None or any(m in low for m in _PR_BODY_MARKERS)
+ is_prish = commit.get("pr_number") is not None or any(m in low for m in CHANGE_BODY_MARKERS)
if not is_prish or count_decision_signals(low) <= 0:
return None
return {
@@ -215,9 +201,9 @@ def git_commit_block(commit: dict, body: str, files: list[str]) -> str:
)
-def pr_commit_block(candidate: dict, files: list[str]) -> str:
- """One PR body's entry in the PR mining prompt."""
- pr_label = f" (PR #{candidate['pr']})" if candidate.get("pr") else ""
+def pr_commit_block(candidate: dict, files: list[str], forge: Forge) -> str:
+ """One PR body's entry in the PR mining prompt, its number as *forge* writes it."""
+ pr_label = f" ({forge.format_change_ref(candidate['pr'])})" if candidate.get("pr") else ""
return (
f"\n--- Commit {candidate['sha'][:8]}{pr_label} ---\n"
f"Subject: {candidate['subject']}\n"
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.py
index 7760b3460..b473add76 100644
--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py
+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py
@@ -32,6 +32,7 @@ from repowise.core.analysis.decisions.policy import (
resolve_policy,
)
from repowise.core.analysis.decisions.scope import resolve_module_nodes
+from repowise.core.forges import detect_forge, get_forge
from .adr import _ADR_STATUS_MAP, bullets, find_adr_files, read_front_matter, split_headings
from .commit_mining import (
@@ -566,13 +567,14 @@ class DecisionExtractor:
return []
ranked = list(candidates.values())[:_MAX_PR_BODIES]
+ forge = get_forge(detect_forge(self._repo_path))
async def _process_batch(batch: list[dict]) -> list[ExtractedDecision]:
bodies_block = ""
source_by_sha: dict[str, str] = {}
for c in batch:
# The file list is what lets the model answer "affected_files".
- bodies_block += pr_commit_block(c, files_by_sha.get(c["sha"], []))
+ bodies_block += pr_commit_block(c, files_by_sha.get(c["sha"], []), forge)
source_by_sha[c["sha"]] = f"{c['subject']}\n{c['body']}"
prompt = PR_BODY_MINING_PROMPT.format(bodies_block=bodies_block)
# Not caught: _run_batches counts a failed batch, so an outage is
diff --git a/packages/core/src/repowise/core/analysis/decisions/reverts.py b/packages/core/src/repowise/core/analysis/decisions/reverts.py
index efb0dcd2b..307f89a1e 100644
--- a/packages/core/src/repowise/core/analysis/decisions/reverts.py
+++ b/packages/core/src/repowise/core/analysis/decisions/reverts.py
@@ -14,8 +14,9 @@ commit whose message fits a stronger rule is never retried with a weaker one:
history has subject ``S``, both compared with a trailing ``(#N)`` or
``(gh-N)`` stripped.
- **pr**: the subject is ``revert:``/``revert(scope):`` and the message
- references ``#N`` or ``/pull/N``, with exactly one commit that is that pull
- request (subject ending ``(#N)`` or ``Merge pull request #N``).
+ references ``#N`` or a change the forge writes (``/pull/N``, ``!N`` on
+ GitLab, an MR or PR link), with exactly one commit that is that change (its
+ merge or squash message names it, read by :func:`repowise.core.forges.change_number`).
Every match also needs the target to be an ancestor of the revert, and the two
must change at least one file in common. A revert that calls itself partial is
@@ -53,6 +54,7 @@ from typing import Any
import structlog
from repowise.core.analysis.git_cli import _git
+from repowise.core.forges import ForgeKind, change_number, change_refs, detect_forge
logger = structlog.get_logger(__name__)
@@ -74,9 +76,10 @@ _SUPERSEDED_BY_WIDTH = 32
_BODY_RE = re.compile(r"This reverts commit ([0-9a-f]{40})\b")
_SUBJECT_RE = re.compile(r'^Revert "(.+)"$')
_CONVENTIONAL_RE = re.compile(r"^revert(?:\([^)]*\))?!?:", re.IGNORECASE)
-_PR_REF_RE = re.compile(r"(?:#|/pull/)(\d+)\b")
+#: A bare ``#N``: an issue, or a pull request on forges that number both alike.
+_HASH_REF_RE = re.compile(r"#(\d{1,9})\b")
+#: Subject normalisation only: the same change re-landed under another PR.
_PR_SUFFIX_RE = re.compile(r"\s*\((?:#|gh-)(\d+)\)\s*$", re.IGNORECASE)
-_MERGE_PR_RE = re.compile(r"^Merge pull request #(\d+)\b")
_PARTIAL_RE = re.compile(r"\bpart(?:ial(?:ly)?|ly)\b", re.IGNORECASE)
_RELAND_WORD_RE = re.compile(r"\s*\(?\b(?:re-?land(?:ed)?|re-?appl(?:y|ied))\b\)?:?", re.IGNORECASE)
_TICKET_PREFIX_RE = re.compile(
@@ -166,11 +169,6 @@ def _changes(repo_path: Path | str, shas: set[str]) -> dict[str, dict[str, str]]
return out
-def _pr_number(subject: str) -> str | None:
- m = _PR_SUFFIX_RE.search(subject) or _MERGE_PR_RE.match(subject)
- return m.group(1) if m else None
-
-
def _read_candidates(repo_path: Path | str, head: str) -> list[tuple[str, str, str]]:
"""(sha, subject, body) of every commit whose message could fit a rule."""
out = _git_out(
@@ -211,9 +209,12 @@ class _History:
by_reland_key: dict[str, list[str]] = field(default_factory=dict)
by_closed_issue: dict[str, list[str]] = field(default_factory=dict)
by_issue_key: dict[str, list[str]] = field(default_factory=dict)
+ forge: ForgeKind = ForgeKind.GENERIC
@classmethod
- def read(cls, repo_path: Path | str, head: str) -> _History | None:
+ def read(
+ cls, repo_path: Path | str, head: str, forge: ForgeKind = ForgeKind.GENERIC
+ ) -> _History | None:
out = _git_out(
repo_path,
"log",
@@ -223,7 +224,7 @@ class _History:
)
if out is None:
return None
- hist = cls()
+ hist = cls(forge=forge)
for raw in out.split(_RECORD):
fields = raw.strip("\n").split(_FIELD, 3)
if len(fields) == 4 and fields[0]:
@@ -241,9 +242,9 @@ class _History:
_append(self.by_closed_issue, issue, sha)
for key in _issue_keys(subject):
_append(self.by_issue_key, key, sha)
- pr = _pr_number(subject)
- if pr:
- _append(self.by_pr, pr, sha)
+ pr = change_number(subject, body, self.forge)
+ if pr is not None:
+ _append(self.by_pr, str(pr), sha)
def is_ancestor(self, older: str, newer: str) -> bool:
# Walk *newer*'s parents, never past *older*'s place in the order: an
@@ -274,7 +275,8 @@ class _History:
others = [s for s in self.by_subject.get(_strip_pr_suffix(m.group(1)), []) if s != sha]
return [RevertLink(sha, others[0], "subject")] if len(others) == 1 else []
if _CONVENTIONAL_RE.match(subject):
- refs = set(_PR_REF_RE.findall(message))
+ refs = set(_HASH_REF_RE.findall(message))
+ refs.update(str(n) for n in change_refs(subject, body, self.forge))
targets = {s for n in refs for s in self.by_pr.get(n, []) if s != sha}
return [RevertLink(sha, targets.pop(), "pr")] if len(targets) == 1 else []
return []
@@ -322,7 +324,9 @@ class _Relands:
# them.
subject = self.hist.subject_of[link.target]
later = set(self.hist.by_reland_key.get(_reland_key(subject), []))
- for issue in _PR_REF_RE.findall(subject):
+ refs = set(_HASH_REF_RE.findall(subject))
+ refs.update(str(n) for n in change_refs(subject, "", self.hist.forge))
+ for issue in refs:
later.update(self.hist.by_closed_issue.get(issue, []))
if self.in_force_at_head(link.target) or any(self.after(link, s) for s in later):
return True
@@ -335,7 +339,7 @@ def find_revert_links(repo_path: Path | str, head: str = "HEAD") -> list[RevertL
# Only messages that can fit a rule; the full history is read only if one
# of them does.
candidates = _read_candidates(repo_path, head)
- hist = _History.read(repo_path, head) if candidates else None
+ hist = _History.read(repo_path, head, detect_forge(repo_path)) if candidates else None
if hist is None:
return []
proposed = [link for c in candidates for link in hist.match(*c)]
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
index 6af503da2..0396aacef 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
@@ -118,23 +118,6 @@ def _truncate_body(body: str) -> str:
return encoded[:_MAX_COMMIT_BODY_BYTES].decode("utf-8", errors="ignore")
-# PR/squash-description markers — a body containing one of these reads like a
-# real PR write-up worth retaining for decision mining (mirrors the extractor's
-# ``_PR_BODY_MARKERS``; kept here to avoid a cross-package import at index time).
-_PR_BODY_MARKERS: tuple[str, ...] = (
- "## why",
- "## motivation",
- "## what",
- "## changes",
- "## context",
- "## summary",
- "closes #",
- "fixes #",
- "resolves #",
- "before:",
- "after:",
-)
-
# Co-change pair extraction widens the window because individual files
# may only co-change a handful of times in 500 commits. On low-churn repos
# the 500-commit window produced 0 co-change pairs every run; 2000 commits
@@ -366,10 +349,6 @@ HOTSPOT_MIN_COMMITS_90D: int = 3
HOTSPOT_MIN_TEMPORAL_SCORE: float = 0.5
HOTSPOT_HIGH_COMMITS_90D: int = 8
-# Regex to extract PR/MR numbers from commit messages.
-# Matches: "#123", "Merge pull request #456", "(#789)", "!42" (GitLab MR)
-_PR_NUMBER_RE = re.compile(r"(?:pull request |)\#(\d+)|\(#(\d+)\)|!(\d+)")
-
# Allowlist of extensions for which per-file git indexing (blame, commit
# history, hotspot/stable classification) is worth running. Anything NOT in
# this set is skipped — data, config, markup, dotfiles, and binaries add no
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
index 91be6cbc0..28f1f3334 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
@@ -17,14 +17,14 @@ from typing import Any
import structlog
+from repowise.core.forges import CHANGE_BODY_MARKERS, ForgeKind, change_number
+
from ._constants import (
_COMMIT_CATEGORIES,
_DECISION_SIGNAL_WORDS,
_MAX_BLAME_SIZE_BYTES,
_MAX_SIGNIFICANT_COMMITS,
_MAX_TOP_AUTHORS,
- _PR_BODY_MARKERS,
- _PR_NUMBER_RE,
HOTSPOT_HALFLIFE_DAYS,
_truncate_body,
is_fix_commit,
@@ -55,7 +55,7 @@ def _body_carries_decision(subject: str, body: str) -> bool:
if not body:
return False
blob = f"{subject}\n{body}".lower()
- if any(marker in blob for marker in _PR_BODY_MARKERS):
+ if any(marker in blob for marker in CHANGE_BODY_MARKERS):
return True
return any(word in blob for word in _DECISION_SIGNAL_WORDS)
@@ -319,6 +319,7 @@ def index_file(
note_agents: dict[str, str] | None = None,
trace_index: Any | None = None,
history_only: bool = False,
+ forge: ForgeKind = ForgeKind.GENERIC,
) -> dict:
"""Index a single file's git history. Runs in executor.
@@ -334,6 +335,9 @@ def index_file(
*history_only* (a non-code file) keeps the history tier: commit counts and
windows, first and last commit, and authorship. Blame, the decayed churn
score, agent provenance and commit-message mining stay code-only.
+
+ *forge* is the repo's forge, read first when a commit message names the
+ change it merged.
"""
now = _window_anchor(as_of_ts)
ninety_days_ago_ts = (now - timedelta(days=90)).timestamp()
@@ -378,7 +382,7 @@ def index_file(
meta["temporal_hotspot_score"] = _temporal_hotspot_score(commits, now)
if include_blame:
_add_blame_ownership(meta, repo, repo_path, now, authors)
- _add_commit_messages(meta, commits)
+ _add_commit_messages(meta, commits, forge)
# Only the per-file ``--follow`` walk reports an original path.
if orig_path:
meta["original_path"] = orig_path
@@ -581,13 +585,15 @@ def _add_blame_ownership(
pass # blame is best-effort
-def _add_commit_messages(meta: dict[str, Any], commits: list[_CommitRec]) -> None:
+def _add_commit_messages(
+ meta: dict[str, Any], commits: list[_CommitRec], forge: ForgeKind = ForgeKind.GENERIC
+) -> None:
"""Significant commits (with PR numbers and decision bodies) and category counts."""
sig_commits: list[dict[str, Any]] = []
for c in commits:
msg = c.subject[:200]
if is_significant_commit(msg, c.author_name, c.author_email):
- sig_commits.append(_significant_entry(c, msg))
+ sig_commits.append(_significant_entry(c, msg, forge))
if len(sig_commits) >= _MAX_SIGNIFICANT_COMMITS:
break
# Every commit is classified, so the category ratios cover the whole history.
@@ -598,19 +604,21 @@ def _add_commit_messages(meta: dict[str, Any], commits: list[_CommitRec]) -> Non
meta["commit_categories_json"] = json.dumps(dict(category_counts))
-def _significant_entry(c: _CommitRec, msg: str) -> dict[str, Any]:
+def _significant_entry(
+ c: _CommitRec, msg: str, forge: ForgeKind = ForgeKind.GENERIC
+) -> dict[str, Any]:
entry: dict[str, Any] = {
"sha": c.sha[:8],
"date": datetime.fromtimestamp(c.ts, tz=UTC).isoformat() if c.ts else "",
"message": msg,
"author": c.author_name,
}
- pr_match = _PR_NUMBER_RE.search(msg)
- if pr_match:
- pr_num = pr_match.group(1) or pr_match.group(2) or pr_match.group(3)
- entry["pr_number"] = int(pr_num)
# Squash-merge bodies carry the rationale the PR miner reads.
raw_body = getattr(c, "body", "") or ""
+ # The full subject: a squash suffix sits at its end, past the 200 kept.
+ pr_number = change_number(c.subject, raw_body, forge)
+ if pr_number is not None:
+ entry["pr_number"] = pr_number
if _body_carries_decision(c.subject, raw_body):
body = _truncate_body(raw_body)
if body:
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
index 5ab88da05..d093a4b25 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -20,6 +20,8 @@ from typing import Any
import structlog
+from repowise.core.forges import detect_forge
+
from ._constants import (
_DEEP_WALK_COMMIT_LIMIT,
_DEEP_WALK_MIN_FALLBACK,
@@ -187,6 +189,8 @@ class GitIndexer:
# naming files the repo excludes, and those rows outlive every prune.
self.record_episodes = record_episodes
self.max_workers = max_workers
+ # Read once: which forge's merge messages name a commit's PR or MR.
+ self.forge = detect_forge(self.repo_path)
import pathspec
@@ -333,6 +337,7 @@ class GitIndexer:
thread_repo,
file_path,
repo_path=self.repo_path,
+ forge=self.forge,
commit_limit=self.commit_limit,
follow_renames=self.follow_renames,
include_blame=include_blame,
@@ -689,6 +694,7 @@ class GitIndexer:
thread_repo,
file_path,
repo_path=self.repo_path,
+ forge=self.forge,
commit_limit=self.commit_limit,
follow_renames=self.follow_renames,
include_blame=include_blame,
@@ -873,6 +879,7 @@ class GitIndexer:
repo,
fp,
repo_path=self.repo_path,
+ forge=self.forge,
commit_limit=self.commit_limit,
follow_renames=self.follow_renames,
include_blame=False,
@@ -1362,6 +1369,7 @@ class GitIndexer:
repo,
file_path,
repo_path=self.repo_path,
+ forge=self.forge,
commit_limit=self.commit_limit,
follow_renames=self.follow_renames,
include_blame=self.tier.includes_blame,
diff --git a/tests/unit/ingestion/test_history_change_numbers.py b/tests/unit/ingestion/test_history_change_numbers.py
new file mode 100644
index 000000000..a8d92ea4d
--- /dev/null
+++ b/tests/unit/ingestion/test_history_change_numbers.py
@@ -0,0 +1,66 @@
+"""The PR or MR number stored on a file's significant commits, read per forge."""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.decisions.commit_mining import pr_commit_block
+from repowise.core.forges import ForgeKind, get_forge
+from repowise.core.ingestion.git_indexer import GitIndexer
+from repowise.core.ingestion.git_indexer.file_history import _significant_entry
+from repowise.core.ingestion.git_indexer.records import _CommitRec
+
+
+def _rec(subject: str, body: str = "") -> _CommitRec:
+ return _CommitRec("a" * 40, "Dev", "[email protected]", 1_700_000_000, False, subject, body)
+
+
+ ("forge", "subject", "body", "expected"),
+ [
+ (ForgeKind.GITHUB, "fix(x): y (#881) (#911)", "", 911),
+ (ForgeKind.GITHUB, "Fixes #12: crash on start", "", None),
+ (ForgeKind.GITHUB, "feat: add JVM PKCS#12 helper", "", None),
+ (ForgeKind.GITLAB, "feat: thing (!17)", "", 17),
+ (ForgeKind.GITHUB, "feat: thing (!17)", "", None),
+ (ForgeKind.GITLAB, "fix: a", "See merge request g/p!42", 42),
+ # A squash suffix past the 200 characters the stored message keeps.
+ (ForgeKind.GITHUB, "docs: " + "x" * 220 + " (#10154)", "", 10154),
+ ],
+)
+def test_the_stored_pr_number_is_the_change_the_commit_merged(
+ forge: ForgeKind, subject: str, body: str, expected: int | None
+) -> None:
+ entry = _significant_entry(_rec(subject, body), subject[:200], forge)
+ assert entry.get("pr_number") == expected
+
+
+def test_the_indexer_reads_its_forge_from_the_remote(tmp_path: Path) -> None:
+ subprocess.run(["git", "init", "-q", str(tmp_path)], check=True)
+ subprocess.run(
+ ["git", "-C", str(tmp_path), "remote", "add", "origin", "[email protected]:g/sub/p.git"],
+ check=True,
+ )
+ assert GitIndexer(tmp_path).forge is ForgeKind.GITLAB
+
+
+ ("forge", "label"),
+ [
+ (ForgeKind.GITHUB, "(#12)"),
+ (ForgeKind.GITLAB, "(!12)"),
+ (ForgeKind.AZURE, "(PR 12)"),
+ (ForgeKind.BITBUCKET, "(#12)"),
+ ],
+)
+def test_the_pr_prompt_labels_the_number_as_the_forge_writes_it(
+ forge: ForgeKind, label: str
+) -> None:
+ candidate = {"sha": "b" * 40, "subject": "s", "body": "b", "pr": 12}
+ block = pr_commit_block(candidate, ["a.py"], get_forge(forge))
+ assert f"--- Commit bbbbbbbb {label} ---" in block
+ no_pr = pr_commit_block({**candidate, "pr": None}, ["a.py"], get_forge(forge))
+ assert "--- Commit bbbbbbbb ---" in no_pr
diff --git a/tests/unit/persistence/test_decision_reverts.py b/tests/unit/persistence/test_decision_reverts.py
index eeaab8656..1107fb8cd 100644
--- a/tests/unit/persistence/test_decision_reverts.py
+++ b/tests/unit/persistence/test_decision_reverts.py
@@ -54,7 +54,7 @@ def history(tmp_path: Path) -> dict[str, str]:
c: dict[str, str] = {"root": str(repo)}
# Every file the cases below edit exists from the start, so each target is
# a modification; the add/delete cases at the end use files of their own.
- for name in ("pool", "cache", "retry", "strict", "tpl", "net", "save", "sort", "parser"):
+ for name in ("pool", "cache", "retry", "strict", "tpl", "net", "save", "sort", "parser", "loader"):
(repo / f"{name}.txt").write_text("start\n")
for name in ("legacy", "ci", "cfg", "misc", "metrics", "other", "settings", "log", "docs"):
(repo / f"{name}.txt").write_text("start\n")
@@ -97,6 +97,10 @@ def history(tmp_path: Path) -> dict[str, str]:
c["tense_target"] = _commit(repo, "Use a topological sort for ordering", "sort.txt")
_revert(repo, c["tense_target"])
_commit(repo, "Fixed #70 -- Used a topological sort for ordering.", "sort.txt")
+ # ... or closing the change a pull URL in the subject named.
+ c["url_target"] = _commit(repo, "Backport https://github.com/o/r/pull/55 to the loader", "loader.txt")
+ _revert(repo, c["url_target"])
+ _commit(repo, "Fixed #55 -- Backported the loader fix again", "loader.txt")
# ... or a second attempt under the same issue key, editing the same files;
c["retry_target"] = _commit(repo, "gh-80: Speed up the parser", "parser.txt")
_revert(repo, c["retry_target"])
@@ -170,6 +174,7 @@ def test_each_rule_links_its_target_and_nothing_else(history):
links = {(link.revert, link.target): link.rule for link in found if not link.relanded}
assert {link.target for link in found if link.relanded} >= {
history["retry_target"],
+ history["url_target"],
history["deleted_target"],
history["added_target"],
history["chain_revert"],
@@ -317,3 +322,40 @@ def test_an_abbreviated_sha_resolves_only_when_unique():
assert _resolve("abc1234", shas) is None
assert _resolve("abc1234f", shas) == shas[1]
assert _resolve("not-a-sha", shas) is None
+
+
+ ("remote", "linked"),
+ [("https://gitlab.com/g/p.git", True), ("https://github.com/o/r.git", False)],
+)
+def test_a_revert_names_a_gitlab_merge_request_by_its_shorthand(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, remote: str, linked: bool
+) -> None:
+ """The MR is the merge commit whose trailer names it; ``!N`` is read on GitLab only."""
+ for var in ("GITHUB_ACTIONS", "GITLAB_CI", "TF_BUILD", "BITBUCKET_BUILD_NUMBER"):
+ monkeypatch.delenv(var, raising=False)
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(repo, "init", "-q", "-b", "main")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "T")
+ _git(repo, "config", "commit.gpgsign", "false")
+ _git(repo, "remote", "add", "origin", remote)
+ _commit(repo, "Initial commit", "pool.txt")
+ _git(repo, "checkout", "-q", "-b", "feat")
+ _commit(repo, "Use a connection pool", "pool.txt")
+ _git(repo, "checkout", "-q", "main")
+ _git(
+ repo,
+ "merge",
+ "--no-ff",
+ "-q",
+ "-m",
+ "Merge branch 'feat' into 'main'\n\nUse a connection pool\n\nSee merge request g/p!42",
+ "feat",
+ )
+ merge = _git(repo, "rev-parse", "HEAD")
+ _commit(repo, "revert: drop the pool from !42, it leaks", "pool.txt")
+
+ links = find_revert_links(repo)
+ assert [(link.target, link.rule) for link in links] == ([(merge, "pr")] if linked else [])