Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions scripts/merge_check.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
"""Before a merge round: is a pull request already on main, and would merging it again duplicate text?

python -I scripts/merge_check.py [--main REF] [--json] [--min-length N] PR=REF [PR=REF ...]
python -I scripts/merge_check.py [--main REF] [--json] [--min-length N] [--depth N] PR=REF [PR=REF ...]

PR is the pull request number and REF its head (a branch, a fetched `refs/pull/PR/head`, a commit). For each one,
against `--main` (default `origin/main`), using one history scan for the whole batch:

- `merges`: first-parent commits on main whose subject is "Merge pull request #PR" or ends with " (#PR)" (squash
merges; "Revert ..." subjects are ignored), newest first. A number that is already there is the case the repeated
merges come from: a rebased copy merged again keeps both copies of what it added.
merges come from: a rebased copy merged again keeps both copies of what it added. The whole first-parent history
is searched, in one `git log` pass; `--depth N` limits it to the newest N commits, and a merge older than that
is then not found.
- `commits`: the PR's commits (merge base..REF) and how many `git cherry` finds on main already (same patch).
- `duplicates`: runs of three or more consecutive lines the merge would add (each at least `--min-length`
characters once stripped) that already stand in the same order in the same file on main. This is what a second
Expand Down Expand Up @@ -62,7 +64,10 @@ def _merged_pr_number(subject):


def prior_merges(repo, main, numbers, depth):
out = git(repo, "log", main, "--first-parent", f"-n{depth}", "--format=%H%x09%s").stdout
# The whole history unless --depth caps it: main outgrows any fixed window, and a merge that falls out of it
# leaves a rebased copy of its PR reading `clean`, the doubled-text case this script is for.
limit = [] if depth is None else [f"-n{depth}"]
out = git(repo, "log", main, "--first-parent", *limit, "--format=%H%x09%s").stdout
hits = {number: [] for number in numbers}
for line in out.splitlines():
sha, _, subject = line.partition("\t")
Expand Down Expand Up @@ -179,7 +184,8 @@ def main(argv=None):
ap.add_argument("--main", default="origin/main", help="the branch the round merges into (default origin/main)")
ap.add_argument("--repo", default=".", help="repository folder (default: the current one)")
ap.add_argument("--min-length", type=int, default=40, help="shortest stripped line counted as a duplicate (40)")
ap.add_argument("--depth", type=int, default=5000, help="first-parent commits searched for earlier merges (5000)")
ap.add_argument("--depth", type=int, default=None,
help="first-parent commits searched for earlier merges (default: the whole history)")
ap.add_argument("--json", action="store_true", help="one JSON report instead of text")
args = ap.parse_args(argv)
try:
Expand Down
37 changes: 37 additions & 0 deletions tests/test_merge_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,21 @@ def squash_merge(self, number, branch, subject=None):
title = subject or f"{branch}: add the effect record section"
self.git("commit", "-q", "-m", f"{title} (#{number})")

def add_commits_to_main(self, count):
"""`count` first-parent commits on main from one `git fast-import` (a `git commit` each would take minutes)."""
parts = []
for i in range(count):
message = f"other work {i}\n"
content = f"Unrelated work on main, step {i}, that never touches the notes file.\n"
parts.append(f"commit refs/heads/main\ncommitter Test <test@example.invalid> 1700000000 +0000\n"
f"data {len(message)}\n{message}")
if i == 0:
parts.append(f"from {self.git('rev-parse', 'main')}\n")
parts.append(f"M 100644 inline docs/other.md\ndata {len(content)}\n{content}\n")
r = subprocess.run(["git", "-C", self.repo, "fast-import", "--quiet"],
input="".join(parts).encode("utf-8"), capture_output=True)
self.assertEqual(r.returncode, 0, r.stderr.decode("utf-8", "replace"))

def run_check(self, *pairs):
out = io.StringIO()
with redirect_stdout(out):
Expand Down Expand Up @@ -303,6 +318,28 @@ def test_a_follow_up_commit_after_a_multi_commit_squash_merge_is_clean(self):
self.assertEqual(len(r["merges"]), 1)
self.assertEqual(r["commits"], {"total": 3, "on_main": 0})

def test_a_merge_older_than_the_old_5000_commit_window_is_found(self):
# main outgrows any fixed window. --depth used to default to 5000 first-parent commits, so a PR merged
# further back than that was not found, and a rebased copy of it read `clean` instead of `already-merged`.
base = self.git("rev-parse", "main")
self.pr_branch("early", base, "\n" + PARAGRAPH)
self.squash_merge(31, "early")
self.git("checkout", "-q", "-b", "early_copy", base)
self.append("docs/notes.md", "\n" + PARAGRAPH)
self.commit("early: add the effect record section (rebased)")
self.git("checkout", "-q", "main")
self.add_commits_to_main(5000)
code, [r] = self.run_check("31=early_copy")
self.assertEqual(code, 1)
self.assertEqual(r["verdict"], "already-merged")
self.assertEqual(len(r["merges"]), 1)
# A window that ends before the merge still misses it: --depth is the cap it says it is.
out = io.StringIO()
with redirect_stdout(out):
mc.main(["--repo", self.repo, "--main", "main", "--json", "--depth", "5000", "31=early_copy"])
[capped] = json.loads(out.getvalue())
self.assertEqual(capped["merges"], [])

def test_a_revert_commit_is_not_counted_as_a_prior_merge(self):
self.write("docs/other.md", "unrelated\n")
self.commit('Revert "pr: something (#24)"')
Expand Down