Repository navigation
Expand file tree
/
Copy pathgithub_api.py
More file actions
283 lines (272 loc) · 13.2 KB
/
Copy pathgithub_api.py
File metadata and controls
283 lines (272 loc) · 13.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
from __future__ import annotations
import base64
import logging
from typing import Any
import httpx
from config import GH_API, GH_SEARCH_CODE, GH_SEARCH_ISSUES, GH_SEARCH_REPOS, GH_TOKEN, _cached, _set_cache, _http_request_capped, _next_gh_key, api_error
logger = logging.getLogger("codesearch.github")
_MAX_BYTES = 512 * 1024 # GitHub API payloads are bounded; cap so a proxy cannot flood RAM
async def _gh_headers(media_type: str = "github+json") -> dict[str, str]:
h = {"User-Agent": "mcp-codesearch/1.0", "Accept": f"application/vnd.{media_type}"}
token = await _next_gh_key() or GH_TOKEN
if token:
h["Authorization"] = f"token {token}"
return h
async def search_github(q: str, search_type: str = "code", count: int = 10,
owner: str = "", repo: str = "", language: str = "",
sort: str = "", order: str = "",
filename: str = "", extension: str = "",
path: str = "", created: str = "",
state: str = "", labels: str = "",
user: str = "", org: str = "",
size: str = "", in_qualifier: str = "",
is_: str = "", pushed: str = "",
stars: str = "", forks: str = "",
topics: str = "", page: int = 1,
exclude_qualifier: str = "",
merged: str = "", head: str = "", base: str = "",
review: str = "") -> dict:
cache_key = f"gh:{search_type}:{q}:{owner}:{repo}:{count}:{sort}:{order}:{filename}:{extension}:{path}:{created}:{state}:{user}:{org}:{page}:{exclude_qualifier}:{merged}:{head}:{base}:{review}:{in_qualifier}:{is_}:{pushed}:{stars}:{forks}:{topics}:{labels}:{size}:{language}"
cached = await _cached(cache_key)
if cached is not None:
return {"success": True, "results": cached, "cached": True}
try:
query_parts = [q]
if owner:
query_parts.append(f"user:{owner}" if not repo else f"repo:{owner}/{repo}")
if repo and not owner:
query_parts.append(f"repo:{repo}")
if user:
query_parts.append(f"user:{user}")
if org:
query_parts.append(f"org:{org}")
if language:
query_parts.append(f"language:{language}")
if filename:
query_parts.append(f"filename:{filename}")
if extension:
query_parts.append(f"extension:{extension}")
if path:
query_parts.append(f"path:{path}")
if size:
query_parts.append(f"size:{size}")
if in_qualifier:
query_parts.append(f"in:{in_qualifier}")
if is_:
query_parts.append(f"is:{is_}")
if created and search_type in ("issues", "repos"):
query_parts.append(f"created:{created}")
if pushed and search_type == "repos":
query_parts.append(f"pushed:{pushed}")
if stars and search_type in ("repos", "issues"):
query_parts.append(f"stars:{stars}")
if forks and search_type == "repos":
query_parts.append(f"forks:{forks}")
if topics and search_type == "repos":
query_parts.append(f"topics:{topics}")
if state and search_type == "issues":
query_parts.append(f"state:{state}")
if labels and search_type == "issues":
for lbl in labels.split(","):
query_parts.append(f"label:{lbl.strip()}")
if merged and search_type == "issues":
query_parts.append(f"merged:{merged}")
if head:
query_parts.append(f"head:{head}")
if base:
query_parts.append(f"base:{base}")
if review and search_type == "issues":
query_parts.append(f"review:{review}")
if exclude_qualifier:
query_parts.append(f"NOT {exclude_qualifier}")
full_query = " ".join(query_parts)
if search_type == "repos":
url = GH_SEARCH_REPOS
elif search_type == "issues":
url = GH_SEARCH_ISSUES
elif search_type == "users":
url = "https://api.github.com/search/users"
else:
url = GH_SEARCH_CODE
params: dict[str, Any] = {"q": full_query, "per_page": min(count, 100)}
if page > 1:
params["page"] = page
if sort:
params["sort"] = sort
if order:
params["order"] = order
mt = "github.v3.text-match+json" if search_type == "code" else "github+json"
r = await _http_request_capped("GET", url, params=params, headers=await _gh_headers(mt),
timeout=15, max_bytes=_MAX_BYTES)
if r.status_code in (401, 403):
# Bad/expired key: the retry's _gh_headers call advances to the next key
r = await _http_request_capped("GET", url, params=params, headers=await _gh_headers(mt),
timeout=15, max_bytes=_MAX_BYTES)
remaining = r.headers.get("x-ratelimit-remaining")
if remaining is not None:
try:
remaining_int = int(remaining)
if remaining_int < 10:
logger.warning("GitHub API rate limit low: %s remaining", remaining_int)
except (ValueError, TypeError):
pass
if r.status_code != 200:
return {"success": False, "error": f"GitHub API: {r.status_code} {r.text[:200]}"}
data = r.json()
items = data.get("items", [])[:count]
results = []
if search_type == "code":
for item in items:
text_matches = item.get("text_matches", [])
snippet = text_matches[0].get("fragment", "") if text_matches else ""
results.append({
"file": item["name"], "path": item["path"],
"url": item["html_url"], "repo": item["repository"]["full_name"],
"snippet": snippet[:500],
})
elif search_type == "repos":
for item in items:
results.append({
"full_name": item["full_name"],
"description": (item.get("description") or "")[:200],
"stars": item.get("stargazers_count", 0),
"forks": item.get("forks_count", 0),
"language": item.get("language") or "",
"topics": item.get("topics", []),
"url": item["html_url"],
"updated_at": item.get("updated_at", ""),
"open_issues": item.get("open_issues_count", 0),
"license": (item.get("license") or {}).get("spdx_id", ""),
})
elif search_type == "users":
for item in items:
results.append({
"login": item.get("login", ""),
"avatar": item.get("avatar_url", ""),
"html_url": item.get("html_url", ""),
"type": item.get("type", "User"),
"score": item.get("score", 0),
})
else:
for item in items:
results.append({
"title": item["title"],
"state": item["state"],
"body": (item.get("body") or "")[:500],
"labels": [l["name"] for l in item.get("labels", [])],
"url": item["html_url"],
"repo": item.get("repository_url", "").replace("https://api.github.com/repos/", ""),
"created_at": item.get("created_at", ""),
"updated_at": item.get("updated_at", ""),
"comments": item.get("comments", 0),
"user": item.get("user", {}).get("login", ""),
})
await _set_cache(cache_key, results)
return {"success": True, "results": results, "total": data.get("total_count", 0)}
except (httpx.HTTPError, ValueError, KeyError) as e:
return {"success": False, "error": str(e)}
async def fetch_readme(owner: str, repo: str, branch: str = "") -> dict:
cache_key = f"readme:{owner}:{repo}:{branch}"
cached = await _cached(cache_key)
if cached is not None:
return cached
try:
url = f"{GH_API}/repos/{owner}/{repo}/readme"
if branch:
url += f"?ref={branch}"
gh_headers = await _gh_headers()
r = await _http_request_capped("GET", url,
headers={**gh_headers, "Accept": "application/vnd.github.raw"},
max_bytes=_MAX_BYTES)
if r.status_code == 404:
return {"success": False, "error": "no README found"}
if r.status_code != 200:
return {"success": False, "error": api_error("GitHub", r)}
result = {"success": True, "content": r.text[:15000], "repo": f"{owner}/{repo}"}
await _set_cache(cache_key, result)
return result
except (httpx.HTTPError, ValueError) as e:
return {"success": False, "error": str(e)}
async def gh_get_languages(owner: str, repo: str) -> dict:
cache_key = f"gh_lang:{owner}:{repo}"
cached = await _cached(cache_key)
if cached is not None:
return cached
try:
r = await _http_request_capped("GET", f"{GH_API}/repos/{owner}/{repo}/languages",
headers=await _gh_headers(), max_bytes=_MAX_BYTES)
if r.status_code != 200:
return {"success": False, "error": api_error("GitHub", r)}
result = {"success": True, "languages": r.json()}
await _set_cache(cache_key, result)
return result
except (httpx.HTTPError, ValueError) as e:
return {"success": False, "error": str(e)}
async def gh_get_topics(owner: str, repo: str) -> dict:
cache_key = f"gh_topics:{owner}:{repo}"
cached = await _cached(cache_key)
if cached is not None:
return cached
try:
gh_hdrs = await _gh_headers()
r = await _http_request_capped("GET", f"{GH_API}/repos/{owner}/{repo}/topics",
headers=gh_hdrs, max_bytes=_MAX_BYTES)
if r.status_code != 200:
return {"success": False, "error": api_error("GitHub", r)}
result = {"success": True, "topics": r.json().get("names", [])}
await _set_cache(cache_key, result)
return result
except (httpx.HTTPError, ValueError) as e:
return {"success": False, "error": str(e)}
async def gh_get_repo(owner: str, repo: str) -> dict:
"""Get repository metadata (stars, forks, license, description, etc.)."""
cache_key = f"gh_repo:{owner}:{repo}"
cached = await _cached(cache_key)
if cached is not None:
return cached
try:
r = await _http_request_capped("GET", f"{GH_API}/repos/{owner}/{repo}",
headers=await _gh_headers(), max_bytes=_MAX_BYTES)
if r.status_code != 200:
return {"success": False, "error": api_error("GitHub", r)}
d = r.json()
result = {"success": True,
"name": d.get("name", ""), "full_name": d.get("full_name", ""),
"description": d.get("description", ""),
"stars": d.get("stargazers_count", 0), "forks": d.get("forks_count", 0),
"watchers": d.get("subscribers_count", 0), "open_issues": d.get("open_issues_count", 0),
"language": d.get("language") or "", "topics": d.get("topics", []),
"license": d.get("license", {}).get("spdx_id", "") if d.get("license") else "",
"url": d.get("html_url", ""), "homepage": d.get("homepage", "") or "",
"created_at": d.get("created_at", ""), "updated_at": d.get("updated_at", ""),
"archived": d.get("archived", False), "fork": d.get("fork", False),
"default_branch": d.get("default_branch", ""),
"pushed_at": d.get("pushed_at", ""),
"size": d.get("size", 0),
"has_wiki": d.get("has_wiki", False),
}
await _set_cache(cache_key, result)
return result
except (httpx.HTTPError, ValueError) as e:
return {"success": False, "error": str(e)}
async def gh_get_releases(owner: str, repo: str, count: int = 5) -> dict:
cache_key = f"gh_rel:{owner}:{repo}:{count}"
cached = await _cached(cache_key)
if cached is not None:
return cached
try:
r = await _http_request_capped("GET", f"{GH_API}/repos/{owner}/{repo}/releases",
params={"per_page": min(count, 20)},
headers=await _gh_headers(), max_bytes=_MAX_BYTES)
if r.status_code != 200:
return {"success": False, "error": api_error("GitHub", r)}
items = r.json()[:count]
results = [{"tag": rel.get("tag_name", ""), "name": rel.get("name", ""),
"published": rel.get("published_at", ""), "prerelease": rel.get("prerelease", False),
"body": (rel.get("body") or "")[:500]}
for rel in items]
result = {"success": True, "releases": results}
await _set_cache(cache_key, result)
return result
except (httpx.HTTPError, ValueError) as e:
return {"success": False, "error": str(e)}