render-lab-tasks-github 0.1.0__py3-none-any.whl → 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. render_lab_tasks_github/client.py +571 -0
  2. render_lab_tasks_github/comment_on_issue.py +18 -0
  3. render_lab_tasks_github/commit_file.py +18 -0
  4. render_lab_tasks_github/commit_files.py +18 -0
  5. render_lab_tasks_github/create_branch.py +18 -0
  6. render_lab_tasks_github/create_issue.py +18 -0
  7. render_lab_tasks_github/delete_branch.py +18 -0
  8. render_lab_tasks_github/delete_repository.py +20 -0
  9. render_lab_tasks_github/dispatch_workflow.py +18 -0
  10. render_lab_tasks_github/ensure_organization_repository.py +20 -0
  11. render_lab_tasks_github/get_branch.py +18 -0
  12. render_lab_tasks_github/get_file_contents.py +18 -0
  13. render_lab_tasks_github/get_issue.py +18 -0
  14. render_lab_tasks_github/get_pr.py +18 -0
  15. render_lab_tasks_github/get_repository.py +18 -0
  16. render_lab_tasks_github/list_organization_repositories.py +20 -0
  17. render_lab_tasks_github/list_prs.py +18 -0
  18. render_lab_tasks_github/list_tree.py +18 -0
  19. render_lab_tasks_github/merge_when_green.py +18 -0
  20. render_lab_tasks_github/open_pr.py +18 -0
  21. render_lab_tasks_github/review_pr.py +18 -0
  22. render_lab_tasks_github/search_code.py +18 -0
  23. render_lab_tasks_github/search_repositories.py +20 -0
  24. render_lab_tasks_github/tasks.py +82 -0
  25. render_lab_tasks_github/types.py +366 -1
  26. render_lab_tasks_github/update_issue.py +18 -0
  27. render_lab_tasks_github/update_repository.py +20 -0
  28. render_lab_tasks_github/webhooks.py +35 -0
  29. {render_lab_tasks_github-0.1.0.dist-info → render_lab_tasks_github-0.1.1.dist-info}/METADATA +32 -5
  30. render_lab_tasks_github-0.1.1.dist-info/RECORD +38 -0
  31. render_lab_tasks_github-0.1.0.dist-info/RECORD +0 -13
  32. {render_lab_tasks_github-0.1.0.dist-info → render_lab_tasks_github-0.1.1.dist-info}/WHEEL +0 -0
  33. {render_lab_tasks_github-0.1.0.dist-info → render_lab_tasks_github-0.1.1.dist-info}/licenses/LICENSE +0 -0
@@ -1,5 +1,6 @@
1
1
  """The injected GitHub interface and its async REST adapter."""
2
2
 
3
+ import base64
3
4
  import os
4
5
  import re
5
6
  from collections.abc import AsyncIterator, Mapping
@@ -9,7 +10,9 @@ from typing import Any, Protocol
9
10
  from urllib.parse import quote
10
11
 
11
12
  import httpx
13
+ from render_lab_tasks_core.http import ApiError, HttpClient, enc, js_string, nullish, pick, query
12
14
 
15
+ from . import types as t
13
16
  from .types import IssueDTO
14
17
 
15
18
 
@@ -22,6 +25,41 @@ class GitHubPort(Protocol):
22
25
  self, owner: str, repo: str, issue_number: int, labels: list[str]
23
26
  ) -> None: ...
24
27
 
