Repository navigation
Expand file tree
/
Copy pathproviders.py
More file actions
662 lines (591 loc) · 21.4 KB
/
Copy pathproviders.py
File metadata and controls
662 lines (591 loc) · 21.4 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
"""SCM provider abstractions for Gitea, GitHub, and GitLab."""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Protocol, cast
from gitea_automation.models import PullRequestReadiness
class ProviderApiError(Exception):
"""Raised when provider API request fails."""
def __init__(
self,
message: str,
*,
status_code: int | None = None,
method: str | None = None,
url: str | None = None,
body: str | None = None,
) -> None:
super().__init__(message)
self.status_code = status_code
self.method = method
self.url = url
self.body = body
class ScmProvider(Protocol):
"""Protocol for source control provider API adapters."""
name: str
token_env_var: str
def get_commit_status(
self,
base_url: str,
owner: str,
repo: str,
sha: str,
token: str,
) -> dict[str, Any]: ...
def find_open_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
target_branch: str,
) -> dict[str, Any] | None: ...
def create_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
target_branch: str,
title_prefix: str,
) -> dict[str, Any]: ...
def get_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
) -> dict[str, Any]: ...
def get_pull_request_readiness(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
) -> PullRequestReadiness: ...
def merge_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
merge_style: str,
) -> None: ...
def get_branch_remote_sha(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
) -> str: ...
class BaseProvider:
"""Shared HTTP utilities for provider implementations."""
name = "base"
token_env_var = ""
def _repo_api_base(self, base_url: str, owner: str, repo: str) -> str:
raise NotImplementedError
def _build_headers(self, token: str) -> dict[str, str]:
raise NotImplementedError
def _request(
self,
method: str,
url: str,
token: str,
payload: dict[str, Any] | None = None,
) -> Any:
data: bytes | None = None
headers = self._build_headers(token)
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
request = urllib.request.Request(url=url, method=method, headers=headers, data=data)
try:
with urllib.request.urlopen(request) as response:
raw = response.read().decode("utf-8")
if not raw:
return {}
return json.loads(raw)
except urllib.error.HTTPError as error:
body = error.read().decode("utf-8", errors="ignore")
raise ProviderApiError(
f"API request failed: {method} {url} [{error.code}] {body}",
status_code=error.code,
method=method,
url=url,
body=body,
) from error
except urllib.error.URLError as error:
raise ProviderApiError(
f"API request failed: {method} {url} ({error.reason})",
method=method,
url=url,
) from error
class GiteaProvider(BaseProvider):
"""Gitea API adapter."""
name = "gitea"
token_env_var = "GITEA_TOKEN"
def _repo_api_base(self, base_url: str, owner: str, repo: str) -> str:
return f"{base_url.rstrip('/')}/api/v1/repos/{owner}/{repo}"
def _build_headers(self, token: str) -> dict[str, str]:
return {"Authorization": f"token {token}", "Accept": "application/json"}
def get_commit_status(
self, base_url: str, owner: str, repo: str, sha: str, token: str
) -> dict[str, Any]:
url = f"{self._repo_api_base(base_url, owner, repo)}/commits/{sha}/status"
response = self._request("GET", url, token)
if not isinstance(response, dict):
raise ProviderApiError("Commit status response is not a JSON object")
return cast(dict[str, Any], response)
def find_open_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
target_branch: str,
) -> dict[str, Any] | None:
query = urllib.parse.urlencode(
{"state": "open", "head": f"{owner}:{branch}", "base": target_branch}
)
url = f"{self._repo_api_base(base_url, owner, repo)}/pulls?{query}"
pulls = self._request("GET", url, token)
if isinstance(pulls, list) and pulls and isinstance(pulls[0], dict):
return cast(dict[str, Any], pulls[0])
return None
def create_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
target_branch: str,
title_prefix: str,
) -> dict[str, Any]:
url = f"{self._repo_api_base(base_url, owner, repo)}/pulls"
payload = {
"base": target_branch,
"head": branch,
"title": f"{title_prefix}: {branch} -> {target_branch}",
"body": "Auto-created by gitea-automation.",
}
response = self._request("POST", url, token, payload)
if not isinstance(response, dict):
raise ProviderApiError("Create pull request response is not a JSON object")
return cast(dict[str, Any], response)
def get_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
) -> dict[str, Any]:
url = f"{self._repo_api_base(base_url, owner, repo)}/pulls/{pull_number}"
response = self._request("GET", url, token)
if not isinstance(response, dict):
raise ProviderApiError("Pull request response is not a JSON object")
return cast(dict[str, Any], response)
def get_pull_request_readiness(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
) -> PullRequestReadiness:
pull = self.get_pull_request(base_url, owner, repo, token, pull_number)
mergeable = pull.get("mergeable")
return PullRequestReadiness(
mergeable=mergeable if isinstance(mergeable, bool) else None,
draft=bool(pull.get("draft", False)),
has_conflicts=bool(pull.get("has_conflicts", False)),
)
def merge_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
merge_style: str,
) -> None:
do_map = {
"merge": "merge",
"rebase": "rebase",
"rebase-merge": "rebase-merge",
"squash": "squash",
"fast-forward-only": "fast-forward-only",
}
payload = {"Do": do_map[merge_style]}
url = f"{self._repo_api_base(base_url, owner, repo)}/pulls/{pull_number}/merge"
self._request("POST", url, token, payload)
def get_branch_remote_sha(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
) -> str:
url = f"{self._repo_api_base(base_url, owner, repo)}/branches/{branch}"
response = self._request("GET", url, token)
if not isinstance(response, dict):
raise ProviderApiError(f"Branch response is not a JSON object: {branch}")
commit = response.get("commit", {})
sha = commit.get("id", "") if isinstance(commit, dict) else ""
if not isinstance(sha, str) or not sha:
raise ProviderApiError(f"Cannot read SHA for remote branch: {branch}")
return sha
class GitHubProvider(BaseProvider):
"""GitHub API adapter."""
name = "github"
token_env_var = "GITHUB_TOKEN"
def _repo_api_base(self, base_url: str, owner: str, repo: str) -> str:
return f"{base_url.rstrip('/')}/repos/{owner}/{repo}"
def _build_headers(self, token: str) -> dict[str, str]:
return {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
}
def get_commit_status(
self, base_url: str, owner: str, repo: str, sha: str, token: str
) -> dict[str, Any]:
url = f"{self._repo_api_base(base_url, owner, repo)}/commits/{sha}/status"
response = self._request("GET", url, token)
if not isinstance(response, dict):
raise ProviderApiError("Commit status response is not a JSON object")
statuses = response.get("statuses", [])
normalized: list[dict[str, Any]] = []
if isinstance(statuses, list):
for row in statuses:
if not isinstance(row, dict):
continue
normalized.append(
{
"context": row.get("context", "unknown"),
"status": row.get("state", "unknown"),
"description": row.get("description", ""),
"target_url": row.get("target_url", ""),
}
)
return {
"state": response.get("state", "unknown"),
"total_count": response.get("total_count", len(normalized)),
"statuses": normalized,
}
def find_open_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
target_branch: str,
) -> dict[str, Any] | None:
query = urllib.parse.urlencode(
{"state": "open", "head": f"{owner}:{branch}", "base": target_branch}
)
url = f"{self._repo_api_base(base_url, owner, repo)}/pulls?{query}"
pulls = self._request("GET", url, token)
if isinstance(pulls, list) and pulls and isinstance(pulls[0], dict):
return cast(dict[str, Any], pulls[0])
return None
def create_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
target_branch: str,
title_prefix: str,
) -> dict[str, Any]:
url = f"{self._repo_api_base(base_url, owner, repo)}/pulls"
payload = {
"base": target_branch,
"head": branch,
"title": f"{title_prefix}: {branch} -> {target_branch}",
"body": "Auto-created by gitea-automation.",
}
response = self._request("POST", url, token, payload)
if not isinstance(response, dict):
raise ProviderApiError("Create pull request response is not a JSON object")
return cast(dict[str, Any], response)
def get_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
) -> dict[str, Any]:
url = f"{self._repo_api_base(base_url, owner, repo)}/pulls/{pull_number}"
response = self._request("GET", url, token)
if not isinstance(response, dict):
raise ProviderApiError("Pull request response is not a JSON object")
return cast(dict[str, Any], response)
def get_pull_request_readiness(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
) -> PullRequestReadiness:
pull = self.get_pull_request(base_url, owner, repo, token, pull_number)
mergeable = pull.get("mergeable")
mergeable_state = str(pull.get("mergeable_state", "")).lower()
return PullRequestReadiness(
mergeable=mergeable if isinstance(mergeable, bool) else None,
draft=bool(pull.get("draft", False)),
has_conflicts=mergeable_state == "dirty",
)
def merge_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
merge_style: str,
) -> None:
merge_method_map = {
"merge": "merge",
"rebase": "rebase",
"squash": "squash",
}
if merge_style not in merge_method_map:
raise ProviderApiError(
f"Merge style '{merge_style}' is not supported by GitHub provider"
)
payload = {"merge_method": merge_method_map[merge_style]}
url = f"{self._repo_api_base(base_url, owner, repo)}/pulls/{pull_number}/merge"
self._request("PUT", url, token, payload)
def get_branch_remote_sha(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
) -> str:
url = f"{self._repo_api_base(base_url, owner, repo)}/branches/{branch}"
response = self._request("GET", url, token)
if not isinstance(response, dict):
raise ProviderApiError(f"Branch response is not a JSON object: {branch}")
commit = response.get("commit", {})
sha = commit.get("sha", "") if isinstance(commit, dict) else ""
if not isinstance(sha, str) or not sha:
raise ProviderApiError(f"Cannot read SHA for remote branch: {branch}")
return sha
class GitLabProvider(BaseProvider):
"""GitLab API adapter."""
name = "gitlab"
token_env_var = "GITLAB_TOKEN"
def _project_id(self, owner: str, repo: str) -> str:
return urllib.parse.quote(f"{owner}/{repo}", safe="")
def _repo_api_base(self, base_url: str, owner: str, repo: str) -> str:
project_id = self._project_id(owner, repo)
return f"{base_url.rstrip('/')}/api/v4/projects/{project_id}"
def _build_headers(self, token: str) -> dict[str, str]:
return {"PRIVATE-TOKEN": token, "Accept": "application/json"}
def get_commit_status(
self, base_url: str, owner: str, repo: str, sha: str, token: str
) -> dict[str, Any]:
url = (
f"{self._repo_api_base(base_url, owner, repo)}/repository/commits/"
f"{sha}/statuses?all=true"
)
response = self._request("GET", url, token)
if not isinstance(response, list):
raise ProviderApiError("Commit statuses response is not a JSON array")
normalized: list[dict[str, Any]] = []
states: list[str] = []
for row in response:
if not isinstance(row, dict):
continue
state = str(row.get("status", "unknown")).lower()
states.append(state)
normalized.append(
{
"context": row.get("name", "unknown"),
"status": state,
"description": row.get("description", ""),
"target_url": row.get("target_url", ""),
}
)
failed_states = {"failed", "canceled", "cancelled"}
pending_states = {"pending", "running", "created", "waiting_for_resource", "preparing"}
success_states = {"success", "skipped", "manual"}
combined_state = "unknown"
if not states:
combined_state = "pending"
elif any(state in failed_states for state in states):
combined_state = "failure"
elif all(state in success_states for state in states):
combined_state = "success"
elif any(state in pending_states for state in states):
combined_state = "pending"
else:
combined_state = "pending"
return {
"state": combined_state,
"total_count": len(normalized),
"statuses": normalized,
}
def find_open_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
target_branch: str,
) -> dict[str, Any] | None:
query = urllib.parse.urlencode(
{
"state": "opened",
"source_branch": branch,
"target_branch": target_branch,
}
)
url = f"{self._repo_api_base(base_url, owner, repo)}/merge_requests?{query}"
merge_requests = self._request("GET", url, token)
if isinstance(merge_requests, list) and merge_requests and isinstance(merge_requests[0], dict):
item = cast(dict[str, Any], merge_requests[0])
if "iid" in item and "number" not in item:
item = dict(item)
item["number"] = item["iid"]
return item
return None
def create_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
target_branch: str,
title_prefix: str,
) -> dict[str, Any]:
url = f"{self._repo_api_base(base_url, owner, repo)}/merge_requests"
payload = {
"source_branch": branch,
"target_branch": target_branch,
"title": f"{title_prefix}: {branch} -> {target_branch}",
"description": "Auto-created by gitea-automation.",
"remove_source_branch": False,
}
response = self._request("POST", url, token, payload)
if not isinstance(response, dict):
raise ProviderApiError("Create merge request response is not a JSON object")
item = cast(dict[str, Any], response)
if "iid" in item and "number" not in item:
item = dict(item)
item["number"] = item["iid"]
return item
def get_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
) -> dict[str, Any]:
url = f"{self._repo_api_base(base_url, owner, repo)}/merge_requests/{pull_number}"
response = self._request("GET", url, token)
if not isinstance(response, dict):
raise ProviderApiError("Merge request response is not a JSON object")
item = cast(dict[str, Any], response)
if "iid" in item and "number" not in item:
item = dict(item)
item["number"] = item["iid"]
return item
def get_pull_request_readiness(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
) -> PullRequestReadiness:
pull = self.get_pull_request(base_url, owner, repo, token, pull_number)
title = str(pull.get("title", ""))
is_draft = bool(pull.get("draft", False)) or bool(pull.get("work_in_progress", False))
is_draft = is_draft or title.lower().startswith("draft")
detailed_status = str(pull.get("detailed_merge_status", "")).lower()
merge_status = str(pull.get("merge_status", "")).lower()
mergeable: bool | None = None
if detailed_status:
if detailed_status in {"mergeable", "ci_must_pass", "checking", "approvals_syncing"}:
mergeable = detailed_status == "mergeable"
elif detailed_status in {"conflict", "not_open", "broken_status", "requested_changes"}:
mergeable = False
elif merge_status:
mergeable = merge_status == "can_be_merged"
has_conflicts = bool(pull.get("has_conflicts", False))
if detailed_status == "conflict":
has_conflicts = True
return PullRequestReadiness(
mergeable=mergeable,
draft=is_draft,
has_conflicts=has_conflicts,
)
def merge_pull_request(
self,
base_url: str,
owner: str,
repo: str,
token: str,
pull_number: int,
merge_style: str,
) -> None:
if merge_style not in {"merge", "squash"}:
raise ProviderApiError(
f"Merge style '{merge_style}' is not supported by GitLab provider"
)
payload: dict[str, Any] = {
"merge_when_pipeline_succeeds": False,
"squash": merge_style == "squash",
}
url = f"{self._repo_api_base(base_url, owner, repo)}/merge_requests/{pull_number}/merge"
self._request("PUT", url, token, payload)
def get_branch_remote_sha(
self,
base_url: str,
owner: str,
repo: str,
token: str,
branch: str,
) -> str:
encoded_branch = urllib.parse.quote(branch, safe="")
url = f"{self._repo_api_base(base_url, owner, repo)}/repository/branches/{encoded_branch}"
response = self._request("GET", url, token)
if not isinstance(response, dict):
raise ProviderApiError(f"Branch response is not a JSON object: {branch}")
commit = response.get("commit", {})
sha = commit.get("id", "") if isinstance(commit, dict) else ""
if not isinstance(sha, str) or not sha:
raise ProviderApiError(f"Cannot read SHA for remote branch: {branch}")
return sha
def create_provider(name: str) -> ScmProvider:
"""Factory for SCM providers by name."""
normalized = name.strip().lower()
if normalized == "gitea":
return GiteaProvider()
if normalized == "github":
return GitHubProvider()
if normalized == "gitlab":
return GitLabProvider()
raise ValueError(f"Unsupported provider: {name}")