Files
claude-config/bin/chunk_pr/approval.py
T

76 lines
4.7 KiB
Python

"""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 chunk_preflight.gathered import Forge
from deploy_release.forge import 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
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 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: a 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. None where no thread waits."""
read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"])
try:
pull = read if isinstance(read, Failure) else json.loads(read)["data"]["repository"]["pullRequest"]
if isinstance(pull, Failure):
return pull
author = pull["author"]["login"]
waiting = 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: {str(read).strip()[:200]}")
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")