28
+ async def comment_on_issue(self, input: t.CommentOnIssueInput) -> t.CommentResult: ...
29
+ async def commit_file(self, input: t.CommitFileInput) -> t.CommitFileResult: ...
30
+ async def commit_files(self, input: t.CommitFilesInput) -> t.CommitFilesResult: ...
31
+ async def create_branch(self, input: t.CreateBranchInput) -> t.CreateBranchResult: ...
32
+ async def create_issue(self, input: t.CreateIssueInput) -> t.IssueDTO: ...
33
+ async def delete_branch(self, input: t.DeleteBranchInput) -> t.DeleteBranchResult: ...
34
+ async def delete_repository(
35
+ self, input: t.DeleteRepositoryInput
36
+ ) -> t.DeleteRepositoryResult: ...
37
+ async def dispatch_workflow(self, input: t.DispatchWorkflowInput) -> t.DispatchResult: ...
38
+ async def ensure_organization_repository(
39
+ self, input: t.EnsureOrganizationRepositoryInput
40
+ ) -> t.EnsureOrganizationRepositoryResult: ...
41
+ async def get_branch(self, input: t.GetBranchInput) -> t.GetBranchResult: ...
42
+ async def get_file_contents(self, input: t.GetFileContentsInput) -> t.FileContentsDTO: ...
43
+ async def get_issue(self, input: t.GetIssueInput) -> t.IssueDTO: ...
44
+ async def get_pr(self, input: t.GetPRInput) -> t.PullRequestDetailDTO: ...
45
+ async def get_repository(self, input: t.GetRepositoryInput) -> t.GetRepositoryResult: ...
46
+ async def list_organization_repositories(
47
+ self, input: t.ListOrganizationRepositoriesInput
48
+ ) -> t.ListOrganizationRepositoriesResult: ...
49
+ async def list_prs(self, input: t.ListPRsInput) -> list[t.PullRequestDTO]: ...
50
+ async def list_tree(self, input: t.ListTreeInput) -> t.ListTreeResult: ...
51
+ async def merge_when_green(self, input: t.MergeWhenGreenInput) -> t.MergeResult: ...
52
+ async def open_pr(self, input: t.OpenPRInput) -> t.PullRequestDTO: ...
53
+ async def review_pr(self, input: t.ReviewPRInput) -> t.ReviewResult: ...
54
+ async def search_code(self, input: t.SearchCodeInput) -> list[t.CodeHitDTO]: ...
55
+ async def search_repositories(
56
+ self, input: t.SearchRepositoriesInput
57
+ ) -> list[t.RepositoryDTO]: ...
58
+ async def update_issue(self, input: t.UpdateIssueInput) -> t.IssueDTO: ...
59
+ async def update_repository(
60
+ self, input: t.UpdateRepositoryInput
61
+ ) -> t.UpdateRepositoryResult: ...
62
+
25
63
 
26
64
  @dataclass(frozen=True)
27
65
  class GitHubDeps:
@@ -48,12 +86,103 @@ def to_issue_dto(raw: dict[str, Any]) -> IssueDTO:
48
86
  }
49
87
 
50
88
 
