Say as each step of deploy-release --cut finishes, end on a Done line, delete the merged release branch, and wait for the checks main's protection requires

This commit is contained in:
2026-11-09 02:44:40 +01:00
parent daf6a38fc3
commit 94aa8bafbf
4 changed files with 114 additions and 20 deletions
+31 -4
View File
@@ -48,14 +48,34 @@ def cut(clone: str, checkout: str) -> str | Failure:
return merged return merged
if isinstance(made := git("tag", "--annotate", "--message", title, tag, merged, cwd=clone), Failure): if isinstance(made := git("tag", "--annotate", "--message", title, tag, merged, cwd=clone), Failure):
return made return made
said(f"tagged {merged[:12]} {tag}")
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure): if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut. # Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
git("tag", "--delete", tag, cwd=clone) git("tag", "--delete", tag, cwd=clone)
return pushed return pushed
said(f"pushed the tag {tag}")
delete_release_branch(clone, f"release-{named}")
moved = deploy(checkout) moved = deploy(checkout)
if isinstance(moved, Failure): if isinstance(moved, Failure):
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.") return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
return f"Cut {tag}.\n\n{moved}" return f"{moved}\n\nDone: {tag} is cut and pushed, and {checkout} is on it."
def said(step: str) -> None:
"""Say on stderr that step finished, so the human sees how far the cut got before the changelog fills the screen."""
print(f"deploy-release: {step}", file=sys.stderr)
def delete_release_branch(clone: str, branch: str) -> None:
"""Delete origin's merged branch, where it is still there; only warn where that fails, since the release is cut by then."""
listed = branch_head(branch, clone)
if listed is None:
return
deleted = listed if isinstance(listed, Failure) else git("push", "--quiet", "origin", "--delete", f"refs/heads/{branch}", cwd=clone)
if isinstance(deleted, Failure):
said(f"warning: the branch {branch} stays on origin: {deleted.reason}")
else:
said(f"deleted the branch {branch} on origin")
def drop_unpushed_cut_tags(clone: str) -> Failure | None: def drop_unpushed_cut_tags(clone: str) -> Failure | None:
@@ -136,6 +156,7 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None:
# Where main moved on, such as to fix a failed check, the branch could no longer merge fast-forward, so it is rebuilt on main. # Where main moved on, such as to fix a failed check, the branch could no longer merge fast-forward, so it is rebuilt on main.
if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title, head), Failure): if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title, head), Failure):
return pushed return pushed
said(f"pushed the branch {branch}")
head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch") head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch")
if isinstance(head, Failure): if isinstance(head, Failure):
return head return head
@@ -144,12 +165,18 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None:
if isinstance(created := forge.create_pull(on, branch, base, title, run), Failure): if isinstance(created := forge.create_pull(on, branch, base, title, run), Failure):
return created return created
number = forge.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}") number = forge.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}")
if isinstance(number, str):
said(f"opened pull request {number}")
if isinstance(number, Failure): if isinstance(number, Failure):
return number return number
print(f"deploy-release: waiting for the checks of pull request {number}", file=sys.stderr) said(f"waiting for the checks of pull request {number}")
if isinstance(passed := forge.checks_passed(on, number, head, run), Failure): if isinstance(passed := forge.checks_passed(on, number, head, base, run), Failure):
return passed return passed
return forge.merge(on, number, head, run) said(f"the checks of pull request {number} passed")
if isinstance(merged := forge.merge(on, number, head, run), Failure):
return merged
said(f"merged pull request {number}")
return None
def branch_head(branch: str, clone: str) -> str | None | Failure: def branch_head(branch: str, clone: str) -> str | None | Failure:
+25 -7
View File
@@ -68,29 +68,47 @@ def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> F
return created if isinstance(created, Failure) else None return created if isinstance(created, Failure) else None
def checks_passed(forge: Forge, number: str, head: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None: def checks_passed(forge: Forge, number: str, head: str, base: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None:
"""None once every check on pull request number, whose head commit is head, has passed, or where it has none; a Failure where one fails.""" """None once every check on pull request number, whose head commit is head, has passed, or where it has none; a Failure where one fails.
On Gitea it also waits for each check the protection of base requires to report: a check CI has yet to queue is no status at all.
"""
if forge == "gh": if forge == "gh":
watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"]) watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"])
if isinstance(watched, Failure) and "no checks reported" not in watched.reason: if isinstance(watched, Failure) and "no checks reported" not in watched.reason:
return watched return watched
return None return None
required = required_checks(base, run)
if isinstance(required, Failure):
return required
while True: while True:
status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status") status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status")
if isinstance(status, Failure): if isinstance(status, Failure):
return status return status
try: try:
count, state = status["total_count"], status["state"] count, state = status["total_count"], status["state"]
except (KeyError, TypeError): passed = {check["context"] for check in status.get("statuses") or [] if check["status"] == "success"}
except (KeyError, TypeError, AttributeError):
return Failure(f"tea api printed no commit status for {head}: {str(status)[:200]}") return Failure(f"tea api printed no commit status for {head}: {str(status)[:200]}")
# Gitea reads a commit with no status as pending, with total_count 0. if state not in ("pending", "success"):
if count == 0 or state == "success":
return None
if state != "pending":
return Failure(f"a check on pull request {number} ended in {state}") return Failure(f"a check on pull request {number} ended in {state}")
# Gitea reads a commit with no status as pending, with total_count 0.
if (count == 0 or state == "success") and required <= passed:
return None
sleep(POLL_SECONDS) sleep(POLL_SECONDS)
def required_checks(base: str, run: Run) -> set[str] | Failure:
"""The checks Gitea's protection of the branch base requires before a merge."""
protections = gitea(run, "repos/{owner}/{repo}/branch_protections")
if isinstance(protections, Failure):
return protections
try:
return {context for rule in protections or [] if base in (rule.get("rule_name"), rule.get("branch_name")) and rule.get("enable_status_check") for context in rule.get("status_check_contexts") or []}
except (AttributeError, TypeError):
return Failure(f"tea api listed branch protections in a shape that can't be read: {str(protections)[:200]}")
def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None: def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None:
"""Merge pull request number, fast-forward only on Gitea and by rebase on GitHub. The forge refuses where the pull request's head is no longer head.""" """Merge pull request number, fast-forward only on Gitea and by rebase on GitHub. The forge refuses where the pull request's head is no longer head."""
if forge == "gh": if forge == "gh":
+5 -2
View File
@@ -23,10 +23,13 @@ landed and changes are unreleased. The release names the version; the tool doesn
titled `Cut release <version>`, and pushes it as the branch release-<version>. The clone's own titled `Cut release <version>`, and pushes it as the branch release-<version>. The clone's own
checkout stays as it is. Where main has moved past the branch, it rebuilds the branch on main. checkout stays as it is. Where main has moved past the branch, it rebuilds the branch on main.
2. It opens a pull request for the branch, with gh on a GitHub origin and tea elsewhere, waits for 2. It opens a pull request for the branch, with gh on a GitHub origin and tea elsewhere, waits for
its checks where there are any, and merges it fast-forward only. GitHub has no such merge, so its checks where there are any, and merges it fast-forward only. On Gitea it also waits for
each check main's branch protection requires to report. GitHub has no fast-forward merge, so
there it rebase-merges the branch, which is already on top of main. there it rebase-merges the branch, which is already on top of main.
3. It tags the merged commit v<version>, annotated `Cut release <version>`, pushes only the tag, 3. It tags the merged commit v<version>, annotated `Cut release <version>`, pushes only the tag,
then moves <checkout> to it as above. deletes the branch on origin, then moves <checkout> to it as above. A failed delete only warns.
It says on stderr as each step finishes, and ends stdout, after the changelog, with the line
`Done: v<version> is cut and pushed, and <checkout> is on it.`
Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request
and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut
commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the
+53 -7
View File
@@ -4,6 +4,7 @@ import pathlib
import subprocess import subprocess
import sys import sys
import tempfile import tempfile
import typing
import unittest import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
@@ -186,6 +187,8 @@ elif args[:2] in (["pulls", "create"], ["pr", "create"]):
save() save()
sys.exit("pull request already exists for these targets") sys.exit("pull request already exists for these targets")
state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "fork": False, "state": "open"}) state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "fork": False, "state": "open"})
elif forge == "tea" and args == ["api", "repos/{owner}/{repo}/branch_protections"]:
print("[]")
elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"): elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"):
checks = state["checks"] checks = state["checks"]
print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1})) print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1}))
@@ -356,9 +359,35 @@ class Cut(unittest.TestCase):
self.assertIn("origin", ran.stderr) self.assertIn("origin", ran.stderr)
self.assertEqual(self.forge_state()["pulls"], []) self.assertEqual(self.forge_state()["pulls"], [])
def test_says_which_pull_request_it_waits_for(self): def test_says_as_each_step_finishes_and_ends_saying_the_release_is_cut_and_the_checkout_on_it(self):
ran = self.cut() ran = self.cut()
self.assertIn("pull request 1", ran.stderr) self.assert_cut(ran)
merged = self.origin_git("rev-parse", "main").strip()
self.assertEqual(ran.stderr.splitlines(), [
"deploy-release: pushed the branch release-0.2.0",
"deploy-release: opened pull request 1",
"deploy-release: waiting for the checks of pull request 1",
"deploy-release: the checks of pull request 1 passed",
"deploy-release: merged pull request 1",
f"deploy-release: tagged {merged[:12]} v0.2.0",
"deploy-release: pushed the tag v0.2.0",
"deploy-release: deleted the branch release-0.2.0 on origin",
])
self.assertEqual(ran.stdout.splitlines()[-1], f"Done: v0.2.0 is cut and pushed, and {self.target} is on it.")
def test_deletes_the_merged_release_branch_on_origin(self):
self.assert_cut(self.cut())
self.assertEqual(self.origin_git("branch", "--list", "release-0.2.0"), "")
def test_only_warns_where_deleting_the_release_branch_fails(self):
hook = self.origin / "hooks" / "pre-receive"
hook.write_text("#!/bin/sh\nif grep -q '^[^ ]* 0000000000000000000000000000000000000000 refs/heads/'; then echo 'deletes are refused' >&2; exit 1; fi\n")
hook.chmod(0o755)
ran = self.cut()
self.assert_cut(ran)
self.assertIn("deploy-release: warning: the branch release-0.2.0 stays on origin:", ran.stderr)
self.assertIn("deletes are refused", ran.stderr)
self.assertEqual(ran.stdout.splitlines()[-1], f"Done: v0.2.0 is cut and pushed, and {self.target} is on it.")
def test_stops_where_the_tag_exists_on_another_commit_and_a_rerun_tags_the_merged_commit(self): def test_stops_where_the_tag_exists_on_another_commit_and_a_rerun_tags_the_merged_commit(self):
self.git(self.clone, "switch", "-q", "-c", "side") self.git(self.clone, "switch", "-q", "-c", "side")
@@ -443,18 +472,35 @@ class Cut(unittest.TestCase):
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0") self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0")
def tea(statuses: list[str], protections: str = "[]") -> typing.Callable[[list[str]], str]:
"""A tea answering each read of the head's status with the next of statuses, and of the branch protections with protections."""
answers = iter(statuses)
return lambda command: protections if command[-1].endswith("/branch_protections") else next(answers)
REQUIRED = '[{"rule_name": "main", "enable_status_check": true, "status_check_contexts": ["CI / tests (pull_request)"]}]'
class ChecksPassed(unittest.TestCase): class ChecksPassed(unittest.TestCase):
def test_waits_on_tea_while_a_check_is_pending(self): def test_waits_on_tea_while_a_check_is_pending(self):
statuses = iter(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}'])
slept = [] slept = []
self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: next(statuses), slept.append)) self.assertIsNone(checks_passed("tea", "1", "abc", "main", tea(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}']), slept.append))
self.assertEqual(slept, [POLL_SECONDS]) self.assertEqual(slept, [POLL_SECONDS])
def test_takes_a_commit_with_no_status_on_tea_as_passed(self): def test_takes_a_commit_with_no_status_on_tea_as_passed_where_the_base_requires_none(self):
self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: '{"state": "pending", "total_count": 0}', self.fail)) self.assertIsNone(checks_passed("tea", "1", "abc", "main", tea(['{"state": "pending", "total_count": 0}']), self.fail))
def test_waits_on_tea_for_a_check_the_base_requires_until_it_reports_and_passes(self):
slept = []
statuses = ['{"state": "pending", "total_count": 0, "statuses": []}', '{"state": "success", "total_count": 1, "statuses": [{"context": "lint", "status": "success"}]}', '{"state": "success", "total_count": 2, "statuses": [{"context": "lint", "status": "success"}, {"context": "CI / tests (pull_request)", "status": "success"}]}']
self.assertIsNone(checks_passed("tea", "1", "abc", "main", tea(statuses, REQUIRED), slept.append))
self.assertEqual(slept, [POLL_SECONDS, POLL_SECONDS])
def test_ignores_on_tea_a_protection_of_another_branch(self):
self.assertIsNone(checks_passed("tea", "1", "abc", "develop", tea(['{"state": "pending", "total_count": 0}'], REQUIRED), self.fail))
def test_fails_on_tea_where_a_check_failed(self): def test_fails_on_tea_where_a_check_failed(self):
self.assertIsInstance(checks_passed("tea", "1", "abc", lambda command: '{"state": "failure", "total_count": 1}', self.fail), Failure) self.assertIsInstance(checks_passed("tea", "1", "abc", "main", tea(['{"state": "failure", "total_count": 1}']), self.fail), Failure)
if __name__ == "__main__": if __name__ == "__main__":