Samyak000 commited on
Commit
61f9f3b
·
verified ·
1 Parent(s): a4939a3

Create github_api

Browse files
Files changed (1) hide show
  1. github_api +361 -0
github_api ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ GitHub App Authentication and API Module for Codesage
4
+ Handles JWT generation, installation token exchange, and GitHub API calls
5
+ """
6
+
7
+ import jwt
8
+ import time
9
+ import requests
10
+ from typing import Dict, List, Optional
11
+ from datetime import datetime, timedelta
12
+ import os
13
+
14
+
15
+ class GitHubAppAuth:
16
+ """
17
+ Enterprise-grade GitHub App authentication
18
+ No PATs, no user passwords - just secure app-level access
19
+ """
20
+
21
+ def __init__(self, app_id: str, private_key: str):
22
+ """
23
+ Initialize GitHub App authentication
24
+
25
+ Args:
26
+ app_id: Your GitHub App ID
27
+ private_key: Contents of your .pem private key file
28
+ """
29
+ self.app_id = app_id
30
+ self.private_key = private_key
31
+ self.base_url = "https://api.github.com"
32
+
33
+ def generate_jwt(self) -> str:
34
+ """
35
+ Generate JWT for GitHub App authentication
36
+ Following official GitHub documentation
37
+
38
+ JWT Rules:
39
+ - Algorithm: RS256
40
+ - Expiry: 10 minutes maximum
41
+ - Issued at: Current time
42
+
43
+ Returns:
44
+ JWT token string
45
+ """
46
+ # Match official GitHub documentation exactly
47
+ # Using 5 minutes instead of 10 to account for clock drift
48
+ payload = {
49
+ # Issued at time
50
+ 'iat': int(time.time()),
51
+ # JWT expiration time (5 minutes to avoid clock drift issues)
52
+ 'exp': int(time.time()) + 300,
53
+ # GitHub App's client ID (App ID)
54
+ 'iss': self.app_id
55
+ }
56
+
57
+ # Generate JWT using RS256 algorithm
58
+ # Private key is already read as string, which PyJWT handles correctly
59
+ jwt_token = jwt.encode(payload, self.private_key, algorithm="RS256")
60
+ return jwt_token
61
+
62
+ def get_installation_token(self, installation_id: int) -> Dict:
63
+ """
64
+ Exchange JWT for Installation Access Token
65
+
66
+ This token:
67
+ - Can access private repos
68
+ - Is scoped to permissions you selected
69
+ - Expires automatically (usually 1 hour)
70
+
71
+ Args:
72
+ installation_id: The installation ID from org install
73
+
74
+ Returns:
75
+ Dict with 'token', 'expires_at', and other metadata
76
+ """
77
+ jwt_token = self.generate_jwt()
78
+
79
+ url = f"{self.base_url}/app/installations/{installation_id}/access_tokens"
80
+ headers = {
81
+ "Authorization": f"Bearer {jwt_token}",
82
+ "Accept": "application/vnd.github+json",
83
+ "X-GitHub-Api-Version": "2022-11-28"
84
+ }
85
+
86
+ response = requests.post(url, headers=headers)
87
+ response.raise_for_status()
88
+
89
+ return response.json()
90
+
91
+ def get_installation_repositories(self, installation_token: str) -> List[Dict]:
92
+ """
93
+ List all repositories accessible to this installation
94
+
95
+ Args:
96
+ installation_token: Active installation access token
97
+
98
+ Returns:
99
+ List of repository objects
100
+ """
101
+ url = f"{self.base_url}/installation/repositories"
102
+ headers = {
103
+ "Authorization": f"Bearer {installation_token}",
104
+ "Accept": "application/vnd.github+json",
105
+ "X-GitHub-Api-Version": "2022-11-28"
106
+ }
107
+
108
+ response = requests.get(url, headers=headers)
109
+ response.raise_for_status()
110
+
111
+ return response.json().get("repositories", [])
112
+
113
+
114
+ class GitHubInsights:
115
+ """
116
+ Fetch powerful insights from GitHub repositories
117
+ All read-only, zero-risk operations
118
+ """
119
+
120
+ def __init__(self, installation_token: str):
121
+ """
122
+ Initialize with an active installation token
123
+
124
+ Args:
125
+ installation_token: Valid installation access token
126
+ """
127
+ self.token = installation_token
128
+ self.base_url = "https://api.github.com"
129
+ self.headers = {
130
+ "Authorization": f"Bearer {installation_token}",
131
+ "Accept": "application/vnd.github+json",
132
+ "X-GitHub-Api-Version": "2022-11-28"
133
+ }
134
+
135
+ def get_commits(self, org: str, repo: str, per_page: int = 30) -> List[Dict]:
136
+ """
137
+ Fetch recent commits from a repository
138
+
139
+ Args:
140
+ org: Organization name
141
+ repo: Repository name
142
+ per_page: Number of commits to fetch (default 30)
143
+
144
+ Returns:
145
+ List of commit objects
146
+ """
147
+ url = f"{self.base_url}/repos/{org}/{repo}/commits"
148
+ params = {"per_page": per_page}
149
+
150
+ response = requests.get(url, headers=self.headers, params=params)
151
+ response.raise_for_status()
152
+
153
+ return response.json()
154
+
155
+ def get_pull_requests(self, org: str, repo: str, state: str = "all") -> List[Dict]:
156
+ """
157
+ Fetch pull requests from a repository
158
+
159
+ Args:
160
+ org: Organization name
161
+ repo: Repository name
162
+ state: "open", "closed", or "all" (default "all")
163
+
164
+ Returns:
165
+ List of pull request objects
166
+ """
167
+ url = f"{self.base_url}/repos/{org}/{repo}/pulls"
168
+ params = {"state": state, "per_page": 100}
169
+
170
+ response = requests.get(url, headers=self.headers, params=params)
171
+ response.raise_for_status()
172
+
173
+ return response.json()
174
+
175
+ def get_issues(self, org: str, repo: str, state: str = "all") -> List[Dict]:
176
+ """
177
+ Fetch issues from a repository
178
+
179
+ Args:
180
+ org: Organization name
181
+ repo: Repository name
182
+ state: "open", "closed", or "all" (default "all")
183
+
184
+ Returns:
185
+ List of issue objects
186
+ """
187
+ url = f"{self.base_url}/repos/{org}/{repo}/issues"
188
+ params = {"state": state, "per_page": 100}
189
+
190
+ response = requests.get(url, headers=self.headers, params=params)
191
+ response.raise_for_status()
192
+
193
+ return response.json()
194
+
195
+ def get_contributors(self, org: str, repo: str) -> List[Dict]:
196
+ """
197
+ Fetch contributors and their stats
198
+
199
+ Args:
200
+ org: Organization name
201
+ repo: Repository name
202
+
203
+ Returns:
204
+ List of contributor objects with stats
205
+ """
206
+ url = f"{self.base_url}/repos/{org}/{repo}/contributors"
207
+ params = {"per_page": 100}
208
+
209
+ response = requests.get(url, headers=self.headers, params=params)
210
+ response.raise_for_status()
211
+
212
+ return response.json()
213
+
214
+ def get_code_frequency(self, org: str, repo: str) -> List[List[int]]:
215
+ """
216
+ Get code frequency stats (additions/deletions per week)
217
+
218
+ Args:
219
+ org: Organization name
220
+ repo: Repository name
221
+
222
+ Returns:
223
+ List of [timestamp, additions, deletions] arrays
224
+ """
225
+ url = f"{self.base_url}/repos/{org}/{repo}/stats/code_frequency"
226
+
227
+ response = requests.get(url, headers=self.headers)
228
+ response.raise_for_status()
229
+
230
+ return response.json()
231
+
232
+ def get_commit_activity(self, org: str, repo: str) -> List[Dict]:
233
+ """
234
+ Get commit activity by week for the last year
235
+
236
+ Args:
237
+ org: Organization name
238
+ repo: Repository name
239
+
240
+ Returns:
241
+ List of activity objects with days and total
242
+ """
243
+ url = f"{self.base_url}/repos/{org}/{repo}/stats/commit_activity"
244
+
245
+ response = requests.get(url, headers=self.headers)
246
+ response.raise_for_status()
247
+
248
+ return response.json()
249
+
250
+ def get_repository_info(self, org: str, repo: str) -> Dict:
251
+ """
252
+ Get detailed repository information
253
+
254
+ Args:
255
+ org: Organization name
256
+ repo: Repository name
257
+
258
+ Returns:
259
+ Repository object with metadata
260
+ """
261
+ url = f"{self.base_url}/repos/{org}/{repo}"
262
+
263
+ response = requests.get(url, headers=self.headers)
264
+ response.raise_for_status()
265
+
266
+ return response.json()
267
+
268
+ def get_languages(self, org: str, repo: str) -> Dict[str, int]:
269
+ """
270
+ Get programming languages used in the repository
271
+
272
+ Args:
273
+ org: Organization name
274
+ repo: Repository name
275
+
276
+ Returns:
277
+ Dict mapping language name to bytes of code
278
+ """
279
+ url = f"{self.base_url}/repos/{org}/{repo}/languages"
280
+
281
+ response = requests.get(url, headers=self.headers)
282
+ response.raise_for_status()
283
+
284
+ return response.json()
285
+
286
+ def get_workflow_runs(self, org: str, repo: str) -> List[Dict]:
287
+ """
288
+ Get GitHub Actions workflow runs (CI/CD insights)
289
+
290
+ Args:
291
+ org: Organization name
292
+ repo: Repository name
293
+
294
+ Returns:
295
+ List of workflow run objects
296
+ """
297
+ url = f"{self.base_url}/repos/{org}/{repo}/actions/runs"
298
+ params = {"per_page": 50}
299
+
300
+ response = requests.get(url, headers=self.headers, params=params)
301
+ response.raise_for_status()
302
+
303
+ return response.json().get("workflow_runs", [])
304
+
305
+ def get_dependabot_alerts(self, org: str, repo: str) -> List[Dict]:
306
+ """
307
+ Get Dependabot security alerts
308
+
309
+ Args:
310
+ org: Organization name
311
+ repo: Repository name
312
+
313
+ Returns:
314
+ List of Dependabot alert objects
315
+ """
316
+ url = f"{self.base_url}/repos/{org}/{repo}/dependabot/alerts"
317
+
318
+ response = requests.get(url, headers=self.headers)
319
+
320
+ # Not all repos have this enabled
321
+ if response.status_code == 404:
322
+ return []
323
+
324
+ response.raise_for_status()
325
+ return response.json()
326
+
327
+
328
+ class TokenManager:
329
+ """
330
+ Manages installation tokens and automatic refresh
331
+ Tokens expire after ~1 hour, this handles recreation
332
+ """
333
+
334
+ def __init__(self, github_auth: GitHubAppAuth):
335
+ self.github_auth = github_auth
336
+ self.token_cache: Dict[int, Dict] = {}
337
+
338
+ def get_token(self, installation_id: int) -> str:
339
+ """
340
+ Get valid installation token, refreshing if needed
341
+
342
+ Args:
343
+ installation_id: The installation ID
344
+
345
+ Returns:
346
+ Valid installation access token
347
+ """
348
+ cached = self.token_cache.get(installation_id)
349
+
350
+ # Check if we have a cached token that's still valid
351
+ if cached:
352
+ expires_at = datetime.fromisoformat(cached["expires_at"].replace("Z", "+00:00"))
353
+ # Refresh if less than 5 minutes remaining
354
+ if datetime.now(expires_at.tzinfo) < expires_at - timedelta(minutes=5):
355
+ return cached["token"]
356
+
357
+ # Get fresh token
358
+ token_data = self.github_auth.get_installation_token(installation_id)
359
+ self.token_cache[installation_id] = token_data
360
+
361
+ return token_data["token"]