Open, mark ready and merge a chunk's pull request with chunk-pr, which picks tea or gh from the remote

This commit is contained in:
2026-11-09 02:03:34 +01:00
parent 81260cdaf0
commit 4d25e43c5e
11 changed files with 275 additions and 10 deletions
Executable
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from chunk_pr import main
sys.exit(main.main(sys.argv[1:]))
View File
+129
View File
@@ -0,0 +1,129 @@
"""Open the chunk's pull request as a draft, mark it ready, or merge it, with gh where origin is on GitHub and tea elsewhere.
usage: chunk-pr open <title> [<body>]
chunk-pr ready
chunk-pr merge --gate-passed
Run it in the chunk's worktree, on the chunk's branch. Each step acts on the open pull request from
origin's own branch of that name whose head is the commit checked out, so push before ready and merge.
open pushes the branch, setting its upstream, then opens a draft pull request into origin's
default branch, titled <title>: one line, as ~/.claude/CLAUDE.md → "Git, commits, and PRs"
says. Where that pull request is open already, it opens no other.
ready marks the pull request ready for review. Gitea has no draft state, so there it drops the
title's `WIP: ` prefix, which Gitea reads as a draft.
merge merges the pull request with a merge commit, and only while its head is still the commit
checked out, so a push after the gate is never merged. --gate-passed says the merge gate
passed on that commit; without it, chunk-pr refuses. A repo whose AGENTS.md names another
merge method merges through its forge instead.
It prints the pull request's number, exit 0. A failure prints git's or the forge's reason, exit 1.
"""
import os
import sys
from chunk_preflight.choices import forge_of
from chunk_preflight.gathered import Forge
from deploy_release.forge import gitea, open_pull, Run, runner
from failure import Failure
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr ready | chunk-pr merge --gate-passed"
def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
done = step(argv, runner(os.getcwd()))
if isinstance(done, Failure):
print(f"chunk-pr: {done.reason}", file=sys.stderr)
return 1
print(done)
return 0
def step(argv: list[str], run: Run) -> str | Failure:
"""Run the step argv names: the line to print, or a Failure. A malformed argv runs nothing."""
match argv:
case ["open", title, *body] if len(body) <= 1:
if not title.strip() or "\n" in title:
return Failure("the title is one line of text")
return opened(title, body[0] if body else "", run)
case ["ready"]:
return marked_ready(run)
case ["merge", "--gate-passed"]:
return merged(run)
case ["merge"]:
return Failure("merge only once the gate has passed, and say so with --gate-passed")
return Failure(USAGE)
def checkout(run: Run) -> tuple[Forge, str, str] | Failure:
"""The forge, the branch checked out and its head commit."""
answers = [run(["git", *args]) for args in (["remote", "get-url", "origin"], ["symbolic-ref", "--short", "HEAD"], ["rev-parse", "HEAD"])]
failed = next((answer for answer in answers if isinstance(answer, Failure)), None)
if failed is not None:
return failed
origin, branch, head = (str(answer).strip() for answer in answers)
return forge_of(origin), branch, head
def pull(run: Run) -> tuple[Forge, str, str] | Failure:
"""The forge, the number of the branch's open pull request at its head, and that head."""
found = checkout(run)
if isinstance(found, Failure):
return found
forge, branch, head = found
number = open_pull(forge, branch, head, run)
if number is None:
return Failure(f"no pull request from origin's {branch} is open at {head[:12]}; push the branch, or open one with chunk-pr open")
return number if isinstance(number, Failure) else (forge, number, head)
def opened(title: str, body: str, run: Run) -> str | Failure:
found = checkout(run)
if isinstance(found, Failure):
return found
forge, branch, head = found
default = run(["git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
if isinstance(default, Failure):
return Failure(f"origin records no default branch; set it with `git remote set-head origin --auto`: {default.reason}")
base = default.strip().removeprefix("origin/")
pushed = run(["git", "push", "--quiet", "--set-upstream", "origin", branch])
if isinstance(pushed, Failure):
return pushed
number = open_pull(forge, branch, head, run)
if isinstance(number, str):
return f"Pull request #{number} is open already."
if isinstance(number, Failure):
return number
command = ["gh", "pr", "create"] if forge == "gh" else ["tea", "pulls", "create"]
created = run([*command, "--draft", "--head", branch, "--base", base, "--title", title, "--body" if forge == "gh" else "--description", body])
if isinstance(created, Failure):
return created
number = open_pull(forge, branch, head, run)
if number is None:
return Failure(f"{command[0]} created the pull request, but no pull request from origin's {branch} is listed open at {head[:12]}")
return number if isinstance(number, Failure) else f"Opened draft pull request #{number}."
def marked_ready(run: Run) -> str | Failure:
found = pull(run)
if isinstance(found, Failure):
return found
forge, number, _ = found
ready = run(["gh", "pr", "ready", number] if forge == "gh" else ["tea", "pulls", "edit", number, "--ready"])
return ready if isinstance(ready, Failure) else f"Marked pull request #{number} ready."
def merged(run: Run) -> str | Failure:
found = pull(run)
if isinstance(found, Failure):
return found
forge, number, head = found
# The forge refuses where the pull request's head has moved off head.
if forge == "gh":
done = run(["gh", "pr", "merge", number, "--merge", "--match-head-commit", head])
else:
done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", "Do=merge", f"head_commit_id={head}")
return done if isinstance(done, Failure) else f"Merged pull request #{number}."
+125
View File
@@ -0,0 +1,125 @@
import json
import pathlib
import subprocess
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from chunk_pr.main import step
from failure import Failure
from test_env import isolated_env
TOOL = pathlib.Path(__file__).resolve().parents[1] / "chunk-pr"
GITHUB = "git@github.com:me/project.git"
GITEA = "ssh://git@gitea.example.org:22/me/project.git"
HEAD = "c0ffee"
GH_LIST = ["gh", "pr", "list", "--head", "item-7", "--json", "number,headRefOid,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.headRefOid}}\t{{.isCrossRepository}}\n{{end}}"]
TEA_LIST = ["tea", "api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]
class Forge:
"""A checkout on branch item-7 at HEAD, whose origin is origin and whose default branch is main. Pull request #12 from item-7 is open at HEAD where open says so, and once a create has run. It records every command run."""
def __init__(self, origin: str, open: bool):
self.open = open
self.ran: list[list[str]] = []
self.answers: dict[tuple[str, ...], str | Failure] = {
("git", "remote", "get-url", "origin"): f"{origin}\n",
("git", "symbolic-ref", "--short", "HEAD"): "item-7\n",
("git", "rev-parse", "HEAD"): f"{HEAD}\n",
("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"): "origin/main\n",
}
def __call__(self, command: list[str]) -> str | Failure:
self.ran.append(command)
if command[2:3] == ["create"]:
self.open = True
if command == GH_LIST:
return f"12\t{HEAD}\tfalse\n" if self.open else ""
if command == TEA_LIST:
return json.dumps([{"number": 12, "head": {"ref": "item-7", "sha": HEAD, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}] if self.open else [])
return self.answers.get(tuple(command), "")
def forge_calls(self) -> list[list[str]]:
"""What it ran beyond reading the checkout and listing pull requests."""
return [command for command in self.ran if tuple(command) not in self.answers and command not in (GH_LIST, TEA_LIST)]
class Open(unittest.TestCase):
def test_github_pushes_and_opens_a_draft_into_the_default_branch(self):
forge = Forge(GITHUB, open=False)
opened = step(["open", "ABC-1 - Do it", "The body."], forge)
self.assertEqual(forge.forge_calls(), [
["git", "push", "--quiet", "--set-upstream", "origin", "item-7"],
["gh", "pr", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "ABC-1 - Do it", "--body", "The body."],
])
self.assertEqual(opened, "Opened draft pull request #12.")
def test_gitea_opens_a_draft_with_tea(self):
forge = Forge(GITEA, open=False)
step(["open", "Do it"], forge)
self.assertEqual(forge.forge_calls()[1], ["tea", "pulls", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "Do it", "--description", ""])
def test_an_open_pull_request_is_kept(self):
forge = Forge(GITEA, open=True)
self.assertEqual(step(["open", "Do it"], forge), "Pull request #12 is open already.")
self.assertEqual(forge.forge_calls(), [["git", "push", "--quiet", "--set-upstream", "origin", "item-7"]])
def test_a_title_of_more_than_one_line_is_refused_before_anything_runs(self):
forge = Forge(GITHUB, open=False)
self.assertIsInstance(step(["open", "Do it\nand more"], forge), Failure)
self.assertEqual(forge.ran, [])
class Ready(unittest.TestCase):
def test_github_marks_it_ready(self):
forge = Forge(GITHUB, open=True)
self.assertEqual(step(["ready"], forge), "Marked pull request #12 ready.")
self.assertEqual(forge.forge_calls(), [["gh", "pr", "ready", "12"]])
def test_gitea_drops_the_wip_prefix_with_tea(self):
forge = Forge(GITEA, open=True)
step(["ready"], forge)
self.assertEqual(forge.forge_calls(), [["tea", "pulls", "edit", "12", "--ready"]])
def test_without_an_open_pull_request_at_the_head_it_fails_naming_the_branch(self):
forge = Forge(GITHUB, open=False)
ready = step(["ready"], forge)
self.assertIsInstance(ready, Failure)
self.assertIn("item-7", ready.reason)
self.assertEqual(forge.forge_calls(), [])
class Merge(unittest.TestCase):
def test_without_the_gate_passed_it_refuses_before_anything_runs(self):
forge = Forge(GITHUB, open=True)
self.assertIsInstance(step(["merge"], forge), Failure)
self.assertEqual(forge.ran, [])
def test_github_merges_pinned_to_the_head(self):
forge = Forge(GITHUB, open=True)
self.assertEqual(step(["merge", "--gate-passed"], forge), "Merged pull request #12.")
self.assertEqual(forge.forge_calls(), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_gitea_merges_pinned_to_the_head(self):
forge = Forge(GITEA, open=True)
step(["merge", "--gate-passed"], forge)
self.assertEqual(forge.forge_calls(), [["tea", "api", "--method", "POST", "--field", "Do=merge", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
def test_a_forge_failure_is_returned(self):
forge = Forge(GITHUB, open=True)
forge.answers[("gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD)] = Failure("gh pr merge: head moved")
self.assertEqual(step(["merge", "--gate-passed"], forge), Failure("gh pr merge: head moved"))
class Launcher(unittest.TestCase):
def test_help_exits_0_and_a_wrong_step_exits_1(self):
self.assertEqual(subprocess.run([str(TOOL), "--help"], capture_output=True, env=isolated_env()).returncode, 0)
wrong = subprocess.run([str(TOOL), "close"], capture_output=True, encoding="utf-8", env=isolated_env())
self.assertEqual((wrong.returncode, wrong.stdout), (1, ""))
self.assertIn("usage", wrong.stderr)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -1,4 +1,4 @@
"""The pull request steps of a cut. They run gh where origin is on GitHub and tea elsewhere, as chunk_preflight tells the two apart.
"""The pull request steps of a cut, whose runner, gitea and open_pull chunk_pr shares. They run gh where origin is on GitHub and tea elsewhere, as chunk_preflight tells the two apart.
Each step is pinned to head, the commit origin's release branch points at: the cut takes only a pull request from origin itself whose head is that commit, and the forge merges it only while its head is still that commit. So a fork's pull request from a branch of the same name, or a push to the branch after its checks passed, is never merged.
"""