|
| 1 | +"""Human-gated PR merging: a condition carrying a JSON payload. |
| 2 | +
|
| 3 | +The headline pattern. A task collects review metadata from a pull request, |
| 4 | +embeds it as JSON in a markdown condition prompt, parks the run until a human |
| 5 | +responds in the Flyte UI, and parses the structured response into a typed |
| 6 | +decision the workflow branches on. Approved PRs get merged. |
| 7 | +
|
| 8 | +Conditions are Flyte's; talking to GitHub is PyGithub's. Nothing here wraps the |
| 9 | +GitHub API — `flyte.new_condition` is the only part that needed inventing. |
| 10 | +
|
| 11 | +Requirements: |
| 12 | + pip install flyte PyGithub |
| 13 | +
|
| 14 | +Setup: |
| 15 | + flyte create secret GITHUB_TOKEN --value <token-with-repo-scope> |
| 16 | +
|
| 17 | +Usage: |
| 18 | + flyte run examples/external_saas_integrations/github_pr_review_gate.py \\ |
| 19 | + gated_merge --repo octocat/hello-world --number 1 |
| 20 | +""" |
| 21 | + |
| 22 | +import asyncio |
| 23 | +import json |
| 24 | +import os |
| 25 | +from datetime import timedelta |
| 26 | +from typing import Any, Literal |
| 27 | + |
| 28 | +from pydantic import BaseModel, Field |
| 29 | + |
| 30 | +import flyte |
| 31 | + |
| 32 | +image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("PyGithub", "pydantic") |
| 33 | + |
| 34 | +env = flyte.TaskEnvironment( |
| 35 | + name="github-review-gate", |
| 36 | + image=image, |
| 37 | + secrets=[flyte.Secret("GITHUB_TOKEN", as_env_var="GITHUB_TOKEN")], |
| 38 | +) |
| 39 | + |
| 40 | +Verdict = Literal["approve", "request_changes", "comment"] |
| 41 | + |
| 42 | + |
| 43 | +class ReviewComment(BaseModel): |
| 44 | + """A single inline review comment.""" |
| 45 | + |
| 46 | + path: str |
| 47 | + line: int | None = None |
| 48 | + body: str |
| 49 | + severity: Literal["info", "warning", "blocking"] = "info" |
| 50 | + |
| 51 | + |
| 52 | +class ReviewDecision(BaseModel): |
| 53 | + """The reviewer's answer, parsed out of their condition response.""" |
| 54 | + |
| 55 | + verdict: Verdict |
| 56 | + summary: str = "" |
| 57 | + comments: list[ReviewComment] = Field(default_factory=list) |
| 58 | + |
| 59 | + @property |
| 60 | + def is_approved(self) -> bool: |
| 61 | + return self.verdict == "approve" |
| 62 | + |
| 63 | + @property |
| 64 | + def blocking_comments(self) -> list[ReviewComment]: |
| 65 | + return [c for c in self.comments if c.severity == "blocking"] |
| 66 | + |
| 67 | + |
| 68 | +def _normalize_verdict(value: str) -> Verdict: |
| 69 | + v = value.strip().lower().replace(" ", "_").replace("-", "_") |
| 70 | + if v in ("approve", "approved", "lgtm", "accept"): |
| 71 | + return "approve" |
| 72 | + if v in ("request_changes", "changes_requested", "reject", "blocked"): |
| 73 | + return "request_changes" |
| 74 | + if v in ("comment", "comments", "neutral", "note"): |
| 75 | + return "comment" |
| 76 | + raise ValueError(f"unknown verdict: {value!r}") |
| 77 | + |
| 78 | + |
| 79 | +def parse_review_payload(payload: str) -> ReviewDecision: |
| 80 | + """Parse a reviewer's response into a `ReviewDecision`. |
| 81 | +
|
| 82 | + Accepts raw JSON, JSON inside a fenced code block, or prose with a JSON |
| 83 | + object somewhere in it — people paste all three. Verdict synonyms are |
| 84 | + normalized. |
| 85 | +
|
| 86 | + Raises: |
| 87 | + ValueError: when no JSON object with a recognizable verdict is found. |
| 88 | + """ |
| 89 | + text = (payload or "").strip() |
| 90 | + if not text: |
| 91 | + raise ValueError("empty review payload") |
| 92 | + |
| 93 | + decoder = json.JSONDecoder() |
| 94 | + idx = text.find("{") |
| 95 | + while idx != -1: |
| 96 | + try: |
| 97 | + obj, _ = decoder.raw_decode(text[idx:]) |
| 98 | + except json.JSONDecodeError: |
| 99 | + obj = None |
| 100 | + if isinstance(obj, dict) and "verdict" in obj: |
| 101 | + comments = obj.get("comments") or [] |
| 102 | + return ReviewDecision( |
| 103 | + verdict=_normalize_verdict(str(obj["verdict"])), |
| 104 | + summary=str(obj.get("summary") or ""), |
| 105 | + comments=[ReviewComment.model_validate(c) for c in comments if isinstance(c, dict)], |
| 106 | + ) |
| 107 | + idx = text.find("{", idx + 1) |
| 108 | + raise ValueError(f"could not extract a review decision from payload: {text[:200]!r}") |
| 109 | + |
| 110 | + |
| 111 | +def _collect_context(repo: str, number: int, max_files: int = 50) -> dict[str, Any]: |
| 112 | + """Gather what a reviewer needs, using PyGithub.""" |
| 113 | + from github import Auth, Github |
| 114 | + |
| 115 | + with Github(auth=Auth.Token(os.environ["GITHUB_TOKEN"])) as gh: |
| 116 | + pr = gh.get_repo(repo).get_pull(number) |
| 117 | + files = [ |
| 118 | + { |
| 119 | + "filename": f.filename, |
| 120 | + "status": f.status, |
| 121 | + "additions": f.additions, |
| 122 | + "deletions": f.deletions, |
| 123 | + # Patches dominate the prompt; keep them for the first handful only. |
| 124 | + "patch": f.patch if i < 20 else None, |
| 125 | + } |
| 126 | + for i, f in enumerate(pr.get_files()[:max_files]) |
| 127 | + ] |
| 128 | + return { |
| 129 | + "repo": repo, |
| 130 | + "number": number, |
| 131 | + "title": pr.title, |
| 132 | + "author": pr.user.login if pr.user else None, |
| 133 | + "body": pr.body or "", |
| 134 | + "base": pr.base.ref, |
| 135 | + "head": pr.head.ref, |
| 136 | + "url": pr.html_url, |
| 137 | + "additions": pr.additions, |
| 138 | + "deletions": pr.deletions, |
| 139 | + "changed_files": pr.changed_files, |
| 140 | + "files": files, |
| 141 | + "prior_reviews": [{"user": r.user.login if r.user else None, "state": r.state} for r in pr.get_reviews()], |
| 142 | + } |
| 143 | + |
| 144 | + |
| 145 | +def build_review_prompt(context: dict[str, Any], instructions: str = "") -> str: |
| 146 | + """Build the markdown prompt the reviewer sees in the Flyte UI. |
| 147 | +
|
| 148 | + The metadata goes in a fenced JSON block so it renders verbatim and can be |
| 149 | + machine-read downstream. |
| 150 | + """ |
| 151 | + instructions = instructions or ( |
| 152 | + "Review this pull request. Respond with a JSON object of the form:\n" |
| 153 | + '`{"verdict": "approve" | "request_changes" | "comment", ' |
| 154 | + '"summary": "...", "comments": [{"path": "...", "line": 1, ' |
| 155 | + '"body": "...", "severity": "info" | "warning" | "blocking"}]}`' |
| 156 | + ) |
| 157 | + return ( |
| 158 | + f"## Review requested: {context['repo']}#{context['number']}\n\n" |
| 159 | + f"**{context['title']}** (by {context.get('author') or 'unknown'})\n\n" |
| 160 | + f"{context.get('body', '')}\n\n" |
| 161 | + f"{instructions}\n\n" |
| 162 | + "### Pull request metadata\n\n" |
| 163 | + "```json\n" |
| 164 | + f"{json.dumps(context, indent=2)}\n" |
| 165 | + "```\n" |
| 166 | + ) |
| 167 | + |
| 168 | + |
| 169 | +@env.task |
| 170 | +async def review_pr(repo: str, number: int, timeout: timedelta | None = None) -> ReviewDecision: |
| 171 | + """Park the run on a human review condition and return the decision.""" |
| 172 | + context = await asyncio.to_thread(_collect_context, repo, number) |
| 173 | + condition = await flyte.new_condition.aio( |
| 174 | + f"review-{repo.replace('/', '-')}-{number}"[:60], |
| 175 | + prompt=build_review_prompt(context), |
| 176 | + prompt_type="markdown", |
| 177 | + data_type=str, |
| 178 | + timeout=timeout, |
| 179 | + ) |
| 180 | + return parse_review_payload(await condition.wait.aio()) |
| 181 | + |
| 182 | + |
| 183 | +@env.task |
| 184 | +async def gated_merge(repo: str, number: int) -> str: |
| 185 | + """Wait for a human review, then merge if approved.""" |
| 186 | + decision = await review_pr(repo, number) |
| 187 | + |
| 188 | + if not decision.is_approved: |
| 189 | + await asyncio.to_thread(_comment, repo, number, f"Review gate blocked this merge: {decision.summary}") |
| 190 | + return f"blocked: {decision.summary}" |
| 191 | + |
| 192 | + return await asyncio.to_thread(_merge, repo, number) |
| 193 | + |
| 194 | + |
| 195 | +def _comment(repo: str, number: int, body: str) -> None: |
| 196 | + from github import Auth, Github |
| 197 | + |
| 198 | + with Github(auth=Auth.Token(os.environ["GITHUB_TOKEN"])) as gh: |
| 199 | + gh.get_repo(repo).get_issue(number).create_comment(body) |
| 200 | + |
| 201 | + |
| 202 | +def _merge(repo: str, number: int) -> str: |
| 203 | + from github import Auth, Github |
| 204 | + |
| 205 | + with Github(auth=Auth.Token(os.environ["GITHUB_TOKEN"])) as gh: |
| 206 | + result = gh.get_repo(repo).get_pull(number).merge(merge_method="squash") |
| 207 | + return f"merged {result.sha}" |
| 208 | + |
| 209 | + |
| 210 | +if __name__ == "__main__": |
| 211 | + flyte.init_from_config() |
| 212 | + run = flyte.with_runcontext().run(gated_merge, repo="octocat/hello-world", number=1) |
| 213 | + print(run.url) |
0 commit comments