-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_client.py
More file actions
249 lines (209 loc) · 8.95 KB
/
github_client.py
File metadata and controls
249 lines (209 loc) · 8.95 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
"""GitHub API client for Tome.
Handles all GitHub interactions: reading repos, getting diffs,
creating branches, committing files, and opening PRs.
All functions accept an optional `token` param. If not provided,
falls back to Config.GITHUB_TOKEN (for backward compat / dev).
"""
import httpx
import base64
import hashlib
import hmac
from datetime import datetime
from config import Config
API = "https://api.github.com"
def _headers(token: str = None) -> dict:
t = token or Config.GITHUB_TOKEN
return {
"Authorization": f"Bearer {t}",
"Accept": "application/vnd.github.v3+json",
"X-GitHub-Api-Version": "2022-11-28",
}
def verify_webhook_signature(payload: bytes, signature: str) -> bool:
if not Config.GITHUB_WEBHOOK_SECRET:
return True # no secret configured, skip verification (dev mode)
expected = "sha256=" + hmac.new(
Config.GITHUB_WEBHOOK_SECRET.encode(), payload, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, signature)
async def get_repo_info(owner: str, repo: str, token: str = None) -> dict:
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(f"{API}/repos/{owner}/{repo}", headers=_headers(token))
resp.raise_for_status()
return resp.json()
async def get_compare(owner: str, repo: str, base: str, head: str, token: str = None) -> dict:
"""Get diff between two commits."""
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(
f"{API}/repos/{owner}/{repo}/compare/{base}...{head}",
headers=_headers(token)
)
resp.raise_for_status()
return resp.json()
async def get_commit_diff(owner: str, repo: str, sha: str, token: str = None) -> str:
"""Get the patch/diff for a specific commit."""
headers = _headers(token)
headers["Accept"] = "application/vnd.github.v3.diff"
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(
f"{API}/repos/{owner}/{repo}/commits/{sha}",
headers=headers
)
resp.raise_for_status()
return resp.text
async def get_push_diff(owner: str, repo: str, before: str, after: str, token: str = None) -> str:
"""Get combined diff for a push (multiple commits)."""
headers = _headers(token)
headers["Accept"] = "application/vnd.github.v3.diff"
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(
f"{API}/repos/{owner}/{repo}/compare/{before}...{after}",
headers=headers
)
resp.raise_for_status()
return resp.text
async def list_directory(owner: str, repo: str, path: str, ref: str = None, token: str = None) -> list[dict]:
"""List files in a repo directory."""
params = {}
if ref:
params["ref"] = ref
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(
f"{API}/repos/{owner}/{repo}/contents/{path}",
headers=_headers(token),
params=params
)
if resp.status_code == 404:
return []
resp.raise_for_status()
data = resp.json()
return data if isinstance(data, list) else [data]
async def get_file_content(owner: str, repo: str, path: str, ref: str = None, token: str = None) -> str | None:
"""Get decoded content of a file."""
params = {}
if ref:
params["ref"] = ref
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(
f"{API}/repos/{owner}/{repo}/contents/{path}",
headers=_headers(token),
params=params
)
if resp.status_code == 404:
return None
resp.raise_for_status()
data = resp.json()
if data.get("encoding") == "base64":
return base64.b64decode(data["content"]).decode("utf-8", errors="replace")
return data.get("content", "")
async def get_all_doc_files(owner: str, repo: str, docs_path: str, ref: str = None, token: str = None) -> dict[str, str]:
"""Recursively get all markdown files in docs directory. Returns {path: content}."""
result = {}
await _walk_docs(owner, repo, docs_path.rstrip("/"), ref, result, token)
return result
async def _walk_docs(owner: str, repo: str, path: str, ref: str, result: dict, token: str = None):
items = await list_directory(owner, repo, path, ref, token)
for item in items:
if item["type"] == "dir":
await _walk_docs(owner, repo, item["path"], ref, result, token)
elif item["type"] == "file" and item["name"].endswith((".md", ".mdx", ".rst", ".txt")):
content = await get_file_content(owner, repo, item["path"], ref, token)
if content:
result[item["path"]] = content
async def get_tree(owner: str, repo: str, ref: str = "HEAD", token: str = None) -> list[dict]:
"""Get full file tree of a repo (recursive)."""
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(
f"{API}/repos/{owner}/{repo}/git/trees/{ref}?recursive=1",
headers=_headers(token)
)
resp.raise_for_status()
return resp.json().get("tree", [])
async def get_default_branch_sha(owner: str, repo: str, branch: str, token: str = None) -> str:
"""Get the latest commit SHA of a branch."""
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(
f"{API}/repos/{owner}/{repo}/git/refs/heads/{branch}",
headers=_headers(token)
)
resp.raise_for_status()
return resp.json()["object"]["sha"]
async def create_branch(owner: str, repo: str, branch_name: str, from_sha: str, token: str = None) -> bool:
"""Create a new branch from a commit SHA."""
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.post(
f"{API}/repos/{owner}/{repo}/git/refs",
headers=_headers(token),
json={"ref": f"refs/heads/{branch_name}", "sha": from_sha}
)
return resp.status_code == 201
async def create_or_update_file(owner: str, repo: str, path: str, content: str,
message: str, branch: str, sha: str = None, token: str = None) -> dict:
"""Create or update a file in the repo."""
payload = {
"message": message,
"content": base64.b64encode(content.encode()).decode(),
"branch": branch,
}
if sha:
payload["sha"] = sha
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.put(
f"{API}/repos/{owner}/{repo}/contents/{path}",
headers=_headers(token),
json=payload
)
resp.raise_for_status()
return resp.json()
async def get_file_sha(owner: str, repo: str, path: str, branch: str, token: str = None) -> str | None:
"""Get the SHA of an existing file (needed for updates)."""
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(
f"{API}/repos/{owner}/{repo}/contents/{path}",
headers=_headers(token),
params={"ref": branch}
)
if resp.status_code == 404:
return None
resp.raise_for_status()
return resp.json().get("sha")
async def create_pull_request(owner: str, repo: str, title: str, body: str,
head: str, base: str, token: str = None) -> dict:
"""Create a pull request."""
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.post(
f"{API}/repos/{owner}/{repo}/pulls",
headers=_headers(token),
json={"title": title, "body": body, "head": head, "base": base}
)
resp.raise_for_status()
return resp.json()
async def create_webhook(owner: str, repo: str, token: str = None) -> dict:
"""Create a webhook on the repo to receive push and PR events."""
webhook_url = f"{Config.BASE_URL}/api/webhook/github"
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.post(
f"{API}/repos/{owner}/{repo}/hooks",
headers=_headers(token),
json={
"name": "web",
"active": True,
"events": ["push", "pull_request"],
"config": {
"url": webhook_url,
"content_type": "json",
"secret": Config.GITHUB_WEBHOOK_SECRET or "",
"insecure_ssl": "0",
},
},
)
resp.raise_for_status()
return resp.json()
async def verify_repo_access(owner: str, repo: str, token: str) -> dict:
"""Verify we can access the repo with the given token. Returns repo info or raises."""
async with httpx.AsyncClient(timeout=15) as client:
resp = await client.get(
f"{API}/repos/{owner}/{repo}",
headers=_headers(token),
)
resp.raise_for_status()
return resp.json()