132 lines
7.3 KiB
Python
132 lines
7.3 KiB
Python
"""What the pull request of a do-epic chunk waits on, read once from its forge (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates").
|
|
|
|
A gate is something only time or a person passes: checks that still run, an approval a reviewer has yet to give, or the new review of a reviewer whose requested changes the worker answered. While a chunk's pull request waits on one, its worker doesn't have anything to do, so do-epic parks the chunk (`parked`). Anything else is news the worker acts on."""
|
|
import dataclasses
|
|
import json
|
|
import typing
|
|
|
|
from forge.pulls import CheckFailed, checks_now, open_pull, Pending, required_checks
|
|
from failure import Failure
|
|
from forge.commands import forge_of, gitea, Run
|
|
from chunk_pr.approval import waiting_threads
|
|
|
|
# What a pull request waits on, as the words after "awaits".
|
|
CHECKS = "its checks"
|
|
APPROVAL = "an approval"
|
|
NEW_REVIEW = "a new review"
|
|
# 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]")
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Gate:
|
|
"""The gate a chunk's open pull request waits on."""
|
|
# The chunk's worktree, where the pull request's branch is checked out.
|
|
worktree: str
|
|
# The pull request's number.
|
|
pull: str
|
|
# CHECKS, APPROVAL or NEW_REVIEW.
|
|
on: str
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Open:
|
|
"""A chunk that waits on no gate, so its worker goes on."""
|
|
# Why, as a sentence without its full stop, for the worker of a chunk that was parked.
|
|
news: str
|
|
|
|
|
|
def gate(branch: str, checkout: str, at: typing.Callable[[str], Run]) -> Gate | Open | Failure:
|
|
"""What the chunk on branch waits on, in a worktree of checkout; at gives the runner of commands in a folder. A Failure where git or the forge cannot be read, which doesn't say anything about the gate.
|
|
|
|
A draft never waits on a gate: its worker still works on it. On Gitea only the checks are a gate, since chunk-pr reads approvals on GitHub only (`chunk_pr.approval.awaited`). Changes a reviewer requested are news until the worker answered them (`answered`); from then on the pull request awaits a new review.
|
|
"""
|
|
worktree = worktree_of(branch, at(checkout))
|
|
if not isinstance(worktree, str):
|
|
return worktree or Open(f"no worktree of {checkout} has the branch {branch} checked out")
|
|
run = at(worktree)
|
|
read = [run(["git", *args]) for args in (["remote", "get-url", "origin"], ["rev-parse", "HEAD"], ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])]
|
|
failed = next((answer for answer in read if isinstance(answer, Failure)), None)
|
|
if failed is not None:
|
|
return failed
|
|
origin, head, base = (str(answer).strip() for answer in read)
|
|
forge = forge_of(origin)
|
|
pull = open_pull(forge, branch, head, run)
|
|
if not isinstance(pull, str):
|
|
return pull or Open(f"no pull request from origin's {branch} is open at {head[:12]}; it may be merged or closed already")
|
|
decision = review_decision(pull, head, run) if forge == "gh" else gitea_decision(pull, run)
|
|
if not isinstance(decision, str):
|
|
return decision or Open(f"pull request #{pull} is a draft")
|
|
required = required_checks(forge, base.removeprefix("origin/"), run)
|
|
checks = required if isinstance(required, Failure) else checks_now(forge, pull, head, required, run)
|
|
if isinstance(checks, CheckFailed):
|
|
return Open(f"{checks.reason}; fix it and push")
|
|
if isinstance(checks, Failure):
|
|
return checks
|
|
if isinstance(checks, Pending):
|
|
return Gate(worktree, pull, CHECKS)
|
|
if decision == "CHANGES_REQUESTED":
|
|
return Open(f"a reviewer requested changes on pull request #{pull}")
|
|
waiting = waiting_threads(pull, run) if forge == "gh" else []
|
|
if isinstance(waiting, Failure):
|
|
return waiting
|
|
if waiting:
|
|
return Open(f"a reviewer's comment on pull request #{pull} waits for an answer, in {', '.join(waiting)}")
|
|
if decision in (ANSWERED, "REVIEW_REQUIRED"):
|
|
return Gate(worktree, pull, NEW_REVIEW if decision == ANSWERED else APPROVAL)
|
|
return Open(f"pull request #{pull} passed its checks" + (" and is approved" if decision == "APPROVED" else ""))
|
|
|
|
|
|
def worktree_of(branch: str, run: Run) -> str | None | Failure:
|
|
"""The worktree, of the checkout run works in, that has branch checked out; None where none has."""
|
|
listed = run(["git", "worktree", "list", "--porcelain"])
|
|
if isinstance(listed, Failure):
|
|
return listed
|
|
for block in listed.split("\n\n"):
|
|
lines = block.splitlines()
|
|
if f"branch refs/heads/{branch}" in lines and lines[0].startswith("worktree "):
|
|
return lines[0].removeprefix("worktree ")
|
|
return None
|
|
|
|
|
|
def review_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 `review_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]}")
|