-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathapi.py
More file actions
1756 lines (1579 loc) · 75 KB
/
Copy pathapi.py
File metadata and controls
1756 lines (1579 loc) · 75 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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import base64
import time
from typing import Any, cast
from urllib.parse import quote
import aiohttp
import httpx
import jwt
import structlog
from cachetools import TTLCache # type: ignore[import-untyped]
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential
from src.core.config import config
from src.core.errors import GitHubGraphQLError
logger = structlog.get_logger(__name__)
_PR_HYGIENE_QUERY = """
query PRHygiene($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
pullRequests(last: 20, states: [MERGED, CLOSED]) {
nodes {
number
title
body
changedFiles
comments {
totalCount
}
closingIssuesReferences(first: 1) {
totalCount
}
reviews(first: 1) {
totalCount
}
}
}
}
}
"""
class GitHubClient:
"""
A client for interacting with the GitHub API.
This client handles the authentication flow for a GitHub App, including
generating a JWT and exchanging it for an installation access token.
Tokens are cached to improve performance and avoid rate limiting.
Architectural Note:
- Implements strict typing for arguments.
- Handles 'Anonymous' access for public repository analysis (Phase 1 requirement).
- Centralizes auth header logic to prevent token leakage.
"""
def __init__(self) -> None:
self._private_key = self._decode_private_key()
self._app_id = config.github.app_id
self._session: aiohttp.ClientSession | None = None
# Cache for installation tokens (TTL: 50 minutes, GitHub tokens expire in 60)
self._token_cache: TTLCache = TTLCache(maxsize=100, ttl=50 * 60)
def _detect_issue_references(self, body: str, title: str) -> bool:
"""Detect if PR body or title contains issue references (e.g. #123)."""
import re
# Simple heuristic: look for #digits
pattern = r"#\d+"
return bool(re.search(pattern, body) or re.search(pattern, title))
async def _get_auth_headers(
self,
installation_id: int | None = None,
user_token: str | None = None,
accept: str = "application/vnd.github.v3+json",
allow_anonymous: bool = False, # <--- NEW: Support for Phase 1 Public Analysis
) -> dict[str, str] | None:
"""
Build auth headers using either installation token, user token, or anonymous mode.
"""
token = user_token
if token:
return {"Authorization": f"Bearer {token}", "Accept": accept}
if installation_id is not None:
token = await self.get_installation_access_token(installation_id)
if token:
return {"Authorization": f"Bearer {token}", "Accept": accept}
if allow_anonymous:
# Public access (Subject to 60 req/hr rate limit per IP)
return {"Accept": accept, "User-Agent": "Watchflow-Analyzer/1.0"}
return None
async def get_installation_access_token(self, installation_id: int) -> str | None:
"""
Gets an access token for a specific installation of the GitHub App.
Caches the token to avoid regenerating it for every request.
"""
if installation_id in self._token_cache:
logger.debug(f"Using cached installation token for installation_id {installation_id}.")
return cast("str", self._token_cache[installation_id])
jwt_token = self._generate_jwt()
headers = {
"Authorization": f"Bearer {jwt_token}",
"Accept": "application/vnd.github.v3+json",
}
url = f"{config.github.api_base_url}/app/installations/{installation_id}/access_tokens"
session = await self._get_session()
async with session.post(url, headers=headers) as response:
if response.status == 201:
data = await response.json()
token = data["token"]
self._token_cache[installation_id] = token
logger.info(f"Generated new installation token for installation_id {installation_id}.")
return cast("str", token)
else:
error_text = await response.text()
logger.error(
f"Failed to get installation access token for installation {installation_id}. "
f"Status: {response.status}, Response: {error_text}"
)
return None
async def get_repository(
self, repo_full_name: str, installation_id: int | None = None, user_token: str | None = None
) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
"""
Fetch repository metadata. Returns (repo_data, None) on success;
(None, {"status": int, "message": str}) on failure for meaningful API responses.
"""
headers = await self._get_auth_headers(installation_id=installation_id, user_token=user_token)
if not headers:
return (
None,
{
"status": 401,
"message": "Authentication required. Provide github_token or installation_id in the request.",
},
)
url = f"{config.github.api_base_url}/repos/{repo_full_name}"
session = await self._get_session()
async with session.get(url, headers=headers) as response:
if response.status == 200:
data = await response.json()
return cast("dict[str, Any]", data), None
try:
body = await response.json()
gh_message = body.get("message", "") if isinstance(body, dict) else ""
except Exception:
gh_message = ""
if response.status == 404:
msg = gh_message or "Repository not found or access denied. Check repo name and token permissions."
return None, {"status": 404, "message": msg}
if response.status == 403:
msg = "GitHub API rate limit exceeded. Try again later or provide github_token for higher limits."
if gh_message and "rate limit" in gh_message.lower():
msg = gh_message
return None, {"status": 403, "message": msg}
if response.status == 401:
return (
None,
{
"status": 401,
"message": gh_message or "Invalid or expired token. Check github_token or installation_id.",
},
)
return None, {"status": response.status, "message": gh_message or f"GitHub API returned {response.status}."}
async def list_directory_any_auth(
self, repo_full_name: str, path: str, installation_id: int | None = None, user_token: str | None = None
) -> list[dict[str, Any]]:
"""List directory contents using installation or user token (auth required)."""
headers = await self._get_auth_headers(installation_id=installation_id, user_token=user_token)
if not headers:
return []
url = f"{config.github.api_base_url}/repos/{repo_full_name}/contents/{path}"
session = await self._get_session()
async with session.get(url, headers=headers) as response:
if response.status == 200:
data = await response.json()
return cast("list[dict[str, Any]]", data if isinstance(data, list) else [data])
# Raise exception for error statuses to avoid silent failures
response.raise_for_status()
return []
async def get_repository_tree(
self,
repo_full_name: str,
ref: str | None = None,
installation_id: int | None = None,
user_token: str | None = None,
recursive: bool = True,
) -> list[dict[str, Any]]:
"""Get the tree of a repository. Requires authentication (github_token or installation_id)."""
start = time.monotonic()
headers = await self._get_auth_headers(
installation_id=installation_id,
user_token=user_token,
)
if not headers:
latency_ms = int((time.monotonic() - start) * 1000)
logger.info(
"get_repository_tree",
operation="get_repository_tree",
subject_ids={
"repo": repo_full_name,
"installation_id": installation_id,
"user_token_present": bool(user_token),
"ref": ref or "main",
},
decision="auth_missing",
latency_ms=latency_ms,
)
return []
ref = ref or "main"
tree_sha = await self._resolve_tree_sha(repo_full_name, ref, headers)
if not tree_sha:
latency_ms = int((time.monotonic() - start) * 1000)
logger.info(
"get_repository_tree",
operation="get_repository_tree",
subject_ids={
"repo": repo_full_name,
"installation_id": installation_id,
"user_token_present": bool(user_token),
"ref": ref,
},
decision="ref_resolution_failed",
latency_ms=latency_ms,
)
return []
url = f"{config.github.api_base_url}/repos/{repo_full_name}/git/trees/{tree_sha}"
if recursive:
url += "?recursive=1"
session = await self._get_session()
async with session.get(url, headers=headers) as response:
if response.status != 200:
latency_ms = int((time.monotonic() - start) * 1000)
logger.info(
"get_repository_tree",
operation="get_repository_tree",
subject_ids={"repo": repo_full_name, "ref": ref, "tree_sha": tree_sha},
decision=f"http_error_{response.status}",
latency_ms=latency_ms,
)
return []
data = await response.json()
return cast("list[dict[str, Any]]", data.get("tree", []))
async def _resolve_tree_sha(self, repo_full_name: str, ref: str, headers: dict[str, str]) -> str | None:
"""Resolve the tree SHA for the given ref (branch, tag, or commit SHA) via the commits API."""
session = await self._get_session()
ref_encoded = quote(ref, safe="")
url = f"{config.github.api_base_url}/repos/{repo_full_name}/commits/{ref_encoded}"
async with session.get(url, headers=headers) as response:
if response.status != 200:
return None
commit_data = await response.json()
if not isinstance(commit_data, dict):
return None
return commit_data.get("commit", {}).get("tree", {}).get("sha")
async def get_file_content(
self,
repo_full_name: str,
file_path: str,
installation_id: int | None,
user_token: str | None = None,
ref: str | None = None,
) -> str | None:
"""
Fetches the content of a file from a repository. Requires authentication (github_token or installation_id).
When ref is provided (branch name, tag, or commit SHA), returns content at that ref; otherwise uses default branch.
"""
headers = await self._get_auth_headers(
installation_id=installation_id,
user_token=user_token,
accept="application/vnd.github.raw",
)
if not headers:
return None
url = f"{config.github.api_base_url}/repos/{repo_full_name}/contents/{file_path}"
params = {"ref": ref} if ref else None
session = await self._get_session()
async with session.get(url, headers=headers, params=params) as response:
if response.status == 200:
logger.info(f"Successfully fetched file '{file_path}' from '{repo_full_name}'.")
return await response.text()
elif response.status == 404:
logger.info(f"File '{file_path}' not found in '{repo_full_name}'.")
return None
else:
error_text = await response.text()
logger.error(
f"Failed to get file content for {repo_full_name}/{file_path}. "
f"Status: {response.status}, Response: {error_text}"
)
response.raise_for_status()
return None
async def close(self) -> None:
"""Closes the aiohttp session."""
if self._session and not self._session.closed:
await self._session.close()
async def create_check_run(
self, repo: str, sha: str, name: str, status: str, conclusion: str, output: dict[str, Any], installation_id: int
) -> dict[str, Any]:
"""Create a check run."""
try:
headers = await self._get_auth_headers(installation_id=installation_id)
if not headers:
return {}
url = f"{config.github.api_base_url}/repos/{repo}/check-runs"
data = {"name": name, "head_sha": sha, "status": status, "conclusion": conclusion, "output": output}
session = await self._get_session()
async with session.post(url, headers=headers, json=data) as response:
if response.status == 201:
return cast("dict[str, Any]", await response.json())
return {}
except Exception as e:
logger.error(f"Error creating check run: {e}")
return {}
async def get_pull_request(self, repo: str, pr_number: int, installation_id: int) -> dict[str, Any] | None:
"""Get pull request details."""
try:
headers = await self._get_auth_headers(installation_id=installation_id)
if not headers:
return None
url = f"{config.github.api_base_url}/repos/{repo}/pulls/{pr_number}"
session = await self._get_session()
async with session.get(url, headers=headers) as response:
if response.status == 200:
return cast("dict[str, Any]", await response.json())
return None
except Exception as e:
logger.error(f"Error getting PR #{pr_number}: {e}")
return None
async def list_pull_requests(
self,
repo: str,
installation_id: int | None = None,
state: str = "all",
per_page: int = 20,
user_token: str | None = None,
) -> list[dict[str, Any]]:
"""List pull requests for a repository."""
try:
headers = await self._get_auth_headers(installation_id=installation_id, user_token=user_token)
if not headers:
return []
url = f"{config.github.api_base_url}/repos/{repo}/pulls?state={state}&per_page={min(per_page, 100)}"
session = await self._get_session()
async with session.get(url, headers=headers) as response:
if response.status == 200:
return cast("list[dict[str, Any]]", await response.json())
return []
except Exception as e:
logger.error(f"Error listing PRs for {repo}: {e}")
return []
async def _get_session(self) -> aiohttp.ClientSession:
"""
Initializes and returns the aiohttp session.
Architectural Note:
- Creates a new session if none exists or if the current session is closed.
- Also recreates the session if the event loop has changed (common in test environments).
"""
try:
if self._session is None or self._session.closed:
self._session = aiohttp.ClientSession()
else:
# Check if we're in a different event loop (avoid deprecated .loop property)
try:
current_loop = asyncio.get_running_loop()
# Try to access session's internal loop to check if it's the same
# If the session's loop is closed, this will fail
if self._session._loop != current_loop or self._session._loop.is_closed():
await self._session.close()
self._session = aiohttp.ClientSession()
except RuntimeError:
# No running loop or loop is closed, recreate session
self._session = aiohttp.ClientSession()
except Exception:
# Fallback: ensure we have a valid session
self._session = aiohttp.ClientSession()
return self._session
def _generate_jwt(self) -> str:
"""Generates a JSON Web Token (JWT) to authenticate as the GitHub App."""
payload = {
"iat": int(time.time()),
"exp": int(time.time()) + (1 * 60),
"iss": self._app_id,
}
return jwt.encode(payload, self._private_key, algorithm="RS256")
@staticmethod
def _decode_private_key() -> str:
try:
decoded_key = base64.b64decode(config.github.private_key).decode("utf-8")
return decoded_key
except Exception as e:
logger.error(f"Failed to decode private key: {e}")
raise ValueError("Invalid private key format.") from e
async def get_pr_files(self, repo_full_name: str, pr_number: int, installation_id: int) -> list[dict[str, Any]]:
"""
Fetch the list of files changed in a pull request.
"""
return await self.get_pull_request_files(repo_full_name, pr_number, installation_id)
async def get_pr_reviews(self, repo_full_name: str, pr_number: int, installation_id: int) -> list[dict[str, Any]]:
"""
Fetch the list of reviews for a pull request.
"""
return await self.get_pull_request_reviews(repo_full_name, pr_number, installation_id)
async def get_pr_checks(self, repo_full_name: str, pr_number: int, installation_id: int) -> list[dict[str, Any]]:
"""
Fetch the list of checks/statuses for a pull request by finding the head SHA first.
"""
try:
pr_data = await self.get_pull_request(repo_full_name, pr_number, installation_id)
if not pr_data:
return []
head_sha = pr_data.get("head", {}).get("sha")
if not head_sha:
return []
# We need to fetch from the check-runs endpoint for this SHA
headers = await self._get_auth_headers(installation_id=installation_id)
if not headers:
return []
url = f"{config.github.api_base_url}/repos/{repo_full_name}/commits/{head_sha}/check-runs"
session = await self._get_session()
async with session.get(url, headers=headers) as response:
if response.status == 200:
data = await response.json()
return cast("list[dict[str, Any]]", data.get("check_runs", []))
return []
except Exception as e:
logger.error(f"Error getting checks for PR #{pr_number}: {e}")
return []
async def get_user_teams(self, repo: str, username: str, installation_id: int) -> list:
"""Fetch the teams a user belongs to in a repo's org."""
headers = await self._get_auth_headers(installation_id=installation_id)
if not headers:
return []
org = repo.split("/")[0]
# Use config base URL instead of hardcoded string
url = f"{config.github.api_base_url}/orgs/{org}/memberships/{username}/teams"
session = await self._get_session()
async with session.get(url, headers=headers) as response:
if response.status == 200:
data = await response.json()
return [cast("dict[str, Any]", team) for team in data]
return []
async def get_user_team_membership(self, repo: str, username: str, installation_id: int) -> dict[str, Any]:
"""Get team membership for a user (with caching)."""
# Implementation with caching
return {}
async def get_codeowners(self, repo: str, installation_id: int) -> dict[str, Any]:
"""Get CODEOWNERS file content."""
try:
content = await self.get_file_content(repo, ".github/CODEOWNERS", installation_id)
return {"content": content} if content else {}
except Exception:
return {}
async def remove_label_from_issue(self, repo: str, issue_number: int, label: str, installation_id: int) -> bool:
"""Remove a single label from an issue or pull request. Returns True on success, False if not found or error."""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
return False
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
encoded_label = quote(label, safe="")
url = f"{config.github.api_base_url}/repos/{repo}/issues/{issue_number}/labels/{encoded_label}"
session = await self._get_session()
async with session.delete(url, headers=headers) as response:
if response.status == 200:
logger.info(f"Removed label '{label}' from #{issue_number} in {repo}")
return True
elif response.status == 404:
# Label wasn't on the issue — not an error
return True
else:
logger.warning(
f"Failed to remove label '{label}' from #{issue_number} in {repo}. Status: {response.status}"
)
return False
except Exception as e:
logger.warning(f"Error removing label '{label}' from #{issue_number} in {repo}: {e}")
return False
async def add_labels_to_issue(
self, repo: str, issue_number: int, labels: list[str], installation_id: int
) -> list[dict[str, Any]]:
"""Add labels to an issue or pull request (PRs are issues in GitHub API)."""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
return []
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
url = f"{config.github.api_base_url}/repos/{repo}/issues/{issue_number}/labels"
data = {"labels": labels}
session = await self._get_session()
async with session.post(url, headers=headers, json=data) as response:
if response.status == 200:
result = await response.json()
logger.info(f"Added labels {labels} to #{issue_number} in {repo}")
return cast("list[dict[str, Any]]", result)
else:
logger.warning(f"Failed to add labels to #{issue_number} in {repo}. Status: {response.status}")
return []
except Exception as e:
logger.warning(f"Error adding labels to #{issue_number} in {repo}: {e}")
return []
async def create_pull_request_comment(
self, repo: str, pr_number: int, comment: str, installation_id: int
) -> dict[str, Any]:
"""Create a comment on a pull request."""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
logger.error(f"Failed to get installation token for {installation_id}")
return {}
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
url = f"{config.github.api_base_url}/repos/{repo}/issues/{pr_number}/comments"
data = {"body": comment}
session = await self._get_session()
async with session.post(url, headers=headers, json=data) as response:
if response.status == 201:
result = await response.json()
logger.info(f"Created comment on PR #{pr_number} in {repo}")
return cast("dict[str, Any]", result)
else:
error_text = await response.text()
logger.error(
f"Failed to create comment on PR #{pr_number} in {repo}. Status: {response.status}, Response: {error_text}"
)
return {}
except Exception as e:
logger.error(f"Error creating comment on PR #{pr_number} in {repo}: {e}")
return {}
async def request_reviewers(
self,
repo: str,
pr_number: int,
reviewers: list[str],
installation_id: int,
team_reviewers: list[str] | None = None,
) -> dict[str, Any]:
"""Request individual and/or team reviewers for a pull request.
GitHub's API uses separate fields:
- `reviewers` → individual user logins
- `team_reviewers` → team slugs (without org prefix, e.g. "frontend")
Mixing them in the wrong field returns 422.
"""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
return {}
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
url = f"{config.github.api_base_url}/repos/{repo}/pulls/{pr_number}/requested_reviewers"
data: dict[str, list[str]] = {}
if reviewers:
data["reviewers"] = reviewers
if team_reviewers:
data["team_reviewers"] = team_reviewers
session = await self._get_session()
async with session.post(url, headers=headers, json=data) as response:
if response.status == 201:
result = await response.json()
logger.info(f"Requested reviewers {reviewers} for PR #{pr_number} in {repo}")
return cast("dict[str, Any]", result)
else:
error_text = await response.text()
logger.warning(
f"Failed to request reviewers for PR #{pr_number} in {repo}. "
f"Status: {response.status}, Response: {error_text}"
)
return {}
except Exception as e:
logger.warning(f"Error requesting reviewers for PR #{pr_number} in {repo}: {e}")
return {}
async def update_check_run(
self, repo: str, check_run_id: int, status: str, conclusion: str, output: dict[str, Any], installation_id: int
) -> dict[str, Any]:
"""Update a check run."""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
logger.error(f"Failed to get installation token for {installation_id}")
return {}
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
url = f"{config.github.api_base_url}/repos/{repo}/check-runs/{check_run_id}"
data = {"status": status, "conclusion": conclusion, "output": output}
session = await self._get_session()
async with session.patch(url, headers=headers, json=data) as response:
if response.status == 200:
result = await response.json()
logger.info(f"Updated check run {check_run_id} for {repo}")
return cast("dict[str, Any]", result)
else:
error_text = await response.text()
logger.error(
f"Failed to update check run {check_run_id} for {repo}. Status: {response.status}, Response: {error_text}"
)
return {}
except Exception as e:
logger.error(f"Error updating check run {check_run_id} for {repo}: {e}")
return {}
async def get_check_runs(self, repo: str, sha: str, installation_id: int) -> list[dict[str, Any]]:
"""Get check runs for a commit."""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
logger.error(f"Failed to get installation token for {installation_id}")
return []
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
url = f"{config.github.api_base_url}/repos/{repo}/commits/{sha}/check-runs"
session = await self._get_session()
async with session.get(url, headers=headers) as response:
if response.status == 200:
data = await response.json()
return cast("list[dict[str, Any]]", data.get("check_runs", []))
else:
error_text = await response.text()
logger.error(
f"Failed to get check runs for {repo} commit {sha}. Status: {response.status}, Response: {error_text}"
)
return []
except Exception as e:
logger.error(f"Error getting check runs for {repo} commit {sha}: {e}")
return []
async def get_pull_request_reviews(self, repo: str, pr_number: int, installation_id: int) -> list[dict[str, Any]]:
"""Get reviews for a pull request.
Paginates through all pages to ensure the full review list is returned.
GitHub defaults to 30 reviews per page; max is 100.
"""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
logger.error(f"Failed to get installation token for {installation_id}")
return []
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
all_reviews: list[dict[str, Any]] = []
page = 1
per_page = 100
session = await self._get_session()
while True:
url = (
f"{config.github.api_base_url}/repos/{repo}/pulls/{pr_number}"
f"/reviews?per_page={per_page}&page={page}"
)
async with session.get(url, headers=headers) as response:
if response.status != 200:
error_text = await response.text()
logger.error(
f"Failed to get reviews for PR #{pr_number} in {repo}. "
f"Status: {response.status}, Response: {error_text}"
)
break
result = await response.json()
if not result:
break
all_reviews.extend(result)
if len(result) < per_page:
break
page += 1
logger.info(f"Retrieved {len(all_reviews)} reviews for PR #{pr_number} in {repo}")
return all_reviews
except Exception as e:
logger.error(f"Error getting reviews for PR #{pr_number} in {repo}: {e}")
return []
async def get_pull_request_review_threads(
self, repo: str, pr_number: int, installation_id: int
) -> list[dict[str, Any]]:
"""Get review threads for a pull request using the GraphQL API."""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
logger.error(f"Failed to get installation token for {installation_id}")
return []
from src.integrations.github.graphql import GitHubGraphQLClient
client = GitHubGraphQLClient(token)
owner, repo_name = repo.split("/", 1)
query = """
query PRReviewThreads($owner: String!, $repo: String!, $pr_number: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $pr_number) {
reviewThreads(first: 50) {
nodes {
isResolved
isOutdated
comments(first: 10) {
nodes {
body
createdAt
author {
login
}
}
}
}
}
}
}
}
"""
variables = {"owner": owner, "repo": repo_name, "pr_number": pr_number}
response_model = await client.execute_query_typed(query, variables)
if response_model.errors:
logger.error("GraphQL query failed", errors=response_model.errors)
return []
repo_node = response_model.data.repository
if not repo_node or not repo_node.pull_request or not repo_node.pull_request.review_threads:
return []
threads = [thread.model_dump() for thread in repo_node.pull_request.review_threads.nodes]
logger.info(f"Retrieved {len(threads)} review threads for PR #{pr_number} in {repo}")
return threads
except Exception as e:
logger.error(f"Error getting review threads for PR #{pr_number} in {repo}: {e}")
return []
async def get_pull_request_files(self, repo: str, pr_number: int, installation_id: int) -> list[dict[str, Any]]:
"""Get files changed in a pull request.
Paginates through all pages to ensure the full file list is returned.
GitHub defaults to 30 files per page; max is 100. PRs with more than
3 000 files are truncated by the API regardless of pagination.
"""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
logger.error(f"Failed to get installation token for {installation_id}")
return []
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
all_files: list[dict[str, Any]] = []
page = 1
per_page = 100
session = await self._get_session()
while True:
url = (
f"{config.github.api_base_url}/repos/{repo}/pulls/{pr_number}/files?per_page={per_page}&page={page}"
)
async with session.get(url, headers=headers) as response:
if response.status != 200:
error_text = await response.text()
logger.error(
f"Failed to get files for PR #{pr_number} in {repo}. "
f"Status: {response.status}, Response: {error_text}"
)
break
result = await response.json()
if not result:
break
all_files.extend(result)
if len(result) < per_page:
break
page += 1
logger.info(f"Retrieved {len(all_files)} files for PR #{pr_number} in {repo}")
return all_files
except Exception as e:
logger.error(f"Error getting files for PR #{pr_number} in {repo}: {e}")
return []
async def create_comment_reply(
self, repo: str, comment_id: int, reply: str, installation_id: int
) -> dict[str, Any]:
"""Create a reply to a comment."""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
logger.error(f"Failed to get installation token for {installation_id}")
return {}
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
url = f"{config.github.api_base_url}/repos/{repo}/issues/comments/{comment_id}/reactions"
data = {"content": "eyes"} # Add a reaction to acknowledge
session = await self._get_session()
async with session.post(url, headers=headers, json=data) as response:
if response.status == 201:
logger.info(f"Added reaction to comment {comment_id} in {repo}")
return cast("dict[str, Any]", await response.json())
else:
error_text = await response.text()
logger.error(
f"Failed to add reaction to comment {comment_id} in {repo}. Status: {response.status}, Response: {error_text}"
)
return {}
except Exception as e:
logger.error(f"Error adding reaction to comment {comment_id} in {repo}: {e}")
return {}
async def create_issue_comment(
self, repo: str, issue_number: int, comment: str, installation_id: int
) -> dict[str, Any]:
"""Create a comment on an issue."""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
logger.error(f"Failed to get installation token for {installation_id}")
return {}
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
url = f"{config.github.api_base_url}/repos/{repo}/issues/{issue_number}/comments"
data = {"body": comment}
session = await self._get_session()
async with session.post(url, headers=headers, json=data) as response:
if response.status == 201:
result = await response.json()
logger.info(f"Created comment on issue #{issue_number} in {repo}")
return cast("dict[str, Any]", result)
else:
error_text = await response.text()
logger.error(
f"Failed to create comment on issue #{issue_number} in {repo}. Status: {response.status}, Response: {error_text}"
)
return {}
except Exception as e:
logger.error(f"Error creating comment on issue #{issue_number} in {repo}: {e}")
return {}
async def create_deployment_status(
self,
repo: str,
deployment_id: int,
state: str,
description: str,
environment: str,
log_url: str,
installation_id: int,
) -> dict[str, Any] | None:
"""Create a deployment status."""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
logger.error(f"Failed to get installation token for {installation_id}")
return None
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
url = f"{config.github.api_base_url}/repos/{repo}/deployments/{deployment_id}/statuses"
data = {"state": state, "description": description, "environment": environment, "log_url": log_url}
session = await self._get_session()
async with session.post(url, headers=headers, json=data) as response:
if response.status == 201:
result = await response.json()
logger.info(f"Created deployment status for deployment {deployment_id} in {repo}")
return cast("dict[str, Any]", result)
else:
error_text = await response.text()
logger.error(
f"Failed to create deployment status for deployment {deployment_id} in {repo}. Status: {response.status}, Response: {error_text}"
)
return None
except Exception as e:
logger.error(f"Error creating deployment status for deployment {deployment_id} in {repo}: {e}")
return None
async def review_deployment_protection_rule(
self, callback_url: str, environment: str, state: str, comment: str, installation_id: int
) -> dict[str, Any] | None:
"""Review a deployment protection rule."""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
logger.error(f"Failed to get installation token for {installation_id} to review deployment.")
return None
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"}
data = {
"state": state, # "approved" or "rejected"
"comment": comment,
"environment_name": environment,
}
session = await self._get_session()
async with session.post(callback_url, headers=headers, json=data) as response:
if response.status in [200, 204]: # 204 No Content is also a success
logger.info(f"Successfully reviewed deployment protection rule with state {state}.")
if response.status == 200:
return cast("dict[str, Any]", await response.json())
else:
return {"status": "success", "state": state}
else:
error_text = await response.text()
logger.error(
f"Failed to review deployment protection rule for environment {environment}. Status: {response.status}, Response: {error_text}"
)
logger.error(f"Request URL: {callback_url}")
logger.error(f"Request payload: {data}")
return None
except Exception as e:
logger.error(f"Error reviewing deployment protection rule: {e}")
return None
async def get_issue_comments(self, repo: str, issue_number: int, installation_id: int) -> list[dict[str, Any]]:
"""Get comments for an issue."""
try:
token = await self.get_installation_access_token(installation_id)
if not token:
logger.error(f"Failed to get installation token for {installation_id}")
return []
headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github.v3+json"}
url = f"{config.github.api_base_url}/repos/{repo}/issues/{issue_number}/comments"
session = await self._get_session()
async with session.get(url, headers=headers) as response:
if response.status == 200:
result = await response.json()
logger.info(f"Retrieved {len(result)} comments for issue #{issue_number} in {repo}")
return cast("list[dict[str, Any]]", result)
else:
error_text = await response.text()
logger.error(
f"Failed to get comments for issue #{issue_number} in {repo}. Status: {response.status}, Response: {error_text}"
)
return []
except Exception as e:
logger.error(f"Error getting comments for issue #{issue_number} in {repo}: {e}")
return []
async def update_deployment_status(
self, callback_url: str, state: str, description: str, environment_url: str | None = None
) -> dict[str, Any] | None:
"""Update deployment status via callback URL."""
try:
# For this method, we need to use a different approach since we don't have the installation_id
# We'll use the JWT token directly