From a3184a4755513ed6d0beceeb07439a25cf38dbd5 Mon Sep 17 00:00:00 2001 From: syfyra <258908070+syfyra@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:26:30 +0100 Subject: [PATCH] scripts: pr_overlap.py lists the open pull requests that change the same files (PR-OVERLAP-CHECK) There was no working way to find the open pull requests that touch a file: GitHub's search does not match pull requests by path, and with about 1,490 of them open, reading them is not an option. Work gets written twice, and the template's "Depends on:" line (every pull request this one conflicts with) is filled in from memory. scripts/pr_overlap.py asks git instead, with no API call and no token. The open pull requests are the ones the remote has a refs/pull/N/merge for; their heads are fetched into refs/pr-overlap/N, a namespace of the tool that follows the open set, so --no-fetch works offline. A pull request's files are those that differ between its head and its merge base with the base branch. With paths it lists the open pull requests that change them. With none it takes the branch's own files, committed or in the working tree, and says how the branch stands to each pull request that changes one: clean or conflict (git merge-tree, with the conflicting files), same, or included. AGENTS.md and CONTRIBUTING.md name it where they ask to check the open pull requests. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 4 + CONTRIBUTING.md | 5 + scripts/pr_overlap.py | 330 +++++++++++++++++++++++++++++++ tests/test_pr_overlap.py | 405 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 744 insertions(+) create mode 100644 scripts/pr_overlap.py create mode 100644 tests/test_pr_overlap.py diff --git a/AGENTS.md b/AGENTS.md index d6788158e4..5a6c21edc2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -61,6 +61,10 @@ loader that maps the game's executable and resolves its imports to shims. Nothin repository. The old open issues are indexed by title in [#18](https://github.com/ubiquitarianism/leonida/issues/18) and the old open pull requests are kept as `old-pr/` branches ([#17](https://github.com/ubiquitarianism/leonida/issues/17)). +- Searching GitHub for pull requests by path (`gh search prs 'path:...'`) returns nothing here, so ask git which + open pull requests change a file: `python -I scripts/pr_overlap.py ...`, before you start on it. + With no argument it takes what your branch changes and says which open pull requests conflict with it; those + belong on the `Depends on:` line as well. ## Before you guess, look diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1cd0b69083..6b596d495c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,6 +20,11 @@ but won't do it yourself? Post `finding: ` there, with where it is and list for others. When two pull requests overlap anyway, the one that lands first is merged and the other is asked to rebase or close. Pull requests target `main`. +GitHub's search does not find pull requests by the files they change. `python -I scripts/pr_overlap.py ...` lists the open pull requests that change them, from git alone (no token, no API call). Run with no +argument on your branch, it lists the ones that change what the branch changes and says which of them it conflicts +with, which is what the template's `Depends on:` line asks for. + The original repository (`ItsNotRexed/Leonida`) went private on 23 November 2026, and its issues and pull requests went with it. A `#N` in the docs, in a code comment or in a commit message from before that date is an **old** number and links nowhere now, including the two this page used to send you to: #166 (GPU test results) and #313 diff --git a/scripts/pr_overlap.py b/scripts/pr_overlap.py new file mode 100644 index 0000000000..04613067d5 --- /dev/null +++ b/scripts/pr_overlap.py @@ -0,0 +1,330 @@ +"""Which open pull requests change the files you are about to change, and does your branch merge with them? + + python -I scripts/pr_overlap.py [PATH ...] [--base REF] [--head REF] [--remote NAME] [--no-fetch] [--json] + +GitHub's search does not find pull requests by the path they change, and with more than a thousand of them open, +reading them is not an option. This asks git instead, with no API call and no token: + +- The open pull requests are the ones the remote has a `refs/pull/N/merge` for: GitHub keeps that ref while a pull + request is open and removes it when it is merged or closed. One `git ls-remote` lists them with their heads. +- The heads are fetched into `refs/pr-overlap/N`, a namespace of this tool. Refs of pull requests that are no longer + open are deleted, so the namespace is the open set as of the last run, and `--no-fetch` works from it offline. +- A pull request's files are the ones that differ between its head and its merge base with `--base` (default + `origin/main`), so what `main` changed since the pull request branched is not counted as the pull request's. + +With PATHs (files or folders, relative to the current folder inside the repository, spelled as git spells them) it +lists the open pull requests that change any of them: the check to run before starting on a file. + +With no PATH it takes your own work: the files `--head` (default HEAD) changes against its merge base with `--base` +and, for HEAD, the files modified or untracked in the working tree. For each pull request that changes one of them +it says how `--head` stands to it: + +- `clean` or `conflict`: what `git merge-tree` says about merging the two (git 2.38 or newer; committed work only), + with the files that conflict. These are the pull requests the template's `Depends on:` line asks for. +- `same`: the pull request's head is `--head`; it is this branch's own pull request. +- `included`: the pull request's head is an ancestor of `--head`: the branch is built on it, or it is this + branch's own pull request with commits not pushed yet. +- `unknown`: git could not try the merge (an older git, or no common history). + +A pull request opened seconds ago can be missing: GitHub writes its merge ref a moment after it is opened. Titles +and authors' logins are not in git, so a pull request is shown with the author name, date and subject of its head +commit. A shallow clone has no merge base for most pull requests: they are counted as skipped, and the report says +that `git fetch --unshallow` is what it needs. + +Exit 0 when it ran, whatever it found; 2 on a usage or git error. It writes refs under `refs/pr-overlap/` and +nothing else. Standard library only; needs git 2.29 or newer for `fetch --stdin`. No game files. +""" +import argparse +import json +import os +import re +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor + +NAMESPACE = "refs/pr-overlap/" +PULL_REF = re.compile(r"refs/pull/(\d+)/(head|merge)") +SHOWN_FILES = 6 + + +class GitError(Exception): + pass + + +def git(repo, *args, check=True, stdin=None): + try: + r = subprocess.run(["git", "-C", repo, *args], capture_output=True, + input=None if stdin is None else stdin.encode("utf-8")) + except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback + raise GitError(f"cannot run git: {e.strerror or e}") from None + r.stdout = r.stdout.decode("utf-8", "replace") + r.stderr = r.stderr.decode("utf-8", "replace") + if check and r.returncode != 0: + raise GitError(f"git {' '.join(args)}: {r.stderr.strip() or r.returncode}") + return r + + +def commit(repo, ref): + """The commit `ref` names, or '' when it names none.""" + return git(repo, "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}", check=False).stdout.strip() + + +def names(text): + """The paths of a NUL-separated list, as `-z` prints them.""" + return [p for p in text.split("\0") if p] + + +def default_remote(repo, base): + """The remote `base` is a branch of (`origin/main` -> `origin`), or `origin`.""" + name, slash, _ = base.partition("/") + return name if slash and name in git(repo, "remote").stdout.split() else "origin" + + +def remote_pull_requests(repo, remote): + """({number: head sha} of the open pull requests, how many pull request heads the remote has at all).""" + heads, is_open = {}, set() + for line in git(repo, "ls-remote", remote, "refs/pull/*/head", "refs/pull/*/merge").stdout.splitlines(): + sha, _, ref = line.partition("\t") + m = PULL_REF.fullmatch(ref.strip()) + if not m: + continue + if m.group(2) == "head": + heads[int(m.group(1))] = sha + else: + is_open.add(int(m.group(1))) + return {n: heads[n] for n in sorted(is_open) if n in heads}, len(heads) + + +def local_pull_requests(repo): + """{number: head sha} of the refs this tool keeps.""" + out = git(repo, "for-each-ref", "--format=%(objectname) %(refname)", NAMESPACE).stdout + found = {} + for line in out.splitlines(): + sha, _, ref = line.partition(" ") + number = ref[len(NAMESPACE):] + if number.isdigit(): + found[int(number)] = sha + return dict(sorted(found.items())) + + +def sync(repo, remote): + """Make refs/pr-overlap/ the remote's open pull requests. Returns (open, fetched, removed, heads on the remote).""" + wanted, total = remote_pull_requests(repo, remote) + have = local_pull_requests(repo) + new = [n for n, sha in wanted.items() if have.get(n) != sha] + stale = [n for n in have if n not in wanted] + if new: + if len(new) > 50: + print(f"pr_overlap: fetching {len(new)} pull request heads from {remote}", file=sys.stderr) + # No tags, no submodules and no FETCH_HEAD: the fetch is for this namespace alone. + git(repo, "fetch", "--quiet", "--no-tags", "--no-recurse-submodules", "--no-write-fetch-head", "--stdin", + remote, stdin="".join(f"+refs/pull/{n}/head:{NAMESPACE}{n}\n" for n in new)) + if stale: + git(repo, "update-ref", "--stdin", stdin="".join(f"delete {NAMESPACE}{n}\n" for n in stale)) + return local_pull_requests(repo), len(new), len(stale), total + + +def changed_files(repo, base, ref): + """The files `ref` changes against its merge base with `base`; None when the two share no history. A rename + counts as both of its paths: whoever works on the old name is affected as well.""" + r = git(repo, "diff", "--name-only", "--no-renames", "-z", f"{base}...{ref}", check=False) + return names(r.stdout) if r.returncode == 0 else None + + +def own_files(repo, base, head): + files = changed_files(repo, base, head) + if files is None: + raise GitError(f"{head} and {base} have no merge base") + work = [] + if head == "HEAD": + work = names(git(repo, "diff", "--name-only", "--no-renames", "-z", "HEAD").stdout) + work += names(git(repo, "ls-files", "--others", "--exclude-standard", "-z").stdout) + return sorted(set(files) | set(work)), sorted(set(work) - set(files)) + + +def repo_paths(top, paths): + """PATH arguments as repository paths with forward slashes; '' is the whole repository.""" + top = os.path.realpath(top) + cwd = os.path.realpath(os.getcwd()) + try: + inside = os.path.normcase(os.path.commonpath([top, cwd])) == os.path.normcase(top) + except ValueError: # another drive + inside = False + found = [] + for path in paths: + full = os.path.realpath(os.path.join(cwd if inside else top, path)) + try: + rel = os.path.relpath(full, top) + except ValueError: + rel = os.pardir + if rel == os.pardir or rel.startswith(os.pardir + os.sep): + raise GitError(f"{path} is not inside the repository {top}") + found.append("" if rel == os.curdir else rel.replace(os.sep, "/")) + return found + + +def touches(path, targets): + return any(not t or path == t or path.startswith(t + "/") for t in targets) + + +def is_ancestor(repo, old, new): + return git(repo, "merge-base", "--is-ancestor", old, new, check=False).returncode == 0 + + +def standing(repo, head_sha, pr_sha): + """How the branch at head_sha stands to a pull request head: (word, conflicting files).""" + if pr_sha == head_sha: + return "same", [] + if is_ancestor(repo, pr_sha, head_sha): + return "included", [] + r = git(repo, "merge-tree", "--write-tree", "--name-only", "--no-messages", "-z", head_sha, pr_sha, check=False) + if r.returncode == 0: + return "clean", [] + if r.returncode == 1: + return "conflict", names(r.stdout)[1:] # the first field is the tree of the conflicted merge + return "unknown", [] + + +def describe(repo, sha): + author, date, subject = (git(repo, "log", "-1", "--format=%an%x00%as%x00%s", sha).stdout.rstrip("\n") + .split("\0") + ["", "", ""])[:3] + return {"author": author, "date": date, "subject": subject} + + +def survey(repo, base, pulls, targets, head_sha, jobs): + """The open pull requests that change a target path, with how head_sha stands to each (None: paths only).""" + def one(item): + number, sha = item + files = changed_files(repo, base, sha) + if files is None: + return {"number": number, "head": sha, "unrelated": True} + shared = [p for p in files if touches(p, targets)] + if not shared: + return None + found = {"number": number, "head": sha, **describe(repo, sha), "files": shared, "changed_files": len(files)} + if head_sha: + found["merge"], found["conflicts"] = standing(repo, head_sha, sha) + return found + + with ThreadPoolExecutor(max_workers=jobs) as pool: + results = [r for r in pool.map(one, pulls.items()) if r] + return [r for r in results if not r.get("unrelated")], sum(1 for r in results if r.get("unrelated")) + + +ORDER = {"conflict": 0, "unknown": 1, "clean": 2, "included": 3, "same": 4, None: 5} + + +def listing(paths, limit=SHOWN_FILES): + return ", ".join(paths[:limit]) + (f" and {len(paths) - limit} more" if len(paths) > limit else "") + + +def print_report(report): + found, by = report["pull_requests"], {} + for pr in found: + by.setdefault(pr.get("merge"), []).append(f"#{pr['number']}") + print(f"{report['open']} open pull request(s) on {report['remote']}" + + (" as of the last fetch" if report["fetched"] is None else + f" ({report['fetched']} head(s) fetched, {report['removed']} no longer open)")) + if report["mode"] == "paths": + print(f"paths: {listing([p or '(the whole repository)' for p in report['paths']])}") + else: + print(f"{len(report['files'])} file(s) changed by {report['head']} against {report['base']}" + + (f", {len(report['uncommitted'])} of them only in the working tree" if report["uncommitted"] else "") + + (f": {listing(report['files'])}" if report["files"] else "")) + if report["unrelated"]: + print(f"{report['unrelated']} pull request(s) share no history with {report['base']} and were skipped" + + (": this clone is shallow, and `git fetch --unshallow` brings the history a merge base needs" + if report["shallow"] else "")) + print() + for pr in found: + word = f"{pr['merge']:<9}" if report["mode"] == "branch" else "" + print(f"#{pr['number']:<6}{word}{pr['date']} {pr['author']}: {pr['subject']}") + print(f" {listing(pr['files'])}" + (f" ({pr['changed_files']} files in all)" + if pr["changed_files"] > len(pr["files"]) else "")) + if pr.get("conflicts"): + print(f" conflicts in: {listing(pr['conflicts'])}") + if found: + print() + if report["mode"] == "paths": + print(f"{len(found)} open pull request(s) change these paths.") + return + if not report["files"]: + print(f"Nothing here differs from {report['base']}. Name the files or folders you plan to change to see " + "which open pull requests change them.") + return + others = [pr for pr in found if pr["merge"] not in ("same", "included")] + print(f"{len(others)} other open pull request(s) change these files" + + "".join(f"; {len(by[word])} {text}: {', '.join(by[word])}" for word, text in ( + ("conflict", "conflict with this branch"), ("clean", "merge cleanly with it"), + ("unknown", "could not be merged for the check")) if word in by) + ".") + for word, text in (("same", "is this branch's own pull request"), + ("included", "is already in this branch (it builds on it, or it is its own pull request)")): + for number in by.get(word, []): + print(f"{number} {text}.") + if report["uncommitted"] and others: + print("The merge check covers committed work only; the working tree's changes are not in it.") + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.strip().splitlines()[0]) + ap.add_argument("paths", nargs="*", metavar="PATH", + help="files or folders to look up; with none, the files of --head and of the working tree") + ap.add_argument("--base", default="origin/main", help="the branch pull requests merge into (default origin/main)") + ap.add_argument("--head", default="HEAD", help="your branch, when no PATH is given (default HEAD)") + ap.add_argument("--remote", help="remote name or URL that has the pull requests (default: the remote of --base)") + ap.add_argument("--repo", default=".", help="repository folder (default: the current one)") + ap.add_argument("--no-fetch", action="store_true", + help="do not contact the remote: use the heads the last run fetched") + ap.add_argument("--jobs", type=int, default=min(16, os.cpu_count() or 4), help="git processes at once") + ap.add_argument("--json", action="store_true", help="one JSON report instead of text") + args = ap.parse_args(argv) + if args.jobs < 1: + ap.error("--jobs must be at least 1") + try: + top = git(args.repo, "rev-parse", "--show-toplevel").stdout.strip() + if not commit(top, args.base): + raise GitError(f"--base {args.base} is not a commit here (git fetch first?)") + remote = args.remote or default_remote(top, args.base) + report = {"remote": remote, "base": args.base, "fetched": None, "removed": None, "open": 0} + # What to look up comes first: a mistyped path or branch should not cost a fetch. + if args.paths: + report.update(mode="paths", paths=repo_paths(top, args.paths)) + targets, head_sha = report["paths"], None + else: + head_sha = commit(top, args.head) + if not head_sha: + raise GitError(f"--head {args.head} is not a commit here") + files, uncommitted = own_files(top, args.base, args.head) + report.update(mode="branch", head=args.head, head_sha=head_sha, files=files, uncommitted=uncommitted) + targets = files + if args.no_fetch: + pulls = local_pull_requests(top) + if not pulls: + raise GitError("no pull request heads here yet: run once without --no-fetch") + else: + pulls, report["fetched"], report["removed"], total = sync(top, remote) + if not total: + print(f"pr_overlap: {remote} has no pull request refs. Is it a fork? Name the repository the pull " + "requests are opened against with --remote (a remote name or its URL).", file=sys.stderr) + report["open"] = len(pulls) + found, report["unrelated"] = survey(top, args.base, pulls, targets, head_sha, args.jobs) if targets else ([], 0) + report["pull_requests"] = sorted(found, key=lambda pr: (ORDER[pr.get("merge")], pr["number"])) + # A shallow clone (the usual checkout of a CI job or an agent's sandbox) has no merge base to offer. + report["shallow"] = bool(report["unrelated"]) and ( + git(top, "rev-parse", "--is-shallow-repository", check=False).stdout.strip() == "true") + except GitError as e: + print(f"pr_overlap: {e}", file=sys.stderr) + return 2 + if args.json: + print(json.dumps(report, indent=2)) + else: + print_report(report) + return 0 + + +if __name__ == "__main__": + try: + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tests/test_pr_overlap.py b/tests/test_pr_overlap.py new file mode 100644 index 0000000000..2553259100 --- /dev/null +++ b/tests/test_pr_overlap.py @@ -0,0 +1,405 @@ +"""scripts/pr_overlap.py on throwaway git repositories (no network, no game data). + + python -I tests/test_pr_overlap.py + +An "upstream" repository gets pull request refs the way GitHub lays them out: refs/pull/N/head for every pull request +and refs/pull/N/merge only while it is open. The script runs in a clone of it, where a branch plays the contributor's +own work. +""" +import contextlib +import io +import json +import os +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) + +import pr_overlap # noqa: E402 + +PAGE = "".join(f"line {i}\n" for i in range(1, 13)) + + +def page(**changed): + """PAGE with some lines replaced: page(line5="mine") changes the fifth line.""" + lines = PAGE.splitlines(keepends=True) + for key, text in changed.items(): + lines[int(key[4:]) - 1] = text + "\n" + return "".join(lines) + + +class PrOverlapTest(unittest.TestCase): + def setUp(self): + td = tempfile.TemporaryDirectory(prefix="leonida pr_overlap ") + self.addCleanup(td.cleanup) + self.root = td.name + env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + env.update({"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "XDG_CONFIG_HOME": td.name}) + patcher = mock.patch.dict(os.environ, env, clear=True) + patcher.start() + self.addCleanup(patcher.stop) + self.upstream = os.path.join(self.root, "upstream") + self.clone = os.path.join(self.root, "clone") + os.mkdir(self.upstream) + self.git(self.upstream, "init", "-q", "-b", "main") + for path, text in (("viewer/index.html", PAGE), ("viewer/studio.html", PAGE), ("tools/a.py", "a = 1\n"), + ("docs/world.md", "# World\n")): + self.write(self.upstream, path, text) + self.commit(self.upstream, "start") + self.git(self.root, "clone", "-q", self.upstream, self.clone) + + def git(self, repo, *args): + r = subprocess.run(["git", "-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "-c", "commit.gpgsign=false", "-c", "protocol.file.allow=always", "-C", repo, *args], + capture_output=True, encoding="utf-8") + self.assertEqual(r.returncode, 0, r.stderr) + return r.stdout.strip() + + def write(self, repo, path, text): + full = os.path.join(repo, path) + os.makedirs(os.path.dirname(full), exist_ok=True) + with open(full, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + + def commit(self, repo, message): + self.git(repo, "add", "-A") + self.git(repo, "commit", "-q", "-m", message) + return self.git(repo, "rev-parse", "HEAD") + + def pull(self, number, changes, subject=None, is_open=True, base="main"): + """A pull request in upstream: a commit on `base` that writes `changes`, with the refs GitHub would keep.""" + self.git(self.upstream, "checkout", "-q", "--detach", base) + for path, text in changes.items(): + self.write(self.upstream, path, text) + sha = self.commit(self.upstream, subject or f"change for pull request {number}") + self.git(self.upstream, "update-ref", f"refs/pull/{number}/head", sha) + if is_open: + # GitHub's test merge is a commit of its own. Which one does not matter here, only that it is not the + # head: the script must take a pull request's commit from the head ref. + self.git(self.upstream, "update-ref", f"refs/pull/{number}/merge", + self.git(self.upstream, "rev-parse", "main")) + self.git(self.upstream, "checkout", "-q", "main") + return sha + + def close(self, number): + self.git(self.upstream, "update-ref", "-d", f"refs/pull/{number}/merge") + + def run_tool(self, *args, repo=None): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = pr_overlap.main(["--repo", repo or self.clone, *args]) + return code, out.getvalue(), err.getvalue() + + def report(self, *args, **kwargs): + code, out, err = self.run_tool("--json", *args, **kwargs) + self.assertEqual(code, 0, err) + return json.loads(out) + + def numbers(self, *args, **kwargs): + return [pr["number"] for pr in self.report(*args, **kwargs)["pull_requests"]] + + def kept_refs(self): + out = self.git(self.clone, "for-each-ref", "--format=%(refname) %(objectname)", "refs/pr-overlap/") + return dict(line.split(" ") for line in out.splitlines()) + + def four_pull_requests(self): + return {1: self.pull(1, {"viewer/index.html": page(line5="pull request 1")}, "viewer: one"), + 2: self.pull(2, {"tools/a.py": "a = 2\n", "viewer2/x.txt": "x\n"}, "tools: two"), + 3: self.pull(3, {"viewer/index.html": page(line2="closed")}, "viewer: three", is_open=False), + 4: self.pull(4, {"viewer/new.js": "new\n", "docs/world.md": "# World\n\nMore.\n"}, "viewer: four")} + + +class PathsTest(PrOverlapTest): + def test_paths_find_the_open_pull_requests_that_change_them(self): + self.four_pull_requests() + report = self.report("viewer/index.html") + self.assertEqual((report["mode"], report["open"], report["paths"]), ("paths", 3, ["viewer/index.html"])) + # Pull request 3 changes the file too, but it is closed: it has no merge ref. + self.assertEqual([(pr["number"], pr["files"], pr["changed_files"]) for pr in report["pull_requests"]], + [(1, ["viewer/index.html"], 1)]) + self.assertNotIn("merge", report["pull_requests"][0]) + # A folder takes everything below it, and only that: viewer2/x.txt is not in viewer. + self.assertEqual(self.numbers("viewer"), [1, 4]) + self.assertEqual(self.report("viewer")["pull_requests"][1]["files"], ["viewer/new.js"]) + self.assertEqual(self.numbers("viewer/"), [1, 4]) + self.assertEqual(self.numbers("viewer2"), [2]) + self.assertEqual(self.numbers("docs/world.md", "tools/a.py"), [2, 4]) + self.assertEqual(self.numbers("viewer/studio.html"), []) + self.assertEqual(self.numbers("."), [1, 2, 4]) + + def test_a_pull_request_is_shown_by_its_head_commit(self): + sha = self.pull(1, {"viewer/index.html": page(line5="x")}, "viewer: a subject (SOME-ID)") + pr, = self.report("viewer")["pull_requests"] + self.assertEqual((pr["head"], pr["author"], pr["subject"]), (sha, "Test", "viewer: a subject (SOME-ID)")) + self.assertRegex(pr["date"], r"^\d{4}-\d\d-\d\d$") + code, out, _ = self.run_tool("viewer") + self.assertEqual(code, 0) + self.assertIn(f"#1 {pr['date']} Test: viewer: a subject (SOME-ID)\n viewer/index.html\n", out) + self.assertIn("1 open pull request(s) change these paths.", out) + # The report above fetched the head already. + self.assertIn("1 open pull request(s) on origin (0 head(s) fetched, 0 no longer open)", out) + + def test_what_main_changed_since_is_not_the_pull_requests(self): + self.pull(1, {"tools/a.py": "a = 2\n"}) + self.write(self.upstream, "docs/world.md", "# World\n\nChanged on main after the pull request branched.\n") + self.commit(self.upstream, "main moves on") + self.git(self.clone, "fetch", "-q", "origin") + # A two-dot diff of main against the old branch would list docs/world.md as well. + self.assertEqual(self.numbers("docs/world.md"), []) + self.assertEqual(self.report("tools")["pull_requests"][0]["files"], ["tools/a.py"]) + + def test_a_rename_counts_for_the_old_and_the_new_path(self): + self.git(self.upstream, "checkout", "-q", "--detach", "main") + self.git(self.upstream, "mv", "viewer/studio.html", "viewer/inspector.html") + sha = self.commit(self.upstream, "rename the studio page") + for kind in ("head", "merge"): + self.git(self.upstream, "update-ref", f"refs/pull/1/{kind}", sha) + self.git(self.upstream, "checkout", "-q", "main") + self.assertEqual(self.numbers("viewer/studio.html"), [1]) + self.assertEqual(self.numbers("viewer/inspector.html"), [1]) + self.assertEqual(self.report("viewer")["pull_requests"][0]["files"], + ["viewer/inspector.html", "viewer/studio.html"]) + + def test_paths_are_relative_to_the_current_folder_inside_the_repository(self): + odd = "docs/with space/ünï.md" + self.four_pull_requests() + self.pull(5, {odd: "text\n"}) + with contextlib.chdir(os.path.join(self.clone, "viewer")): + self.assertEqual(self.report("index.html")["paths"], ["viewer/index.html"]) + self.assertEqual(self.numbers("index.html"), [1]) + self.assertEqual(self.numbers(".."), [1, 2, 4, 5]) + self.assertEqual(self.numbers(os.path.join("..", "tools")), [2]) + # From outside the repository a path is relative to its root; names need not be ASCII or free of spaces. + self.assertEqual(self.report(odd)["pull_requests"][0]["files"], [odd]) + self.assertIn(odd, self.run_tool("docs")[1]) + code, _, err = self.run_tool(os.path.join("..", "elsewhere")) + self.assertEqual(code, 2) + self.assertIn("is not inside the repository", err) + + def test_a_pull_request_without_common_history_is_counted_not_listed(self): + self.pull(1, {"viewer/index.html": page(line5="x")}) + self.git(self.upstream, "checkout", "-q", "--orphan", "island") + sha = self.commit(self.upstream, "another history") + self.git(self.upstream, "update-ref", "refs/pull/2/head", sha) + self.git(self.upstream, "update-ref", "refs/pull/2/merge", sha) + self.git(self.upstream, "checkout", "-q", "main") + report = self.report("viewer") + self.assertEqual((report["open"], report["unrelated"], [pr["number"] for pr in report["pull_requests"]]), + (2, 1, [1])) + self.assertIn("1 pull request(s) share no history with origin/main and were skipped", + self.run_tool("viewer")[1]) + + + def test_a_shallow_clone_is_told_why_nothing_was_found(self): + self.pull(1, {"viewer/index.html": page(line5="x")}) + self.write(self.upstream, "tools/a.py", "a = 3\n") + self.commit(self.upstream, "main moves on") + shallow = os.path.join(self.root, "shallow") + self.git(self.root, "clone", "-q", "--depth", "1", "file://" + self.upstream.replace(os.sep, "/"), shallow) + report = self.report("viewer", repo=shallow) + self.assertEqual((report["open"], report["unrelated"], report["shallow"], report["pull_requests"]), + (1, 1, True, [])) + self.assertIn("1 pull request(s) share no history with origin/main and were skipped: this clone is shallow, " + "and `git fetch --unshallow` brings the history a merge base needs", + self.run_tool("viewer", repo=shallow)[1]) + # In a full clone the same pull request is found, and nothing is said about shallowness. + report = self.report("viewer") + self.assertEqual((report["unrelated"], report["shallow"], [pr["number"] for pr in report["pull_requests"]]), + (0, False, [1])) + + +class BranchTest(PrOverlapTest): + def work(self): + """The contributor's branch: two commits, a modified file and an untracked one.""" + self.git(self.clone, "checkout", "-q", "-b", "work") + self.write(self.clone, "viewer/index.html", page(line5="mine")) + self.commit(self.clone, "viewer: my change") + self.write(self.clone, "tests/new_test.py", "mine = True\n") + head = self.commit(self.clone, "tests: my test") + self.write(self.clone, "docs/world.md", "# World\n\nNot committed yet.\n") + self.write(self.clone, "notes/todo.txt", "untracked\n") + # Edited again since its commit: a file of the branch, not one that is only in the working tree. + self.write(self.clone, "tests/new_test.py", "mine = True # and more\n") + return head + + def test_the_branchs_files_and_how_it_merges_with_each_pull_request(self): + head = self.work() + self.pull(1, {"viewer/index.html": page(line5="theirs")}, "same line") + self.pull(2, {"viewer/index.html": page(line11="theirs")}, "another line") + self.pull(3, {"docs/world.md": "# World\n\nTheirs.\n"}, "the file modified in the working tree") + self.pull(4, {"tests/new_test.py": "theirs = True\n"}, "the same new file") + self.pull(5, {"notes/todo.txt": "theirs\n"}, "the untracked file") + self.pull(6, {"tools/a.py": "a = 6\n"}, "a file the branch leaves alone") + self.pull(7, {"viewer/index.html": page(line5="closed")}, "closed", is_open=False) + report = self.report() + self.assertEqual((report["mode"], report["head"], report["head_sha"], report["open"]), + ("branch", "HEAD", head, 6)) + self.assertEqual(report["files"], ["docs/world.md", "notes/todo.txt", "tests/new_test.py", "viewer/index.html"]) + self.assertEqual(report["uncommitted"], ["docs/world.md", "notes/todo.txt"]) + # Conflicts first, then by number. The merge is of commits: the working tree's files overlap but cannot + # conflict. + self.assertEqual([(pr["number"], pr["merge"], pr["conflicts"]) for pr in report["pull_requests"]], + [(1, "conflict", ["viewer/index.html"]), (4, "conflict", ["tests/new_test.py"]), + (2, "clean", []), (3, "clean", []), (5, "clean", [])]) + code, out, _ = self.run_tool() + self.assertEqual(code, 0) + self.assertIn("4 file(s) changed by HEAD against origin/main, 2 of them only in the working tree: " + "docs/world.md, notes/todo.txt, tests/new_test.py, viewer/index.html", out) + self.assertRegex(out, r"#1 conflict \d{4}-\d\d-\d\d Test: same line\n viewer/index.html\n" + r" conflicts in: viewer/index.html\n") + self.assertIn("5 other open pull request(s) change these files; 2 conflict with this branch: #1, #4; " + "3 merge cleanly with it: #2, #3, #5.", out) + self.assertIn("The merge check covers committed work only", out) + + def test_another_head_is_compared_without_the_working_tree(self): + self.work() + self.pull(1, {"viewer/index.html": page(line5="theirs")}) + self.pull(3, {"docs/world.md": "# World\n\nTheirs.\n"}) + self.git(self.clone, "branch", "other", "HEAD~1") + report = self.report("--head", "other") + self.assertEqual((report["files"], report["uncommitted"]), (["viewer/index.html"], [])) + self.assertEqual([(pr["number"], pr["merge"]) for pr in report["pull_requests"]], [(1, "conflict")]) + self.assertNotIn("committed work only", self.run_tool("--head", "other")[1]) + + def test_the_branchs_own_pull_request_and_one_it_is_built_on(self): + self.work() + self.git(self.clone, "stash", "-q", "--include-untracked") + self.git(self.clone, "push", "-q", "origin", "HEAD:refs/pull/8/head", "HEAD:refs/pull/8/merge") + self.pull(2, {"viewer/index.html": page(line11="theirs")}) + def standing(): + return [(pr["number"], pr["merge"]) for pr in self.report()["pull_requests"]] + + self.assertEqual(standing(), [(2, "clean"), (8, "same")]) + out = self.run_tool()[1] + self.assertIn("1 other open pull request(s) change these files; 1 merge cleanly with it: #2.", out) + self.assertIn("#8 is this branch's own pull request.", out) + # A commit that is not pushed yet: the pull request's head is now behind the branch. + self.write(self.clone, "tools/a.py", "a = 8\n") + self.commit(self.clone, "one more") + self.assertEqual(standing(), [(2, "clean"), (8, "included")]) + self.assertIn("#8 is already in this branch", self.run_tool()[1]) + + def test_a_branch_without_changes_has_nothing_to_compare(self): + self.pull(1, {"viewer/index.html": page(line5="theirs")}) + report = self.report() + self.assertEqual((report["files"], report["pull_requests"]), ([], [])) + out = self.run_tool()[1] + self.assertIn("0 file(s) changed by HEAD against origin/main", out) + self.assertIn("Name the files or folders you plan to change", out) + + def test_a_pull_request_that_is_on_main_already_changes_nothing(self): + # GitHub removes the merge ref of a merged pull request; one that still has it must not be listed either, + # since its head is its own merge base with main. + sha = self.pull(1, {"viewer/index.html": page(line5="merged")}) + self.git(self.upstream, "merge", "-q", "--no-ff", "-m", "Merge pull request #1", sha) + self.git(self.clone, "pull", "-q", "origin", "main") + self.git(self.clone, "checkout", "-q", "-b", "work") + self.write(self.clone, "viewer/index.html", page(line5="merged", line9="mine")) + self.commit(self.clone, "mine") + self.assertEqual(self.report()["open"], 1) + self.assertEqual(self.numbers(), []) + self.assertEqual(self.numbers("viewer"), []) + + +class RefsTest(PrOverlapTest): + def test_the_kept_refs_are_the_open_pull_requests_of_the_last_run(self): + shas = self.four_pull_requests() + self.git(self.upstream, "tag", "v1", shas[1]) + report = self.report("viewer") + self.assertEqual((report["open"], report["fetched"], report["removed"]), (3, 3, 0)) + self.assertEqual(self.kept_refs(), {f"refs/pr-overlap/{n}": shas[n] for n in (1, 2, 4)}) + # Nothing else is touched: no tags, no FETCH_HEAD. + self.assertEqual(self.git(self.clone, "tag"), "") + self.assertFalse(os.path.exists(os.path.join(self.clone, ".git", "FETCH_HEAD"))) + + # Pull request 1 closes, 2 gets a new commit, 9 is opened; 4 stays as it is. + self.close(1) + moved = self.pull(2, {"tools/a.py": "a = 22\n", "viewer/studio.html": page(line3="two")}, + base="refs/pull/2/head") + opened = self.pull(9, {"viewer/index.html": page(line7="nine")}) + report = self.report("viewer") + self.assertEqual((report["open"], report["fetched"], report["removed"]), (3, 2, 1)) + self.assertEqual(self.kept_refs(), {"refs/pr-overlap/2": moved, "refs/pr-overlap/4": shas[4], + "refs/pr-overlap/9": opened}) + self.assertEqual([pr["number"] for pr in report["pull_requests"]], [2, 4, 9]) + report = self.report("viewer") + self.assertEqual((report["fetched"], report["removed"]), (0, 0)) + + def test_a_repository_whose_pull_requests_are_all_closed_is_not_taken_for_a_fork(self): + self.pull(1, {"viewer/index.html": page(line5="closed")}, is_open=False) + code, out, err = self.run_tool("viewer") + self.assertEqual((code, err), (0, "")) + self.assertIn("0 open pull request(s) on origin (0 head(s) fetched, 0 no longer open)", out) + self.assertEqual(self.kept_refs(), {}) + + def test_no_fetch_works_from_the_kept_refs_without_the_remote(self): + self.four_pull_requests() + code, _, err = self.run_tool("--no-fetch", "viewer") + self.assertEqual(code, 2) + self.assertIn("run once without --no-fetch", err) + self.assertEqual(self.numbers("viewer"), [1, 4]) + self.git(self.clone, "remote", "set-url", "origin", os.path.join(self.root, "gone")) + report = self.report("--no-fetch", "viewer") + self.assertEqual((report["open"], report["fetched"], report["removed"]), (3, None, None)) + self.assertEqual([pr["number"] for pr in report["pull_requests"]], [1, 4]) + self.assertIn("3 open pull request(s) on origin as of the last fetch", self.run_tool("--no-fetch", "viewer")[1]) + code, out, err = self.run_tool("viewer") + self.assertEqual((code, out), (2, "")) + self.assertIn("pr_overlap: git ls-remote", err) + + def test_the_remote_is_the_one_of_the_base_or_the_one_named(self): + self.four_pull_requests() + # origin becomes a fork: it has the branches, not the pull request refs. + fork = os.path.join(self.root, "fork.git") + self.git(self.root, "clone", "-q", "--bare", self.upstream, fork) + self.git(self.clone, "remote", "set-url", "origin", fork) + self.git(self.clone, "remote", "add", "upstream", self.upstream) + self.git(self.clone, "fetch", "-q", "upstream") + code, out, err = self.run_tool("viewer") + self.assertEqual(code, 0) + self.assertIn("0 open pull request(s) on origin", out) + self.assertIn("origin has no pull request refs. Is it a fork?", err) + report = self.report("--base", "upstream/main", "viewer") + self.assertEqual((report["remote"], [pr["number"] for pr in report["pull_requests"]]), ("upstream", [1, 4])) + report = self.report("--remote", self.upstream, "viewer") + self.assertEqual((report["remote"], [pr["number"] for pr in report["pull_requests"]]), (self.upstream, [1, 4])) + + +class ErrorsTest(PrOverlapTest): + def test_usage_and_git_errors_exit_2_with_one_line(self): + self.pull(1, {"viewer/index.html": page(line5="x")}) + # What to look up is checked before the remote is asked: a mistyped path or branch costs no fetch. + self.assertEqual(self.run_tool(os.path.join("..", "elsewhere"))[0], 2) + self.assertEqual(self.run_tool("--head", "nowhere")[0], 2) + self.assertEqual(self.kept_refs(), {}) + for args, message in ((["--base", "origin/nowhere", "viewer"], "--base origin/nowhere is not a commit here"), + (["--head", "nowhere"], "--head nowhere is not a commit here"), + (["--remote", "nowhere", "viewer"], "git ls-remote nowhere")): + code, out, err = self.run_tool(*args) + self.assertEqual((code, out), (2, ""), args) + self.assertIn(message, err) + self.assertTrue(err.startswith("pr_overlap: "), err) + code, out, err = self.run_tool("viewer", repo=self.root) + self.assertEqual((code, out), (2, "")) + self.assertIn("pr_overlap: git rev-parse", err) + with self.assertRaises(SystemExit) as stop, contextlib.redirect_stderr(io.StringIO()): + pr_overlap.main(["--repo", self.clone, "--jobs", "0"]) + self.assertEqual(stop.exception.code, 2) + + def test_a_missing_git_is_an_error_message_not_a_traceback(self): + with mock.patch.object(pr_overlap.subprocess, "run", side_effect=FileNotFoundError(2, "No such file")): + code, out, err = self.run_tool("viewer") + self.assertEqual((code, out), (2, "")) + self.assertIn("pr_overlap: cannot run git: No such file", err) + + def test_one_job_gives_the_same_answer(self): + self.four_pull_requests() + self.assertEqual(self.numbers("--jobs", "1", "."), [1, 2, 4]) + + +if __name__ == "__main__": + unittest.main()