89
+ def repo_path(owner: str, repo: str) -> str:
90
+ return "/repos/" + enc(owner) + "/" + enc(repo)
91
+
92
+
93
+ def combined_path(repo: str) -> str:
94
+ return repo_path(*parse_repo(repo))
95
+
96
+
97
+ def pull(raw: Any, *, listed: bool = False) -> t.PullRequestDTO:
98
+ return {
99
+ "number": raw["number"],
100
+ "title": raw["title"],
101
+ "url": raw["html_url"],
102
+ "state": raw["state"],
103
+ "merged": raw.get("merged_at") is not None if listed else nullish(raw.get("merged"), False),
104
+ "mergedAt": raw.get("merged_at"),
105
+ "author": (raw.get("user") or {}).get("login"),
106
+ "head": raw["head"]["ref"],
107
+ "base": raw["base"]["ref"],
108
+ }
109
+
110
+
111
+ def repository(raw: Any) -> t.RepositoryDTO:
112
+ return {
113
+ "id": raw["id"],
114
+ "nodeId": nullish(raw.get("node_id"), ""),
115
+ "owner": nullish((raw.get("owner") or {}).get("login"), raw["full_name"].split("/")[0]),
116
+ "name": raw["name"],
117
+ "fullName": raw["full_name"],
118
+ "htmlUrl": raw["html_url"],
119
+ "cloneUrl": nullish(raw.get("clone_url"), ""),
120
+ "sshUrl": nullish(raw.get("ssh_url"), ""),
121
+ "defaultBranch": nullish(raw.get("default_branch"), ""),
122
+ "visibility": nullish(raw.get("visibility"), "private" if raw.get("private") else "public"),
123
+ "isTemplate": nullish(raw.get("is_template"), False),
124
+ "archived": nullish(raw.get("archived"), False),
125
+ "disabled": nullish(raw.get("disabled"), False),
126
+ "createdAt": nullish(raw.get("created_at"), ""),
127
+ "updatedAt": nullish(raw.get("updated_at"), ""),
128
+ "pushedAt": raw.get("pushed_at"),
129
+ "stars": nullish(raw.get("stargazers_count"), 0),
130
+ "forks": nullish(raw.get("forks_count"), 0),
131
+ "isFork": nullish(raw.get("fork"), False),
132
+ "language": raw.get("language"),
133
+ "topics": nullish(raw.get("topics"), []),
134
+ "openIssues": nullish(raw.get("open_issues_count"), 0),
135
+ }
136
+
137
+
138
+ def repo_body(input: Mapping[str, Any], create: bool = False) -> dict[str, Any]:
139
+ fields = {
140
+ "name": "name",
141
+ "description": "description",
142
+ "homepage": "homepage",
143
+ "visibility": "visibility",
144
+ "hasIssues": "has_issues",
145
+ "hasProjects": "has_projects",
146
+ "hasWiki": "has_wiki",
147
+ "hasDiscussions": "has_discussions",
148
+ "isTemplate": "is_template",
149
+ }
150
+ fields.update(
151
+ {
152
+ "autoInit": "auto_init",
153
+ "gitignoreTemplate": "gitignore_template",
154
+ "licenseTemplate": "license_template",
155
+ }
156
+ if create
157
+ else {"defaultBranch": "default_branch", "archived": "archived"}
158
+ )
159
+ return {dst: input[src] for src, dst in fields.items() if src in input}
160
+
161
+
162
+ def compatible(existing: t.RepositoryDTO, input: t.EnsureOrganizationRepositoryInput) -> None:
163
+ problems = [
164
+ f"{key} is {js_string(existing.get(key))}"
165
+ for key in ("visibility", "isTemplate")
166
+ if key in input and existing.get(key) != input.get(key)
167
+ ]
168
+ if problems:
169
+ raise ValueError(
170
+ f"Existing repository {existing['fullName']} is incompatible: {', '.join(problems)}."
171
+ )
172
+
173
+
51
174
  class GitHubClient:
52
175
  """Caller owns the injected HTTP client; construction reads no credentials."""
53
176
 
54
177
  def __init__(self, http: httpx.AsyncClient, env: Mapping[str, str] | None = None) -> None:
55
178
  self.http = http
56
179
  self.env = os.environ if env is None else env
180
+ self.api = HttpClient(
181
+ http,
182
+ "https://api.github.com",
183
+ auth=lambda: {**self._headers(), "Content-Type": "application/json; charset=utf-8"},
184
+ label="GitHub API",
185
+ )
57
186
 
58
187
  def _headers(self) -> dict[str, str]:
59
188
  headers = {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28"}
@@ -106,6 +235,448 @@ class GitHubClient:
106
235
  )
107
236
  response.raise_for_status()
108
237
 
