Repository navigation
Expand file tree
/
Copy pathgithub_cli.py
More file actions
1034 lines (931 loc) · 36.1 KB
/
Copy pathgithub_cli.py
File metadata and controls
1034 lines (931 loc) · 36.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
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
from __future__ import annotations
import json
import os
import subprocess
import time
from fnmatch import fnmatchcase
from typing import Any, Callable, TypeVar
from urllib.parse import quote, urlparse
GH_RETRY_ATTEMPTS = 4
GH_RETRY_DELAY_SECONDS = 1.5
DEFAULT_OWNER = "open-telemetry"
COPILOT_REVIEWER_BOT_ID = "BOT_kgDOCnlnWA"
CODE_SCANNING_APP_ID = 57789 # github-advanced-security
GITHUB_ACTIONS_APP_ID = 15368
REQUEST_COPILOT_REVIEW_MUTATION = """
mutation($pullRequestId: ID!, $botId: ID!) {
requestReviews(input: {
pullRequestId: $pullRequestId
botIds: [$botId]
union: true
}) {
pullRequest {
id
}
}
}
"""
def normalize_repo(repo: str) -> str:
return repo if "/" in repo else f"{DEFAULT_OWNER}/{repo}"
def repo_state_key(repo: str) -> str:
return normalize_repo(repo).split("/", 1)[1]
class TransientGhError(RuntimeError):
pass
class GhNotFoundError(RuntimeError):
pass
_RETRYABLE_GH_ERROR_FRAGMENTS = (
"http 499",
"http 5",
"gateway timeout",
"graphql: something went wrong while executing your query",
"timeout",
"temporarily unavailable",
"connection reset",
"connection refused",
"error connecting to api.github.com",
"x509: certificate is not valid for any names, but wanted to match api.github.com",
)
def is_retryable_gh_error(stderr: str) -> bool:
text = stderr.lower()
return any(fragment in text for fragment in _RETRYABLE_GH_ERROR_FRAGMENTS)
def sleep_for_retry(attempt: int) -> None:
time.sleep(GH_RETRY_DELAY_SECONDS * (attempt + 1))
_T = TypeVar("_T")
def _run_gh(
cmd: list[str],
token: str | None,
input_text: str | None,
allowed_exit_codes: frozenset[int] | set[int],
parse_stdout: Callable[[str], _T],
) -> _T:
env = {**os.environ, "GH_TOKEN": token} if token else None
last_stderr = ""
for attempt in range(GH_RETRY_ATTEMPTS):
proc = subprocess.run(
cmd,
input=input_text,
capture_output=True,
text=True,
check=False,
encoding="utf-8",
errors="replace",
env=env,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
)
if proc.returncode in allowed_exit_codes:
try:
return parse_stdout(proc.stdout)
except json.JSONDecodeError as error:
if attempt == GH_RETRY_ATTEMPTS - 1:
message = (
f"{' '.join(cmd)} returned invalid JSON after "
f"{GH_RETRY_ATTEMPTS} attempts: {error}"
)
raise TransientGhError(message) from error
sleep_for_retry(attempt)
continue
last_stderr = proc.stderr.strip()
if attempt == GH_RETRY_ATTEMPTS - 1 or not is_retryable_gh_error(last_stderr):
break
sleep_for_retry(attempt)
message = f"{' '.join(cmd)} failed: {last_stderr}"
if is_retryable_gh_error(last_stderr):
raise TransientGhError(message)
if last_stderr.strip().lower() == "gh: not found (http 404)":
raise GhNotFoundError(message)
raise RuntimeError(message)
def run_gh(
cmd: list[str],
token: str | None = None,
input_text: str | None = None,
allowed_exit_codes: frozenset[int] | set[int] = frozenset({0}),
) -> str:
return _run_gh(cmd, token, input_text, allowed_exit_codes, lambda stdout: stdout)
def run_gh_json(cmd: list[str], token: str | None = None, input_text: str | None = None) -> Any:
return _run_gh(
cmd,
token,
input_text,
frozenset({0}),
lambda stdout: json.loads(stdout or "null"),
)
def gh_api(path: str, paginate: bool = False, token: str | None = None) -> Any:
cmd = ["gh", "api", "-H", "Accept: application/vnd.github+json"]
if paginate:
cmd += ["--paginate", "--slurp"]
cmd.append(path)
data = run_gh_json(cmd, token=token)
if paginate and isinstance(data, list):
flat: list[Any] = []
for page in data:
if isinstance(page, list):
flat.extend(page)
else:
flat.append(page)
return flat
return data
def request_copilot_review(pull_request_id: str, token: str | None = None) -> None:
# Success here only means GitHub accepted the mutation. It does not mean
# GitHub recorded the reviewer, so callers have to read the pull request
# back to find out whether the request landed.
gh_graphql(
REQUEST_COPILOT_REVIEW_MUTATION,
{
"pullRequestId": pull_request_id,
"botId": COPILOT_REVIEWER_BOT_ID,
},
token=token,
)
def gh_graphql(query: str, fields: dict[str, Any], token: str | None = None) -> dict[str, Any]:
cmd = ["gh", "api", "graphql", "-f", f"query={query}"]
for name, value in fields.items():
if value is None:
continue
cmd.extend(["-F", f"{name}={value}"])
return run_gh_json(cmd, token=token)
def gh_pr_view(repo: str, number: int) -> dict[str, Any]:
fields = ",".join([
"id", "number", "title", "body", "url", "author", "state", "isDraft",
"mergeable", "mergeStateStatus", "createdAt", "updatedAt", "headRefOid",
"headRefName", "headRepository", "reviewDecision", "assignees", "baseRefName",
"labels",
])
cmd = ["gh", "pr", "view", str(number), "--repo", repo, "--json", fields]
last: dict[str, Any] = {}
for attempt in range(GH_RETRY_ATTEMPTS):
last = run_gh_json(cmd) or {}
if last.get("mergeable") not in (None, "", "UNKNOWN"):
return last
if attempt < GH_RETRY_ATTEMPTS - 1:
sleep_for_retry(attempt)
return last
PR_REVIEWS_QUERY = """
query($owner: String!, $name: String!, $number: Int!, $after: String) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
reviews(first: 100, after: $after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
fullDatabaseId
commit {
oid
}
comments {
totalCount
}
url
body
state
submittedAt
updatedAt
lastEditedAt
author {
login
}
}
}
}
}
}
"""
PR_ISSUE_COMMENTS_QUERY = """
query($owner: String!, $name: String!, $number: Int!, $after: String) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
comments(first: 100, after: $after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
fullDatabaseId
url
body
author {
__typename
login
}
createdAt
lastEditedAt
isMinimized
}
}
}
}
}
"""
def fetch_pr_issue_comments(
owner: str,
repo_name: str,
number: int,
) -> list[dict[str, Any]]:
comments: list[dict[str, Any]] = []
after: str | None = None
while True:
data = gh_graphql(
PR_ISSUE_COMMENTS_QUERY,
{"owner": owner, "name": repo_name, "number": number, "after": after},
)
pull_request = (((data.get("data") or {}).get("repository") or {}).get("pullRequest") or {})
connection = pull_request.get("comments") or {}
for comment in connection.get("nodes") or []:
try:
database_id = int(comment.get("fullDatabaseId"))
except (TypeError, ValueError):
continue
created_at = comment.get("createdAt") or ""
content_updated_at = comment.get("lastEditedAt") or created_at
author = comment.get("author") or {}
author_login = author.get("login") or ""
if author.get("__typename") == "Bot" and not author_login.endswith("[bot]"):
author_login = f"{author_login}[bot]"
comments.append({
"id": database_id,
"html_url": comment.get("url") or "",
"created_at": created_at,
"updated_at": content_updated_at,
"content_updated_at": content_updated_at,
"minimized": bool(comment.get("isMinimized")),
"user": {"login": author_login} if author_login else {},
"body": comment.get("body") or "",
})
page_info = connection.get("pageInfo") or {}
if not page_info.get("hasNextPage"):
return comments
after = page_info.get("endCursor") or None
if after is None:
raise TransientGhError(
"issue-comment pagination hasNextPage without endCursor"
)
def fetch_pr_reviews(owner: str, repo_name: str, number: int) -> list[dict[str, Any]]:
reviews: list[dict[str, Any]] = []
after: str | None = None
while True:
data = gh_graphql(
PR_REVIEWS_QUERY,
{"owner": owner, "name": repo_name, "number": number, "after": after},
)
pull_request = (((data.get("data") or {}).get("repository") or {}).get("pullRequest") or {})
connection = pull_request.get("reviews") or {}
for review in connection.get("nodes") or []:
# The numeric database id is the stable `source_id` used downstream
# to build discussion ids and exclusion keys, all of which require an
# int. `fullDatabaseId` is only null for unsubmitted PENDING reviews,
# which the API never returns for a token that is not their author,
# so a review without a usable id is dropped rather than given a
# synthetic id that would be filtered back out (or collide).
try:
database_id = int(review.get("fullDatabaseId"))
except (TypeError, ValueError):
continue
reviews.append({
"id": database_id,
"commit_id": ((review.get("commit") or {}).get("oid") or ""),
"finding_count": int(
(review.get("comments") or {}).get("totalCount") or 0
),
"url": review.get("url") or "",
"user": review.get("author") or {},
"state": review.get("state") or "",
"body": review.get("body") or "",
"submitted_at": review.get("submittedAt") or "",
"updated_at": review.get("updatedAt") or "",
"content_updated_at": (
review.get("lastEditedAt")
or review.get("submittedAt")
or ""
),
})
page_info = connection.get("pageInfo") or {}
if not page_info.get("hasNextPage"):
break
after = page_info.get("endCursor") or None
if after is None:
break
return reviews
PR_CHECKS_QUERY = """
query($id: ID!, $after: String) {
node(id: $id) {
... on PullRequest {
commits(last: 1) {
nodes {
commit {
oid
statusCheckRollup {
contexts(first: 100, after: $after) {
nodes {
__typename
... on StatusContext {
context
state
targetUrl
createdAt
description
isRequired(pullRequestId: $id)
}
... on CheckRun {
name
status
conclusion
startedAt
completedAt
detailsUrl
url
isRequired(pullRequestId: $id)
checkSuite {
app {
databaseId
}
workflowRun {
databaseId
workflow {
name
}
}
}
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
}
}
}
}
}
"""
def check_bucket(
state: str,
*,
integration_id: int | None = None,
workflow_run_id: int | None = None,
) -> str:
if state == "SUCCESS":
return "pass"
if state in ("SKIPPED", "NEUTRAL"):
return "skipping"
if state == "ACTION_REQUIRED":
if (
integration_id == GITHUB_ACTIONS_APP_ID
and workflow_run_id is not None
):
return "maintainer_action_required"
return "action_required"
if state in ("ERROR", "FAILURE", "TIMED_OUT", "STARTUP_FAILURE"):
return "fail"
if state == "CANCELLED":
return "cancel"
return "pending"
def normalize_check(node: dict[str, Any]) -> dict[str, Any]:
is_status = node.get("__typename") == "StatusContext"
suite = node.get("checkSuite") or {}
app = suite.get("app") or {}
workflow_run = suite.get("workflowRun") or {}
workflow = workflow_run.get("workflow") or {}
integration_id = None if is_status else app.get("databaseId")
workflow_run_id = None if is_status else workflow_run.get("databaseId")
state = (
node.get("state")
if is_status
else node.get("conclusion") or node.get("status")
) or ""
return {
"name": (node.get("context") if is_status else node.get("name")) or "",
"state": state,
"bucket": check_bucket(
state,
integration_id=integration_id,
workflow_run_id=workflow_run_id,
),
"workflow": workflow.get("name") or "",
"workflow_run_id": workflow_run_id,
"description": node.get("description") or "",
"link": (node.get("targetUrl") if is_status else node.get("detailsUrl")) or "",
"started_at": (node.get("createdAt") if is_status else node.get("startedAt")) or "",
"completed_at": (node.get("createdAt") if is_status else node.get("completedAt")) or "",
"check_run_id": None if is_status else check_run_id(node["url"]),
"integration_id": integration_id,
"status_context": is_status,
}
def check_run_id(url: str) -> int:
return int(urlparse(url).path.rstrip("/").rsplit("/", 1)[-1])
def check_attempt_order(check: dict[str, Any]) -> tuple[int, int | str]:
if check["status_context"]:
return 0, check["started_at"]
return 1, check["check_run_id"] or 0
def check_identity(check: dict[str, Any]) -> tuple[str, str, int | None]:
# Separate workflows can name a job identically, so the workflow keeps their
# checks apart while rerun attempts of one check still collapse.
return check["workflow"], check["name"], check["integration_id"]
def check_execution_identity(check: dict[str, Any]) -> tuple[int | None, str, int | None]:
# Two runs of one workflow can be in flight for the same commit, so a check
# that finished in one run must not hide the one still running in another.
return check["workflow_run_id"], check["name"], check["integration_id"]
def gh_pr_check_rollup(
repo: str,
pr_id: str,
non_blocking_check_patterns: list[str],
) -> dict[str, Any] | None:
del repo
checks_by_identity: dict[
tuple[str, str, int | None, bool], tuple[dict[str, Any], bool]
] = {}
latest_by_execution: dict[tuple[int | None, str, int | None], dict[str, Any]] = {}
code_scanning_executions: set[tuple[int | None, str, int | None]] = set()
after: str | None = None
head_oid = ""
try:
while True:
data = gh_graphql(PR_CHECKS_QUERY, {"id": pr_id, "after": after})
pull_request = (data.get("data") or {}).get("node") or {}
commits = pull_request.get("commits") or {}
commit_nodes = commits.get("nodes") or []
commit = (commit_nodes[0] if commit_nodes else {}).get("commit") or {}
page_oid = commit.get("oid") or ""
if head_oid and page_oid and page_oid != head_oid:
# The pages describe two different commits, so neither is whole.
return None
head_oid = page_oid or head_oid
rollup = commit.get("statusCheckRollup") or {}
contexts = rollup.get("contexts") or {}
for node in contexts.get("nodes") or []:
is_required = bool(node.get("isRequired"))
name = (node.get("context") or node.get("name") or "")
app = ((node.get("checkSuite") or {}).get("app") or {})
check = normalize_check(node)
identity = check_identity(check)
execution = check_execution_identity(check)
latest_attempt = latest_by_execution.get(execution)
if latest_attempt is None or check_attempt_order(
check
) >= check_attempt_order(latest_attempt):
latest_by_execution[execution] = check
if app.get("databaseId") == CODE_SCANNING_APP_ID:
code_scanning_executions.add(execution)
if not is_required and not any(
fnmatchcase(name, pattern)
for pattern in non_blocking_check_patterns
):
continue
required_identity = (*identity, is_required)
previous = checks_by_identity.get(required_identity)
if previous is None or check_attempt_order(check) >= check_attempt_order(previous[0]):
checks_by_identity[required_identity] = (check, is_required)
page_info = contexts.get("pageInfo") or {}
if not page_info.get("hasNextPage"):
break
after = page_info.get("endCursor") or None
if after is None:
break
except RuntimeError:
return None
checks = list(checks_by_identity.values())
return {
"head_oid": head_oid,
"required": [check for check, is_required in checks if is_required],
"non_blocking_failures": [
check
for check, is_required in checks
if not is_required
and check.get("bucket") in ("fail", "cancel")
],
"code_scanning": [
check
for execution, check in latest_by_execution.items()
if execution in code_scanning_executions
],
# Every check at the head, not just the required ones, because the
# optional job that uploads a code scanning analysis is what decides
# whether an undetermined result is final.
"pending": [
check
for check in latest_by_execution.values()
if check["bucket"] == "pending"
],
}
def gh_pr_checks(repo: str, pr_id: str) -> list[dict[str, Any]] | None:
rollup = gh_pr_check_rollup(repo, pr_id, [])
return None if rollup is None else rollup["required"]
def gh_branch_rules(repo: str, base_branch: str) -> list[dict[str, Any]] | None:
encoded_branch = quote(base_branch, safe="")
try:
rules = gh_api(
f"/repos/{repo}/rules/branches/{encoded_branch}?per_page=100",
paginate=True,
)
except RuntimeError:
return None
return list(rules or [])
def required_check_contexts(
rules: list[dict[str, Any]] | None,
) -> list[dict[str, Any]] | None:
if rules is None:
return None
contexts: list[dict[str, Any]] = []
for rule in rules:
if rule.get("type") != "required_status_checks":
continue
parameters = rule.get("parameters") or {}
for check in parameters.get("required_status_checks") or []:
context = check.get("context") or ""
requirement = {
"context": context,
"integration_id": check.get("integration_id"),
}
if context and requirement not in contexts:
contexts.append(requirement)
return contexts
def code_scanning_tools(rules: list[dict[str, Any]] | None) -> list[str]:
tools: list[str] = []
for rule in rules or []:
if rule.get("type") != "code_scanning":
continue
parameters = rule.get("parameters") or {}
for tool in parameters.get("code_scanning_tools") or []:
name = tool.get("tool") or ""
if name and name not in tools:
tools.append(name)
return tools
def required_code_scanning_checks(
code_scanning_checks: list[dict[str, Any]],
tools: list[str],
checks_still_running: bool,
) -> list[dict[str, Any]]:
# A code_scanning ruleset rule holds the merge on a check named after the
# tool, but GitHub never reports that check as required. NEUTRAL there means
# the alerts introduced by the PR could not be determined, which also holds
# the merge, so it cannot be treated as a skip. While other checks are still
# running that NEUTRAL is usually a placeholder for an analysis that has not
# been uploaded yet, and code scanning replaces it in place without any
# event that would refresh a stale failure.
required: list[dict[str, Any]] = []
for check in code_scanning_checks:
if check["name"] not in tools:
continue
if check["bucket"] == "skipping":
check = {
**check,
"bucket": "pending" if checks_still_running else "fail",
}
required.append(check)
return required
def merge_code_scanning_checks(
checks: list[dict[str, Any]],
code_scanning_checks: list[dict[str, Any]],
) -> list[dict[str, Any]]:
# The same check can also be a configured required context, in which case
# the code scanning bucket wins because it accounts for NEUTRAL.
identities = {
(check["name"], check["integration_id"]) for check in code_scanning_checks
}
return [
check
for check in checks
if (check.get("name"), check.get("integration_id")) not in identities
] + code_scanning_checks
def settled_check_suite_app_ids(repo: str, head_sha: str) -> set[int]:
# An app is settled once every check suite it created for this head has
# completed, which means it has reported every context it is going to.
if not head_sha:
return set()
try:
pages = gh_api(
f"/repos/{repo}/commits/{head_sha}/check-suites?per_page=100",
paginate=True,
)
except RuntimeError:
return set()
settled: dict[int, bool] = {}
for page in pages or []:
for suite in page.get("check_suites") or []:
app_id = (suite.get("app") or {}).get("id")
if app_id is None:
continue
completed = suite.get("status") == "completed"
settled[app_id] = settled.get(app_id, True) and completed
return {app_id for app_id, completed in settled.items() if completed}
def unreported_required_contexts(
checks: list[dict[str, Any]],
required_contexts: list[dict[str, Any]],
) -> list[dict[str, Any]]:
unreported: list[dict[str, Any]] = []
for requirement in required_contexts:
context = requirement["context"]
integration_id = requirement.get("integration_id")
matching_checks = [check for check in checks if check.get("name") == context]
reported = any(
(
integration_id is None
or check.get("integration_id") == integration_id
)
for check in matching_checks
)
# Legacy statuses have no integration ID, so use them only when the
# requirement name is unambiguous.
if not reported and any(
check.get("status_context") for check in matching_checks
):
reported = sum(
candidate.get("context") == context
for candidate in required_contexts
) == 1
if not reported:
unreported.append(requirement)
return unreported
def include_missing_required_checks(
checks: list[dict[str, Any]] | None,
required_contexts: list[dict[str, Any]] | None,
settled_app_ids: set[int] | None = None,
) -> list[dict[str, Any]] | None:
if checks is None or required_contexts is None:
return None
complete = list(checks)
for requirement in unreported_required_contexts(checks, required_contexts):
context = requirement["context"]
integration_id = requirement.get("integration_id")
# A settled app will never report this context, so it cannot be pending.
if integration_id is not None and integration_id in (settled_app_ids or set()):
continue
complete.append({
"name": context,
"state": "EXPECTED",
"bucket": "pending",
"workflow": "",
"description": "Required check has not reported yet.",
"link": "",
"started_at": "",
"completed_at": "",
"integration_id": integration_id,
"status_context": False,
})
return complete
def _list_open_pulls(repo: str) -> list[dict[str, Any]]:
return gh_api(
f"/repos/{repo}/pulls?state=open&per_page=100",
paginate=True,
) or []
_DRAFT_TRANSITION_BATCH_SIZE = 50
def fetch_latest_draft_transitions(
repo: str,
pr_numbers: list[int],
) -> dict[int, str]:
if any(
not isinstance(number, int) or isinstance(number, bool) or number <= 0
for number in pr_numbers
):
raise ValueError("pull request numbers must be positive integers")
owner, repo_name = repo.split("/", 1)
numbers = sorted(set(pr_numbers))
transitions: dict[int, str] = {}
for start in range(0, len(numbers), _DRAFT_TRANSITION_BATCH_SIZE):
batch = numbers[start:start + _DRAFT_TRANSITION_BATCH_SIZE]
selections = " ".join(
f"pr_{n}: pullRequest(number: {n})"
f" {{timelineItems(last: 1, itemTypes: [CONVERT_TO_DRAFT_EVENT])"
f" {{nodes {{... on ConvertToDraftEvent {{createdAt}}}}}}}}"
for n in batch
)
query = (
f"query($owner: String!, $name: String!)"
f" {{repository(owner: $owner, name: $name) {{{selections}}}}}"
)
data = gh_graphql(query, {"owner": owner, "name": repo_name})
repository = ((data.get("data") or {}).get("repository") or {})
for number in batch:
pull_request = repository.get(f"pr_{number}") or {}
nodes = ((pull_request.get("timelineItems") or {}).get("nodes") or [])
if nodes and nodes[0].get("createdAt"):
transitions[number] = nodes[0]["createdAt"]
return transitions
def list_open_prs(repo: str) -> list[dict[str, Any]]:
return [
{
"number": pull["number"],
"title": pull["title"],
"author": pull.get("user"),
"authorAssociation": pull.get("author_association") or "",
"assignees": pull.get("assignees") or [],
"isDraft": pull.get("draft", False),
"createdAt": pull.get("created_at"),
"url": pull.get("html_url"),
"labels": [
label["name"]
for label in pull.get("labels") or []
if (
isinstance(label, dict)
and isinstance(label.get("name"), str)
and label["name"].strip()
)
],
}
for pull in _list_open_pulls(repo)
]
def detect_repo() -> str:
proc = subprocess.run(
["gh", "repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"],
capture_output=True,
text=True,
check=True,
encoding="utf-8",
errors="replace",
)
return proc.stdout.strip()
def load_team_members(org: str, team_slugs: list[str]) -> set[str]:
token = os.environ.get("PR_DASHBOARD_TOKEN") or None
logins: set[str] = set()
for slug in team_slugs:
members = gh_api(
f"/orgs/{org}/teams/{slug}/members?per_page=100",
paginate=True,
token=token,
)
logins.update(m["login"].lower() for m in members)
return logins
def load_reviewer_set(org: str, approver_team_slugs: list[str]) -> set[str]:
reviewers = load_team_members(org, approver_team_slugs)
if not reviewers:
raise RuntimeError(
f"no reviewers found in teams {approver_team_slugs}; "
f"the dashboard app token must have org members read permission"
)
return reviewers
REVIEW_THREADS_QUERY = """
query($owner: String!, $name: String!, $number: Int!, $after: String) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
# Keep this page small to limit GitHub GraphQL rate-limit cost;
# pagination still fetches every review thread.
reviewThreads(first: 10, after: $after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
id
isResolved
isOutdated
path
line
# Keep this page small to limit GitHub GraphQL rate-limit cost;
# pagination still fetches every comment for long threads.
comments(first: 10) {
pageInfo {
hasNextPage
endCursor
}
nodes {
id
url
body
createdAt
lastEditedAt
author {
login
}
reactionGroups {
content
# Keep this page small to limit GitHub GraphQL
# rate-limit cost for this nested connection.
users(first: 10) {
nodes {
login
}
}
}
}
}
}
}
}
}
}
"""
REVIEW_THREAD_COMMENTS_QUERY = """
query($thread_id: ID!, $after: String) {
node(id: $thread_id) {
... on PullRequestReviewThread {
comments(first: 100, after: $after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
id
url
body
createdAt
lastEditedAt
author {
login
}
reactionGroups {
content
# This paginated path is uncommon; keep the same cap
# used by the initial review-thread comment query.
users(first: 10) {
nodes {
login
}
}
}
}
}
}
}
}
"""
def fetch_remaining_review_thread_comments(thread_id: str, after: str | None) -> list[dict[str, Any]]:
comments: list[dict[str, Any]] = []
while after:
data = gh_graphql(
REVIEW_THREAD_COMMENTS_QUERY,
{"thread_id": thread_id, "after": after},
)
connection = (((data.get("data") or {}).get("node") or {}).get("comments") or {})
comments.extend(connection.get("nodes") or [])
page_info = connection.get("pageInfo") or {}
if not page_info.get("hasNextPage"):
break
after = page_info.get("endCursor") or ""
return comments
def fetch_review_threads(owner: str, repo_name: str, number: int) -> list[dict[str, Any]]:
threads: list[dict[str, Any]] = []
after: str | None = None
while True:
data = gh_graphql(
REVIEW_THREADS_QUERY,
{"owner": owner, "name": repo_name, "number": number, "after": after},
)
page = (((data.get("data") or {}).get("repository") or {}).get("pullRequest") or {}).get("reviewThreads") or {}
for thread in page.get("nodes") or []:
comments = thread.get("comments") or {}
page_info = comments.get("pageInfo") or {}
if page_info.get("hasNextPage"):
nodes = list(comments.get("nodes") or [])
nodes.extend(fetch_remaining_review_thread_comments(
thread.get("id") or "",
page_info.get("endCursor") or "",
))
comments["nodes"] = nodes
comments["pageInfo"] = {"hasNextPage": False, "endCursor": ""}
thread["comments"] = comments
threads.append(thread)
page_info = page.get("pageInfo") or {}
if not page_info.get("hasNextPage"):
return threads
after = page_info.get("endCursor") or ""
REVIEW_REQUESTS_QUERY = """
query($owner: String!, $name: String!, $number: Int!, $after: String) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
reviewRequests(first: 100, after: $after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
requestedReviewer {
__typename
... on Bot {
login
}
... on User {