-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathgithub.py
More file actions
331 lines (284 loc) · 11.2 KB
/
Copy pathgithub.py
File metadata and controls
331 lines (284 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""GitHub data fetching via gh CLI + local git.
File stats come from the local checkout (git diff --numstat), everything
else (PR metadata, reviews, comments, check runs) from the GitHub API.
Also handles team membership checks for the ownership gate.
"""
import json
import subprocess
from dataclasses import dataclass, field
from pathlib import Path
@dataclass
class PRData:
"""All GitHub data needed to evaluate a PR."""
number: int
repo: str
title: str
state: str
draft: bool
mergeable_state: str
author: str
labels: list[str]
base_sha: str
head_sha: str
files: list[dict]
reviews: list[dict]
review_comments: list[dict]
check_runs: list[dict]
pr_reactions: list[dict] = field(default_factory=list)
@property
def file_paths(self) -> list[str]:
return [f["filename"] for f in self.files]
@property
def lines_added(self) -> int:
return sum(f["additions"] for f in self.files)
@property
def lines_deleted(self) -> int:
return sum(f["deletions"] for f in self.files)
@property
def lines_total(self) -> int:
return self.lines_added + self.lines_deleted
@property
def has_new_files(self) -> bool:
return any(f.get("status") == "A" for f in self.files)
_TRUSTED_ASSOCIATIONS = {"MEMBER", "OWNER", "COLLABORATOR"}
TRUSTED_REACTOR_BOTS = {
"chatgpt-codex-connector[bot]",
"copilot-pull-request-reviewer[bot]",
"greptile-apps[bot]",
"hex-security-app[bot]",
"posthog[bot]",
"veria-ai[bot]",
}
def _normalize_reviews_for_prompt(reviews_raw: list[dict], head_sha: str) -> list[dict]:
"""Normalize top-level reviews for the reviewer prompt.
Preserve trusted/bot reviews, and annotate whether each review was left on
the current PR head. This lets the LLM distinguish active feedback from
older context that may already have been addressed in follow-up commits.
"""
normalized_reviews = []
for review in reviews_raw:
if not (
review.get("author_association") in _TRUSTED_ASSOCIATIONS
or review.get("author_association") == "BOT"
or review.get("user", {}).get("type") == "Bot"
):
continue
commit_id = review.get("commit_id")
normalized_reviews.append(
{
"user": review["user"]["login"],
"state": review["state"],
"body": review.get("body", ""),
"commit_id": commit_id,
"is_current_head": commit_id == head_sha,
"submitted_at": review.get("submitted_at"),
}
)
return normalized_reviews
def _normalize_pr_reactions(reactions_raw: list[dict], author: str) -> list[dict]:
normalized = []
for reaction in reactions_raw:
login = (reaction.get("user") or {}).get("login", "")
if login == author or login.lower() not in TRUSTED_REACTOR_BOTS:
continue
normalized.append(
{
"user": login,
"emoji": {"+1": "👍", "-1": "👎", "eyes": "👀"}.get(reaction.get("content"), reaction.get("content")),
"created_at": reaction.get("created_at"),
}
)
return normalized
def _gh_api(endpoint: str, *, paginate: bool = False) -> dict | list:
cmd = ["gh", "api", endpoint]
if paginate:
cmd.append("--paginate")
else:
sep = "&" if "?" in endpoint else "?"
cmd[2] = f"{endpoint}{sep}per_page=100"
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
raise RuntimeError(f"gh api {endpoint} failed: {result.stderr.strip()}")
return json.loads(result.stdout)
_REVIEW_THREADS_QUERY = """
query($owner: String!, $name: String!, $pr: Int!, $threadCursor: String) {
repository(owner: $owner, name: $name) {
pullRequest(number: $pr) {
reviewThreads(first: 100, after: $threadCursor) {
pageInfo { hasNextPage endCursor }
nodes {
isResolved
isOutdated
path
line
comments(first: 50) {
pageInfo { hasNextPage }
nodes {
author { login __typename }
authorAssociation
body
databaseId
replyTo { databaseId }
}
}
}
}
}
}
}
"""
def _gh_graphql(query: str, variables: dict | None = None) -> dict:
"""Run a GraphQL query via gh api graphql with proper variable passing."""
cmd = ["gh", "api", "graphql", "-f", f"query={query}"]
for key, value in (variables or {}).items():
if value is None:
cmd.extend(["-F", f"{key}=null"])
elif isinstance(value, int):
cmd.extend(["-F", f"{key}={value}"])
else:
cmd.extend(["-f", f"{key}={value}"])
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
raise RuntimeError(f"gh api graphql failed: {result.stderr.strip()}")
data = json.loads(result.stdout)
if "errors" in data:
raise RuntimeError(f"GraphQL errors: {data['errors']}")
return data
def _fetch_review_threads(repo: str, pr_number: int) -> list[dict]:
"""Fetch review threads with resolution status via GraphQL.
Returns a flat list of comment dicts enriched with is_resolved and
is_outdated from their parent thread. Paginates through all threads
and raises if any comment page is truncated.
"""
owner, name = repo.split("/", 1)
variables: dict = {"owner": owner, "name": name, "pr": pr_number, "threadCursor": None}
comments: list[dict] = []
while True:
data = _gh_graphql(_REVIEW_THREADS_QUERY, variables)
review_threads = data["data"]["repository"]["pullRequest"]["reviewThreads"]
threads = review_threads["nodes"]
for thread in threads:
comment_page = thread["comments"]
if comment_page["pageInfo"]["hasNextPage"]:
raise RuntimeError(
f"Review thread on {thread.get('path')}:{thread.get('line')} "
f"has >50 comments — pagination not implemented, escalate to human review"
)
for c in comment_page["nodes"]:
assoc = c.get("authorAssociation", "")
is_bot = (c.get("author") or {}).get("__typename") == "Bot"
if assoc not in _TRUSTED_ASSOCIATIONS and assoc != "BOT" and not is_bot:
continue
reply_to = c.get("replyTo")
comments.append(
{
"user": (c.get("author") or {}).get("login", "ghost"),
"body": c.get("body", ""),
"path": thread.get("path", ""),
"line": thread.get("line"),
"in_reply_to_id": reply_to["databaseId"] if reply_to else None,
"is_resolved": thread["isResolved"],
"is_outdated": thread["isOutdated"],
}
)
page_info = review_threads["pageInfo"]
if not page_info["hasNextPage"]:
break
variables["threadCursor"] = page_info["endCursor"]
return comments
def _git_diff_files(base_sha: str, head_sha: str, repo_root: Path) -> list[dict]:
"""Get changed files with line counts and status from the local checkout."""
diff_range = f"{base_sha}...{head_sha}"
run_opts = {"capture_output": True, "text": True, "timeout": 30, "cwd": repo_root}
numstat = subprocess.run(["git", "diff", "--numstat", diff_range], **run_opts)
if numstat.returncode != 0:
raise RuntimeError(f"git diff --numstat failed: {numstat.stderr.strip()}")
name_status = subprocess.run(["git", "diff", "--name-status", diff_range], **run_opts)
status_map: dict[str, str] = {}
for line in name_status.stdout.strip().splitlines():
parts = line.split("\t", 1)
if len(parts) == 2:
status_map[parts[1]] = parts[0]
files = []
for line in numstat.stdout.strip().splitlines():
if not line:
continue
parts = line.split("\t", 2)
if len(parts) != 3:
continue
added, deleted, filename = parts
is_binary = added == "-"
files.append(
{
"filename": filename,
"additions": int(added) if not is_binary else 0,
"deletions": int(deleted) if not is_binary else 0,
"binary": is_binary,
"status": status_map.get(filename, "M"),
}
)
return files
def ensure_commits(pr_number: int, head_sha: str, repo_root: Path) -> None:
"""Fetch PR commits if not available locally."""
result = subprocess.run(
["git", "cat-file", "-t", head_sha],
cwd=repo_root,
capture_output=True,
timeout=5,
)
if result.returncode == 0:
return
subprocess.run(
["git", "fetch", "origin", f"pull/{pr_number}/head"],
cwd=repo_root,
capture_output=True,
timeout=30,
)
def fetch_pr(pr_number: int, repo: str, repo_root: Path | None = None) -> PRData:
"""Fetch PR data: metadata from API, file stats from local git."""
pr = _gh_api(f"repos/{repo}/pulls/{pr_number}")
reviews_raw = _gh_api(f"repos/{repo}/pulls/{pr_number}/reviews", paginate=True)
base_sha = pr["base"]["sha"]
head_sha = pr["head"]["sha"]
check_runs_resp = _gh_api(f"repos/{repo}/commits/{head_sha}/check-runs")
pr_reactions: list[dict] = []
try:
reactions_raw = _gh_api(f"repos/{repo}/issues/{pr_number}/reactions", paginate=True)
pr_reactions = _normalize_pr_reactions(reactions_raw, pr["user"]["login"])
except Exception as exc:
print(f"warning: reaction fetch failed ({exc}); continuing without reaction context")
git_root = repo_root or Path.cwd()
ensure_commits(pr_number, head_sha, git_root)
files = _git_diff_files(base_sha, head_sha, git_root)
review_comments = _fetch_review_threads(repo, pr_number)
return PRData(
number=pr_number,
repo=repo,
title=pr["title"],
state=pr["state"],
draft=pr.get("draft", False),
mergeable_state=pr.get("mergeable_state", "unknown"),
author=pr["user"]["login"],
labels=[label["name"] for label in pr.get("labels", [])],
base_sha=base_sha,
head_sha=head_sha,
files=files,
reviews=_normalize_reviews_for_prompt(reviews_raw, head_sha),
review_comments=review_comments,
check_runs=check_runs_resp.get("check_runs", []),
pr_reactions=pr_reactions,
)
def check_team_membership(author: str, team_slug: str) -> bool:
"""Check if author is an active member of the given GitHub team."""
try:
result = subprocess.run(
["gh", "api", f"orgs/PostHog/teams/{team_slug}/memberships/{author}"],
capture_output=True,
text=True,
timeout=10,
)
if result.returncode == 0:
return json.loads(result.stdout).get("state") == "active"
except (subprocess.TimeoutExpired, json.JSONDecodeError):
pass
return False