Repository navigation
Expand file tree
/
Copy pathpr-dash.py
More file actions
executable file
·4584 lines (3983 loc) · 170 KB
/
Copy pathpr-dash.py
File metadata and controls
executable file
·4584 lines (3983 loc) · 170 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 python3
"""
PR Dashboard — a local web UI for tracking your active GitHub pull requests.
Aggregates PRs from three sources into a single view:
1. Local git worktrees (shows dirty/unpushed status)
2. Extra branches listed in ~/.worktrees.txt
3. Open PRs authored by you that aren't checked out locally
PRs are aggregated across several repos: the repo containing the current directory
plus any extras listed in PR_DASH_REPOS (none by default).
Polls PR metadata every 30 s and running CI every 15 s while viewed (10 min when idle).
Unchanged comments and settled CI are reused for up to 5 min; Refresh bypasses these caches.
Environment variables:
PR_DASH_DEBUG=1 Enable verbose logging (also: WORKTREES_DEBUG)
PR_DASH_CMD_TIMEOUT=30 Per-command timeout in seconds (also: WORKTREES_CMD_TIMEOUT)
PR_DASH_BATCH_SIZE=15 Branches per GraphQL batch (also: WORKTREES_BATCH_SIZE)
PR_DASH_PARALLEL=4 Parallel batch workers (also: WORKTREES_PARALLEL)
PR_DASH_RATE_LIMIT_COOLDOWN=900
Seconds without GitHub calls after GitHub reports a rate
limit (the limits are per user, shared with every other
tool signed in as you).
PR_DASH_REPOS=... Comma-separated extra repos to include, each
"owner/name" or "owner/name=/path/to/checkout".
Unset or empty for current repo only.
PR_DASH_BOTS=... Comma-separated extra bot logins to hide from the
reviewer list (any *[bot], *-bot, *-ci login is
already treated as a bot).
Requires: gh (GitHub CLI), git, flask
"""
import argparse
from concurrent.futures import as_completed
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
from datetime import datetime
from datetime import timedelta
from datetime import timezone
import json
import os
from pathlib import Path
import random
import re
import subprocess
import threading
import time
from urllib.parse import urlencode
from urllib.parse import urlsplit
from flask import Flask
from flask import jsonify
from flask import render_template_string
from flask import request
app = Flask(__name__)
# Cache for PR dashboard data
_cache = {
'data': [],
'review_requests': [],
'last_updated': None,
'updating': False,
'is_stale': False, # True if last fetch failed and we're showing cached data
}
_cache_lock = threading.Lock()
# GitHub repo info (cached)
_repo_info = {
'owner': None,
'name': None,
'current_user': None,
}
# Track last API access for adaptive refresh rate (using dict to avoid global statement)
_api_state: dict[str, datetime | None] = {'last_access': None}
_api_access_lock = threading.Lock()
# GitHub quota guard. The REST (5,000/h) and GraphQL (5,000 points/h) limits are per *user*,
# shared with every other tool signed in as you (gh in other shells, the editor, Tau). When GitHub
# says we are over, every further call is a wasted process and a 403, and a REST fallback on top
# of a GraphQL limit just drains the second bucket too. So: remember the limit, make no gh calls
# until it has had time to reset, and let the refresh loop sleep through it instead of retrying
# every 15 s. GitHub's windows are an hour from the first request, so a hit near the end of a
# window clears sooner than this; the next cycle after the cooldown finds out either way.
_RATE_LIMIT_COOLDOWN_SECONDS = int(os.environ.get('PR_DASH_RATE_LIMIT_COOLDOWN', '900'))
_rate_limit_state: dict[str, datetime | None] = {'until': None}
_rate_limit_lock = threading.Lock()
# Closed PR details rarely change; updatedAt invalidates edits made after closing.
_closed_pr_cache: dict[tuple[str, str], tuple[str, dict]] = {}
_closed_pr_cache_lock = threading.Lock()
_METADATA_INTERVAL = 30
_ACTIVE_CI_INTERVAL = 15
_SETTLED_INTERVAL = 300
_CLOSED_LIST_INTERVAL = 600
# Cache raw snapshots, not parsed rows: relative times and local git state still update each cycle.
_list_cache: dict[tuple[str, ...], tuple[float, list[dict]]] = {}
# One bounded (at most 200 numbers) authoritative open-PR snapshot per configured repo.
_open_pr_numbers: dict[str, set[int]] = {}
_field_cache: dict[tuple[str, str, str], tuple[tuple[str, ...], float, dict]] = {}
_rest_cache: dict[str, tuple[dict[str, str], dict | list]] = {}
_fetch_cache_lock = threading.Lock()
_refresh_wakeup = threading.Event()
def _store_snapshot(cache: dict, key: object, value: object) -> None:
"""Bound each cache to 1024 snapshots of at most 128 KiB of encoded data each.
Oversized snapshots are served uncached; the oldest entry is evicted on overflow.
The caller holds the cache's lock.
"""
if len(json.dumps(value).encode()) > 128 * 1024:
cache.pop(key, None)
return
if len(cache) >= 1024 and key not in cache:
cache.pop(next(iter(cache)))
cache[key] = deepcopy(value)
def _is_rate_limit_error(message: str) -> bool:
lowered = (message or '').lower()
return 'rate limit' in lowered or 'secondary limit' in lowered or 'abuse detection' in lowered
def _note_rate_limited(message: str) -> None:
"""Start (or extend) the cooldown after GitHub reported a rate limit."""
until = datetime.now(timezone.utc) + timedelta(seconds=_RATE_LIMIT_COOLDOWN_SECONDS)
with _rate_limit_lock:
current = _rate_limit_state['until']
if current is None or until > current:
_rate_limit_state['until'] = until
print(f'[gh] GitHub rate limit hit; no GitHub calls until {until:%H:%M:%S} UTC ({message[:120]})')
def rate_limited_until() -> datetime | None:
"""When the cooldown ends, or None when GitHub calls are allowed."""
with _rate_limit_lock:
until = _rate_limit_state['until']
if until and until <= datetime.now(timezone.utc):
_rate_limit_state['until'] = None
return None
return until
def run_command(cmd: list[str], capture_output: bool = True, debug: bool = False) -> tuple[bool, str]:
"""Run a shell command and return success status and output."""
timeout = int(os.environ.get('PR_DASH_CMD_TIMEOUT', os.environ.get('WORKTREES_CMD_TIMEOUT', '30')))
try:
result = subprocess.run(
cmd,
capture_output=capture_output,
text=True,
check=False,
timeout=timeout,
)
output = result.stdout.strip()
if result.returncode != 0:
# gh treats 304 as an error. Keep included HTTP responses so the caller can
# distinguish Not Modified from a failed fetch without retrying it.
if not (cmd[:2] == ['gh', 'api'] and '--include' in cmd and output.startswith('HTTP/')):
output = result.stderr.strip() or output
if debug:
print(f'[cmd] {" ".join(cmd[:3])}... failed: {output[:100] if output else "no output"}')
return result.returncode == 0, output
except subprocess.TimeoutExpired:
if debug:
print(f'[cmd] {" ".join(cmd[:3])}... timed out after {timeout}s')
return False, ''
except Exception as e:
if debug:
print(f'[cmd] {" ".join(cmd[:3])}... exception: {e}')
return False, ''
def run_gh_command(cmd: list[str], max_retries: int = 3) -> tuple[bool, str]:
"""Run a GitHub CLI command with retry logic for transient failures."""
debug = os.environ.get('PR_DASH_DEBUG', os.environ.get('WORKTREES_DEBUG', '')).lower() in ('1', 'true', 'yes')
last_error = ''
if rate_limited_until():
# Every call during the cooldown would be another 403; spend nothing.
return False, 'GitHub rate limit cooldown'
for attempt in range(max_retries):
success, output = run_command(cmd, debug=debug)
not_modified = (
cmd[:2] == ['gh', 'api']
and '--include' in cmd
and output.startswith('HTTP/')
and output.splitlines()[0].split()[1:2] == ['304']
)
if success or not_modified:
return True, output
last_error = output
if _is_rate_limit_error(last_error):
_note_rate_limited(last_error)
return False, last_error
if attempt < max_retries - 1:
# Exponential backoff with jitter: base * 2^attempt + random jitter
base_delay = 0.5 * (2**attempt)
jitter = random.uniform(0, 0.5)
delay = base_delay + jitter
if debug:
print(f'[gh] Retry {attempt + 1}/{max_retries} after {delay:.2f}s for: {" ".join(cmd[:4])}...')
time.sleep(delay)
if debug:
print(
f'[gh] All {max_retries} attempts failed for: {" ".join(cmd[:4])}... last_error={last_error[:100] if last_error else "none"}'
)
return False, ''
def _parallel_workers() -> int:
"""Worker count for parallel per-PR fetches (PR_DASH_PARALLEL / WORKTREES_PARALLEL)."""
return max(1, int(os.environ.get('PR_DASH_PARALLEL', os.environ.get('WORKTREES_PARALLEL', '4'))))
def get_repo_info() -> tuple[str, str]:
"""Get repository owner and name."""
if _repo_info['owner'] and _repo_info['name']:
return _repo_info['owner'], _repo_info['name']
success, output = run_gh_command(['gh', 'repo', 'view', '--json', 'owner,name', '-q', '.owner.login + "|" + .name'])
if success and output and '|' in output:
owner, name = output.split('|', 1)
else:
success, output = run_command(['git', 'remote', 'get-url', 'origin'])
nwo = _remote_to_nwo(output) if success else ''
if '/' not in nwo:
return '', ''
owner, name = nwo.split('/', 1)
_repo_info['owner'] = owner
_repo_info['name'] = name
return owner, name
# Repos aggregated in addition to the one containing the current directory.
# Override with PR_DASH_REPOS; e.g. 'myorg/other-repo,myorg/mobile=/path/to/mobile'.
_DEFAULT_EXTRA_REPOS: list[str] = []
_repos_state: dict[str, list[dict] | None] = {'repos': None}
_repos_lock = threading.Lock()
def _remote_to_nwo(url: str) -> str:
"""Reduce a git remote URL to "owner/name"."""
url = url.strip()
if url.endswith('.git'):
url = url[:-4]
parts = [p for p in url.replace(':', '/').split('/') if p]
if len(parts) >= 2:
return f'{parts[-2]}/{parts[-1]}'
return ''
def _detect_local_path(nwo: str) -> str:
"""Find a local checkout of owner/name by probing common sibling locations."""
name = nwo.split('/')[-1]
cwd = Path.cwd()
candidates = [cwd.parent / name, Path.home() / 'workspace' / name, Path.home() / name]
for candidate in candidates:
if not (candidate / '.git').exists():
continue
success, output = run_command(['git', '-C', str(candidate), 'remote', 'get-url', 'origin'])
if success and output and _remote_to_nwo(output) == nwo:
return str(candidate)
return ''
def get_repos() -> list[dict]:
"""Repos to aggregate: the current directory's repo first, then PR_DASH_REPOS extras.
Each entry is {'nwo', 'owner', 'name', 'path', 'primary'}. 'path' is a local
checkout used for worktree/dirty state, and is empty when none was found.
"""
with _repos_lock:
cached = _repos_state['repos']
if cached is not None:
return cached
repos: list[dict] = []
seen: set[str] = set()
owner, name = get_repo_info()
if owner and name:
nwo = f'{owner}/{name}'
seen.add(nwo)
repos.append({'nwo': nwo, 'owner': owner, 'name': name, 'path': str(Path.cwd()), 'primary': True})
raw = os.environ.get('PR_DASH_REPOS')
specs = raw.split(',') if raw is not None else list(_DEFAULT_EXTRA_REPOS)
for spec in specs:
spec_nwo, _, spec_path = spec.partition('=')
spec_nwo = spec_nwo.strip()
if '/' not in spec_nwo or spec_nwo in seen:
continue
seen.add(spec_nwo)
extra_owner, extra_name = spec_nwo.split('/', 1)
repos.append(
{
'nwo': spec_nwo,
'owner': extra_owner,
'name': extra_name,
'path': spec_path.strip() or _detect_local_path(spec_nwo),
'primary': False,
}
)
if repos:
with _repos_lock:
_repos_state['repos'] = repos
return repos
def make_pr_key(nwo: str, branch: str) -> str:
"""Cache/row key for a PR. Branch names collide across repos, so scope by repo."""
return f'{nwo}#{branch}'
def get_current_user() -> str:
"""Get current GitHub username."""
if _repo_info['current_user']:
return _repo_info['current_user']
success, output = run_gh_command(['gh', 'api', 'user', '--jq', '.login'])
if success and output:
_repo_info['current_user'] = output.strip()
return _repo_info['current_user']
return ''
# Cache for batch PR data (refreshed each cycle)
_pr_cache: dict[str, dict] = {}
_pr_cache_lock = threading.Lock()
# Persistent PR cache that survives fetch failures (stale data fallback)
_last_successful_pr_cache: dict[str, dict] = {}
_last_successful_pr_cache_lock = threading.Lock()
# Persistent cache for conflict states (survives UNKNOWN responses from GitHub)
_conflict_cache: dict[str, bool] = {}
_conflict_cache_lock = threading.Lock()
# statusCheckRollup and comments are expensive GraphQL sub-queries: including them
# in a `gh pr list` over many open PRs makes GitHub return HTTP 504. They're fetched
# per-PR (cheap) and merged in instead — see _fetch_pr_heavy_fields.
_PR_HEAVY_FIELDS = ['statusCheckRollup', 'comments']
_PR_LIST_FIELDS = ','.join(
[
'number',
'title',
'state',
'isDraft',
'url',
'mergedAt',
'closedAt',
'updatedAt',
'createdAt',
'headRefName',
'headRefOid',
'reviewDecision',
'reviews',
'latestReviews',
'reviewRequests',
'statusCheckRollup',
'comments',
'mergeable',
]
)
_PR_LIST_FIELDS_LIGHT = ','.join(f for f in _PR_LIST_FIELDS.split(',') if f not in _PR_HEAVY_FIELDS)
_REVIEW_REQUEST_FIELDS = ','.join(
[
'number',
'title',
'state',
'isDraft',
'url',
'updatedAt',
'createdAt',
'headRefName',
'headRefOid',
'author',
'reviewDecision',
'reviews',
'latestReviews',
'reviewRequests',
'statusCheckRollup',
]
)
_REVIEW_REQUEST_FIELDS_LIGHT = ','.join(f for f in _REVIEW_REQUEST_FIELDS.split(',') if f not in _PR_HEAVY_FIELDS)
def _fetch_pr_list(cmd: list[str], max_age: float, force: bool = False) -> tuple[list[dict], bool]:
"""Reuse discovery snapshots between their polls, never caching failed responses."""
key = tuple(cmd)
with _fetch_cache_lock:
cached = _list_cache.get(key)
if cached and not force and time.monotonic() - cached[0] < max_age:
return deepcopy(cached[1]), True
with _fetch_cache_lock:
_list_cache.pop(key, None)
ok, output = run_gh_command(cmd)
if not ok:
return [], False
try:
prs = json.loads(output)
except json.JSONDecodeError:
return [], False
if not isinstance(prs, list) or not all(isinstance(pr, dict) for pr in prs):
return [], False
with _fetch_cache_lock:
_store_snapshot(_list_cache, key, (time.monotonic(), prs))
return prs, True
def _fetch_pr_heavy_fields(
nwo: str, pr_number: str, fields: list[str] | None = None, expected_head: str = ''
) -> tuple[str, dict] | None:
"""Fetch only the expensive fields whose cached snapshots need revalidation."""
fields = _PR_HEAVY_FIELDS if fields is None else fields
ok, detail = run_gh_command(
['gh', 'pr', 'view', pr_number, '--repo', nwo, '--json', ','.join(['number', 'headRefOid', *fields])]
)
if ok and detail:
try:
data = json.loads(detail)
if isinstance(data, dict) and all(
field in data and isinstance(data[field], (list, type(None))) for field in fields
):
if expected_head and data.get('headRefOid') != expected_head:
return None
return pr_number, {field: data[field] for field in fields}
except json.JSONDecodeError:
pass
if rate_limited_until():
return None
rest_data = _fetch_rest_pr_details(nwo, pr_number, fields=','.join(fields))
if not rest_data or (expected_head and rest_data.get('headRefOid') != expected_head):
return None
return pr_number, {field: rest_data[field] for field in fields}
def _enrich_open_pr(nwo: str, pr: dict, include_comments: bool = True, force: bool = False) -> dict:
"""Invalidate comments on PR activity, but poll CI independently of updatedAt."""
full = dict(pr)
number = str(pr['number'])
head = str(pr.get('headRefOid') or '')
fields = _PR_HEAVY_FIELDS if include_comments else ['statusCheckRollup']
due: list[str] = []
revisions: dict[str, tuple[str, ...]] = {}
for field in fields:
revision = (head,) if field == 'statusCheckRollup' else (head, str(pr.get('updatedAt') or ''))
revisions[field] = revision
with _fetch_cache_lock:
cached = _field_cache.get((nwo, number, field))
if cached:
cached_revision, fetched_at, data = cached
# Never carry CI for a previous head onto a newly pushed commit.
if cached_revision[0] == head:
full.update(deepcopy(data))
rollup = data.get('statusCheckRollup')
settled = rollup and all(
(ctx.get('status') or '').upper() == 'COMPLETED'
or (ctx.get('__typename') == 'StatusContext' and ctx.get('state') in ('SUCCESS', 'FAILURE', 'ERROR'))
for ctx in rollup
if ctx
)
if field == 'statusCheckRollup' and not rollup:
# Repositories without CI should not be polled as perpetually running.
# Allow two minutes for checks to register after recent PR activity.
changed_at = parse_timestamp(pr.get('updatedAt'))
settled = changed_at is None or (datetime.now(timezone.utc) - changed_at).total_seconds() >= 120
max_age = _ACTIVE_CI_INTERVAL if field == 'statusCheckRollup' and not settled else _SETTLED_INTERVAL
if not force and head and cached_revision == revision and time.monotonic() - fetched_at < max_age:
continue
due.append(field)
if due:
result = _fetch_pr_heavy_fields(nwo, number, due, expected_head=head)
if result is None:
full['_details_stale'] = True
# A failed forced refresh must retry too, even if the old snapshot's
# normal TTL has not expired. Keep its data, but not its freshness.
with _fetch_cache_lock:
for field in due:
key = (nwo, number, field)
cached = _field_cache.get(key)
if cached:
_store_snapshot(_field_cache, key, (cached[0], time.monotonic() - _SETTLED_INTERVAL, cached[2]))
else:
full.update(result[1])
with _fetch_cache_lock:
for field in due:
_store_snapshot(
_field_cache,
(nwo, number, field),
(revisions[field], time.monotonic(), {field: result[1][field]}),
)
return full
def _fetch_search_pr_numbers(nwo: str, query: str, max_pages: int = 1) -> tuple[list[str], bool]:
"""Find PR numbers through GitHub's conditionally revalidated REST search API."""
numbers: list[str] = []
for page in range(1, max_pages + 1):
params = urlencode(
{'q': f'repo:{nwo} {query}', 'per_page': 100, 'page': page, 'sort': 'updated', 'order': 'desc'}
)
data = _fetch_rest_json(f'search/issues?{params}')
if not isinstance(data, dict) or not isinstance(data.get('items'), list) or data.get('incomplete_results'):
return [], False
if not all(isinstance(item, dict) and isinstance(item.get('number'), int) for item in data['items']):
return [], False
page_numbers = [str(item['number']) for item in data['items']]
numbers.extend(page_numbers)
if len(page_numbers) < 100:
break
return numbers, True
def _fetch_authored_pr_numbers(nwo: str, state: str, username: str) -> tuple[list[str], bool]:
"""Find authored PR numbers with REST when the gh author filter is unavailable."""
if not username:
return [], False
return _fetch_search_pr_numbers(nwo, f'is:pr is:{state} author:{username}', max_pages=2)
def _fetch_rest_page(endpoint: str) -> tuple[dict | list, dict[str, str]] | None:
"""Revalidate REST pages with ETags; authenticated 304s spend no primary quota."""
with _fetch_cache_lock:
cached = _rest_cache.get(endpoint)
cmd = ['gh', 'api', endpoint, '--include']
if cached and cached[0].get('etag'):
cmd.extend(['--header', f'If-None-Match: {cached[0]["etag"]}'])
ok, output = run_gh_command(cmd)
if not ok:
return None
headers_text, separator, body = output.replace('\r\n', '\n').partition('\n\n')
lines = headers_text.splitlines()
status = lines[0].split()[1:2] if lines else []
headers = {name.lower(): value.strip() for line in lines[1:] if ':' in line for name, value in [line.split(':', 1)]}
if status == ['304'] and cached:
# Retain Link as well as the body: a 304 need not repeat pagination headers.
headers = {**cached[0], **headers}
with _fetch_cache_lock:
_store_snapshot(_rest_cache, endpoint, (headers, cached[1]))
return deepcopy(cached[1]), headers
if status != ['200'] or not separator:
return None
try:
value = json.loads(body)
except json.JSONDecodeError:
return None
if not isinstance(value, (dict, list)):
return None
with _fetch_cache_lock:
_store_snapshot(_rest_cache, endpoint, (headers, value))
return value, headers
def _fetch_rest_json(endpoint: str) -> dict | list | None:
"""Fetch one JSON resource through GitHub's REST API."""
page = _fetch_rest_page(endpoint)
return page[0] if page else None
def _fetch_rest_items(endpoint: str, jq: str = '.[]') -> list[dict] | None:
"""Revalidate each REST page; a failed page is never a successful partial list."""
items: list[dict] = []
for _ in range(20):
page = _fetch_rest_page(endpoint)
if page is None:
return None
value, headers = page
values = value.get('check_runs') if isinstance(value, dict) and jq == '.check_runs[]' else value
if not isinstance(values, list) or not all(isinstance(item, dict) for item in values):
return None
items.extend(values)
next_page = re.search(r'<([^>]+)>;\s*rel="next"', headers.get('link', ''))
if not next_page:
return items
url = urlsplit(next_page.group(1))
if url.scheme != 'https' or url.netloc != 'api.github.com':
return None
endpoint = url.path.lstrip('/') + ('?' + url.query if url.query else '')
return None
def _fetch_rest_pr_details(nwo: str, pr_number: str, enrich: bool = True, fields: str | None = None) -> dict | None:
"""Build the requested PR fields from REST, without unrelated enrichment calls."""
wanted = set((fields if fields is not None else _PR_LIST_FIELDS if enrich else '').split(','))
basic = _fetch_rest_json(f'repos/{nwo}/pulls/{pr_number}')
if not isinstance(basic, dict):
return None
head = basic.get('head') or {}
head_sha = head.get('sha', '')
mergeable = basic.get('mergeable')
if mergeable is True:
mergeable = 'MERGEABLE'
elif mergeable is False:
mergeable = 'CONFLICTING'
mapped_reviews = []
comments = []
check_runs = []
if wanted.intersection(('reviews', 'latestReviews')):
reviews = _fetch_rest_items(f'repos/{nwo}/pulls/{pr_number}/reviews?per_page=100')
if reviews is None:
return None
mapped_reviews = [
{
'author': {'login': (review.get('user') or {}).get('login', '')},
'state': review.get('state'),
'submittedAt': review.get('submitted_at'),
'body': review.get('body', ''),
}
for review in reviews
]
if 'comments' in wanted:
for endpoint in (
f'repos/{nwo}/issues/{pr_number}/comments?per_page=100',
f'repos/{nwo}/pulls/{pr_number}/comments?per_page=100',
):
fetched_comments = _fetch_rest_items(endpoint)
if fetched_comments is None:
return None
for comment in fetched_comments:
comments.append(
{
'author': {'login': (comment.get('user') or {}).get('login', '')},
'createdAt': comment.get('created_at'),
'updatedAt': comment.get('updated_at'),
}
)
if 'statusCheckRollup' in wanted and head_sha:
checks = _fetch_rest_items(f'repos/{nwo}/commits/{head_sha}/check-runs?per_page=100', '.check_runs[]')
if checks is None:
return None
for check in checks:
check_runs.append(
{
'__typename': 'CheckRun',
'name': check.get('name', ''),
'workflowName': (check.get('app') or {}).get('name', ''),
'status': check.get('status'),
'conclusion': check.get('conclusion'),
'detailsUrl': check.get('html_url', ''),
'completedAt': check.get('completed_at'),
'startedAt': check.get('started_at'),
}
)
requested = basic.get('requested_reviewers') or []
review_requests = []
for reviewer in requested:
if reviewer.get('login'):
review_requests.append({'login': reviewer['login']})
elif reviewer.get('name'):
review_requests.append({'__typename': 'Team', 'name': reviewer['name']})
return {
'number': basic.get('number'),
'title': basic.get('title', ''),
'state': basic.get('state'),
'author': {'login': (basic.get('user') or {}).get('login', '')},
'isDraft': basic.get('draft', False),
'url': basic.get('html_url', ''),
'mergedAt': basic.get('merged_at'),
'closedAt': basic.get('closed_at'),
'updatedAt': basic.get('updated_at'),
'createdAt': basic.get('created_at'),
'headRefName': head.get('ref', ''),
'headRefOid': head_sha,
'reviewDecision': None,
'reviews': mapped_reviews,
'latestReviews': [],
'reviewRequests': review_requests,
'statusCheckRollup': check_runs,
'comments': comments,
'mergeable': mergeable,
}
def _fetch_pr_details(args: tuple[str, str, str]) -> dict | None:
"""Fetch one PR's requested fields from GraphQL, falling back to REST."""
nwo, pr_number, fields = args
ok, detail = run_gh_command(['gh', 'pr', 'view', pr_number, '--repo', nwo, '--json', fields])
if ok and detail:
try:
return json.loads(detail)
except json.JSONDecodeError:
pass
if rate_limited_until():
# The GraphQL bucket is gone; five REST calls per PR would only take the REST one with it.
return None
return _fetch_rest_pr_details(nwo, pr_number, fields=fields)
def _closed_pr_details(nwo: str, pr: dict, force: bool = False) -> dict | None:
"""A closed PR's full record: the light list fields plus checks and comments.
Reuse details while updatedAt is unchanged, unless the user forces a refresh."""
number = str(pr.get('number'))
updated_at = str(pr.get('updatedAt') or '')
key = (nwo, number)
with _closed_pr_cache_lock:
cached = _closed_pr_cache.get(key)
if cached and cached[0] == updated_at and not force:
return dict(cached[1])
heavy = _fetch_pr_heavy_fields(nwo, number)
if not heavy:
with _closed_pr_cache_lock:
_closed_pr_cache.pop(key, None)
return {**pr, '_details_stale': True}
full = {**pr, **heavy[1]}
with _closed_pr_cache_lock:
_store_snapshot(_closed_pr_cache, key, (updated_at, full))
return full
def fetch_user_prs(force: bool = False) -> tuple[dict[str, dict], bool]:
"""Fetch relevant PRs authored by the current user across all configured repos.
Returns (key_to_pr dict, open_fetch_success bool) where the key is
"owner/name#branch" (see make_pr_key). Success is True only when the open-PR
fetch succeeded for every repo, so a stale repo can't silently drop rows.
"""
repos = get_repos()
if not repos:
return {}, False
all_prs: dict[str, dict] = {}
all_success = True
with ThreadPoolExecutor(max_workers=len(repos)) as executor:
for prs, ok in executor.map(lambda repo: _fetch_user_prs_for_repo(repo, force=force), repos):
all_prs.update(prs)
all_success = all_success and ok
return all_prs, all_success
def _fetch_user_prs_for_repo(repo: dict, force: bool = False) -> tuple[dict[str, dict], bool]:
"""Fetch the current user's PRs for a single repo.
Includes open PRs, closed-but-unmerged PRs, and recently merged PRs (last 30 days).
The open discovery list is authoritative. Expensive fields are revalidated only
when due or invalidated; closed discovery is slower and supplementary.
"""
nwo = repo['nwo']
current_user = get_current_user()
all_prs: dict[str, dict] = {}
debug = os.environ.get('PR_DASH_DEBUG', os.environ.get('WORKTREES_DEBUG', '')).lower() in ('1', 'true', 'yes')
raw_open, open_success = _fetch_pr_list(
[
'gh',
'pr',
'list',
'--repo',
nwo,
'--author',
'@me',
'--state',
'open',
'--limit',
'200',
'--json',
_PR_LIST_FIELDS_LIGHT,
],
_METADATA_INTERVAL,
force=force,
)
if not open_success:
open_numbers, fallback_success = _fetch_authored_pr_numbers(nwo, 'open', current_user)
if fallback_success:
open_success = True
with ThreadPoolExecutor(max_workers=_parallel_workers()) as executor:
raw_open = [
pr
for pr in executor.map(
_fetch_pr_details,
[(nwo, number, _PR_LIST_FIELDS_LIGHT) for number in open_numbers],
)
if pr
]
open_success = len(raw_open) == len(open_numbers)
if debug:
print(f'[fetch] {nwo}: REST fallback found {len(raw_open)} open PRs')
elif debug:
print(f'[fetch] {nwo}: open PR fetch failed, including REST fallback')
closed_force = force
if open_success:
numbers = {pr['number'] for pr in raw_open if pr.get('number') is not None}
with _fetch_cache_lock:
previous = _open_pr_numbers.get(nwo, numbers)
_open_pr_numbers[nwo] = numbers
# A PR leaving the open list must appear as closed/merged immediately, not
# disappear until the slower closed discovery poll catches up.
closed_force = force or bool(previous - numbers)
with ThreadPoolExecutor(max_workers=_parallel_workers()) as executor:
for raw_pr in executor.map(
lambda pr: _enrich_open_pr(nwo, pr, force=force),
[pr for pr in raw_open if pr.get('headRefName') and pr.get('number') is not None],
):
branch = raw_pr['headRefName']
parsed = _parse_pr(raw_pr, current_user, repo)
if parsed:
all_prs[make_pr_key(nwo, branch)] = parsed
# Closed discovery normally runs every ten minutes, or when a PR leaves the open list.
merged_cutoff = datetime.now(timezone.utc) - timedelta(days=30)
raw_closed, closed_success = _fetch_pr_list(
[
'gh',
'pr',
'list',
'--repo',
nwo,
'--author',
'@me',
'--state',
'closed',
'--limit',
'200',
'--json',
_PR_LIST_FIELDS_LIGHT,
],
_CLOSED_LIST_INTERVAL,
force=closed_force,
)
relevant_closed: list[dict] = []
if closed_success:
try:
for pr in raw_closed:
if not isinstance(pr, dict) or not pr.get('headRefName') or pr.get('number') is None:
continue
merged_at = pr.get('mergedAt')
if not merged_at:
relevant_closed.append(pr)
else:
merged_time = parse_timestamp(merged_at)
if merged_time and merged_time >= merged_cutoff:
relevant_closed.append(pr)
except (json.JSONDecodeError, KeyError, TypeError):
closed_success = False
if not closed_success and not rate_limited_until():
# GraphQL list failed for a reason other than quota: find the numbers through REST search
# and take each PR's basic record (one REST call each, no checks or comments).
numbers, search_success = _fetch_authored_pr_numbers(nwo, 'closed', current_user)
if search_success:
closed_success = True
if debug:
print(f'[fetch] {nwo}: using REST fallback for closed PR discovery')
with ThreadPoolExecutor(max_workers=_parallel_workers()) as executor:
for raw_pr in executor.map(lambda n: _fetch_rest_pr_details(nwo, n, enrich=False), numbers[:20]):
if not raw_pr or not raw_pr.get('headRefName'):
continue
merged_at = raw_pr.get('mergedAt')
if merged_at:
merged_time = parse_timestamp(merged_at)
if not merged_time or merged_time < merged_cutoff:
continue
relevant_closed.append(raw_pr)
if closed_success:
if debug:
print(f'[fetch] {nwo}: found {len(relevant_closed)} closed/recently-merged PRs')
def _closed_row(pr: dict) -> tuple[str, dict] | None:
full = _closed_pr_details(nwo, pr, force=force)
if not full:
return None
branch = full.get('headRefName', '')
parsed = _parse_pr(full, current_user, repo) if branch else None
return (make_pr_key(nwo, branch), parsed) if parsed else None
with ThreadPoolExecutor(max_workers=_parallel_workers()) as executor:
for result in executor.map(_closed_row, relevant_closed):
if result and result[0] not in all_prs:
all_prs[result[0]] = result[1]
elif debug:
print(f'[fetch] {nwo}: closed PR fetch failed, including REST fallback')
return all_prs, open_success
def fetch_review_requests(force: bool = False) -> tuple[list[dict], bool]:
"""Fetch PRs needing review and recently reviewed by the current user, across repos.
Returns pending review requests (direct + team-based) and open PRs
the user has already reviewed. Each entry is tagged with review_status
('pending'/'reviewed') and is_direct_request so the frontend can filter:
active-only mode shows only pending direct requests.
"""
current_user = get_current_user()
repos = get_repos()
if not repos:
return [], False
pending_prs: list[dict] = []
all_success = True
with ThreadPoolExecutor(max_workers=len(repos)) as executor:
for prs, ok in executor.map(lambda repo: _fetch_review_requests_for_repo(repo, force=force), repos):
pending_prs.extend(prs)
all_success = all_success and ok
if not all_success:
return [], False
pending_prs.sort(key=lambda p: p.get('updatedAt', ''), reverse=True)
results = []
for pr in pending_prs:
repo = pr.get('_repo', {})
check_runs = parse_status_check_rollup(pr.get('statusCheckRollup'))
ci_symbol, ci_class, ci_url = get_ci_status_summary(check_runs)
author = pr.get('author', {})
author_login = author.get('login', '') if author else ''
approvers = []
all_reviewers = set()
user_approved = False
all_reviews = list(pr.get('reviews', []) or []) + list(pr.get('latestReviews', []) or [])
for review in all_reviews:
if not review:
continue
reviewer = review.get('author', {})
username = reviewer.get('login', '') if reviewer else ''
if not username or is_bot_user(username):
continue
if username.lower() == current_user.lower():
if review.get('state') == 'APPROVED':
user_approved = True
continue
all_reviewers.add(username)
if review.get('state') == 'APPROVED':
approvers.append(username)
approvers = list(dict.fromkeys(approvers))
approvers_set = set(approvers)
pending_reviewers = []
for req in pr.get('reviewRequests', []) or []:
if not req or req.get('__typename') == 'Team':
continue
username = req.get('login') or req.get('name', '')
if not username or is_bot_user(username) or username.lower() == current_user.lower():
continue
pending_reviewers.append(username)
pending_reviewers = list(dict.fromkeys(pending_reviewers))
pending_set = set(pending_reviewers)
commented_reviewers = [u for u in all_reviewers if u not in approvers_set and u not in pending_set]
updated_dt = parse_timestamp(pr.get('updatedAt'))
updated_at = format_relative_time(updated_dt) if updated_dt else ''
results.append(
{
'number': pr.get('number'),
'title': pr.get('title', ''),
'url': pr.get('url', ''),
'branch': pr.get('headRefName', ''),
'repo': repo.get('nwo', ''),
'repo_label': repo.get('name', ''),
'is_primary_repo': repo.get('primary', True),
'pr_key': make_pr_key(repo.get('nwo', ''), str(pr.get('number', ''))),
'author': author_login,
'isDraft': pr.get('isDraft', False),
'ci_symbol': ci_symbol,
'ci_class': ci_class,
'ci_url': ci_url,
'check_runs': check_runs,
'updated_at': updated_at,
'approvers': approvers,
'pending_reviewers': pending_reviewers,
'commented_reviewers': commented_reviewers,