238
+ async def open_pr(self, input: t.OpenPRInput) -> t.PullRequestDTO:
239
+ raw = await self.api.call(
240
+ combined_path(input["repo"]) + "/pulls",
241
+ method="POST",
242
+ body=pick(input, "title", "head", "base", "body", "draft"),
243
+ )
244
+ return pull(raw)
245
+
246
+ async def review_pr(self, input: t.ReviewPRInput) -> t.ReviewResult:
247
+ body: dict[str, Any] = {"event": input["event"]}
248
+ if input.get("body") is not None:
249
+ body["body"] = input["body"]
250
+ if input.get("comments"):
251
+ body["comments"] = input["comments"]
252
+ raw = await self.api.call(
253
+ combined_path(input["repo"]) + "/pulls/" + enc(input["number"]) + "/reviews",
254
+ method="POST",
255
+ body=body,
256
+ )
257
+ return {"number": input["number"], "reviewId": raw["id"], "event": input["event"]}
258
+
259
+ async def merge_when_green(self, input: t.MergeWhenGreenInput) -> t.MergeResult:
260
+ path = combined_path(input["repo"])
261
+ number = input["number"]
262
+ pr = await self.api.call(path + "/pulls/" + enc(number))
263
+ ref = enc(pr["head"]["sha"])
264
+ checks = await self.api.call(path + "/commits/" + ref + "/check-runs?per_page=100")
265
+ status = await self.api.call(path + "/commits/" + ref + "/status")
266
+ pending = any(run["status"] != "completed" for run in checks["check_runs"])
267
+ failing = any(
268
+ run.get("conclusion") in ("failure", "timed_out", "cancelled", "action_required")
269
+ for run in checks["check_runs"]
270
+ )
271
+ state = "pending" if pending else "failing" if failing else "green"
272
+ if state == "green" and status["total_count"] > 0:
273
+ state = (
274
+ "failing"
275
+ if status["state"] in ("failure", "error")
276
+ else "pending"
277
+ if status["state"] == "pending"
278
+ else "green"
279
+ )
280
+ if state != "green":
281
+ raise RuntimeError(f"PR #{js_string(number)} checks {state}")
282
+ raw = await self.api.call(
283
+ path + "/pulls/" + enc(number) + "/merge",
284
+ method="PUT",
285
+ body={"merge_method": nullish(input.get("method"), "merge")},
286
+ )
287
+ result: t.MergeResult = {
288
+ "number": number,
289
+ "merged": raw["merged"],
290
+ "state": "closed" if raw["merged"] else "open",
291
+ }
292
+ if raw.get("sha"):
293
+ result["sha"] = raw["sha"]
294
+ return result
295
+
296
+ async def dispatch_workflow(self, input: t.DispatchWorkflowInput) -> t.DispatchResult:
297
+ await self.api.call(
298
+ combined_path(input["repo"])
299
+ + "/actions/workflows/"
300
+ + enc(input["workflowId"])
301
+ + "/dispatches",
302
+ method="POST",
303
+ body=pick(input, "ref", "inputs"),
304
+ )
305
+ return {"workflowId": input["workflowId"], "ref": input["ref"], "dispatched": True}
306
+
307
+ async def _search(self, kind: str, value: str, limit: float) -> list[Any]:
308
+ try:
309
+ raw = await self.api.call(
310
+ "/search/"
311
+ + kind
312
+ + "?"
313
+ + query(
314
+ {
315
+ "q": value,
316
+ "per_page": limit,
317
+ **({"sort": "stars"} if kind == "repositories" else {}),
318
+ }
319
+ )
320
+ )
321
+ return list(raw["items"][: int(limit)])
322
+ except ApiError as error:
323
+ if error.status == 401 or "requires authentication" in str(error).lower():
324
+ raise ValueError(
325
+ "GitHub search requires GITHUB_TOKEN (code and repository "
326
+ "search are authenticated endpoints)"
327
+ ) from None
328
+ raise
329
+
330
+ async def search_code(self, input: t.SearchCodeInput) -> list[t.CodeHitDTO]:
331
+ rows = await self._search("code", input["query"], nullish(input.get("limit"), 30))
332
+ return [
333
+ {"repo": r["repository"]["full_name"], "path": r["path"], "url": r["html_url"]}
334
+ for r in rows
335
+ ]
336
+
337
+ async def search_repositories(self, input: t.SearchRepositoriesInput) -> list[t.RepositoryDTO]:
338
+ rows = await self._search("repositories", input["query"], nullish(input.get("limit"), 30))
339
+ return [repository(r) for r in rows]
340
+
341
+ async def create_issue(self, input: t.CreateIssueInput) -> t.IssueDTO:
342
+ return to_issue_dto(
343
+ await self.api.call(
344
+ combined_path(input["repo"]) + "/issues",
345
+ method="POST",
346
+ body=pick(input, "title", "body", "labels", "assignees"),
347
+ )
348
+ )
349
+
350
+ async def get_issue(self, input: t.GetIssueInput) -> t.IssueDTO:
351
+ return to_issue_dto(
352
+ await self.api.call(combined_path(input["repo"]) + "/issues/" + enc(input["number"]))
353
+ )
354
+
355
+ async def comment_on_issue(self, input: t.CommentOnIssueInput) -> t.CommentResult:
356
+ raw = await self.api.call(
357
+ combined_path(input["repo"]) + "/issues/" + enc(input["number"]) + "/comments",
358
+ method="POST",
359
+ body={"body": input["body"]},
360
+ )
361
+ return {"id": raw["id"], "url": raw["html_url"]}
362
+
363
+ async def update_issue(self, input: t.UpdateIssueInput) -> t.IssueDTO:
364
+ return to_issue_dto(
365
+ await self.api.call(
366
+ combined_path(input["repo"]) + "/issues/" + enc(input["number"]),
367
+ method="PATCH",
368
+ body={
369
+ k: v
370
+ for k, v in pick(input, "state", "body", "assignees", "labels").items()
371
+ if v is not None
372
+ },
373
+ )
374
+ )
375
+
376
+ async def get_pr(self, input: t.GetPRInput) -> t.PullRequestDetailDTO:
377
+ raw = await self.api.call(combined_path(input["repo"]) + "/pulls/" + enc(input["number"]))
378
+ return {
379
+ **pull(raw),
380
+ "mergeable": raw.get("mergeable"),
381
+ "draft": nullish(raw.get("draft"), False),
382
+ "mergedBy": (raw.get("merged_by") or {}).get("login"),
383
+ "additions": nullish(raw.get("additions"), 0),
384
+ "deletions": nullish(raw.get("deletions"), 0),
385
+ "comments": nullish(raw.get("comments"), 0),
386
+ }
387
+
388
+ async def get_file_contents(self, input: t.GetFileContentsInput) -> t.FileContentsDTO:
389
+ raw = await self.api.call(
390
+ combined_path(input["repo"])
391
+ + "/contents/"
392
+ + quote(input["path"], safe="/")
393
+ + ("?" + query({"ref": input["ref"]}) if input.get("ref") else "")
394
+ )
395
+ if isinstance(raw, list) or raw.get("type") != "file":
396
+ raise ValueError(
397
+ f'"{input["path"]}" is not a file (got '
398
+ f'"{"directory" if isinstance(raw, list) else raw.get("type")}").'
399
+ )
400
+ content = (
401
+ base64.b64decode(raw["content"]).decode("utf-8", errors="replace")
402
+ if raw["encoding"] == "base64"
403
+ else raw["content"]
404
+ )
405
+ return {"path": raw["path"], "content": content, "sha": raw["sha"], "encoding": "utf-8"}
406
+
407
+ async def commit_file(self, input: t.CommitFileInput) -> t.CommitFileResult:
408
+ path = combined_path(input["repo"]) + "/contents/" + quote(input["path"], safe="/")
409
+ sha = input.get("sha")
410
+ if sha is None:
411
+ try:
412
+ current = await self.api.call(
413
+ path + ("?" + query({"ref": input["branch"]}) if input.get("branch") else "")
414
+ )
415
+ if isinstance(current, dict):
416
+ sha = current.get("sha")
417
+ except ApiError as error:
418
+ if error.status != 404:
419
+ raise
420
+ body = {
421
+ "message": input["message"],
422
+ "content": base64.b64encode(input["content"].encode()).decode(),
423
+ }
424
+ if input.get("branch"):
425
+ body["branch"] = input["branch"]
426
+ if sha:
427
+ body["sha"] = sha
428
+ raw = await self.api.call(path, method="PUT", body=body)
429
+ return {
430
+ "commitSha": nullish(raw["commit"].get("sha"), ""),
431
+ "contentSha": nullish((raw.get("content") or {}).get("sha"), ""),
432
+ "path": input["path"],
433
+ }
434
+
435
+ async def get_repository(self, input: t.GetRepositoryInput) -> t.GetRepositoryResult:
436
+ return {
437
+ "repository": repository(await self.api.call(repo_path(input["owner"], input["repo"])))
438
+ }
439
+
440
+ async def update_repository(self, input: t.UpdateRepositoryInput) -> t.UpdateRepositoryResult:
441
+ return {
442
+ "repository": repository(
443
+ await self.api.call(
444
+ repo_path(input["owner"], input["repo"]), method="PATCH", body=repo_body(input)
445
+ )
446
+ )
447
+ }
448
+
449
+ async def ensure_organization_repository(
450
+ self, input: t.EnsureOrganizationRepositoryInput
451
+ ) -> t.EnsureOrganizationRepositoryResult:
452
+ async def existing() -> t.RepositoryDTO:
453
+ result = repository(await self.api.call(repo_path(input["org"], input["name"])))
454
+ compatible(result, input)
455
+ return result
456
+
457
+ try:
458
+ return {"repository": await existing(), "created": False}
459
+ except ApiError as error:
460
+ if error.status != 404:
461
+ raise
462
+ try:
463
+ result = repository(
464
+ await self.api.call(
465
+ "/orgs/" + enc(input["org"]) + "/repos",
466
+ method="POST",
467
+ body=repo_body(input, True),
468
+ )
469
+ )
470
+ return {"repository": result, "created": True}
471
+ except Exception as error:
472
+ try:
473
+ return {"repository": await existing(), "created": True}
474
+ except Exception:
475
+ raise error from None
476
+
477
+ async def delete_repository(self, input: t.DeleteRepositoryInput) -> t.DeleteRepositoryResult:
478
+ missing = False
479
+ try:
480
+ await self.api.call(repo_path(input["owner"], input["repo"]), method="DELETE")
481
+ except ApiError as error:
482
+ if error.status != 404:
483
+ raise
484
+ missing = True
485
+ return {
486
+ "owner": input["owner"],
487
+ "repo": input["repo"],
488
+ "deleted": True,
489
+ "alreadyMissing": missing,
490
+ }
491
+
492
+ async def list_organization_repositories(
493
+ self, input: t.ListOrganizationRepositoriesInput
494
+ ) -> t.ListOrganizationRepositoriesResult:
495
+ size = nullish(input.get("pageSize"), 100)
496
+ limit = nullish(input.get("limit"), 100)
497
+ page = nullish(input.get("startPage"), 1)
498
+ if size <= 0:
499
+ raise ValueError("pageSize must be positive")
500
+ repositories: list[t.RepositoryDTO] = []
501
+ while len(repositories) < limit:
502
+ raw = await self.api.call(
503
+ "/orgs/"
504
+ + enc(input["org"])
505
+ + "/repos?"
506
+ + query(
507
+ {
508
+ "type": nullish(input.get("type"), "all"),
509
+ **pick(input, "sort", "direction"),
510
+ "per_page": size,
511
+ "page": page,
512
+ }
513
+ )
514
+ )
515
+ for row in raw:
516
+ dto = repository(row)
517
+ if input.get("namePrefix") and not dto["name"].startswith(input["namePrefix"]):
518
+ continue
519
+ repositories.append(dto)
520
+ if len(repositories) >= limit:
521
+ break
522
+ if len(raw) < size:
523
+ return {"repositories": repositories, "nextPage": None}
524
+ page += 1
525
+ return {"repositories": repositories, "nextPage": page}
526
+
527
+ async def get_branch(self, input: t.GetBranchInput) -> t.GetBranchResult:
528
+ raw = await self.api.call(
529
+ repo_path(input["owner"], input["repo"]) + "/branches/" + enc(input["branch"])
530
+ )
531
+ return {
532
+ "branch": {
533
+ "name": raw["name"],
534
+ "commitSha": raw["commit"]["sha"],
535
+ "protected": nullish(raw.get("protected"), False),
536
+ }
537
+ }
538
+
539
+ async def _ref(self, path: str, branch: str) -> tuple[str, str]:
540
+ ref = await self.api.call(path + "/git/ref/heads/" + quote(branch, safe="/"))
541
+ commit = await self.api.call(path + "/git/commits/" + enc(ref["object"]["sha"]))
542
+ return ref["object"]["sha"], commit["tree"]["sha"]
543
+
544
+ async def create_branch(self, input: t.CreateBranchInput) -> t.CreateBranchResult:
545
+ path = repo_path(input["owner"], input["repo"])
546
+ source = input.get("from")
547
+ if source is None:
548
+ source = (await self.api.call(path))["default_branch"]
549
+ sha, _ = await self._ref(path, source)
550
+ try:
551
+ await self.api.call(
552
+ path + "/git/refs",
553
+ method="POST",
554
+ body={"ref": "refs/heads/" + input["branch"], "sha": sha},
555
+ )
556
+ return {"branch": input["branch"], "sha": sha, "created": True}
557
+ except ApiError as error:
558
+ if error.status != 422 or "already exists" not in str(error).lower():
559
+ raise
560
+ existing, _ = await self._ref(path, input["branch"])
561
+ return {"branch": input["branch"], "sha": existing, "created": False}
562
+
563
+ async def delete_branch(self, input: t.DeleteBranchInput) -> t.DeleteBranchResult:
564
+ missing = False
565
+ try:
566
+ await self.api.call(
567
+ repo_path(input["owner"], input["repo"])
568
+ + "/git/refs/heads/"
569
+ + quote(input["branch"], safe="/"),
570
+ method="DELETE",
571
+ )
572
+ except ApiError as error:
573
+ if error.status != 404 and not (
574
+ error.status == 422 and "does not exist" in str(error).lower()
575
+ ):
576
+ raise
577
+ missing = True
578
+ return {"branch": input["branch"], "deleted": True, "alreadyMissing": missing}
579
+
580
+ async def list_prs(self, input: t.ListPRsInput) -> list[t.PullRequestDTO]:
581
+ owner, repo = parse_repo(input["repo"])
582
+ params = {
583
+ "state": nullish(input.get("state"), "open"),
584
+ "per_page": nullish(input.get("limit"), 30),
585
+ }
586
+ if input.get("head"):
587
+ params["head"] = owner + ":" + input["head"]
588
+ if input.get("base"):
589
+ params["base"] = input["base"]
590
+ return [
591
+ pull(row, listed=True)
592
+ for row in await self.api.call(repo_path(owner, repo) + "/pulls?" + query(params))
593
+ ]
594
+
595
+ async def list_tree(self, input: t.ListTreeInput) -> t.ListTreeResult:
596
+ path = combined_path(input["repo"])
597
+ ref = input.get("ref")
598
+ if ref is None:
599
+ ref = (await self.api.call(path))["default_branch"]
600
+ raw = await self.api.call(
601
+ path
602
+ + "/git/trees/"
603
+ + enc(ref)
604
+ + ("?recursive=1" if nullish(input.get("recursive"), True) else "")
605
+ )
606
+ return {
607
+ "paths": [e["path"] for e in raw["tree"] if e.get("type") == "blob" and e.get("path")],
608
+ "truncated": nullish(raw.get("truncated"), False),
609
+ }
610
+
611
+ async def commit_files(self, input: t.CommitFilesInput) -> t.CommitFilesResult:
612
+ files = input["files"]
613
+ if not files:
614
+ raise ValueError("github.commitFiles requires at least one file.")
615
+ seen: set[str] = set()
616
+ total = 0
617
+ for file in files:
618
+ name = file["path"]
619
+ if not name or name.startswith("/") or ".." in name.split("/"):
620
+ raise ValueError(f'Invalid repository path "{name}".')
621
+ if name in seen:
622
+ raise ValueError(f'Duplicate file path "{name}".')
623
+ seen.add(name)
624
+ total += (
625
+ len(base64.b64decode(file["content"]))
626
+ if file.get("encoding") == "base64"
627
+ else len(file["content"].encode())
628
+ )
629
+ if total > 3500000:
630
+ raise ValueError(
631
+ f"github.commitFiles payload is {total} bytes, above the maxBytes "
632
+ f"limit of 3500000. Narrow the request or write it to an external "
633
+ f"destination and return a reference."
634
+ )
635
+ path = repo_path(input["owner"], input["repo"])
636
+ head, base_tree = await self._ref(path, input["branch"])
637
+ if "expectedHeadSha" in input and input["expectedHeadSha"] != head:
638
+ raise ValueError(
639
+ f"github.commitFiles expected head {input['expectedHeadSha']}, but "
640
+ f"branch {input['branch']} is at {head}."
641
+ )
642
+ tree = []
643
+ for file in files:
644
+ blob = await self.api.call(
645
+ path + "/git/blobs",
646
+ method="POST",
647
+ body={
648
+ "content": file["content"],
649
+ "encoding": "base64" if file.get("encoding") == "base64" else "utf-8",
650
+ },
651
+ )
652
+ tree.append(
653
+ {
654
+ "path": file["path"],
655
+ "mode": nullish(file.get("mode"), "100644"),
656
+ "type": "blob",
657
+ "sha": blob["sha"],
658
+ }
659
+ )
660
+ new_tree = await self.api.call(
661
+ path + "/git/trees", method="POST", body={"base_tree": base_tree, "tree": tree}
662
+ )
663
+ commit = await self.api.call(
664
+ path + "/git/commits",
665
+ method="POST",
666
+ body={"message": input["message"], "tree": new_tree["sha"], "parents": [head]},
667
+ )
668
+ await self.api.call(
669
+ path + "/git/refs/heads/" + quote(input["branch"], safe="/"),
670
+ method="PATCH",
671
+ body={"sha": commit["sha"]},
672
+ )
673
+ return {
674
+ "commitSha": commit["sha"],
675
+ "treeSha": new_tree["sha"],
676
+ "branch": input["branch"],
677
+ "fileCount": len(files),
678
+ }
679
+
109
680
 
