|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Run PR triage slash commands from issue comments.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import argparse |
| 7 | +import json |
| 8 | +import os |
| 9 | +import subprocess |
| 10 | +import sys |
| 11 | +import traceback |
| 12 | +from pathlib import Path |
| 13 | +from typing import Any |
| 14 | +from urllib.parse import quote |
| 15 | + |
| 16 | +from common import REPO_ROOT, gh, gh_json, progress |
| 17 | + |
| 18 | + |
| 19 | +COMMANDS = { |
| 20 | + "/run-spotless": "run_spotless", |
| 21 | + "/fix-ci": "fix_ci", |
| 22 | + "/resolve-conflicts": "resolve_conflicts", |
| 23 | + "/review": "review", |
| 24 | +} |
| 25 | +OUTPUT_LIMIT = 6000 |
| 26 | + |
| 27 | + |
| 28 | +def parse_args() -> argparse.Namespace: |
| 29 | + parser = argparse.ArgumentParser(description=__doc__) |
| 30 | + subparsers = parser.add_subparsers(dest="command", required=True) |
| 31 | + subparsers.add_parser("authorize", help="authorize the issue commenter and PR author") |
| 32 | + subparsers.add_parser("execute", help="run the selected PR triage command and comment with the result") |
| 33 | + return parser.parse_args() |
| 34 | + |
| 35 | + |
| 36 | +def event_payload() -> dict[str, Any]: |
| 37 | + path = os.environ.get("GITHUB_EVENT_PATH") |
| 38 | + if not path: |
| 39 | + raise RuntimeError("GITHUB_EVENT_PATH is not set") |
| 40 | + return json.loads(Path(path).read_text(encoding="utf-8")) |
| 41 | + |
| 42 | + |
| 43 | +def event_repo() -> str: |
| 44 | + return os.environ["GITHUB_REPOSITORY"] |
| 45 | + |
| 46 | + |
| 47 | +def pr_number() -> str: |
| 48 | + return os.environ["PR_NUMBER"] |
| 49 | + |
| 50 | + |
| 51 | +def parsed_command() -> tuple[str, str]: |
| 52 | + payload = event_payload() |
| 53 | + comment = payload.get("comment") or {} |
| 54 | + body = str(comment.get("body") or "").strip() |
| 55 | + first_line = body.splitlines()[0].strip() if body else "" |
| 56 | + requested = first_line.split(maxsplit=1)[0].lower() if first_line else "" |
| 57 | + command = COMMANDS.get(requested, "") |
| 58 | + return requested, command |
| 59 | + |
| 60 | + |
| 61 | +def gh_json_or_none(args: list[str]) -> object | None: |
| 62 | + result = gh(args, check=False) |
| 63 | + if result.returncode == 0: |
| 64 | + return json.loads(result.stdout or "null") |
| 65 | + if "HTTP 404" in result.stderr or "Not Found" in result.stderr: |
| 66 | + return None |
| 67 | + raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "gh api failed") |
| 68 | + |
| 69 | + |
| 70 | +def has_repo_write(login: str) -> bool: |
| 71 | + encoded_login = quote(login, safe="") |
| 72 | + data = gh_json_or_none(["api", f"repos/{event_repo()}/collaborators/{encoded_login}/permission"]) |
| 73 | + if not isinstance(data, dict): |
| 74 | + return False |
| 75 | + return data.get("permission") in {"admin", "maintain", "write"} |
| 76 | + |
| 77 | + |
| 78 | +def comment_on_pr(body: str) -> None: |
| 79 | + gh(["issue", "comment", pr_number(), "--repo", event_repo(), "--body", body]) |
| 80 | + |
| 81 | + |
| 82 | +def authorization_reason() -> str | None: |
| 83 | + payload = event_payload() |
| 84 | + comment = payload.get("comment") or {} |
| 85 | + commenter = str((comment.get("user") or {}).get("login") or "") |
| 86 | + |
| 87 | + if not has_repo_write(commenter): |
| 88 | + return ( |
| 89 | + "for security reasons, PR triage commands can only be run by users " |
| 90 | + "who have write access to this repository" |
| 91 | + ) |
| 92 | + |
| 93 | + pr = gh_json(["api", f"repos/{event_repo()}/pulls/{pr_number()}"]) |
| 94 | + author = pr["user"]["login"] |
| 95 | + if not has_repo_write(author): |
| 96 | + return ( |
| 97 | + "for security reasons, PR triage commands are only supported on PRs " |
| 98 | + "from authors who already have write access to this repository" |
| 99 | + ) |
| 100 | + return None |
| 101 | + |
| 102 | + |
| 103 | +def authorize_command() -> int: |
| 104 | + requested, command = parsed_command() |
| 105 | + if requested != "/help" and not command: |
| 106 | + # Not a recognized PR triage command: stay silent and skip. |
| 107 | + print("false") |
| 108 | + return 0 |
| 109 | + reason = authorization_reason() |
| 110 | + if reason: |
| 111 | + comment_on_pr(f"I did not run `{requested}`: {reason}.") |
| 112 | + print("false") |
| 113 | + return 0 |
| 114 | + print("true") |
| 115 | + return 0 |
| 116 | + |
| 117 | + |
| 118 | +def output_file() -> Path: |
| 119 | + return Path(os.environ["RUNNER_TEMP"]) / "pr-triage-output.txt" |
| 120 | + |
| 121 | + |
| 122 | +def command_args(command: str) -> list[str]: |
| 123 | + if command == "run_spotless": |
| 124 | + return [sys.executable, ".github/scripts/pr-triage/run_spotless.py", pr_number()] |
| 125 | + if command == "fix_ci": |
| 126 | + return [sys.executable, ".github/scripts/pr-triage/fix_ci.py", pr_number()] |
| 127 | + if command == "resolve_conflicts": |
| 128 | + return [sys.executable, ".github/scripts/pr-triage/resolve_conflicts.py", pr_number()] |
| 129 | + if command == "review": |
| 130 | + return [sys.executable, ".github/scripts/pr-triage/review.py", pr_number()] |
| 131 | + raise RuntimeError(f"Unknown command: {command}") |
| 132 | + |
| 133 | + |
| 134 | +def run_command(command: str) -> int: |
| 135 | + cmd = command_args(command) |
| 136 | + progress("Running: " + " ".join(cmd)) |
| 137 | + path = output_file() |
| 138 | + with path.open("w", encoding="utf-8", errors="replace") as output: |
| 139 | + proc = subprocess.Popen( |
| 140 | + cmd, |
| 141 | + cwd=REPO_ROOT, |
| 142 | + stdout=subprocess.PIPE, |
| 143 | + stderr=subprocess.STDOUT, |
| 144 | + text=True, |
| 145 | + encoding="utf-8", |
| 146 | + errors="replace", |
| 147 | + bufsize=1, |
| 148 | + ) |
| 149 | + if proc.stdout is not None: |
| 150 | + for line in proc.stdout: |
| 151 | + print(line, end="", flush=True) |
| 152 | + output.write(line) |
| 153 | + status = proc.wait() |
| 154 | + return status |
| 155 | + |
| 156 | + |
| 157 | +def finish_command(requested: str, exit_code: int) -> int: |
| 158 | + if exit_code == 0: |
| 159 | + status = "completed successfully" |
| 160 | + else: |
| 161 | + status = "failed" |
| 162 | + |
| 163 | + path = output_file() |
| 164 | + if path.exists(): |
| 165 | + output = path.read_text(encoding="utf-8", errors="replace") |
| 166 | + if len(output) > OUTPUT_LIMIT: |
| 167 | + output = "...[output truncated]...\n" + output[-OUTPUT_LIMIT:] |
| 168 | + else: |
| 169 | + output = "No command output was captured." |
| 170 | + |
| 171 | + comment_on_pr(f"`{requested}` {status}.\n\n```text\n{output}\n```") |
| 172 | + return 0 |
| 173 | + |
| 174 | + |
| 175 | +def execute_command() -> int: |
| 176 | + requested, command = parsed_command() |
| 177 | + if requested == "/help": |
| 178 | + supported = ", ".join(f"`{command_name}`" for command_name in COMMANDS) |
| 179 | + comment_on_pr(f"Supported PR triage commands: {supported}.") |
| 180 | + return 0 |
| 181 | + if not command: |
| 182 | + # authorize_command() already filtered unsupported/unauthorized cases. |
| 183 | + return 0 |
| 184 | + |
| 185 | + try: |
| 186 | + exit_code = run_command(command) |
| 187 | + except Exception: |
| 188 | + exit_code = 1 |
| 189 | + output_file().write_text(traceback.format_exc(), encoding="utf-8", errors="replace") |
| 190 | + finish_command(requested, exit_code) |
| 191 | + raise |
| 192 | + |
| 193 | + finish_command(requested, exit_code) |
| 194 | + return exit_code |
| 195 | + |
| 196 | + |
| 197 | +def main() -> int: |
| 198 | + args = parse_args() |
| 199 | + if args.command == "authorize": |
| 200 | + return authorize_command() |
| 201 | + if args.command == "execute": |
| 202 | + return execute_command() |
| 203 | + raise AssertionError(args.command) |
| 204 | + |
| 205 | + |
| 206 | +if __name__ == "__main__": |
| 207 | + sys.exit(main()) |
0 commit comments