97 lines
5.4 KiB
Python
97 lines
5.4 KiB
Python
"""Finding a pull request from origin's own branch, and waiting for its checks.
|
|
|
|
Each call is pinned to head, a commit on that branch: it takes only a pull request from origin itself whose head is that commit. So a fork's pull request from a branch of the same name is never taken.
|
|
"""
|
|
import fnmatch
|
|
import time
|
|
import typing
|
|
|
|
from failure import Failure
|
|
from forge.commands import Forge, gitea, Run
|
|
|
|
# How long checks_passed waits between two reads of the head commit's status on Gitea.
|
|
POLL_SECONDS = 10
|
|
# How long checks_passed waits for the checks before it gives up; CI took about 3 minutes in 2026-11.
|
|
WAIT_SECONDS = 30 * 60
|
|
|
|
|
|
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."""
|
|
return pull_at(forge, branch, head, "open", run)
|
|
|
|
|
|
def merged_pull(forge: Forge, branch: str, head: str, run: Run) -> str | None | Failure:
|
|
"""The number of the merged pull request from origin's own branch whose head was head; None where there is none. A rebase or a squash merge counts: the pull request keeps the head it had."""
|
|
return pull_at(forge, branch, head, "merged", run)
|
|
|
|
|
|
def pull_at(forge: Forge, branch: str, head: str, state: typing.Literal["open", "merged"], run: Run) -> str | None | Failure:
|
|
if forge == "gh":
|
|
# gh lists the open pull requests unless told another state.
|
|
listed = run(["gh", "pr", "list", "--head", branch, *(["--state", "merged"] if state == "merged" else []), "--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; the pull request sought is among the newest. Gitea has no merged state: a merged pull request is a closed one marked merged.
|
|
pulls = gitea(run, f"repos/{{owner}}/{{repo}}/pulls?state={'open' if state == 'open' else 'closed'}&limit=50")
|
|
if isinstance(pulls, Failure):
|
|
return pulls
|
|
try:
|
|
# Match the label, not the ref: once origin deletes a merged branch, Gitea reports its ref as refs/pull/<N>/head.
|
|
return next((str(pull["number"]) for pull in pulls if pull["head"]["label"] == branch and pull["head"]["sha"] == head and pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"] and (state == "open" or pull["merged"] is True)), None)
|
|
except (KeyError, TypeError):
|
|
return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}")
|
|
|
|
|
|
def required_checks(forge: Forge, base: str, run: Run) -> set[str] | Failure:
|
|
"""The checks, or glob patterns of checks, that the forge's protection of the branch base requires before a merge. None on GitHub, where gh's watch covers them.
|
|
|
|
Gitea answers a branch with the protection rule it applies there, so the cut never picks among the rules itself.
|
|
"""
|
|
if forge == "gh":
|
|
return set()
|
|
branch = gitea(run, f"repos/{{owner}}/{{repo}}/branches/{base}")
|
|
if isinstance(branch, Failure):
|
|
return branch
|
|
try:
|
|
return set(branch.get("status_check_contexts") or []) if branch.get("enable_status_check") else set()
|
|
except (AttributeError, TypeError):
|
|
return Failure(f"tea api answered branch {base} in a shape that can't be read: {str(branch)[:200]}")
|
|
|
|
|
|
def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: Run, sleep: typing.Callable[[float], None] = time.sleep, settle: int = 0) -> Failure | None:
|
|
"""None once every check on pull request number, whose head commit is head, has passed, or where it has none for settle seconds; a Failure where one fails, or where they have not all passed within WAIT_SECONDS.
|
|
|
|
On Gitea it also waits for a passed check to match each of required: a check CI has yet to queue is no status at all.
|
|
"""
|
|
if forge == "gh":
|
|
for waited in range(0, settle + 1, POLL_SECONDS):
|
|
watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"])
|
|
if not isinstance(watched, Failure):
|
|
return None
|
|
if "no checks reported" not in watched.reason:
|
|
return watched
|
|
if waited < settle:
|
|
sleep(POLL_SECONDS)
|
|
return None
|
|
for _ in range(WAIT_SECONDS // POLL_SECONDS + 1):
|
|
status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status")
|
|
if isinstance(status, Failure):
|
|
return status
|
|
try:
|
|
count, state = status["total_count"], status["state"]
|
|
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]}")
|
|
if state not in ("pending", "success"):
|
|
return Failure(f"a check on pull request {number} ended in {state}")
|
|
# Gitea matches a required context as a glob, and reads a commit with no status as pending, with total_count 0.
|
|
missing = sorted(pattern for pattern in required if not fnmatch.filter(passed, pattern))
|
|
if (count == 0 and _ * POLL_SECONDS >= settle or state == "success") and not missing:
|
|
return None
|
|
if _ < WAIT_SECONDS // POLL_SECONDS:
|
|
sleep(POLL_SECONDS)
|
|
waited_on = f"{', '.join(missing)}, which the protection requires, never passed" if missing else "a check is still pending"
|
|
return Failure(f"gave up on pull request {number} after {WAIT_SECONDS // 60} minutes: {waited_on}")
|