149 lines
7.9 KiB
Python
149 lines
7.9 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 no time: it is empty, and answers nobody.
|
|
said: tuple[str, ...]
|
|
|
|
|
|
def text(value: object) -> str:
|
|
"""value, which a forge's answer must hold as a string. Raises TypeError where it is none."""
|
|
if not isinstance(value, str):
|
|
raise TypeError(f"{value!r} is not a string")
|
|
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."""
|
|
try:
|
|
pull = json.loads(printed)
|
|
author = text(pull["author"]["login"])
|
|
reviews = tuple(Review(text(review["author"]["login"]), text(review["state"]), text(review["submittedAt"] or ""), text(review["commit"]["oid"]) if review["state"] == CHANGES_REQUESTED else "") for review in pull["reviews"])
|
|
commented = tuple(text(comment["createdAt"]) for comment in pull["comments"] if text(comment["author"]["login"]) == author)
|
|
return PullView(bool(pull["isDraft"]), text(pull["reviewDecision"] or ""), reviews, tuple(review.submitted_at for review in reviews if review.author == author) + commented)
|
|
except (ValueError, KeyError, TypeError):
|
|
return Failure(f"gh pr view printed no review decision: {printed.strip()[:200]}")
|
|
|
|
|
|
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 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.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."""
|
|
path: str
|
|
resolved: bool
|
|
# 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, as gh printed THREADS' answer, with each field checked here."""
|
|
try:
|
|
pull = json.loads(printed)["data"]["repository"]["pullRequest"]
|
|
threads = tuple(Thread(text(thread["path"]), bool(thread["isResolved"]), tuple(text(comment["author"]["login"]) for comment in thread["comments"]["nodes"])) for thread in pull["reviewThreads"]["nodes"])
|
|
return text(pull["author"]["login"]), threads
|
|
except (ValueError, KeyError, TypeError):
|
|
return Failure(f"gh api graphql printed no review threads: {printed.strip()[:200]}")
|
|
|
|
|
|
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 not thread.resolved and any(last != author for last in thread.last)})
|