102 lines
5.3 KiB
Python
102 lines
5.3 KiB
Python
"""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.
|
|
"""
|
|
import json
|
|
import subprocess
|
|
import time
|
|
import typing
|
|
|
|
from failure import Failure
|
|
from chunk_preflight.choices import Forge
|
|
|
|
# How long the cut waits between two reads of the head commit's status on Gitea.
|
|
POLL_SECONDS = 10
|
|
|
|
# Runs a command in the clone: what it printed, or a Failure with its reason.
|
|
Run = typing.Callable[[list[str]], str | Failure]
|
|
|
|
|
|
def runner(cwd: str) -> Run:
|
|
def run(command: list[str]) -> str | Failure:
|
|
try:
|
|
done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)
|
|
except OSError as failure:
|
|
return Failure(f"{command[0]} could not start: {failure}")
|
|
if done.returncode:
|
|
return Failure(f"{' '.join(command[:3])}: {(done.stderr or done.stdout).strip()}")
|
|
return done.stdout
|
|
return run
|
|
|
|
|
|
def gitea(run: Run, endpoint: str, *fields: str) -> typing.Any | Failure:
|
|
"""What Gitea's API answered at endpoint, parsed; with fields, `key=value` strings, a POST of them. tea api exits 0 on an HTTP error too, so an answer with Gitea's `message` key is a Failure."""
|
|
answered = run(["tea", "api", *(["--method", "POST"] if fields else []), *[word for field in fields for word in ("--field", field)], endpoint])
|
|
if isinstance(answered, Failure) or not answered.strip():
|
|
return answered
|
|
try:
|
|
parsed = json.loads(answered)
|
|
except ValueError:
|
|
return Failure(f"tea api {endpoint} printed no JSON: {answered.strip()[:200]}")
|
|
if isinstance(parsed, dict) and "message" in parsed:
|
|
return Failure(f"tea api {endpoint}: {parsed['message']}")
|
|
return parsed
|
|
|
|
|
|
def open_pull(forge: Forge, branch: str, head: str, run: Run) -> str | None | Failure:
|
|
"""The number of the open pull request from origin's own branch whose head is head; None where there is none."""
|
|
if forge == "gh":
|
|
listed = run(["gh", "pr", "list", "--head", branch, "--json", "number,headRefOid,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.headRefOid}}\t{{.isCrossRepository}}\n{{end}}"])
|
|
if isinstance(listed, Failure):
|
|
return listed
|
|
rows = [line.split("\t") for line in listed.splitlines()]
|
|
return next((row[0] for row in rows if row[1:] == [head, "false"]), None)
|
|
# Gitea lists at most 50 a page; a release's pull request is among the newest.
|
|
pulls = gitea(run, "repos/{owner}/{repo}/pulls?state=open&limit=50")
|
|
if isinstance(pulls, Failure):
|
|
return pulls
|
|
try:
|
|
return next((str(pull["number"]) for pull in pulls if pull["head"]["ref"] == branch and pull["head"]["sha"] == head and pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"]), None)
|
|
except (KeyError, TypeError):
|
|
return Failure(f"tea api listed pull requests in a shape the cut doesn't read: {str(pulls)[:200]}")
|
|
|
|
|
|
def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> Failure | None:
|
|
body = ["--body" if forge == "gh" else "--description", "Rename ## Unreleased in CHANGELOG.md to the version."]
|
|
command = ["gh", "pr"] if forge == "gh" else ["tea", "pulls"]
|
|
created = run([*command, "create", "--head", branch, "--base", base, "--title", title, *body])
|
|
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:
|
|
"""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."""
|
|
if forge == "gh":
|
|
watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"])
|
|
if isinstance(watched, Failure) and "no checks reported" not in watched.reason:
|
|
return watched
|
|
return None
|
|
while True:
|
|
status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status")
|
|
if isinstance(status, Failure):
|
|
return status
|
|
try:
|
|
count, state = status["total_count"], status["state"]
|
|
except (KeyError, TypeError):
|
|
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 count == 0 or state == "success":
|
|
return None
|
|
if state != "pending":
|
|
return Failure(f"a check on pull request {number} ended in {state}")
|
|
sleep(POLL_SECONDS)
|
|
|
|
|
|
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."""
|
|
if forge == "gh":
|
|
# GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title.
|
|
merged = run(["gh", "pr", "merge", number, "--rebase", "--match-head-commit", head])
|
|
else:
|
|
merged = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", "Do=fast-forward-only", f"head_commit_id={head}")
|
|
return merged if isinstance(merged, Failure) else None
|