110
681
  @asynccontextmanager
111
682
  async def github_dependencies(deps: GitHubDeps | None) -> AsyncIterator[GitHubDeps]:
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import GitHubDeps, github_dependencies
5
+ from .retry import GITHUB_RETRY
6
+ from .types import CommentOnIssueInput, CommentResult
7
+
8
+
9
+ async def comment_on_issue_impl(
10
+ ctx: TaskContext, input: CommentOnIssueInput, *, deps: GitHubDeps | None = None
11
+ ) -> CommentResult:
12
+ async with github_dependencies(deps) as resolved:
13
+ return await resolved.github.comment_on_issue(input)
14
+
15
+
16
+ @app.task(name="github.commentOnIssue", retry=GITHUB_RETRY)
17
+ async def comment_on_issue(ctx: TaskContext, input: CommentOnIssueInput) -> CommentResult:
18
+ return await comment_on_issue_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import GitHubDeps, github_dependencies
5
+ from .retry import GITHUB_RETRY
6
+ from .types import CommitFileInput, CommitFileResult
7
+
8
+
9
+ async def commit_file_impl(
10
+ ctx: TaskContext, input: CommitFileInput, *, deps: GitHubDeps | None = None
11
+ ) -> CommitFileResult:
12
+ async with github_dependencies(deps) as resolved:
13
+ return await resolved.github.commit_file(input)
14
+
15
+
16
+ @app.task(name="github.commitFile", retry=GITHUB_RETRY)
17
+ async def commit_file(ctx: TaskContext, input: CommitFileInput) -> CommitFileResult:
18
+ return await commit_file_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import GitHubDeps, github_dependencies
5
+ from .retry import GITHUB_RETRY
6
+ from .types import CommitFilesInput, CommitFilesResult
7
+
8
+
9
+ async def commit_files_impl(
10
+ ctx: TaskContext, input: CommitFilesInput, *, deps: GitHubDeps | None = None
11
+ ) -> CommitFilesResult:
12
+ async with github_dependencies(deps) as resolved:
13
+ return await resolved.github.commit_files(input)
14
+
15
+
16
+ @app.task(name="github.commitFiles", retry=GITHUB_RETRY)
17
+ async def commit_files(ctx: TaskContext, input: CommitFilesInput) -> CommitFilesResult:
18
+ return await commit_files_impl(ctx, input)