|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Gate the pr-review workflow: resolve trigger, validate, emit outputs. |
| 3 | +
|
| 4 | +Reads trigger context from environment variables, decides whether the agent |
| 5 | +should run, and writes outputs to $GITHUB_OUTPUT: |
| 6 | +
|
| 7 | + should_run - "true" if the agent should run, else "false" |
| 8 | + pr_number - PR number to review |
| 9 | + model - resolved Copilot model (default if override invalid) |
| 10 | + model_warning - human-readable warning if the requested model was rejected |
| 11 | + triggered_by - short string for the review-body footer |
| 12 | + base_ref_oid - PR base commit SHA, used by the agent's checkout step |
| 13 | +
|
| 14 | +Required env: GH_TOKEN, EVENT_NAME, DEFAULT_MODEL, ALLOWED_MODELS, plus the |
| 15 | +trigger-specific variables documented inline. |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import os |
| 21 | +import re |
| 22 | +import sys |
| 23 | +from pathlib import Path |
| 24 | + |
| 25 | +from common import gh_json, progress |
| 26 | + |
| 27 | + |
| 28 | +REVIEW_RE = re.compile(r"^/review(?:\s+(\S+))?\s*$") |
| 29 | + |
| 30 | + |
| 31 | +def emit(outputs: dict[str, str]) -> None: |
| 32 | + path = os.environ.get("GITHUB_OUTPUT") |
| 33 | + if not path: |
| 34 | + for key, value in outputs.items(): |
| 35 | + print(f"{key}={value}") |
| 36 | + return |
| 37 | + with Path(path).open("a", encoding="utf-8") as f: |
| 38 | + for key, value in outputs.items(): |
| 39 | + if "\n" in value: |
| 40 | + f.write(f"{key}<<__GATE_EOF__\n{value}\n__GATE_EOF__\n") |
| 41 | + else: |
| 42 | + f.write(f"{key}={value}\n") |
| 43 | + |
| 44 | + |
| 45 | +def skip(reason: str) -> int: |
| 46 | + progress(f"Gate: {reason} - skipping run.") |
| 47 | + emit( |
| 48 | + { |
| 49 | + "should_run": "false", |
| 50 | + "pr_number": "", |
| 51 | + "model": "", |
| 52 | + "model_warning": "", |
| 53 | + "triggered_by": "", |
| 54 | + "base_ref_oid": "", |
| 55 | + } |
| 56 | + ) |
| 57 | + return 0 |
| 58 | + |
| 59 | + |
| 60 | +def resolve_model(requested: str, default_model: str, allowed_models: str) -> tuple[str, str]: |
| 61 | + if not requested: |
| 62 | + return default_model, "" |
| 63 | + allowed = {m.strip() for m in allowed_models.split(",") if m.strip()} |
| 64 | + if requested in allowed: |
| 65 | + return requested, "" |
| 66 | + return ( |
| 67 | + default_model, |
| 68 | + f"requested model `{requested}` is not in the allowlist; using default `{default_model}`.", |
| 69 | + ) |
| 70 | + |
| 71 | + |
| 72 | +def commenter_has_write_access(repo: str, login: str) -> bool: |
| 73 | + # gh returns non-zero (404) for users without an explicit collaborator |
| 74 | + # entry, which we treat the same as "no write access". This also denies |
| 75 | + # on transient gh/API failures, which is the safer default for a gate |
| 76 | + # that controls whether the reviewer agent runs. |
| 77 | + try: |
| 78 | + result = gh_json( |
| 79 | + ["api", f"repos/{repo}/collaborators/{login}/permission", "-q", ".permission"], |
| 80 | + ) |
| 81 | + except Exception: |
| 82 | + return False |
| 83 | + # gh_json returns parsed JSON; with -q the output is a bare string. |
| 84 | + return result in {"admin", "write"} |
| 85 | + |
| 86 | + |
| 87 | +class SkipRun(Exception): |
| 88 | + """Raised to abort the gate cleanly with a skip outcome.""" |
| 89 | + |
| 90 | + |
| 91 | +def resolve_trigger(env: dict[str, str]) -> tuple[str, str, str, str]: |
| 92 | + """Return (pr, model, warning, triggered_by). Raises SkipRun to skip.""" |
| 93 | + event = env.get("EVENT_NAME", "") |
| 94 | + default_model = env.get("DEFAULT_MODEL", "") |
| 95 | + allowed_models = env.get("ALLOWED_MODELS", "") |
| 96 | + repo = env.get("GITHUB_REPOSITORY", "") |
| 97 | + |
| 98 | + if event == "pull_request_target": |
| 99 | + pr = env.get("PR_FROM_PR_EVENT", "") |
| 100 | + if not pr: |
| 101 | + raise SkipRun("no PR number on pull_request_target event") |
| 102 | + model, warning = resolve_model("", default_model, allowed_models) |
| 103 | + return pr, model, warning, "ready_for_review" |
| 104 | + |
| 105 | + if event == "issue_comment": |
| 106 | + pr = env.get("PR_FROM_COMMENT", "") |
| 107 | + if not pr: |
| 108 | + raise SkipRun("no PR number on issue_comment event") |
| 109 | + body = (env.get("COMMENT_BODY", "") or "").strip() |
| 110 | + match = REVIEW_RE.match(body) |
| 111 | + if not match: |
| 112 | + raise SkipRun("comment body does not match /review[ <model>]") |
| 113 | + author = env.get("COMMENT_AUTHOR", "") |
| 114 | + if not author or not commenter_has_write_access(repo, author): |
| 115 | + raise SkipRun(f"commenter @{author} lacks write permission") |
| 116 | + requested_model = match.group(1) or "" |
| 117 | + model, warning = resolve_model(requested_model, default_model, allowed_models) |
| 118 | + return pr, model, warning, f"`/review` by @{author}" |
| 119 | + |
| 120 | + raise SkipRun(f"unsupported event: {event}") |
| 121 | + |
| 122 | + |
| 123 | +def pr_state(repo: str, pr: str) -> dict | None: |
| 124 | + try: |
| 125 | + return gh_json( |
| 126 | + ["pr", "view", pr, "--repo", repo, "--json", "state,baseRefOid,isDraft,number"], |
| 127 | + ) |
| 128 | + except Exception: |
| 129 | + return None |
| 130 | + |
| 131 | + |
| 132 | +def main() -> int: |
| 133 | + env = os.environ |
| 134 | + repo = env.get("GITHUB_REPOSITORY", "") |
| 135 | + |
| 136 | + try: |
| 137 | + pr, model, warning, triggered_by = resolve_trigger(env) |
| 138 | + info = pr_state(repo, pr) |
| 139 | + if not info: |
| 140 | + raise SkipRun(f"PR #{pr} not found") |
| 141 | + if info.get("state") != "OPEN": |
| 142 | + raise SkipRun(f"PR #{pr} is not open (state={info.get('state')})") |
| 143 | + if info.get("isDraft") and env.get("EVENT_NAME") != "issue_comment": |
| 144 | + raise SkipRun(f"PR #{pr} is a draft and trigger is {env.get('EVENT_NAME')}") |
| 145 | + base_ref_oid = info.get("baseRefOid", "") |
| 146 | + except SkipRun as e: |
| 147 | + return skip(str(e)) |
| 148 | + |
| 149 | + progress(f"Gate accepted: pr={pr} trigger={triggered_by} model={model}") |
| 150 | + emit( |
| 151 | + { |
| 152 | + "should_run": "true", |
| 153 | + "pr_number": str(pr), |
| 154 | + "model": model, |
| 155 | + "model_warning": warning, |
| 156 | + "triggered_by": triggered_by, |
| 157 | + "base_ref_oid": base_ref_oid, |
| 158 | + } |
| 159 | + ) |
| 160 | + return 0 |
| 161 | + |
| 162 | + |
| 163 | +if __name__ == "__main__": |
| 164 | + sys.exit(main()) |
0 commit comments