Files

188 lines
9.4 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 dataclasses
import json
from failure import Failure
from forge.commands import Forge, gitea, Run
# GitHub's review decisions on a pull request. CHANGES_REQUESTED is also the state of the review that asked for them.
APPROVED = "APPROVED"
REVIEW_REQUIRED = "REVIEW_REQUIRED"
CHANGES_REQUESTED = "CHANGES_REQUESTED"
# What `review_decision` returns in place of 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
view = pull_view(viewed)
if isinstance(view, Failure):
return view
if view.draft:
return None
return ANSWERED if view.decision == CHANGES_REQUESTED and answered(view, head) else view.decision
@dataclasses.dataclass(frozen=True)
class Review:
"""One review of a pull request. GitHub lists a reply in a thread as a review of its own."""
author: str
state: str
# Empty for a review its author has yet to submit.
submitted_at: str
# The commit a review that requested changes was made on; empty for any other review.
commit: str
@dataclasses.dataclass(frozen=True)
class PullView:
"""A pull request as `gh pr view --json isDraft,reviewDecision,author,reviews,comments` prints it."""
draft: bool
# Empty where its branch protection asks for no review.
decision: str
reviews: tuple[Review, ...]
# When its author submitted each review and made each comment. A review the author has yet to submit has an empty time, and doesn't answer anyone.
said: tuple[str, ...]
# What `held` gives where the answer lacks the key asked for: of no type a field may have, so each field's check refuses it.
MISSING = object()
def held(value: object, *path: str) -> object:
"""What a forge's answer holds along path, one key per level; MISSING where a level is no object or lacks its key."""
for key in path:
value = value.get(key, MISSING) if isinstance(value, dict) else MISSING
return value
def pull_view(printed: str) -> PullView | Failure:
"""The pull request that gh printed, with each field checked here, so what decides on it meets no other shape."""
unshaped = Failure(f"gh pr view printed no review decision: {printed.strip()[:200]}")
try:
pull = json.loads(printed)
except ValueError:
return unshaped
author, draft, decision, listed, comments = held(pull, "author", "login"), held(pull, "isDraft"), held(pull, "reviewDecision") or "", held(pull, "reviews"), held(pull, "comments")
if not isinstance(author, str) or draft is MISSING or not isinstance(decision, str) or not isinstance(listed, list) or not isinstance(comments, list):
return unshaped
reviews = []
for review in listed:
reviewer, state, submitted_at = held(review, "author", "login"), held(review, "state"), held(review, "submittedAt") or ""
commit = held(review, "commit", "oid") if state == CHANGES_REQUESTED else ""
if not isinstance(reviewer, str) or not isinstance(state, str) or not isinstance(submitted_at, str) or not isinstance(commit, str):
return unshaped
reviews.append(Review(reviewer, state, submitted_at, commit))
commented = []
for comment in comments:
commenter, created_at = held(comment, "author", "login"), held(comment, "createdAt")
if not isinstance(commenter, str):
return unshaped
if commenter != author:
continue
if not isinstance(created_at, str):
return unshaped
commented.append(created_at)
return PullView(bool(draft), decision, tuple(reviews), tuple(review.submitted_at for review in reviews if review.author == author) + tuple(commented))
def answered(pull: PullView, head: str) -> bool:
"""Whether the worker answered the newest review that requested changes on pull, 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. False where pull lists no review that requested changes.
The review names the commit it was made on, so a head that differs shows the worker pushed. A commit's date cannot show that: it says when the commit was made, never when it was pushed.
"""
asked = max((review for review in pull.reviews if review.state == CHANGES_REQUESTED), key=lambda review: review.submitted_at, default=None)
if asked is None:
return False
return asked.commit != head or any(at > asked.submitted_at for at in pull.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
title = viewed.get("title") if isinstance(viewed, dict) else None
if not isinstance(title, str):
return Failure(f"tea api printed no title of pull request {pull}: {str(viewed)[:200]}")
return None if title.upper().startswith(GITEA_DRAFT) else ""
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
threads = threads_read(read)
if isinstance(threads, Failure):
return threads
return waits(*threads)
@dataclasses.dataclass(frozen=True)
class Thread:
"""One review thread of a pull request that nobody resolved."""
path: str
# Who wrote its last comment; empty for a thread without one.
last: tuple[str, ...]
def threads_read(printed: str) -> tuple[str, tuple[Thread, ...]] | Failure:
"""Who opened the pull request and its review threads that nobody resolved, as gh printed THREADS' answer, with each field checked here."""
unshaped = Failure(f"gh api graphql printed no review threads: {printed.strip()[:200]}")
try:
pull = held(json.loads(printed), "data", "repository", "pullRequest")
except ValueError:
return unshaped
author, nodes = held(pull, "author", "login"), held(pull, "reviewThreads", "nodes")
if not isinstance(author, str) or not isinstance(nodes, list):
return unshaped
threads = []
for thread in nodes:
resolved = held(thread, "isResolved")
if resolved is MISSING:
return unshaped
# A resolved thread is skipped unread: its last comment may be a deleted account's, whose author gh prints as null.
if resolved:
continue
path, comments = held(thread, "path"), held(thread, "comments", "nodes")
if not isinstance(path, str) or not isinstance(comments, list):
return unshaped
last = tuple(login for comment in comments if isinstance(login := held(comment, "author", "login"), str))
if len(last) != len(comments):
return unshaped
threads.append(Thread(path, last))
return author, tuple(threads)
def waits(author: str, threads: tuple[Thread, ...]) -> list[str]:
"""The files of the threads that wait for an answer from author, who opened the pull request."""
return sorted({thread.path for thread in threads if any(last != author for last in thread.last)})