Files
claude-config/bin/forge/reviews.py
T

87 lines
5.7 KiB
Python

"""A pull request's review state, read once from its forge: the review decision, whether it is a draft, whether the worker answered the changes a reviewer requested, and the review threads that wait for an answer. chunk-pr and do-epic decide on what this reads, and run no review query of their own."""
import json
import typing
from failure import Failure
from forge.commands import Forge, gitea, Run
# What `review_decision` returns in place of GitHub's `CHANGES_REQUESTED` once the worker answered those changes: GitHub keeps its decision until the reviewer reviews again.
ANSWERED = "CHANGES_ANSWERED"
# What the title of a draft opens with on Gitea, in any case: Gitea's default `WORK_IN_PROGRESS_PREFIXES`.
GITEA_DRAFT = ("WIP:", "[WIP]")
# 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 review_decision(forge: Forge, pull: str, head: str, run: Run) -> str | None | Failure:
"""The review decision on the pull request, whose head commit is head: `answered_decision` on GitHub, `gitea_decision` on Gitea. None where it is a draft."""
return answered_decision(pull, head, run) if forge == "gh" else gitea_decision(pull, run)
def github_decision(pull: str, run: Run) -> str | Failure:
"""GitHub's review decision on the pull request as it stands, read once: `APPROVED`, `REVIEW_REQUIRED`, `CHANGES_REQUESTED`, or empty where its branch protection asks for no review."""
viewed = run(["gh", "pr", "view", pull, "--json", "reviewDecision"])
if isinstance(viewed, Failure):
return viewed
try:
decision: str = json.loads(viewed)["reviewDecision"] or ""
return decision
except (ValueError, KeyError, TypeError):
return Failure(f"gh pr view printed no review decision: {viewed.strip()[:200]}")
def answered_decision(pull: str, head: str, run: Run) -> str | None | Failure:
"""GitHub's review decision on the pull request, whose head commit is head, read once: `APPROVED`, `REVIEW_REQUIRED`, `CHANGES_REQUESTED`, or empty where its branch protection asks for no review. ANSWERED in place of `CHANGES_REQUESTED` once the worker answered those changes. None where it is a draft."""
viewed = run(["gh", "pr", "view", pull, "--json", "isDraft,reviewDecision,author,reviews,comments"])
if isinstance(viewed, Failure):
return viewed
try:
parsed = json.loads(viewed)
if parsed["isDraft"]:
return None
decision = str(parsed["reviewDecision"] or "")
return ANSWERED if decision == "CHANGES_REQUESTED" and answered(parsed, head) else decision
except (ValueError, KeyError, TypeError):
return Failure(f"gh pr view printed no review decision: {viewed.strip()[:200]}")
def answered(pull: dict[str, typing.Any], head: str) -> bool:
"""Whether the worker answered the newest review that requested changes on pull, as `gh pr view --json author,reviews,comments` prints it, whose head commit is head: the head is no longer the commit that review was made on, or the pull request's author commented or replied in a thread after it. GitHub lists a reply in a thread as a review of its own. False where it lists no review that requested changes. Raises KeyError or TypeError where pull has another shape.
The review names its commit, so no clock tells whether the worker pushed: a commit's date says when it was made, never when it was pushed.
"""
asked = max((review for review in pull["reviews"] if review["state"] == "CHANGES_REQUESTED"), key=lambda review: review["submittedAt"], default=None)
if asked is None:
return False
author = pull["author"]["login"]
# A review the author has yet to submit has no time, and answers nobody.
said = [review["submittedAt"] or "" for review in pull["reviews"] if review["author"]["login"] == author] + [comment["createdAt"] for comment in pull["comments"] if comment["author"]["login"] == author]
return asked["commit"]["oid"] != head or any(at > asked["submittedAt"] for at in said)
def gitea_decision(pull: str, run: Run) -> str | None | Failure:
"""What stands in for `answered_decision` on Gitea, read once: empty, since no review is a gate there, and None where the pull request is a draft, which Gitea tells by its title (GITEA_DRAFT)."""
viewed = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{pull}")
if isinstance(viewed, Failure):
return viewed
try:
return None if viewed["title"].upper().startswith(GITEA_DRAFT) else ""
except (KeyError, TypeError, AttributeError):
return Failure(f"tea api printed no title of pull request {pull}: {str(viewed)[:200]}")
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]}")