-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathgithub_fetcher.py
More file actions
333 lines (284 loc) · 10.4 KB
/
github_fetcher.py
File metadata and controls
333 lines (284 loc) · 10.4 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
332
333
"""GitHub URL parsing and content fetching for PR code review."""
import re
from typing import Literal
import httpx
# Import config from cr package
from cr.config import GITHUB_TOKEN, GITHUB_API_BASE
UrlType = Literal["pr", "issue"]
def _get_login(user: dict) -> str:
"""Get user login, falling back to username (Gitea compat)."""
return user.get("login") or user.get("username") or "unknown"
def parse_github_url(url: str) -> tuple[str, str, int, UrlType]:
"""Parse a GitHub/Gitea/GitLab/Bitbucket URL into (owner, repo, number, type).
Args:
url: Issue/PR/MR URL from any supported forge
Returns:
Tuple of (owner, repo, number, type)
Raises:
ValueError: If URL format is invalid
Examples:
>>> parse_github_url("https://github.com/owner/repo/pull/35")
('owner', 'repo', 35, 'pr')
>>> parse_github_url("https://gitea.example.com/org/repo/pulls/42")
('org', 'repo', 42, 'pr')
>>> parse_github_url("https://gitlab.com/org/repo/-/merge_requests/10")
('org', 'repo', 10, 'pr')
>>> parse_github_url("https://bitbucket.org/org/repo/pull-requests/5")
('org', 'repo', 5, 'pr')
>>> parse_github_url("https://github.com/owner/repo/issues/1")
('owner', 'repo', 1, 'issue')
"""
# PR patterns — accept any domain, support multiple forge URL formats:
# GitHub: /owner/repo/pull/123
# Gitea: /owner/repo/pulls/123
# GitLab: /owner/repo/-/merge_requests/123
# Bitbucket: /owner/repo/pull-requests/123
pr_pattern = r"^https?://[^/]+/([^/]+)/([^/]+)/(?:-/)?(?:pulls?|merge_requests|pull-requests)/(\d+)(?:[/?#].*)?$"
pr_match = re.search(pr_pattern, url)
if pr_match:
return pr_match.group(1), pr_match.group(2), int(pr_match.group(3)), "pr"
# Issue patterns — GitHub/Gitea/GitLab
# GitLab: /owner/repo/-/issues/123
issue_pattern = r"^https?://[^/]+/([^/]+)/([^/]+)/(?:-/)?issues/(\d+)(?:[/?#].*)?$"
issue_match = re.search(issue_pattern, url)
if issue_match:
return issue_match.group(1), issue_match.group(2), int(issue_match.group(3)), "issue"
raise ValueError(
f"Invalid URL: {url}\n"
"Expected: https://host/owner/repo/{pull,pulls,merge_requests,pull-requests}/123\n"
" or: https://host/owner/repo/issues/123"
)
def _get_headers() -> dict[str, str]:
"""Get HTTP headers for GitHub API requests."""
headers = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "asyncreview-cli",
}
if GITHUB_TOKEN:
headers["Authorization"] = f"token {GITHUB_TOKEN}"
return headers
async def fetch_pr(owner: str, repo: str, number: int) -> dict:
"""Fetch PR with full code review context.
Returns dict with:
- metadata: title, body, author, state, etc.
- files: list of changed files with patches
- commits: commit history
- comments: PR discussion comments
"""
async with httpx.AsyncClient() as client:
# Fetch PR metadata
pr_resp = await client.get(
f"{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls/{number}",
headers=_get_headers(),
timeout=30.0,
)
pr_resp.raise_for_status()
pr_data = pr_resp.json()
# Fetch changed files with patches
files_resp = await client.get(
f"{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls/{number}/files",
headers=_get_headers(),
params={"per_page": 100},
timeout=30.0,
)
files_resp.raise_for_status()
files_data = files_resp.json()
# Fetch commits
commits_resp = await client.get(
f"{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls/{number}/commits",
headers=_get_headers(),
params={"per_page": 100},
timeout=30.0,
)
commits_list = []
if commits_resp.status_code == 200:
commits_data = commits_resp.json()
commits_list = [
{
"sha": c["sha"][:7],
"message": c["commit"]["message"].split("\n")[0], # First line only
"author": c["commit"]["author"]["name"],
}
for c in commits_data
]
# Fetch PR comments
comments_resp = await client.get(
f"{GITHUB_API_BASE}/repos/{owner}/{repo}/issues/{number}/comments",
headers=_get_headers(),
params={"per_page": 50},
timeout=30.0,
)
comments_list = []
if comments_resp.status_code == 200:
comments_data = comments_resp.json()
comments_list = [
{
"author": _get_login(c["user"]),
"body": c["body"],
}
for c in comments_data
]
# Build structured result
files = [
{
"path": f["filename"],
"status": f.get("status", "modified"),
"additions": f.get("additions", 0),
"deletions": f.get("deletions", 0),
"patch": f.get("patch", ""),
}
for f in files_data
]
return {
"type": "pr",
"owner": owner,
"repo": repo,
"number": number,
"title": pr_data.get("title", ""),
"body": pr_data.get("body") or "",
"author": _get_login(pr_data["user"]),
"state": pr_data.get("state", "open"),
"base_branch": pr_data.get("base", {}).get("ref", "main"),
"head_branch": pr_data.get("head", {}).get("ref", "unknown"),
"files": files,
"commits": commits_list,
"comments": comments_list,
"additions": pr_data.get("additions", 0),
"deletions": pr_data.get("deletions", 0),
"changed_files_count": pr_data.get("changed_files", 0),
}
async def fetch_issue(owner: str, repo: str, number: int) -> dict:
"""Fetch issue content and comments (secondary use case)."""
async with httpx.AsyncClient() as client:
# Fetch issue metadata
issue_resp = await client.get(
f"{GITHUB_API_BASE}/repos/{owner}/{repo}/issues/{number}",
headers=_get_headers(),
timeout=30.0,
)
issue_resp.raise_for_status()
issue_data = issue_resp.json()
# Fetch comments
comments_resp = await client.get(
f"{GITHUB_API_BASE}/repos/{owner}/{repo}/issues/{number}/comments",
headers=_get_headers(),
params={"per_page": 50},
timeout=30.0,
)
comments_list = []
if comments_resp.status_code == 200:
comments_data = comments_resp.json()
comments_list = [
{
"author": _get_login(c["user"]),
"body": c["body"],
}
for c in comments_data
]
return {
"type": "issue",
"owner": owner,
"repo": repo,
"number": number,
"title": issue_data.get("title", ""),
"body": issue_data.get("body") or "",
"author": _get_login(issue_data["user"]),
"state": issue_data.get("state", "open"),
"labels": [l["name"] for l in issue_data.get("labels", [])],
"comments": comments_list,
}
def build_pr_context(data: dict) -> str:
"""Build a structured text representation of a PR for RLM input.
Optimized for code review - includes full diff patches.
"""
lines = [
f"# Pull Request: {data['title']}",
f"",
f"**Repository:** {data['owner']}/{data['repo']}",
f"**Author:** {data['author']}",
f"**Branch:** {data['head_branch']} → {data['base_branch']}",
f"**Changes:** +{data['additions']} -{data['deletions']} across {data['changed_files_count']} files",
f"",
]
# PR description
if data["body"]:
lines.extend([
"## Description",
"",
data["body"],
"",
])
# Commits
if data["commits"]:
lines.extend([
"## Commits",
"",
])
for commit in data["commits"]:
lines.append(f"- `{commit['sha']}` {commit['message']} ({commit['author']})")
lines.append("")
# Changed files with patches
lines.extend([
"## Changed Files",
"",
])
for file in data["files"]:
status_icon = {"added": "+", "removed": "-", "modified": "~"}.get(file["status"], "~")
lines.append(f"### [{status_icon}] {file['path']}")
lines.append(f"*+{file['additions']} -{file['deletions']}*")
lines.append("")
if file["patch"]:
lines.append("```diff")
lines.append(file["patch"])
lines.append("```")
lines.append("")
# Comments/Discussion
if data["comments"]:
lines.extend([
"## Discussion",
"",
])
for comment in data["comments"]:
lines.append(f"**{comment['author']}:**")
lines.append(comment["body"])
lines.append("")
return "\n".join(lines)
def build_issue_context(data: dict) -> str:
"""Build a text representation of an issue for RLM input."""
lines = [
f"# Issue: {data['title']}",
f"",
f"**Repository:** {data['owner']}/{data['repo']}",
f"**Author:** {data['author']}",
f"**State:** {data['state']}",
]
if data["labels"]:
lines.append(f"**Labels:** {', '.join(data['labels'])}")
lines.append("")
# Issue body
if data["body"]:
lines.extend([
"## Description",
"",
data["body"],
"",
])
# Comments
if data["comments"]:
lines.extend([
"## Discussion",
"",
])
for comment in data["comments"]:
lines.append(f"**{comment['author']}:**")
lines.append(comment["body"])
lines.append("")
return "\n".join(lines)
def build_review_context(data: dict) -> str:
"""Build a structured text representation for RLM input.
Dispatches to PR or Issue context builder based on type.
"""
if data["type"] == "pr":
return build_pr_context(data)
else:
return build_issue_context(data)