From 04fc8425742cf230aeb728549d958704a6920ed2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 20:48:22 +0000 Subject: [PATCH] Refuse a push of a branch whose pull request contains another open pull request A pull request based on main that was built on another open pull request lands both changes in one squash commit under one title and leaves the other open with nothing to add. Scripts/stacked-pull-request-check.py finds a branch whose open pull request holds the head commit of another and is not based on that one's branch, and the push hook runs it on the branch being pushed. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HLuVQLHq43QvdYBYGWTdSo --- .claude/hooks/lint-before-push.sh | 17 +++- .claude/rules/scripts.md | 1 + .github/workflows/ci.yml | 4 + Scripts/stacked-pull-request-check.py | 111 ++++++++++++++++++++++++++ 4 files changed, 132 insertions(+), 1 deletion(-) create mode 100755 Scripts/stacked-pull-request-check.py diff --git a/.claude/hooks/lint-before-push.sh b/.claude/hooks/lint-before-push.sh index 2d9e0b8f34..82bcc40aa7 100755 --- a/.claude/hooks/lint-before-push.sh +++ b/.claude/hooks/lint-before-push.sh @@ -1,6 +1,6 @@ #!/bin/bash # PreToolUse hook on Bash: block `git push`, `gh stack push|sync` and `gh pr create` when SwiftFormat --lint fails -# in the worktree the command runs in. Exit 2 blocks the command and shows stderr to Claude; exit 0 lets it run. +# in the worktree the command runs in, or when the branch's pull request contains another open pull request. Exit 2 blocks the command and shows stderr to Claude; exit 0 lets it run. set -u input=$(cat) case "$input" in @@ -23,4 +23,19 @@ if ! (cd "$root" && ./CLI/lint.sh --check >"$root/.build/swiftformat-lint.out" 2 } >&2 exit 2 fi +# A pull request never contains another open one (`.claude/rules/scripts.md`). A check that could not read GitHub +# (exit 2) lets the push through and says so; only a branch that breaks the rule (exit 1) blocks it. +if [[ -f "$root/Scripts/stacked-pull-request-check.py" ]]; then + stacked=$(cd "$root" && python3 -I Scripts/stacked-pull-request-check.py 2>&1) + case $? in + 1) + { + echo "The push was not run: this branch's pull request contains another open pull request." + echo "$stacked" + } >&2 + exit 2 + ;; + 2) echo "$stacked" >&2 ;; + esac +fi exit 0 diff --git a/.claude/rules/scripts.md b/.claude/rules/scripts.md index 6120610ff4..b7ff70d7e3 100644 --- a/.claude/rules/scripts.md +++ b/.claude/rules/scripts.md @@ -12,6 +12,7 @@ What each script is for. Read this before running or changing one, and before wr - `./CLI/lint.sh --check` reports what SwiftFormat would change and changes nothing. The committed `PreToolUse` hook (`.claude/hooks/lint-before-push.sh`, wired in `.claude/settings.json`) runs it before `git push`, `gh stack` and `gh pr create`, in the worktree the command runs in, and blocks the command when it fails. - `.claude/hooks/pre-push` is the same check as a git hook, for a session that started outside the checkout, where Claude Code loads no hook: `git config core.hooksPath .claude/hooks` in a clone (never `--global`, which replaces every other repository’s hooks) makes git refuse a push while `./CLI/lint.sh --check` fails or cannot run. `--self-test` runs inside `pre-review.py --self-test`. +- `Scripts/stacked-pull-request-check.py [--all | BRANCH]` exits 1 when a branch's open pull request contains the head commit of another open pull request and is not based on that one's branch. The rule: a pull request that builds on an open pull request takes that one's branch as its base, lands after it and never contains it, so that its diff shows only its own change, and two changes that must land together are one pull request from the start; `--all` checks every open pull request as GitHub has it. `lint-before-push.sh` runs it on the branch being pushed and blocks the push at exit 1; when GitHub cannot be read (exit 2) the push goes through with a line that the check did not run. The git hook does not run it. - `Scripts/changed-line-coverage.sh [--full] [--first REGEX]… [--no-rest] [--debug] [BASE]` runs the suites the change touches with coverage (every other test only for lines those leave, `--full` for the whole suite at once; `--first OneTest --no-rest --debug` is the loop for covering a line, seconds a try; generated code is not compiled unless `--compile-checks`), and prints every added or changed line under `Sources/` and `Plugins/` that no test executed (default base `upstream/main` where that remote exists, else `origin/main`). - `Scripts/fuzz-corpus.sh [--features …] [--seed N] [--iterations M|corpus] [--seeds N,N…] [--release]` runs the graph fuzzer's long run and prints its pin lines. - `Scripts/fuzzer-coverage-report.sh RUN [BASE]` lists the changed generator lines no fuzzer corpus graph executed, from a run's `fuzzer-coverage` artifact, against another base; `graph-fuzzer.yml`'s `coverage` input makes the report for a commit before review ("Coverage of a change" in `.claude/rules/fuzzer-corpora.md`). diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e4658d3b9..e2a3b83030 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4193,6 +4193,10 @@ jobs: # named only by reading the log of the step it was stopped in. - name: Check the Unfinished Tests Script Against Its Fixtures run: python3 -I Scripts/unfinished-tests.py --self-test + # The push hook refuses a branch whose pull request contains another + # open pull request; the rule it applies is checked here on stand-ins. + - name: Check the Stacked Pull Request Script Against Its Fixtures + run: python3 -I Scripts/stacked-pull-request-check.py --self-test # Scripts/changed-line-coverage.sh is how a change is checked before it # is pushed; its report of the files no report records must agree with # this job's, or a change passes there and fails here. diff --git a/Scripts/stacked-pull-request-check.py b/Scripts/stacked-pull-request-check.py new file mode 100755 index 0000000000..a4a251f90c --- /dev/null +++ b/Scripts/stacked-pull-request-check.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +""" +usage: stacked-pull-request-check.py [--all | BRANCH] + stacked-pull-request-check.py --self-test + +A pull request that builds on an open pull request takes that pull request's branch as its base, lands after it and +never contains it, so that its diff shows only its own change; two changes that must land together are one pull +request from the start. A pull request based on main that contains another's commits lands both in one squash commit +under one title, and leaves the other open with nothing to add. + +With no argument this checks the branch checked out here, as `.claude/hooks/lint-before-push.sh` does before a push, +and exits 1 when the branch has an open pull request that contains the head commit of another open pull request and +is not based on that one's branch. For a branch with no pull request yet it prints the base its pull request must take +and exits 0. BRANCH checks that branch's pull request as GitHub has it, and --all every open pull request. It exits 2 +when GitHub cannot be read, which is no pass: the hook then lets the push through and says the check did not run. +""" + +import json +import subprocess +import sys + + +def check(pulls, target, contains): + """Returns (whether `target` breaks the rule, the lines to print). `pulls` is the open pull requests as (number, + head branch, head commit, base branch); `target` is a head branch, with or without a pull request among them; + `contains(commit)` says whether `target` holds that commit.""" + own = next((pull for pull in pulls if pull[1] == target), None) + contained = [pull for pull in pulls if pull[1] != target and contains(pull[2])] + if not contained: + return False, [f"{target}: contains no other open pull request"] + if own is None: + return False, [f"{target}: contains {', '.join(f'#{number}' for number, _, _, _ in contained)}. Open its pull request with the branch of the one it builds on as its base ({' or '.join(branch for _, branch, _, _ in contained)}, whichever contains the other), not main."] + if any(branch == own[3] for _, branch, _, _ in contained): + return False, [f"{target} (#{own[0]}): based on {own[3]}, the pull request it builds on"] + return True, [f"{target} (#{own[0]}, base {own[3]}) contains the head of open pull request #{number} ({branch} {commit[:9]}). Change #{own[0]}'s base to {branch}, so that its diff shows only its own change, or make the two one pull request." for number, branch, commit, _ in contained] + + +def api(path): + result = subprocess.run(["gh", "api", f"repos/{{owner}}/{{repo}}/{path}"], capture_output=True, text=True) + if result.returncode != 0: + print(f"stacked-pull-request-check.py did NOT run: GitHub could not be read ({path}): {result.stderr.strip()[:300]}", file=sys.stderr) + raise SystemExit(2) + return json.loads(result.stdout) + + +def contains_on_github(inner, outer): + """Whether commit `inner` is `outer` or an ancestor of it, as GitHub has them.""" + return api(f"compare/{inner}...{outer}")["behind_by"] == 0 + + +def contains_here(commit, branch): + """Whether `commit` is HEAD or an ancestor of it, fetching its branch when the commit is not in this clone.""" + if subprocess.run(["git", "cat-file", "-e", f"{commit}^{{commit}}"], capture_output=True).returncode != 0: + subprocess.run(["git", "fetch", "--quiet", "origin", branch], capture_output=True) + return subprocess.run(["git", "merge-base", "--is-ancestor", commit, "HEAD"], capture_output=True).returncode == 0 + + +def self_test(): + failures = [] + + def expect(name, pulls, target, held, expected_failure, expected_text): + failed, lines = check(pulls, target, lambda commit: commit in held) + if failed != expected_failure or expected_text not in "\n".join(lines): + failures.append(f"{name}: expected {'a failure' if expected_failure else 'a pass'} that says {expected_text!r}, got {failed} and {lines}") + + first = (11, "first", "a" * 40, "main") + on_main = (12, "second", "b" * 40, "main") + on_first = (12, "second", "b" * 40, "first") + expect("a pull request on main that holds another's head", [first, on_main], "second", {first[2]}, True, "Change #12's base to first") + expect("a pull request based on the one it holds", [first, on_first], "second", {first[2]}, False, "based on first") + expect("a pull request that holds no other", [first, on_main], "second", set(), False, "contains no other open pull request") + expect("the pull request another one holds", [first, on_main], "first", set(), False, "contains no other open pull request") + expect("a branch with no pull request that holds one", [first], "third", {first[2]}, False, "Open its pull request with the branch of the one it builds on as its base (first") + expect("a branch with no pull request that holds none", [first], "third", set(), False, "contains no other open pull request") + expect("a pull request on main that holds two, one of them its base's own base", [first, on_first, (13, "third", "c" * 40, "main")], "third", {first[2], on_first[2]}, True, "Change #13's base to second") + expect("a pull request based on the outer of the two it holds", [first, on_first, (13, "third", "c" * 40, "second")], "third", {first[2], on_first[2]}, False, "based on second") + if failures: + print("\n".join(failures)) + return 1 + print("self-test passed") + return 0 + + +def main(arguments): + if arguments == ["--self-test"]: + return self_test() + if len(arguments) > 1 or (arguments and arguments[0].startswith("-") and arguments[0] != "--all"): + sys.exit(__doc__) + listed = [pull for page in (1, 2) for pull in api(f"pulls?state=open&per_page=100&page={page}")] + # An open pull request whose head is already on main holds nothing a branch could wrongly contain. + pulls = [(pull["number"], pull["head"]["ref"], pull["head"]["sha"], pull["base"]["ref"]) for pull in listed if not contains_on_github(pull["head"]["sha"], "main")] + branches = {branch: commit for _, branch, commit, _ in pulls} + names = {commit: branch for branch, commit in branches.items()} + if not arguments: + targets = [(subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], capture_output=True, text=True).stdout.strip(), lambda commit: contains_here(commit, names[commit]))] + else: + chosen = sorted(branches) if arguments[0] == "--all" else [arguments[0]] + missing = [branch for branch in chosen if branch not in branches] + if missing: + sys.exit(f"stacked-pull-request-check.py: {missing[0]} has no open pull request with commits of its own") + targets = [(branch, lambda commit, head=branches[branch]: contains_on_github(commit, head)) for branch in chosen] + failed = False + for target, contains in targets: + target_failed, lines = check(pulls, target, contains) + failed = failed or target_failed + print("\n".join(("FAIL " if target_failed else "") + line for line in lines)) + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:]))