"""A cut's pull request steps on the forge origin lives on: gh on GitHub, tea elsewhere, as chunk_preflight tells them apart.""" import json import subprocess import time import typing from chunk_preflight.choices import Forge, pulls_command from chunk_preflight.facts import open_pulls from failure import Failure # How long tea waits between two reads of the pull request's checks. 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 open_pull(forge: Forge, branch: str, run: Run) -> str | None | Failure: """The number of branch's open pull request; None where it has none.""" listed = run(pulls_command(forge, branch)) if isinstance(listed, Failure): return listed found = open_pulls(listed, forge, branch) return found[0].split()[0].removeprefix("#") if found else None 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: read = run(["tea", "api", f"repos/{{owner}}/{{repo}}/commits/{head}/status"]) if isinstance(read, Failure): return read # Gitea reads a commit with no status as pending, with total_count 0. try: status = json.loads(read) count, state = status["total_count"], status["state"] except (ValueError, KeyError, TypeError): return Failure(f"tea api printed no commit status for {head}: {read.strip()[:200]}") 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, run: Run) -> Failure | None: # 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. command = ["gh", "pr", "merge", number, "--rebase"] if forge == "gh" else ["tea", "pulls", "merge", "--style", "fast-forward-only", number] merged = run(command) return merged if isinstance(merged, Failure) else None