"""What the pull request of a do-epic chunk waits on, read once from its forge (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates"). A gate is something only time or a person passes: checks that still run, or an approval a reviewer has yet to give. While a chunk's pull request waits on one, its worker has nothing to do, so do-epic parks the chunk (`parked`). Anything else is news the worker acts on.""" import dataclasses import json import typing from forge.pulls import CheckFailed, checks_now, open_pull, Pending, required_checks from failure import Failure from forge.commands import forge_of, Run from chunk_pr.approval import waiting_threads # What a pull request waits on, as the words after "awaits". CHECKS = "its checks" APPROVAL = "an approval" @dataclasses.dataclass(frozen=True) class Gate: """The gate a chunk's open pull request waits on.""" # The chunk's worktree, where the pull request's branch is checked out. worktree: str # The pull request's number. pull: str # CHECKS or APPROVAL. on: str @dataclasses.dataclass(frozen=True) class Open: """A chunk that waits on no gate, so its worker goes on.""" # Why, as a sentence without its full stop, for the worker of a chunk that was parked. news: str def gate(branch: str, checkout: str, at: typing.Callable[[str], Run]) -> Gate | Open | Failure: """What the chunk on branch waits on, in a worktree of checkout; at gives the runner of commands in a folder. A Failure where git or the forge cannot be read, which says nothing about the gate. A draft never waits on a gate: its worker still works on it. On Gitea only the checks are a gate, since chunk-pr reads approvals on GitHub only (`chunk_pr.approval.awaited`). """ worktree = worktree_of(branch, at(checkout)) if not isinstance(worktree, str): return worktree or Open(f"no worktree of {checkout} has the branch {branch} checked out") run = at(worktree) read = [run(["git", *args]) for args in (["remote", "get-url", "origin"], ["rev-parse", "HEAD"], ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])] failed = next((answer for answer in read if isinstance(answer, Failure)), None) if failed is not None: return failed origin, head, base = (str(answer).strip() for answer in read) forge = forge_of(origin) pull = open_pull(forge, branch, head, run) if not isinstance(pull, str): return pull or Open(f"no pull request from origin's {branch} is open at {head[:12]}") decision = review_decision(pull, run) if forge == "gh" else "" if not isinstance(decision, str): return decision or Open(f"pull request #{pull} is a draft") required = required_checks(forge, base.removeprefix("origin/"), run) checks = required if isinstance(required, Failure) else checks_now(forge, pull, head, required, run) if isinstance(checks, CheckFailed): return Open(f"{checks.reason}; fix it and push") if isinstance(checks, Failure): return checks if isinstance(checks, Pending): return Gate(worktree, pull, CHECKS) if decision == "CHANGES_REQUESTED": return Open(f"a reviewer requested changes on pull request #{pull}") waiting = waiting_threads(pull, run) if forge == "gh" else [] if isinstance(waiting, Failure): return waiting if waiting: return Open(f"a reviewer's comment on pull request #{pull} waits for an answer, in {', '.join(waiting)}") if decision == "REVIEW_REQUIRED": return Gate(worktree, pull, APPROVAL) return Open(f"pull request #{pull} passed its checks" + (" and is approved" if decision == "APPROVED" else "")) def worktree_of(branch: str, run: Run) -> str | None | Failure: """The worktree, of the checkout run works in, that has branch checked out; None where none has.""" listed = run(["git", "worktree", "list", "--porcelain"]) if isinstance(listed, Failure): return listed for block in listed.split("\n\n"): lines = block.splitlines() if f"branch refs/heads/{branch}" in lines and lines[0].startswith("worktree "): return lines[0].removeprefix("worktree ") return None def review_decision(pull: str, run: Run) -> str | None | Failure: """GitHub's review decision on the pull request, read once: `APPROVED`, `REVIEW_REQUIRED`, `CHANGES_REQUESTED`, or empty where its branch protection asks for no review. None where it is a draft.""" viewed = run(["gh", "pr", "view", pull, "--json", "isDraft,reviewDecision"]) if isinstance(viewed, Failure): return viewed try: parsed = json.loads(viewed) return None if parsed["isDraft"] else str(parsed["reviewDecision"] or "") except (ValueError, KeyError, TypeError): return Failure(f"gh pr view printed no review decision: {viewed.strip()[:200]}")