"""The human approval that `chunk-pr merge` waits for where the project's config sets `wait-for-approval`.""" import json import pathlib import time import typing from failure import Failure from forge.commands import Forge, Run # A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed. POLL_SECONDS = 60 WAIT_SECONDS = 90 * 60 # The environment variable do-epic sets to 1 for its chunks' workers. With it, merge doesn't wait for an approval: do-epic parks the chunk and polls the forge itself, so the chunk holds no running slot meanwhile (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates"). PARKS = "CHUNK_PR_PARKS" def awaited(forge: Forge, wait_for_approval: bool) -> bool | Failure: """Whether merge waits for an approval: the project config's `wait-for-approval`. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails, and merge never skips an approval the config requires.""" if wait_for_approval and forge != "gh": return Failure("the project's config sets wait-for-approval, but chunk-pr reads approvals on GitHub only, so it cannot merge this pull request; ask the human to merge it") return wait_for_approval # Each review thread, with whether it is resolved and who wrote its last comment, beside who opened the pull request. gh fills {owner} and {repo} from the checkout. THREADS = """query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { author { login } reviewThreads(first: 100) { nodes { isResolved path comments(last: 1) { nodes { author { login } } } } } } } }""" def approval(number: str, run: Run) -> bool | Failure: """Whether GitHub reports pull request number approved, as its branch protection asks, read once: False while it still wants a review. A Failure where a reviewer requested changes, or where the protection asks for no review.""" viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"]) try: decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"] except (ValueError, KeyError, TypeError): return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}") if isinstance(decision, Failure): return decision if decision == "CHANGES_REQUESTED": return Failure(f"a reviewer requested changes on pull request {number}") if not decision: return Failure("wait-for-approval is set, but the branch protection requires no review, so GitHub reports no decision; ask the human to require a review in the protection or to set wait-for-approval to false") if decision not in ("APPROVED", "REVIEW_REQUIRED"): return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision") return decision == "APPROVED" def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None: """None once GitHub reports pull request number approved; a Failure where `approval` fails, where a reviewer's comment waits for an answer, or where no approval came within WAIT_SECONDS.""" for waited in range(0, WAIT_SECONDS + 1, POLL_SECONDS): read = approval(number, run) if read is True or isinstance(read, Failure): return None if read is True else read asked = unanswered(number, run) if asked is not None: return asked if waited < WAIT_SECONDS: sleep(POLL_SECONDS) return Failure(f"pull request {number} wasn't approved within {WAIT_SECONDS // 60} minutes; run chunk-pr merge again once it is") def left_to_park(number: str, run: Run) -> Failure: """Why a merge under PARKS ends at once where pull request number passed its checks and awaits an approval, in place of waiting as `approved` does: a reviewer's comment waits for an answer, which the worker gives first, or else do-epic parks the chunk, so the worker ends its run.""" return unanswered(number, run) or Failure(f"pull request {number} passed its checks and awaits an approval; end your run now, since do-epic parks the chunk and resumes this session once it is approved or a reviewer comments") def unanswered(number: str, run: Run) -> Failure | None: """A Failure naming the files where a reviewer's comment waits for an answer on pull request number, as `waiting_threads` finds them, or saying why they cannot be read. None where no thread waits.""" waiting = waiting_threads(number, run) if isinstance(waiting, Failure): return waiting if not waiting: return None return Failure(f"a reviewer's comment on pull request {number} waits for an answer, in {', '.join(waiting)}; answer it in its thread, push any fix, and run chunk-pr merge again") def waiting_threads(number: str, run: Run) -> list[str] | Failure: """The files where a reviewer's comment waits for an answer on pull request number, read once: those of each review thread nobody resolved, whose last comment someone other than the pull request's author wrote. So a thread the worker answered, as that author, waits for the reviewer again.""" read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"]) if isinstance(read, Failure): return read try: pull = json.loads(read)["data"]["repository"]["pullRequest"] author = pull["author"]["login"] return sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])}) except (ValueError, KeyError, TypeError): return Failure(f"gh api graphql printed no review threads: {read.strip()[:200]}")