-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub_client.py
More file actions
557 lines (508 loc) · 19.1 KB
/
github_client.py
File metadata and controls
557 lines (508 loc) · 19.1 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
import os
import requests
from typing import Optional, List, Dict
from dotenv import load_dotenv
load_dotenv()
class GitHubClient:
"""Handles GitHub API interactions."""
def __init__(self):
self.client_id = os.getenv("GITHUB_CLIENT_ID")
self.client_secret = os.getenv("GITHUB_CLIENT_SECRET")
self.api_base = "https://api.github.com"
def get_authorization_url(self, redirect_uri: str, state: str) -> str:
"""
Generate GitHub OAuth authorization URL.
Scopes: repo (for creating issues in public/private repos)
"""
scopes = "repo"
auth_url = (
f"https://github.com/login/oauth/authorize?"
f"client_id={self.client_id}&"
f"redirect_uri={redirect_uri}&"
f"scope={scopes}&"
f"state={state}"
)
return auth_url
def exchange_code_for_token(self, code: str) -> dict:
"""
Exchange authorization code for access token.
Returns token data including access_token.
"""
try:
response = requests.post(
"https://github.com/login/oauth/access_token",
headers={"Accept": "application/json"},
data={
"client_id": self.client_id,
"client_secret": self.client_secret,
"code": code
}
)
if response.status_code == 200:
token_data = response.json()
if "access_token" in token_data:
return token_data
else:
raise Exception(f"No access token in response: {token_data}")
else:
raise Exception(f"Token exchange failed: {response.status_code} - {response.text}")
except Exception as e:
print(f"❌ Token exchange error: {e}")
raise
def get_user_info(self, access_token: str) -> dict:
"""Get authenticated user's GitHub info."""
try:
response = requests.get(
f"{self.api_base}/user",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
}
)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"Failed to get user info: {response.status_code}")
except Exception as e:
print(f"❌ Error getting user info: {e}")
raise
def list_user_repos(self, access_token: str, per_page: int = 100) -> List[Dict]:
"""
List all repositories the user has access to (owned + collaborator).
Returns list of {name, full_name, owner, private, description}
"""
try:
repos = []
# Get user's own repos
response = requests.get(
f"{self.api_base}/user/repos",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
},
params={"per_page": per_page, "sort": "updated"}
)
if response.status_code == 200:
user_repos = response.json()
for repo in user_repos:
repos.append({
"name": repo["name"],
"full_name": repo["full_name"],
"owner": repo["owner"]["login"],
"private": repo["private"],
"description": repo.get("description", ""),
"url": repo["html_url"]
})
return repos
except Exception as e:
print(f"❌ Error listing repos: {e}")
return []
def get_repo_labels(self, access_token: str, repo_full_name: str) -> List[str]:
"""
Fetch all labels from a repository.
Returns list of label names.
"""
try:
response = requests.get(
f"{self.api_base}/repos/{repo_full_name}/labels",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
},
params={"per_page": 100}
)
if response.status_code == 200:
labels = response.json()
return [label["name"] for label in labels]
else:
print(f"⚠️ Could not fetch labels: {response.status_code}")
return []
except Exception as e:
print(f"⚠️ Error fetching labels: {e}")
return []
async def create_issue(
self,
access_token: str,
repo_full_name: str,
title: str,
body: str,
labels: Optional[List[str]] = None
) -> Optional[dict]:
"""
Create an issue in the specified repository.
repo_full_name: "owner/repo"
Returns issue data if successful.
"""
try:
issue_data = {
"title": title,
"body": body
}
if labels:
issue_data["labels"] = labels
response = requests.post(
f"{self.api_base}/repos/{repo_full_name}/issues",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
},
json=issue_data
)
if response.status_code == 201:
issue = response.json()
return {
"success": True,
"issue_number": issue["number"],
"issue_url": issue["html_url"],
"title": issue["title"]
}
else:
error_msg = response.json().get("message", response.text)
print(f"❌ GitHub API error: {response.status_code} - {error_msg}")
return {
"success": False,
"error": f"GitHub API error: {error_msg}"
}
except Exception as e:
print(f"❌ Error creating issue: {e}")
import traceback
traceback.print_exc()
return {
"success": False,
"error": str(e)
}
def list_issues(
self,
access_token: str,
repo_full_name: str,
state: str = "open",
per_page: int = 10
) -> List[Dict]:
"""
List issues in a repository.
Returns list of issue dicts.
"""
try:
response = requests.get(
f"{self.api_base}/repos/{repo_full_name}/issues",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
},
params={
"state": state,
"per_page": per_page,
"sort": "created",
"direction": "desc"
}
)
if response.status_code == 200:
issues = response.json()
return [
{
"number": issue["number"],
"title": issue["title"],
"state": issue["state"],
"body": issue.get("body", ""),
"labels": [label["name"] for label in issue.get("labels", [])],
"url": issue["html_url"],
"created_at": issue["created_at"],
"user": issue["user"]["login"] if issue.get("user") else None
}
for issue in issues
if "pull_request" not in issue # Filter out PRs
]
else:
print(f"❌ Error listing issues: {response.status_code}")
return []
except Exception as e:
print(f"❌ Error listing issues: {e}")
return []
def get_issue(
self,
access_token: str,
repo_full_name: str,
issue_number: int
) -> Optional[Dict]:
"""
Get details of a specific issue.
Returns issue dict if successful.
"""
try:
response = requests.get(
f"{self.api_base}/repos/{repo_full_name}/issues/{issue_number}",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
}
)
if response.status_code == 200:
issue = response.json()
return {
"number": issue["number"],
"title": issue["title"],
"state": issue["state"],
"body": issue.get("body", ""),
"labels": [label["name"] for label in issue.get("labels", [])],
"url": issue["html_url"],
"created_at": issue["created_at"],
"updated_at": issue["updated_at"],
"user": issue["user"]["login"] if issue.get("user") else None,
"assignees": [a["login"] for a in issue.get("assignees", [])],
"comments": issue.get("comments", 0)
}
elif response.status_code == 404:
return None
else:
print(f"❌ Error getting issue: {response.status_code}")
return None
except Exception as e:
print(f"❌ Error getting issue: {e}")
return None
def add_issue_comment(
self,
access_token: str,
repo_full_name: str,
issue_number: int,
body: str
) -> Optional[Dict]:
"""
Add a comment to an issue.
Returns comment data if successful.
"""
try:
response = requests.post(
f"{self.api_base}/repos/{repo_full_name}/issues/{issue_number}/comments",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
},
json={"body": body}
)
if response.status_code == 201:
comment = response.json()
return {
"success": True,
"comment_id": comment["id"],
"comment_url": comment["html_url"]
}
else:
error_msg = response.json().get("message", response.text)
print(f"❌ GitHub API error: {response.status_code} - {error_msg}")
return {
"success": False,
"error": f"GitHub API error: {error_msg}"
}
except Exception as e:
print(f"❌ Error adding comment: {e}")
return {
"success": False,
"error": str(e)
}
def get_repo_labels_with_details(
self,
access_token: str,
repo_full_name: str
) -> List[Dict]:
"""
Fetch all labels from a repository with full details.
Returns list of label dicts with name, color, description.
"""
try:
response = requests.get(
f"{self.api_base}/repos/{repo_full_name}/labels",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
},
params={"per_page": 100}
)
if response.status_code == 200:
labels = response.json()
return [
{
"name": label["name"],
"color": label["color"],
"description": label.get("description", "")
}
for label in labels
]
else:
print(f"⚠️ Could not fetch labels: {response.status_code}")
return []
except Exception as e:
print(f"⚠️ Error fetching labels: {e}")
return []
def list_pull_requests(
self,
access_token: str,
repo_full_name: str,
state: str = "open",
per_page: int = 10
) -> List[Dict]:
"""
List pull requests in a repository.
Returns list of PR dicts.
"""
try:
response = requests.get(
f"{self.api_base}/repos/{repo_full_name}/pulls",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
},
params={
"state": state,
"per_page": per_page,
"sort": "created",
"direction": "desc"
}
)
if response.status_code == 200:
pulls = response.json()
return [
{
"number": pr["number"],
"title": pr["title"],
"state": pr["state"],
"user": pr["user"]["login"] if pr.get("user") else None,
"head": pr["head"]["ref"],
"base": pr["base"]["ref"],
"mergeable": pr.get("mergeable"),
"url": pr["html_url"],
"created_at": pr["created_at"],
"draft": pr.get("draft", False),
}
for pr in pulls
]
else:
print(f"Error listing PRs: {response.status_code}")
return []
except Exception as e:
print(f"Error listing PRs: {e}")
return []
def get_pull_request(
self,
access_token: str,
repo_full_name: str,
pr_number: int
) -> Optional[Dict]:
"""
Get details of a specific pull request.
"""
try:
response = requests.get(
f"{self.api_base}/repos/{repo_full_name}/pulls/{pr_number}",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
}
)
if response.status_code == 200:
pr = response.json()
return {
"number": pr["number"],
"title": pr["title"],
"state": pr["state"],
"body": pr.get("body", ""),
"user": pr["user"]["login"] if pr.get("user") else None,
"head": pr["head"]["ref"],
"base": pr["base"]["ref"],
"mergeable": pr.get("mergeable"),
"mergeable_state": pr.get("mergeable_state"),
"merged": pr.get("merged", False),
"url": pr["html_url"],
"created_at": pr["created_at"],
"updated_at": pr["updated_at"],
"draft": pr.get("draft", False),
"labels": [label["name"] for label in pr.get("labels", [])],
"reviewers": [r["login"] for r in pr.get("requested_reviewers", [])],
}
elif response.status_code == 404:
return None
else:
print(f"Error getting PR: {response.status_code}")
return None
except Exception as e:
print(f"Error getting PR: {e}")
return None
def merge_pull_request(
self,
access_token: str,
repo_full_name: str,
pr_number: int,
merge_method: str = "squash"
) -> Dict:
"""
Merge a pull request.
merge_method: 'merge', 'squash', or 'rebase'
Returns dict with success status and message.
"""
try:
response = requests.put(
f"{self.api_base}/repos/{repo_full_name}/pulls/{pr_number}/merge",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
},
json={"merge_method": merge_method}
)
if response.status_code == 200:
data = response.json()
return {
"success": True,
"sha": data.get("sha"),
"message": data.get("message", "Pull request merged")
}
elif response.status_code == 405:
return {
"success": False,
"error": "PR cannot be merged (not mergeable, or merge blocked by branch protection rules)"
}
elif response.status_code == 409:
return {
"success": False,
"error": "Merge conflict — the PR has conflicts that must be resolved first"
}
else:
error_msg = response.json().get("message", response.text)
return {
"success": False,
"error": f"GitHub API error ({response.status_code}): {error_msg}"
}
except Exception as e:
print(f"Error merging PR: {e}")
return {
"success": False,
"error": str(e)
}
def get_repo_permissions(self, access_token: str, repo_full_name: str) -> Optional[Dict]:
"""
Get repository permissions for the authenticated user.
Returns permissions dict (admin/push/pull) if successful.
"""
try:
response = requests.get(
f"{self.api_base}/repos/{repo_full_name}",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json"
}
)
if response.status_code == 200:
repo = response.json()
return repo.get("permissions", {})
else:
error_msg = None
try:
error_msg = response.json().get("message")
except Exception:
error_msg = response.text
print(f"⚠️ Could not fetch repo permissions: {response.status_code} - {error_msg}")
return {
"_error": error_msg or "Unknown error",
"_status": response.status_code
}
except Exception as e:
print(f"⚠️ Error fetching repo permissions: {e}")
return None