-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpr_status.py
More file actions
executable file
·1109 lines (946 loc) · 37.9 KB
/
Copy pathpr_status.py
File metadata and controls
executable file
·1109 lines (946 loc) · 37.9 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
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.13"
# dependencies = []
# ///
"""PR Status Analyzer — diagnose why a PR can't merge."""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
from datetime import datetime, timezone
# ---------------------------------------------------------------------------
# gh CLI wrapper
# ---------------------------------------------------------------------------
def run_gh(*args: str, timeout: int = 30, repo: str | None = None) -> dict | list | str:
"""Run a gh CLI command, return parsed JSON or raw text.
Raises RuntimeError on non-zero exit or timeout.
"""
cmd: list[str] = ["gh"]
if repo:
cmd.extend(["-R", repo])
cmd.extend(args)
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
)
except subprocess.TimeoutExpired as exc:
raise RuntimeError(f"gh command timed out after {timeout}s: {' '.join(cmd)}") from exc
if result.returncode != 0:
stderr = result.stderr.strip()
raise RuntimeError(f"gh failed (exit {result.returncode}): {stderr}")
text = result.stdout.strip()
if not text:
return ""
try:
return json.loads(text)
except json.JSONDecodeError:
return text
def run_gh_api(endpoint: str, *, repo: str | None = None, timeout: int = 30) -> dict | list | str:
"""Call gh api with proper error propagation."""
cmd = ["gh", "api"]
if repo:
cmd.extend(["-H", "Accept: application/vnd.github+json"])
cmd.append(endpoint)
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired as exc:
raise RuntimeError(f"gh api timed out after {timeout}s: {endpoint}") from exc
text = result.stdout.strip()
parsed = None
if text:
try:
parsed = json.loads(text)
except json.JSONDecodeError:
parsed = None
if result.returncode != 0:
status_code = None
if parsed and isinstance(parsed, dict):
msg = parsed.get("message", "")
# Try to extract HTTP status from stderr
m = re.search(r"HTTP (\d{3})", result.stderr)
if m:
status_code = int(m.group(1))
raise RuntimeError(f"gh api failed ({status_code or result.returncode}): {msg}")
raise RuntimeError(f"gh api failed (exit {result.returncode}): {result.stderr.strip()}")
return parsed if parsed is not None else text
# ---------------------------------------------------------------------------
# Pure helpers (no gh calls — testable in isolation)
# ---------------------------------------------------------------------------
def parse_pr_identifier(value: str | None, local_repo: str | None = None) -> tuple[str | None, str | None]:
"""Parse a PR identifier into (pr_number_or_empty, repo_override).
Returns (None, None) to signal "detect from current branch".
"""
if not value:
return None, None
# URL form
m = re.match(r"https?://github\.com/([^/]+/[^/]+)/pull/(\d+)", value)
if m:
repo_from_url = m.group(1)
pr_number = m.group(2)
repo_override = repo_from_url if repo_from_url != local_repo else None
return pr_number, repo_override
# Numeric
if value.isdigit():
return value, None
print(f"Error: Cannot parse PR identifier: {value}", file=sys.stderr)
sys.exit(2)
def classify_bot(login: str) -> bool:
"""Return True if login looks like a bot account.
Catches GitHub App bots (renovate[bot], dependabot[bot], etc.)
but not service-account bots using regular user accounts
(e.g. codecov-commenter). Intentional: suffix check avoids
maintaining a hardcoded bot list.
"""
return login.endswith("[bot]")
def extract_run_ids_from_checks(checks: list[dict]) -> list[str]:
"""Extract unique GitHub Actions run IDs from failed check links."""
run_ids: set[str] = set()
for check in checks:
if check.get("bucket") != "fail":
continue
link = check.get("link") or ""
m = re.search(r"/actions/runs/(\d+)", link)
if m:
run_ids.add(m.group(1))
return sorted(run_ids, key=int)
def merge_state_message(state: str) -> str:
"""Return an actionable message for a merge state."""
messages = {
"DIRTY": "Branch has merge conflicts that need resolution",
"BEHIND": "Branch is behind base and needs to be updated",
"BLOCKED": "Merge is blocked by branch protection rules",
"UNSTABLE": "Some required checks are failing",
"UNKNOWN": "GitHub is still computing merge status — try again shortly",
}
return messages.get(state, f"Merge state: {state}")
def find_error_keywords(body: str) -> list[str]:
"""Return error-related keywords found in a comment body."""
keyword_patterns: list[tuple[str, str]] = [
("error", r"(?i)\berror\b"),
("failure", r"(?i)\bfail(?:ed|ure|ing)?\b"),
("warning", r"(?i)\bwarn(?:ing)?\b"),
("conflict", r"(?i)\bconflicts?\b"),
("deprecated", r"(?i)\bdeprecated?\b"),
("vulnerability", r"(?i)\bvulnerabilit(?:y|ies)\b"),
("breaking", r"(?i)\bbreaking\b"),
]
found = []
for label, pat in keyword_patterns:
if re.search(pat, body):
found.append(label)
return found
def is_stale_approval(approval_time_str: str | None, head_commit_time_str: str | None) -> bool:
"""Return True if approval predates the head commit."""
if not approval_time_str or not head_commit_time_str:
return False
try:
approved = datetime.fromisoformat(approval_time_str.replace("Z", "+00:00"))
committed = datetime.fromisoformat(head_commit_time_str.replace("Z", "+00:00"))
return approved < committed
except (ValueError, TypeError):
return False
# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------
def cmd_detect_repo(_args: argparse.Namespace) -> int:
"""Detect GitHub repo from git remote."""
try:
url = subprocess.run(
["git", "remote", "get-url", "origin"],
capture_output=True, text=True, check=True,
).stdout.strip()
except subprocess.CalledProcessError:
print("Error: Not a git repository or no origin remote", file=sys.stderr)
return 2
if "github.com" not in url:
print(f"Error: Not a GitHub repository (remote: {url})", file=sys.stderr)
return 2
m = re.search(r"github\.com[:/]([^/]+)/([^.\s]+?)(?:\.git)?$", url)
if not m:
print(f"Error: Cannot parse GitHub URL: {url}", file=sys.stderr)
return 2
repo = f"{m.group(1)}/{m.group(2)}"
print(repo)
return 0
def filter_noise_lines(lines: list[str]) -> list[str]:
"""Remove GitHub Actions boilerplate noise from log lines.
Keeps ##[error] lines (they carry signal). Removes group/endgroup
markers, debug lines, action downloads, cache messages, runner
version info, and progress indicators.
"""
noise_patterns = [
re.compile(r"^##\[group\]"),
re.compile(r"^##\[endgroup\]"),
re.compile(r"^##\[debug\]"),
re.compile(r"^Download action repository\b"),
re.compile(r"^Cache restored\b"),
re.compile(r"^Receiving objects:\s"),
re.compile(r"^Resolving deltas:\s"),
re.compile(r"^Runner version\b"),
re.compile(r"^Operating System$"),
]
result: list[str] = []
for line in lines:
stripped = line.strip()
if stripped.startswith("##[error]"):
result.append(line)
continue
if any(p.search(stripped) for p in noise_patterns):
continue
result.append(line)
return result
def extract_error_annotations(lines: list[str], *, context: int = 2) -> list[str]:
"""Extract ##[error] lines with surrounding context.
Returns deduplicated lines around each error annotation.
"""
if not lines:
return []
error_indices = [i for i, line in enumerate(lines) if "##[error]" in line]
if not error_indices:
return []
include: set[int] = set()
for idx in error_indices:
start = max(0, idx - context)
end = min(len(lines), idx + context + 1)
include.update(range(start, end))
return [lines[i] for i in sorted(include)]
def extract_test_summary(lines: list[str]) -> list[str]:
"""Extract test failure summaries from log lines.
Captures the pytest "short test summary info" section (concise)
and individual FAILED/ERROR/AssertionError lines. Avoids capturing
full tracebacks from the FAILURES section.
"""
if not lines:
return []
result: list[str] = []
# Extract pytest "short test summary info" section (concise one-liners)
in_short_summary = False
for line in lines:
stripped = line.strip()
if "short test summary info" in stripped:
in_short_summary = True
result.append(line)
continue
if in_short_summary:
if stripped.startswith("===") or stripped.startswith("---"):
result.append(line)
break
result.append(line)
# Extract individual FAILED / ERROR lines not already captured
seen = set(result)
for line in lines:
stripped = line.strip()
if line in seen:
continue
if (
stripped.startswith("FAILED ")
or stripped.startswith("ERROR ")
or "AssertionError" in stripped
):
result.append(line)
seen.add(line)
return result
def truncate_log_lines(lines: list[str], *, head: int = 100, tail: int = 400) -> list[str]:
"""Truncate log lines keeping head and tail sections.
Errors typically appear at the end of CI logs, so we keep the last
``tail`` lines plus the first ``head`` lines for setup context.
Both ``head`` and ``tail`` must be non-negative.
"""
total = head + tail
if len(lines) <= total:
return lines
skipped = len(lines) - total
head_part = lines[:head] if head else []
tail_part = lines[-tail:] if tail else []
return head_part + [f"--- {skipped} lines truncated ---"] + tail_part
def _detect_local_repo() -> str | None:
"""Detect local repo silently, return owner/repo or None."""
try:
url = subprocess.run(
["git", "remote", "get-url", "origin"],
capture_output=True, text=True, check=True,
).stdout.strip()
except subprocess.CalledProcessError:
return None
m = re.search(r"github\.com[:/]([^/]+)/([^.\s]+?)(?:\.git)?$", url)
return f"{m.group(1)}/{m.group(2)}" if m else None
def _resolve_pr(args: argparse.Namespace) -> tuple[str, str | None]:
"""Resolve PR number and repo from args. Exits on failure."""
local_repo = _detect_local_repo()
pr_input = getattr(args, "pr", None)
pr_number, repo_override = parse_pr_identifier(pr_input, local_repo)
repo = args.repo or repo_override
if pr_number is None:
# Detect from current branch
try:
data = run_gh("pr", "view", "--json", "number", repo=repo)
pr_number = str(data["number"])
except RuntimeError as exc:
print(f"Error detecting PR from current branch: {exc}", file=sys.stderr)
sys.exit(2)
return pr_number, repo
def cmd_check_cli(_args: argparse.Namespace) -> int:
"""Verify gh auth and repo access."""
# Check gh exists
try:
subprocess.run(["gh", "--version"], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
print("Error: gh CLI is not installed — https://cli.github.com/", file=sys.stderr)
return 2
# Check auth
try:
run_gh("auth", "status")
except RuntimeError:
print("Error: gh is not authenticated — run: gh auth login", file=sys.stderr)
return 2
# Check repo access
local_repo = _detect_local_repo()
if local_repo:
try:
run_gh("api", f"repos/{local_repo}")
print(f"Authenticated with access to {local_repo}")
except RuntimeError:
login = _get_current_login()
_handle_access_failure(login, local_repo)
return 2
else:
print("Authenticated (not in a GitHub repository)")
return 0
def _get_current_login() -> str:
"""Get current gh login."""
try:
return run_gh("api", "user", "--jq", ".login")
except RuntimeError:
return "unknown"
def _handle_access_failure(login: str, repo: str) -> None:
"""Handle repo access failure with interactive/non-interactive detection."""
is_interactive = os.isatty(0) and os.isatty(1)
if is_interactive:
print(f"Current account '{login}' cannot access '{repo}'", file=sys.stderr)
print("", file=sys.stderr)
print("To fix:", file=sys.stderr)
print(" 1. Check accounts: gh auth status", file=sys.stderr)
print(" 2. Switch accounts: gh auth switch", file=sys.stderr)
print(" 3. Or login: gh auth login", file=sys.stderr)
else:
print(f"Error: Account '{login}' cannot access '{repo}'", file=sys.stderr)
print("Run: gh auth switch or gh auth login", file=sys.stderr)
def cmd_status(args: argparse.Namespace) -> int:
"""PR metadata: merge state, reviews, draft, checks summary."""
pr, repo = _resolve_pr(args)
data = run_gh(
"pr", "view", pr, "--json",
"number,title,state,isDraft,mergeable,mergeStateStatus,"
"reviewDecision,reviewRequests,latestReviews,"
"headRefName,baseRefName,statusCheckRollup",
repo=repo,
)
if args.format == "json":
print(json.dumps(data, indent=2))
else:
_print_status_text(data)
return 0
def _print_status_text(data: dict) -> None:
"""Print human-readable PR status."""
print(f"PR #{data['number']}: {data['title']}")
print(f"Branch: {data['headRefName']} -> {data['baseRefName']}")
print(f"State: {data['state']}", end="")
if data.get("isDraft"):
print(" (DRAFT)", end="")
print()
print(f"Merge state: {data.get('mergeStateStatus', 'N/A')}")
print(f"Review decision: {data.get('reviewDecision') or 'NONE'}")
rollup = data.get("statusCheckRollup") or []
if rollup:
states = {}
for c in rollup:
s = (c.get("conclusion") or c.get("status") or "PENDING").upper()
bucket = "pass" if s == "SUCCESS" else "fail" if s == "FAILURE" else "pending"
states[bucket] = states.get(bucket, 0) + 1
print(f"Checks: {states.get('pass', 0)} passed, {states.get('fail', 0)} failed, {states.get('pending', 0)} pending")
def cmd_checks(args: argparse.Namespace) -> int:
"""Detailed check results."""
pr, repo = _resolve_pr(args)
try:
checks = run_gh("pr", "checks", pr, "--json", "bucket,name,state,description,link,workflow", repo=repo)
except RuntimeError:
checks = []
if args.format == "json":
print(json.dumps(checks, indent=2))
return 0
if not checks:
print("No checks found.")
return 0
for c in checks:
bucket = c.get("bucket", "?")
icon = {"pass": "+", "fail": "X", "pending": "~"}.get(bucket, "?")
print(f" [{icon}] {c.get('name', '?')}: {c.get('state', '?')}")
return 0
def cmd_comments(args: argparse.Namespace) -> int:
"""All PR comments and reviews."""
pr, repo = _resolve_pr(args)
data = run_gh(
"pr", "view", pr, "--json",
"comments,reviews",
repo=repo,
)
comments = (data.get("comments") or [])[-100:] # limit to last 100
reviews = data.get("reviews") or []
if args.format == "json":
print(json.dumps({"comments": comments, "reviews": reviews}, indent=2))
return 0
if reviews:
print("=== Reviews ===")
for r in reviews:
author = r.get("author", {}).get("login", "?")
state = r.get("state", "?")
body = (r.get("body") or "").strip()
ts = r.get("submittedAt", "")
print(f" {author} ({state}) [{ts}]")
if body:
for line in body.split("\n")[:5]:
print(f" {line}")
print()
if comments:
print("=== Comments ===")
for c in comments:
author = c.get("author", {}).get("login", "?")
body = (c.get("body") or "").strip()
ts = c.get("createdAt", "")
print(f" {author} [{ts}]")
if body:
for line in body.split("\n")[:5]:
print(f" {line}")
elif not reviews:
print("No comments or reviews.")
return 0
def cmd_bot_comments(args: argparse.Namespace) -> int:
"""Filter for bot authors + error keywords."""
pr, repo = _resolve_pr(args)
data = run_gh("pr", "view", pr, "--json", "comments", repo=repo)
comments = (data.get("comments") or [])[-100:]
bot_comments = []
for c in comments:
author = c.get("author", {}).get("login", "")
if not classify_bot(author):
continue
body = (c.get("body") or "").strip()
keywords = find_error_keywords(body)
bot_comments.append({
"author": author,
"createdAt": c.get("createdAt", ""),
"error_keywords": keywords,
"body_preview": body[:300],
})
if args.format == "json":
print(json.dumps(bot_comments, indent=2))
return 0
if not bot_comments:
print("No bot comments found.")
return 0
print(f"Found {len(bot_comments)} bot comment(s):")
for bc in bot_comments:
kw = ", ".join(bc["error_keywords"]) if bc["error_keywords"] else "none"
print(f" {bc['author']} [{bc['createdAt']}] error keywords: {kw}")
if bc["error_keywords"]:
preview = bc["body_preview"].replace("\n", " ")[:120]
print(f" {preview}...")
return 0
def cmd_failed_runs(args: argparse.Namespace) -> int:
"""Extract run IDs from failed checks."""
pr, repo = _resolve_pr(args)
try:
checks = run_gh("pr", "checks", pr, "--json", "bucket,link", repo=repo)
except RuntimeError:
checks = []
run_ids = extract_run_ids_from_checks(checks)
if args.format == "json":
print(json.dumps(run_ids))
else:
if run_ids:
print(" ".join(run_ids))
else:
print("No failed runs found.")
return 0
def cmd_analyze_logs(args: argparse.Namespace) -> int:
"""Download and pattern-match failed CI logs."""
run_id = args.run_id
# Resolve repo: from PR arg, --repo flag, or local git remote
pr_input = getattr(args, "pr", None)
local_repo = _detect_local_repo()
_, repo_override = parse_pr_identifier(pr_input, local_repo)
repo = args.repo or repo_override or local_repo
try:
logs = run_gh("run", "view", run_id, "--log-failed", repo=repo, timeout=60)
except RuntimeError as exc:
print(f"Error fetching logs: {exc}", file=sys.stderr)
return 2
if not logs:
print("No failed logs found (run may have succeeded or be in progress).")
return 0
raw_lines = str(logs).split("\n")
# Extract signal before filtering
error_annotations = extract_error_annotations(raw_lines)
test_summary = extract_test_summary(raw_lines)
# Filter noise, then truncate with tighter window
filtered = filter_noise_lines(raw_lines)
truncated = truncate_log_lines(filtered, head=50, tail=200)
# Structured output: signal first, then filtered log
if error_annotations:
print("=== Error Annotations (##[error]) ===")
for line in error_annotations:
print(line)
print()
if test_summary:
print("=== Test Failure Summary ===")
for line in test_summary:
print(line)
print()
print(f"=== Filtered Log ({len(truncated)} lines) ===")
print("\n".join(truncated))
# Pattern matching
full_text = "\n".join(filtered)
patterns = {
"Permission denied": r"(?i)permission denied",
"Command not found": r"(?i)command not found",
"Missing file/directory": r"(?i)no such file or directory",
"Test failures": r"(?i)(test.*fail|fail.*test|assertion.*error)",
"Syntax/parse error": r"(?i)(syntax.*error|parse.*error)",
"Timeout": r"(?i)(timeout|timed out)",
"Out of memory": r"(?i)(out of memory|oom)",
"Network error": r"(?i)(connection.*refused|connection.*timeout|network.*error)",
}
print("\n=== Error Patterns ===")
found_any = False
for label, pat in patterns.items():
if re.search(pat, full_text):
print(f" Found: {label}")
found_any = True
if not found_any:
print(" No common patterns matched — review logs above.")
return 0
def cmd_required_checks(args: argparse.Namespace) -> int:
"""Fetch branch protection required status checks."""
pr, repo = _resolve_pr(args)
# Get base branch
pr_data = run_gh("pr", "view", pr, "--json", "baseRefName", repo=repo)
base_branch = pr_data["baseRefName"]
effective_repo = repo or _detect_local_repo()
if not effective_repo:
print("Error: Cannot determine repository", file=sys.stderr)
return 2
required = _fetch_required_checks(effective_repo, base_branch)
if required is None:
return 0 # already printed info message
if args.format == "json":
print(json.dumps(required, indent=2))
else:
if required:
print(f"Required checks for {base_branch}:")
for name in required:
print(f" - {name}")
else:
print(f"No required status checks configured for {base_branch}.")
return 0
def _fetch_required_checks(repo: str, branch: str) -> list[str] | None:
"""Fetch required status check names. Returns None if no protection."""
encoded_branch = branch.replace("/", "%2F")
owner, repo_name = repo.split("/")
# Try legacy branch protection API
try:
data = run_gh_api(
f"repos/{owner}/{repo_name}/branches/{encoded_branch}/protection/required_status_checks",
)
if isinstance(data, dict):
contexts = data.get("contexts") or []
checks = data.get("checks") or []
names = list(set(contexts + [c.get("context", "") for c in checks]))
return [n for n in names if n]
except RuntimeError as exc:
err_str = str(exc)
if "404" in err_str:
# Try rulesets API as fallback
return _fetch_required_checks_rulesets(owner, repo_name, branch)
if "403" in err_str:
print(
"Warning: Insufficient permissions to read branch protection. "
"Fix with: gh auth refresh -s repo",
file=sys.stderr,
)
return None
raise
return []
def _fetch_required_checks_rulesets(owner: str, repo_name: str, branch: str) -> list[str] | None:
"""Try repository rulesets API for required checks."""
try:
rulesets = run_gh_api(f"repos/{owner}/{repo_name}/rulesets")
except RuntimeError:
# No branch protection at all
print(f"Info: No branch protection configured for {branch}.")
return None
if not isinstance(rulesets, list):
print(f"Info: No branch protection configured for {branch}.")
return None
required_names: set[str] = set()
for ruleset in rulesets:
rs_id = ruleset.get("id")
if not rs_id:
continue
try:
detail = run_gh_api(f"repos/{owner}/{repo_name}/rulesets/{rs_id}")
except RuntimeError:
continue
rules = detail.get("rules") or []
for rule in rules:
if rule.get("type") == "required_status_checks":
params = rule.get("parameters") or {}
for check in params.get("required_status_checks") or []:
name = check.get("context") or ""
if name:
required_names.add(name)
if not required_names:
print(f"Info: No required status checks found in rulesets for {branch}.")
return None
return sorted(required_names)
def cmd_missing_checks(args: argparse.Namespace) -> int:
"""Compare required vs actual checks, report absent ones."""
pr, repo = _resolve_pr(args)
# Get base branch + actual checks
pr_data = run_gh("pr", "view", pr, "--json", "baseRefName", repo=repo)
base_branch = pr_data["baseRefName"]
effective_repo = repo or _detect_local_repo()
if not effective_repo:
print("Error: Cannot determine repository", file=sys.stderr)
return 2
required = _fetch_required_checks(effective_repo, base_branch)
if required is None:
return 0
if not required:
print("No required status checks configured.")
return 0
try:
checks = run_gh("pr", "checks", pr, "--json", "name", repo=repo)
except RuntimeError:
checks = []
actual_names = {c.get("name", "") for c in checks}
missing = [r for r in required if r not in actual_names]
if args.format == "json":
print(json.dumps({"required": required, "actual": sorted(actual_names), "missing": missing}, indent=2))
else:
if missing:
print(f"Missing required checks ({len(missing)}):")
for name in missing:
print(f" ! {name}")
else:
print(f"All {len(required)} required checks are present.")
return 0
def _fetch_unresolved_thread_count(pr: str, repo: str | None) -> int:
"""Fetch count of unresolved review threads via GraphQL."""
effective_repo = repo or _detect_local_repo()
if not effective_repo:
return 0
owner, name = effective_repo.split("/")
query = """
query($owner: String!, $name: String!, $pr: Int!) {
repository(owner: $owner, name: $name) {
pullRequest(number: $pr) {
reviewThreads(first: 100) {
nodes { isResolved }
}
}
}
}
"""
try:
result = subprocess.run(
["gh", "api", "graphql",
"-F", f"owner={owner}", "-F", f"name={name}", "-F", f"pr={pr}",
"-f", f"query={query}"],
capture_output=True, text=True, timeout=30,
)
if result.returncode != 0:
return 0
data = json.loads(result.stdout)
threads = (
data.get("data", {})
.get("repository", {})
.get("pullRequest", {})
.get("reviewThreads", {})
.get("nodes", [])
)
return sum(1 for t in threads if not t.get("isResolved", True))
except (subprocess.TimeoutExpired, json.JSONDecodeError, RuntimeError):
return 0
def cmd_diagnose(args: argparse.Namespace) -> int:
"""Full blocker report — the primary command."""
pr, repo = _resolve_pr(args)
blockers: list[dict] = []
# --- Fetch PR data ---
pr_data = run_gh(
"pr", "view", pr, "--json",
"number,title,state,isDraft,mergeable,mergeStateStatus,"
"reviewDecision,reviewRequests,latestReviews,"
"headRefName,baseRefName,statusCheckRollup",
repo=repo,
)
title = pr_data.get("title", "")
head_ref = pr_data.get("headRefName", "")
base_ref = pr_data.get("baseRefName", "")
state = pr_data.get("state", "")
if args.format != "json":
print(f"=== PR #{pr}: {title} ===")
print(f"Branch: {head_ref} -> {base_ref}")
print(f"State: {state}")
print()
# 1. Draft status
if pr_data.get("isDraft"):
blockers.append({
"type": "draft",
"message": "PR is in draft mode",
"fix": "Mark as ready for review",
})
# 2. Merge state
merge_state = pr_data.get("mergeStateStatus", "UNKNOWN")
if merge_state not in ("CLEAN", "HAS_HOOKS"):
blockers.append({
"type": "merge_state",
"state": merge_state,
"message": merge_state_message(merge_state),
"fix": {
"DIRTY": "Resolve merge conflicts",
"BEHIND": f"Rebase or merge {base_ref} into {head_ref}",
"BLOCKED": "Satisfy branch protection requirements",
"UNSTABLE": "Fix failing required checks",
"UNKNOWN": "Wait for GitHub to recompute — try again shortly",
}.get(merge_state, "Investigate merge state"),
})
# 3. Review decision
review_decision = pr_data.get("reviewDecision") or ""
if review_decision == "CHANGES_REQUESTED":
reviewers = [
r.get("author", {}).get("login", "?")
for r in (pr_data.get("latestReviews") or [])
if r.get("state") == "CHANGES_REQUESTED"
]
blockers.append({
"type": "review",
"decision": review_decision,
"reviewers": reviewers,
"message": f"Changes requested by: {', '.join(reviewers)}",
"fix": "Address review feedback and re-request review",
})
elif review_decision == "REVIEW_REQUIRED":
pending = [
r.get("login") or r.get("name") or r.get("slug") or "?"
for r in (pr_data.get("reviewRequests") or [])
]
blockers.append({
"type": "review",
"decision": review_decision,
"pending_reviewers": pending,
"message": f"Review required — pending: {', '.join(pending) or 'unassigned'}",
"fix": "Request review or wait for pending reviewers",
})
# 4. Unresolved review threads (via GraphQL — not available in gh pr view --json)
unresolved_count = _fetch_unresolved_thread_count(pr, repo)
if unresolved_count > 0:
blockers.append({
"type": "unresolved_threads",
"count": unresolved_count,
"message": f"{unresolved_count} unresolved review thread(s)",
"fix": "Resolve all review conversations",
})
# 5. Stale approvals
approvals = [
r for r in (pr_data.get("latestReviews") or [])
if r.get("state") == "APPROVED"
]
if approvals:
# Get head commit date
try:
commit_data = run_gh(
"pr", "view", pr, "--json", "commits", repo=repo,
)
commits = commit_data.get("commits") or []
if commits:
head_commit_date = commits[-1].get("committedDate") or ""
stale = [
a.get("author", {}).get("login", "?")
for a in approvals
if is_stale_approval(a.get("submittedAt", ""), head_commit_date)
]
if stale:
blockers.append({
"type": "stale_approvals",
"reviewers": stale,
"message": f"Stale approval(s) from: {', '.join(stale)} (pre-date latest push)",
"fix": "Re-request review from stale approvers",
})
except RuntimeError:
pass # non-critical
# 6. CI checks
try:
checks = run_gh("pr", "checks", pr, "--json", "bucket,name,state,link,workflow", repo=repo)
except RuntimeError:
checks = []
if checks:
counts = {"pass": 0, "fail": 0, "pending": 0}
failing_names = []
pending_names = []
for c in checks:
bucket = c.get("bucket", "pending")
counts[bucket] = counts.get(bucket, 0) + 1
if bucket == "fail":
failing_names.append(c.get("name", "?"))
elif bucket == "pending":
pending_names.append(c.get("name", "?"))
if counts["fail"] > 0:
blockers.append({
"type": "ci_failure",
"pass": counts["pass"],
"fail": counts["fail"],
"pending": counts["pending"],
"failing_checks": failing_names,
"message": f"{counts['fail']} check(s) failing: {', '.join(failing_names)}",
"fix": "Investigate failing checks — use: failed-runs / analyze-logs",
})
elif counts["pending"] > 0:
blockers.append({
"type": "ci_pending",
"pass": counts["pass"],
"pending": counts["pending"],
"pending_checks": pending_names,
"message": f"{counts['pending']} check(s) still pending: {', '.join(pending_names)}",
"fix": "Wait for pending checks to complete",
})
# 7. Missing required checks
effective_repo = repo or _detect_local_repo()
if effective_repo:
required = _fetch_required_checks(effective_repo, base_ref)
if required:
actual_names = {c.get("name", "") for c in checks}
missing = [r for r in required if r not in actual_names]
if missing:
blockers.append({
"type": "missing_checks",
"missing": missing,
"message": f"Missing required check(s): {', '.join(missing)}",
"fix": "Ensure CI workflows are triggered for this PR",
})
# 8. Bot comments with errors
try:
comment_data = run_gh("pr", "view", pr, "--json", "comments", repo=repo)
comments = (comment_data.get("comments") or [])[-100:]
bot_errors = []
for c in comments:
author = c.get("author", {}).get("login", "")
if not classify_bot(author):
continue
body = (c.get("body") or "").strip()
keywords = find_error_keywords(body)
if keywords:
bot_errors.append({"author": author, "keywords": keywords})
if bot_errors:
summary = "; ".join(f"{b['author']}: {','.join(b['keywords'])}" for b in bot_errors[:5])
blockers.append({
"type": "bot_errors",