-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitgraph.py
More file actions
executable file
·5849 lines (5261 loc) · 260 KB
/
Copy pathgitgraph.py
File metadata and controls
executable file
·5849 lines (5261 loc) · 260 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
"""gg (gitgraph) - GitHub issue / PR / comment / @mention relation graph rendered as ASCII.
Usage:
gg [777] the TUI (default), optionally starting on #777 (also owner/repo#777, @login)
gg tutorial the TUI with the guided tour
gg graph [777] [--hops 2] text graph: overview of open items, or the neighbourhood of one item
gg show 777 details of one node
gg ask 4563 "why does it mention #3859?" # one-shot question to claude with the item as context
gg update update this installation from GitHub
gg ai [NAME] list / pick the AI CLI (claude, codex, gemini, grok, …)
gg config [KEY [VALUE]] show / set persistent settings (~/.config/gitgraph/config.json)
gg todo print the markdown of everything marked with m in the tui
gg todo done|remove ID tick off / delete a mark (ID: 750, #750, owner/name#750, comment url); clear-done drops ticked ones
gg check [-r owner/name] diagnose: gh accounts for the host, access, open counts, GraphQL fields
gg mcp MCP stdio server for Claude Code in another window (claude mcp add -s user gg -- gg mcp)
gg cache [clear all|items|ai|logs|REPO] what is stored locally (issue/PR bodies, AI results, logs) and how to remove it
Only dependency: the `gh` CLI (authenticated). No pip packages.
"""
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import time
import unicodedata
from collections import defaultdict, deque
from datetime import datetime, timezone
VERSION = "0.21.0"
REPO_URL = "https://github.com/Daejun/gitgraph"
RAW_URL = "https://raw.githubusercontent.com/Daejun/gitgraph/main/gitgraph.py"
CACHE_DIR = os.path.expanduser("~/.cache/gitgraph")
CONFIG_PATH = os.path.expanduser("~/.config/gitgraph/config.json")
# key -> (env var, default, help)
CONFIG_KEYS = {
"claude_bin": ("GITGRAPH_CLAUDE", "claude", "AI CLI used for translation / summaries / questions: claude, codex, "
"gemini, grok, or any binary taking -p PROMPT — pick with `gg ai`"),
"repos": ("GITGRAPH_REPOS", "", "default repos, comma separated (owner/name or host/owner/name)"),
"me": ("GITGRAPH_ME", "", "logins that count as \"me\", comma separated (default: gh accounts)"),
"lang": ("GITGRAPH_LANG", "Korean", "language for translations, summaries and answers"),
"translate": ("GITGRAPH_TRANSLATE", "zh", "zh | all | none"),
"tr_model": ("GITGRAPH_TR_MODEL", "haiku", "model for translation / summaries (claude only)"),
"ask_model": ("GITGRAPH_ASK_MODEL", "sonnet", "model for `a` / `gg ask` (claude only)"),
"batch": ("GITGRAPH_BATCH", "10", "tui: nodes per translate/summary call"),
"ai_parallel": ("GITGRAPH_AI_PARALLEL", "3", "tui: how many AI CLI calls may run at the same time"),
"retries": ("GITGRAPH_RETRIES", "3", "gh api retries on transient network errors"),
"fetch_parallel": ("GITGRAPH_FETCH_PARALLEL", "8", "how many gh queries run at the same time when filling the cache"),
"theme": ("GITGRAPH_THEME", "dark", "colour theme: dark | light | basic (8 colours, no dim — e.g. PuTTY)"),
"todo_file": ("GITGRAPH_TODO", "~/gitgraph-todo.md", "markdown written from the marks made with m in the tui (for the next session)"),
"side_width": ("GITGRAPH_SIDE_WIDTH", "0.4", "tui: fraction of the width for the side column"),
"expand_focused": ("GITGRAPH_EXPAND_FOCUSED", "true", "tui: give the focused side panel more height (accordion)"),
"expanded_weight": ("GITGRAPH_EXPANDED_WEIGHT", "2", "tui: how much taller the focused side panel is"),
"screen_mode": ("GITGRAPH_SCREEN_MODE", "normal", "tui: normal | half | full (+ / _ cycle at runtime)"),
"border": ("GITGRAPH_BORDER", "rounded", "tui: rounded | single | double | bold | hidden"),
}
def load_config():
try:
with open(CONFIG_PATH) as f:
return json.load(f)
except (OSError, json.JSONDecodeError):
return {}
CONFIG = load_config()
def cfg(key):
"""CLI option (handled by the caller) > environment variable > config file > built-in default."""
env, default, _ = CONFIG_KEYS[key]
return os.environ.get(env) or str(CONFIG.get(key, "") or "") or default
def save_config():
os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
with open(CONFIG_PATH, "w") as f:
json.dump(CONFIG, f, indent=2, ensure_ascii=False)
def ai_cmd(args):
"""gg ai list the AI CLIs gg knows, which are installed, which is selected; pick one by number
gg ai NAME select NAME (claude | codex | gemini | grok | any binary that takes -p PROMPT)"""
import shutil
known = ["claude", "codex", "gemini", "grok"]
cur = cfg("claude_bin")
if args:
choice = args[0]
if not shutil.which(choice):
print(f"{choice}: not found in PATH", file=sys.stderr)
return 1
CONFIG["claude_bin"] = choice
save_config()
print(f"AI CLI = {choice} ({AI_BACKENDS.get(ai_backend(choice), ('generic: -p PROMPT', ''))[0]})")
return 0
rows = []
for name in known:
path = shutil.which(name)
how, login = AI_BACKENDS[name]
rows.append((name, path, how, login))
if cur not in known and shutil.which(cur):
rows.append((cur, shutil.which(cur), "generic: -p PROMPT", ""))
print("AI CLIs for translation / summaries / questions:\n")
for i, (name, path, how, login) in enumerate(rows, 1):
mark = "*" if name == cur else " "
state = path or "not installed"
print(f" {mark}{i}) {name:8} {state:32} {how}" + (f" (login: {login})" if login and path else ""))
print(f"\n* = current ({cur}). Choose a number to switch, Enter to keep: ", end="", flush=True)
try:
with open("/dev/tty") as tty:
ans = tty.readline().strip()
except OSError:
ans = ""
if ans.isdigit() and 1 <= int(ans) <= len(rows):
name, path, how, login = rows[int(ans) - 1]
if not path:
print(f"{name} is not installed", file=sys.stderr)
return 1
CONFIG["claude_bin"] = name
save_config()
print(f"AI CLI = {name}")
return 0
def config_cmd(args):
"""gg config show everything and where each value comes from
gg config KEY VALUE store VALUE in ~/.config/gitgraph/config.json
gg config KEY show one value
gg config unset KEY remove it from the file"""
if not args:
for k, (env, default, help_) in CONFIG_KEYS.items():
src = "env" if os.environ.get(env) else ("config" if CONFIG.get(k) else "default")
print(f"{k:12} = {cfg(k) or '(empty)':24} [{src:7}] {help_}")
print(f"\nfile: {CONFIG_PATH} (env var wins over the file; CLI options win over both)")
return 0
if args[0] == "unset":
key = args[1] if len(args) > 1 else ""
if key not in CONFIG_KEYS:
print(f"unknown key {key!r}; keys: {', '.join(CONFIG_KEYS)}", file=sys.stderr)
return 1
CONFIG.pop(key, None)
else:
key = args[0]
if key not in CONFIG_KEYS:
print(f"unknown key {key!r}; keys: {', '.join(CONFIG_KEYS)}", file=sys.stderr)
return 1
if len(args) == 1:
print(cfg(key))
return 0
CONFIG[key] = " ".join(args[1:])
os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
with open(CONFIG_PATH, "w") as f:
json.dump(CONFIG, f, indent=2, ensure_ascii=False)
print(f"{key} = {cfg(key) or '(unset)'} -> {CONFIG_PATH}")
return 0
ENV_REPOS = [r.strip() for r in cfg("repos").split(",") if r.strip()]
PAGE = 50
ME = [m.strip().lower() for m in cfg("me").split(",") if m.strip()]
ENRICH_BATCH = int(cfg("batch")) # tui: nodes per translate/summary call
AI_PARALLEL = max(1, int(cfg("ai_parallel") or 3)) # concurrent AI CLI calls
def log(msg):
sys.stderr.write(f"[gitgraph] {msg}\n")
sys.stderr.flush()
PROGRESS = None # optional callable(phase, done, total, detail) — the TUI installs one
def progress(phase, done, total=None, detail=""):
if PROGRESS:
PROGRESS(phase, done, total, detail)
# --------------------------------------------------------------------------
# repo discovery: git repos under the directory gg was started in
# --------------------------------------------------------------------------
DEFAULT_HOST = "github.com"
_REMOTE_RE = re.compile(r"^(?:https?://(?:[^@/]+@)?|ssh://(?:[^@/]+@)?|[^@/]+@)?(?P<host>[\w.-]+)(?::\d+)?[:/]"
r"(?P<owner>[\w.-]+)/(?P<name>[\w.-]+?)(?:\.git)?/?$")
def split_repo(repo):
"""'owner/name' -> (github.com, owner, name); 'ghe.example.com/owner/name' -> (host, owner, name)."""
parts = repo.split("/")
if len(parts) >= 3:
return parts[0], parts[1], "/".join(parts[2:])
return DEFAULT_HOST, parts[0], parts[1] if len(parts) > 1 else ""
def make_repo(host, owner, name):
return f"{owner}/{name}" if host == DEFAULT_HOST else f"{host}/{owner}/{name}"
def qualify(repo, host):
"""A bare 'owner/name' seen inside a repo on `host` belongs to that host."""
return repo if len(repo.split("/")) >= 3 or host == DEFAULT_HOST else f"{host}/{repo}"
def repo_host(repo):
return split_repo(repo)[0]
def discover_repos(root, depth=2):
"""[(owner/name, dir)] for the repo containing root plus git repos up to `depth` levels below it."""
dirs = []
r = subprocess.run(["git", "-C", root, "rev-parse", "--show-toplevel"], capture_output=True, text=True)
if r.returncode == 0 and r.stdout.strip():
dirs.append(r.stdout.strip())
root = os.path.abspath(root)
for dirpath, dirnames, filenames in os.walk(root):
level = dirpath[len(root):].count(os.sep)
if ".git" in dirnames or ".git" in filenames:
dirs.append(dirpath)
dirnames[:] = []
continue
if level >= depth:
dirnames[:] = []
continue
dirnames[:] = sorted(d for d in dirnames if not d.startswith("."))
best = {} # repo -> dir (shallowest wins; a dir named like the repo wins ties)
for d in dict.fromkeys(dirs):
for rank_remote, repo in github_remotes(d):
rank = (d.count(os.sep), rank_remote, os.path.basename(d) != split_repo(repo)[2], d)
if repo not in best or rank < best[repo][0]:
best[repo] = (rank, d)
return sorted(((repo, d) for repo, (rank, d) in best.items()), key=lambda x: best[x[0]][0])
def is_github_host(host):
"""github.com, any host with 'github' in its name (Enterprise), or a host gh is logged in to."""
host = host.lower()
return host == DEFAULT_HOST or "github" in host or host in gh_hosts()
_ssh_hosts = {}
def resolve_ssh_alias(host):
"""'gh-work' (an alias in ~/.ssh/config) -> its real HostName, via `ssh -G`; hosts with a dot are returned as is."""
if "." in host or host in _ssh_hosts:
return _ssh_hosts.get(host, host)
real = host
try:
r = subprocess.run(["ssh", "-G", host], capture_output=True, text=True, timeout=5)
for line in r.stdout.splitlines():
if line.startswith("hostname "):
real = line.split(None, 1)[1].strip()
break
except (OSError, subprocess.TimeoutExpired):
pass
_ssh_hosts[host] = real
return real
SKIPPED_REMOTES = [] # (dir, remote name, url, reason) — shown when nothing usable was found
_ACCT_IN_HELPER = re.compile(r"username=([A-Za-z0-9](?:[A-Za-z0-9-]*))|(?:auth token\s+)?-u\s+([A-Za-z0-9](?:[A-Za-z0-9-]*))")
def git_account_hint(d, host, url=""):
"""Which gh account this checkout uses for `host`, from its own git config: the standard
credential.<host>.username, a gh credential helper that names one (`gh auth token -u LOGIN`, what
`gh auth setup-git -u` writes), or a user@ in the remote URL. None when nothing says so.
Worth reading because the active gh account is often not the one a private repo is shared with, and
this is known before the first API call — the cache in accounts.json only learns it after one."""
m = re.match(r"https?://([^@/]+)@", url or "")
hinted = [m.group(1)] if m else []
r = subprocess.run(["git", "-C", d, "config", "--get-regexp",
r"^credential\.https://" + re.escape(host) + r"\."], capture_output=True, text=True)
for line in r.stdout.splitlines():
key, _, val = line.partition(" ")
if key.endswith(".username"):
hinted.insert(0, val.strip())
elif key.endswith(".helper"):
mm = _ACCT_IN_HELPER.search(val)
if mm:
hinted.append(mm.group(1) or mm.group(2))
known = gh_accounts(host)
return next((h for h in hinted if h in known), None)
def github_remotes(d):
"""[(rank, repo)] for every remote of the git repo at d whose URL points at a GitHub host.
rank: 0 = origin, 1 = a remote named github*, 2 = anything else."""
r = subprocess.run(["git", "-C", d, "remote", "-v"], capture_output=True, text=True)
if r.returncode != 0:
return []
out, seen = [], set()
for line in r.stdout.splitlines():
parts = line.split()
if len(parts) < 2 or (len(parts) > 2 and parts[2] != "(fetch)"):
continue
name, url = parts[0], parts[1]
m = _REMOTE_RE.match(url)
if not m:
SKIPPED_REMOTES.append((d, name, url, "URL not understood"))
continue
host = resolve_ssh_alias(m.group("host").lower())
if not is_github_host(host):
SKIPPED_REMOTES.append((d, name, url, f"host {host!r} is not github.com / github.* / a gh-logged-in host"))
continue
repo = make_repo(host, m.group("owner"), m.group("name"))
if repo in seen:
continue
seen.add(repo)
hint = git_account_hint(d, host, url)
if hint: # a first guess for graphql(); anything already verified in accounts.json wins
_pref_map().setdefault(host, {}).setdefault(repo, hint)
out.append((0 if name == "origin" else 1 if name.lower().startswith("github") else 2, repo))
return sorted(out)
def choose_repos(cands):
"""Ask on the terminal which of several discovered repos to use. Returns a list."""
home = os.path.expanduser("~")
lines = [f"gg: several GitHub repos under {os.getcwd().replace(home, '~')}:"]
for i, (repo, d) in enumerate(cands, 1):
lines.append(f" {i}) {repo} ({d.replace(home, '~')})")
lines.append(" a) all of them (first one is primary)")
sys.stderr.write("\n".join(lines) + "\nchoose [1]: ")
sys.stderr.flush()
try:
with open("/dev/tty") as tty:
ans = tty.readline().strip().lower()
except OSError:
ans = ""
if ans in ("a", "all"):
return [c[0] for c in cands]
picks = []
for tok in re.split(r"[\s,]+", ans or "1"):
if tok.isdigit() and 1 <= int(tok) <= len(cands):
picks.append(cands[int(tok) - 1][0])
return picks or [cands[0][0]]
_parent_cache = {}
def parent_repo(repo):
"""If repo is a fork, the repo it was forked from (owner/name or host/owner/name); else None."""
if repo in _parent_cache:
return _parent_cache[repo]
host, owner, name = split_repo(repo)
res = None
try:
d = graphql("query($o:String!,$n:String!){ repository(owner:$o,name:$n){ isFork parent{ nameWithOwner } } }",
{"o": owner, "n": name}, host)
r = (d or {}).get("repository") or {}
if r.get("isFork") and r.get("parent"):
res = qualify(r["parent"]["nameWithOwner"], host)
except GhError:
pass
_parent_cache[repo] = res
return res
def unfork(repos):
"""Replace forks by their parents (a clone's `origin` is usually the fork; the issues/PRs live upstream)."""
out = []
for repo in repos:
parent = parent_repo(repo)
if parent:
if parent not in out:
log(f"{repo} is a fork of {parent}; using {parent} (pass -r {repo} to look at the fork itself)")
out.append(parent)
elif repo not in out:
out.append(repo)
return out
def seed_account_hints(repos, d=None):
"""For repos named on the command line (or in $GITGRAPH_REPOS) there is no discovery step, so look
for their checkouts the same way discovery does — the repo we are standing in (from any depth) plus
the ones a couple of levels below — and read the account each one uses from its git config. Only a
first guess: a verified account in accounts.json wins, and a wrong guess costs the one fallback it
costs today. Skipped entirely once every repo has a remembered account (i.e. after the first run)."""
if not repos:
return
if not all((_pref_map().get(repo_host(r)) or {}).get(r) for r in repos):
for repo, checkout in discover_repos(d or os.getcwd()):
host = repo_host(repo)
hint = git_account_hint(checkout, host)
if hint:
_pref_map().setdefault(host, {}).setdefault(repo, hint)
# what the primary repo uses is also the best guess for the repos it references (stubs)
primary = repos[0]
fav = (_pref_map().get(repo_host(primary)) or {}).get(primary)
if fav:
_acct_hint[repo_host(primary)] = fav
def resolve_repos(explicit=None, interactive=False):
"""-r > $GITGRAPH_REPOS > repos found under cwd (ask if several; forks -> their parent)."""
if explicit:
seed_account_hints(explicit)
return list(explicit)
if ENV_REPOS:
seed_account_hints(ENV_REPOS)
return ENV_REPOS
cands = discover_repos(os.getcwd())
cands = [(r, d) for r, d in cands]
if not cands:
home = os.path.expanduser("~")
seen = "\n".join(f" {d.replace(home, '~')}: {name} {url} — {why}" for d, name, url, why in SKIPPED_REMOTES[:12])
raise ValueError(f"no GitHub repo found under {os.getcwd().replace(home, '~')} (this directory and 2 levels below)"
+ (f"\n remotes seen but skipped:\n{seen}" if seen else "\n no git remotes found here")
+ "\n -> pass -r owner/name, set GITGRAPH_REPOS, or run inside the repo")
if len(cands) == 1:
picked = unfork([cands[0][0]])
seed_account_hints(picked)
return picked
if interactive:
picked = unfork(choose_repos(cands))
seed_account_hints(picked)
return picked
raise ValueError("several repos under " + os.getcwd() + ": " + ", ".join(c[0] for c in cands)
+ " — pass repos=[\"owner/name\", ...]")
# --------------------------------------------------------------------------
# gh access (with multi-account fallback for private repos)
# --------------------------------------------------------------------------
class GhError(Exception):
pass
_accounts = None # host -> [login, ...] (active first)
_tokens = {}
def gh_accounts(host=None):
"""Login names gh knows for `host` (active first); host=None -> every host, github.com first."""
global _accounts
if _accounts is None:
r = subprocess.run(["gh", "auth", "status"], capture_output=True, text=True)
by_host, cur = {}, None
for line in (r.stdout + r.stderr).splitlines():
m = re.search(r"Logged in to (\S+) account (\S+)", line)
if m:
cur = (m.group(1), m.group(2))
by_host.setdefault(cur[0], []).append(cur[1])
elif "Active account: true" in line and cur:
by_host[cur[0]].remove(cur[1])
by_host[cur[0]].insert(0, cur[1])
_accounts = by_host
if host:
return list(_accounts.get(host, []))
return list(_accounts.get(DEFAULT_HOST, [])) + [a for h, l in _accounts.items() if h != DEFAULT_HOST for a in l]
def gh_hosts():
gh_accounts()
return set(_accounts or {})
def gh_token(user, host=DEFAULT_HOST):
key = (host, user)
if key in _tokens:
return _tokens[key]
r = subprocess.run(["gh", "auth", "token", "-h", host, "-u", user], capture_output=True, text=True)
tok = r.stdout.strip() or None
_tokens[key] = tok
return tok
# Bare "502|503|504" used to be in here, which made any error mentioning such a number transient —
# "Could not resolve to an issue or pull request with the number of 4503" then cost 2+4+8s of retries.
TRANSIENT_RE = re.compile(r"TLS handshake timeout|connection reset|i/o timeout|timeout|EOF|"
r"temporarily unavailable|no such host|HTTP 5\d\d|"
r"bad gateway|service unavailable|server error", re.I)
GH_RETRIES = int(cfg("retries"))
def gh_api(args, body, env):
"""`gh api …` with retries on transient network errors (TLS handshake timeout, resets, 5xx)."""
for attempt in range(GH_RETRIES + 1):
r = subprocess.run(["gh", "api"] + args, input=body, capture_output=True, text=True, env=env)
err = (r.stderr or "").strip()
if r.returncode == 0 or not TRANSIENT_RE.search(err) or attempt == GH_RETRIES:
return r
wait = 2 ** (attempt + 1)
log(f"gh: {err.splitlines()[-1][:120]} — retrying in {wait}s ({attempt + 1}/{GH_RETRIES})")
progress("fetch", 0, None, f"network error, retry {attempt + 1}/{GH_RETRIES} in {wait}s")
time.sleep(wait)
return r
_acct_pref = None # {host: {repo: login}} — which account could actually see a repo, across runs
_acct_hint = {} # {host: login} — this run's guess from git config, for repos we know nothing about
def _accounts_path():
return os.path.join(CACHE_DIR, "accounts.json") # resolved per call, like the other caches
def _pref_map():
global _acct_pref
if _acct_pref is None:
_acct_pref = read_json(_accounts_path()) or {}
return _acct_pref
def _query_repo(query, variables):
"""owner/name the query is about, for remembering which account can see it."""
if variables and variables.get("owner") and variables.get("name"):
return f"{variables['owner']}/{variables['name']}"
m = re.search(r'repository\(owner:"([^"]+)",\s*name:"([^"]+)"\)', query)
return f"{m.group(1)}/{m.group(2)}" if m else None
def _prefer_account(host, user, repo=None):
"""Remember the account that could see this repo: first in this process, then in the cache, so the
next run does not spend a round trip discovering it again (the active gh account is often not the
one a private repo is shared with)."""
if _accounts and user in _accounts.get(host, []):
_accounts[host].remove(user)
_accounts[host].insert(0, user)
if not repo or not user:
return
d = _pref_map().setdefault(host, {})
if d.get(repo) != user:
d[repo] = user
try:
write_json(_accounts_path(), _acct_pref)
except OSError:
pass
def graphql(query, variables=None, host=DEFAULT_HOST):
"""Run a GraphQL query through `gh api graphql` against `host` (github.com or a GitHub Enterprise host).
If the active account gets NOT_FOUND (private repo not visible), retry
with the other accounts registered for that host; the account that works
is moved to the front for the rest of the process.
"""
accts = gh_accounts(host) or [None]
repo = _query_repo(query, variables)
fav = (_pref_map().get(host) or {}).get(repo) or _acct_hint.get(host)
if fav in accts and accts[0] != fav: # the account that saw this repo last time
accts = [fav] + [a for a in accts if a != fav]
body = json.dumps({"query": query, "variables": variables or {}})
last_err = None
for i, acct in enumerate(accts):
env = dict(os.environ)
if acct:
tok = gh_token(acct, host)
if not tok:
continue
env["GH_TOKEN"] = tok
env["GH_ENTERPRISE_TOKEN"] = tok
r = gh_api(["graphql", "--hostname", host, "--input", "-"], body, env)
try:
data = json.loads(r.stdout) if r.stdout.strip() else {}
except json.JSONDecodeError:
data = {}
errs = data.get("errors") or []
if not errs and r.returncode == 0:
if (_pref_map().get(host) or {}).get(repo) != acct:
_prefer_account(host, acct, repo)
return data.get("data", {})
types = {e.get("type") for e in errs}
partial = data.get("data") or {}
if errs and types <= {"NOT_FOUND"} and any(v is not None for v in partial.values()):
# partial NOT_FOUND (e.g. one alias in a stub batch): usable; a null repository is not
if (_pref_map().get(host) or {}).get(repo) != acct:
_prefer_account(host, acct, repo)
return data.get("data", {})
last_err = errs or r.stderr.strip() or f"gh exit {r.returncode}"
if "NOT_FOUND" in types or "Could not resolve" in (r.stderr or ""):
continue # try next account
if TRANSIENT_RE.search(r.stderr or ""):
raise GhError(f"cannot reach {host}: {r.stderr.strip().splitlines()[-1][:160]}\n"
" check: `gh api user` works? proxy needed (export HTTPS_PROXY=http://host:port)? "
"VPN/DNS? retries: GITGRAPH_RETRIES (default 3)")
break
if isinstance(last_err, list) and last_err and all(e.get("type") == "NOT_FOUND" for e in last_err):
msg = last_err[0].get("message", "not found")
raise GhError(f"{msg} on {host} with any gh account ({', '.join(gh_accounts(host)) or 'none logged in — gh auth login -h ' + host})")
raise GhError(f"graphql failed: {last_err}")
# --------------------------------------------------------------------------
# fetch + cache
# --------------------------------------------------------------------------
COMMENT_FIELDS = "databaseId url author{login} body createdAt"
CROSSREF_FIELDS = """
timelineItems(first:100, itemTypes:[CROSS_REFERENCED_EVENT]){ nodes{
... on CrossReferencedEvent{ createdAt source{ __typename
... on Issue{ number title state createdAt author{login} repository{nameWithOwner} }
... on PullRequest{ number title state isDraft createdAt author{login} repository{nameWithOwner} } } } } }
"""
ISSUE_FIELDS = f"""
number title state body createdAt updatedAt url author{{login}} labels(first:10){{nodes{{name}}}}
comments(first:100){{ totalCount nodes{{ {COMMENT_FIELDS} }} }}
{CROSSREF_FIELDS}
"""
PR_FIELDS = ISSUE_FIELDS + f"""
isDraft closingIssuesReferences(first:20){{nodes{{number repository{{nameWithOwner}}}}}}
reviews(first:50){{ nodes{{ databaseId url author{{login}} body state createdAt
comments(first:50){{ nodes{{ {COMMENT_FIELDS} }} }} }} }}
"""
Q_ISSUES = f"""
query($owner:String!,$name:String!,$after:String,$states:[IssueState!]) {{
repository(owner:$owner,name:$name){{
issues(first:{PAGE}, after:$after, states:$states, orderBy:{{field:CREATED_AT,direction:DESC}}){{
pageInfo{{hasNextPage endCursor}} nodes{{ {ISSUE_FIELDS} }} }} }} }}
"""
Q_PRS = f"""
query($owner:String!,$name:String!,$after:String,$states:[PullRequestState!]) {{
repository(owner:$owner,name:$name){{
pullRequests(first:{PAGE}, after:$after, states:$states, orderBy:{{field:CREATED_AT,direction:DESC}}){{
pageInfo{{hasNextPage endCursor}} nodes{{ {PR_FIELDS} }} }} }} }}
"""
def _login(a):
return (a or {}).get("login") or "ghost"
def _norm_comment(c, kind, review_state=None):
return {"id": f"c{c.get('databaseId')}", "author": _login(c.get("author")),
"body": c.get("body") or "", "created": c.get("createdAt"),
"url": c.get("url"), "kind": kind, "review_state": review_state}
def _norm_item(repo, n, is_pr):
comments = [_norm_comment(c, "comment") for c in n["comments"]["nodes"]]
if is_pr:
for rv in n.get("reviews", {}).get("nodes", []):
if (rv.get("body") or "").strip():
comments.append(_norm_comment(rv, "review", rv.get("state")))
for rc in rv.get("comments", {}).get("nodes", []):
comments.append(_norm_comment(rc, "review_comment", rv.get("state")))
comments.sort(key=lambda c: c["created"] or "")
crossrefs = []
for ev in n["timelineItems"]["nodes"]:
s = (ev or {}).get("source") or {}
if not s.get("number"):
continue
crossrefs.append({"repo": s["repository"]["nameWithOwner"], "number": s["number"],
"is_pr": s["__typename"] == "PullRequest", "title": s.get("title"),
"state": s.get("state"), "draft": s.get("isDraft", False),
"created": s.get("createdAt"), "author": _login(s.get("author")),
"when": ev.get("createdAt")})
closes = []
if is_pr:
for c in n.get("closingIssuesReferences", {}).get("nodes", []):
closes.append({"repo": c["repository"]["nameWithOwner"], "number": c["number"]})
return {"repo": repo, "number": n["number"], "is_pr": is_pr, "title": n["title"],
"state": n["state"], "draft": n.get("isDraft", False), "body": n.get("body") or "",
"created": n["createdAt"], "updated": n["updatedAt"], "url": n["url"],
"author": _login(n.get("author")), "labels": [l["name"] for l in n["labels"]["nodes"]],
"comments": comments, "comments_total": n["comments"]["totalCount"],
"crossrefs": crossrefs, "closes": closes}
Q_LIST = """
query($owner:String!,$name:String!,$after:String,$states:[IssueState!]) {
repository(owner:$owner,name:$name){ issues(first:100, after:$after, states:$states,
orderBy:{field:CREATED_AT,direction:DESC}){
pageInfo{hasNextPage endCursor} nodes{ number updatedAt } } } }
"""
Q_LIST_PR = """
query($owner:String!,$name:String!,$after:String,$states:[PullRequestState!]) {
repository(owner:$owner,name:$name){ pullRequests(first:100, after:$after, states:$states,
orderBy:{field:CREATED_AT,direction:DESC}){
pageInfo{hasNextPage endCursor} nodes{ number updatedAt } } } }
"""
ITEM_BATCH = 10 # numbers per query when only a few items changed
MAX_ITEM_BATCH = 25 # cold start: how many may share one query (bigger = fewer `gh` processes)
FETCH_PARALLEL = max(1, int(cfg("fetch_parallel") or 8)) # concurrent `gh api graphql` queries
def list_open(repo):
"""{(is_pr, number): updatedAt} for every open issue and PR — light queries (no bodies). The issue
and pull-request connections are independent, so they are paged at the same time; only the pages
within one connection have to be sequential (each needs the previous cursor)."""
from concurrent.futures import ThreadPoolExecutor
host, owner, name = split_repo(repo)
def page_all(q, is_pr):
res, after = {}, None
while True:
d = graphql(q, {"owner": owner, "name": name, "after": after, "states": ["OPEN"]}, host)
conn = (d.get("repository") or {}).get("pullRequests" if is_pr else "issues")
if conn is None:
raise GhError(f"{repo}: repository not found on {host}")
for n in conn["nodes"]:
res[(is_pr, n["number"])] = n["updatedAt"]
if not conn["pageInfo"]["hasNextPage"]:
return res
after = conn["pageInfo"]["endCursor"]
out = {}
with ThreadPoolExecutor(max_workers=2) as pool:
for res in pool.map(lambda a: page_all(*a), ((Q_LIST, False), (Q_LIST_PR, True))):
out.update(res)
return out
def fetch_batch(repo, is_pr, numbers):
"""One query: the full records of these issue (or PR) numbers."""
host, owner, name = split_repo(repo)
fields = PR_FIELDS if is_pr else ISSUE_FIELDS
kind = "pullRequest" if is_pr else "issue"
aliases = " ".join(f"n{n}: {kind}(number:{n}){{ {fields} }}" for n in numbers)
d = graphql(f'query {{ repository(owner:"{owner}", name:"{name}") {{ {aliases} }} }}', host=host)
rep_ = d.get("repository") or {}
return [_norm_item(repo, rep_[f"n{n}"], is_pr) for n in numbers if rep_.get(f"n{n}")]
def fetch_items(repo, is_pr, numbers, note="changed items", spread=False, on_batch=None):
return fetch_groups(repo, [(is_pr, numbers)], note, spread, on_batch)
def fetch_groups(repo, groups, note="items", spread=False, on_batch=None):
"""Full records (bodies, comments, cross references) of the given issue or PR numbers: one query per
batch of numbers, FETCH_PARALLEL queries in flight (each batch is an independent query, so this is
where a cold start gets its speed — pagination cannot be parallelised, batches can).
Every query is a `gh` process, and that costs ~0.4s before any network happens, so `spread` (the
cold start) makes the batches as large as it can while still filling every parallel slot — a few
big queries beat many small ones. The incremental refresh keeps ITEM_BATCH: there the item count is
small and the batches are what limits the response size."""
from concurrent.futures import ThreadPoolExecutor
host, owner, name = split_repo(repo)
total = sum(len(nums) for _, nums in groups)
size = ITEM_BATCH
if spread: # one query per parallel slot rather than many small ones (each is a `gh` process)
size = max(ITEM_BATCH, min(MAX_ITEM_BATCH, -(-total // FETCH_PARALLEL)))
batches = [(is_pr, nums[i:i + size]) for is_pr, nums in groups for i in range(0, len(nums), size)]
done = [0]
def fetch(job):
out = fetch_batch(repo, job[0], job[1])
done[0] += len(job[1])
progress("fetch", done[0], total, f"{repo}: {note}")
if on_batch:
on_batch(out) # from a worker thread: the caller may draw what has arrived
return out
if len(batches) <= 1 or FETCH_PARALLEL <= 1:
return [it for job in batches for it in fetch(job)]
with ThreadPoolExecutor(max_workers=min(FETCH_PARALLEL, len(batches))) as pool:
return [it for part in pool.map(fetch, batches) for it in part] # in order; raises on failure
def refresh_items(repo, cached, on_batch=None):
"""Incremental update of the open items of a repo: only items whose updatedAt moved (or new ones) are fetched
again; items that are no longer open are dropped. Returns (items, n_changed, n_dropped)."""
listing = list_open(repo)
by_key = {(it["is_pr"], it["number"]): it for it in cached}
changed = [k for k, u in listing.items() if k not in by_key or (by_key[k].get("updated") or "") < u]
dropped = [k for k in by_key if k not in listing]
log(f"{repo}: {len(listing)} open, {len(changed)} changed, {len(dropped)} closed since the last fetch")
progress("fetch", 0, len(changed) or None, f"{repo}: {len(changed)} changed")
fresh = {}
for is_pr in (False, True):
nums = sorted(n for p, n in changed if p == is_pr)
if nums:
for it in fetch_items(repo, is_pr, nums, on_batch=on_batch):
fresh[(it["is_pr"], it["number"])] = it
items = [fresh.get(k) or by_key[k] for k in listing if k in fresh or k in by_key]
items.sort(key=lambda it: it["created"], reverse=True)
return items, len(changed), len(dropped)
def fetch_open_streaming(repo, on_batch=None):
"""Every open issue/PR of a repo, with the listing and the record fetch overlapped: each page of
numbers (100 at a time, and the pages of a connection have to be walked in order) is handed to the
record pool as soon as it lands, so the first records are already being fetched while the last
pages are still being listed."""
from concurrent.futures import ThreadPoolExecutor
host, owner, name = split_repo(repo)
futures, done, lock = [], [0], __import__("threading").Lock()
pool = ThreadPoolExecutor(max_workers=FETCH_PARALLEL)
def records(is_pr, batch):
out = fetch_batch(repo, is_pr, batch)
with lock:
done[0] += len(batch)
n = done[0]
progress("fetch", n, None, f"{repo}: items")
if on_batch:
on_batch(out)
return out
def page_and_submit(q, is_pr):
after = None
while True:
d = graphql(q, {"owner": owner, "name": name, "after": after, "states": ["OPEN"]}, host)
conn = (d.get("repository") or {}).get("pullRequests" if is_pr else "issues")
if conn is None:
raise GhError(f"{repo}: repository not found on {host}")
nums = sorted((n["number"] for n in conn["nodes"]), reverse=True)
for i in range(0, len(nums), MAX_ITEM_BATCH):
futures.append(pool.submit(records, is_pr, nums[i:i + MAX_ITEM_BATCH]))
if not conn["pageInfo"]["hasNextPage"]:
return
after = conn["pageInfo"]["endCursor"]
try:
with ThreadPoolExecutor(max_workers=2) as lister: # the two connections are independent
list(lister.map(lambda a: page_and_submit(*a), ((Q_LIST, False), (Q_LIST_PR, True))))
return [it for f in futures for it in f.result()] # in submission order; raises on failure
finally:
pool.shutdown()
def fetch_repo(repo, state, on_batch=None):
"""Every issue/PR of a repo, for a cold cache. For the usual state="open" this lists the open
numbers first (one cheap query per 100) and then pulls the records in parallel batches; a full
`--state all` build still pages through the heavy connection query."""
if state == "open":
items = fetch_open_streaming(repo, on_batch)
items.sort(key=lambda it: it["created"], reverse=True)
if not items:
log(f"{repo}: no open issues or PRs came back — run `gg check -r {repo}` to see why")
return items
host, owner, name = split_repo(repo)
items = []
for q, is_pr, states in ((Q_ISSUES, False, ["OPEN"]), (Q_PRS, True, ["OPEN"])):
after = None
while True:
vars_ = {"owner": owner, "name": name, "after": after,
"states": states if state == "open" else None}
data = graphql(q, vars_, host)
if not data.get("repository"):
raise GhError(f"{repo}: repository not found on {host} with any gh account "
f"({', '.join(gh_accounts(host)) or 'none logged in'})")
conn = data["repository"]["issues" if not is_pr else "pullRequests"]
for n in conn["nodes"]:
items.append(_norm_item(repo, n, is_pr))
log(f"{repo}: fetched {len(items)} items so far")
progress("fetch", len(items), None, repo)
if not conn["pageInfo"]["hasNextPage"]:
break
after = conn["pageInfo"]["endCursor"]
if not items:
log(f"{repo}: no {'open ' if state == 'open' else ''}issues or PRs came back — run `gg check -r {repo}` to see why")
return items
def _cache_path(kind, repo, state=""):
os.makedirs(CACHE_DIR, exist_ok=True)
return os.path.join(CACHE_DIR, f"{kind}__{repo.replace('/', '__')}{'__' + state if state else ''}.json")
def load_items(repo, state, max_age_min, refresh=False, on_batch=None):
"""Cached items of a repo. Within max_age they are used as they are; after that (state=open) only what changed on
GitHub is fetched again; --refresh forces a full fetch."""
p = _cache_path("items", repo, state)
cached = None
if not refresh and os.path.exists(p):
with open(p) as f:
d = json.load(f)
if time.time() - d["fetched_at"] < max_age_min * 60:
return d["items"], d["fetched_at"]
cached = d["items"]
if cached is not None and state == "open":
try:
items, _, _ = refresh_items(repo, cached, on_batch=on_batch)
with open(p, "w") as f:
json.dump({"fetched_at": time.time(), "repo": repo, "state": state, "items": items}, f)
secure(p)
return items, time.time()
except GhError as e:
log(f"{repo}: incremental refresh failed ({e}); fetching everything")
items = fetch_repo(repo, state, on_batch=on_batch)
with open(p, "w") as f:
json.dump({"fetched_at": time.time(), "repo": repo, "state": state, "items": items}, f)
secure(p)
return items, time.time()
STUB_BATCH = 50
def resolve_stubs(repo, numbers, max_age_min):
"""Look up title/state for referenced-but-unfetched items of one repo, cached per repo."""
return resolve_stubs_many({repo: numbers}, max_age_min).get(repo, {})
def resolve_stubs_many(by_repo, max_age_min):
"""{repo: numbers} -> {repo: {number: info}}, cached per repo under stubs__<repo>.json.
Every repo's batches go through one pool, FETCH_PARALLEL queries at a time: a repo that references
hundreds of closed items used to look them up STUB_BATCH at a time, one query after another, which
was the last sequential stretch of a cold start (8s of a 21s build on a 584-item repo)."""
from concurrent.futures import ThreadPoolExecutor
now = time.time()
caches, jobs = {}, []
for repo, numbers in by_repo.items():
cache = read_json(_cache_path("stubs", repo)) or {}
caches[repo] = cache
need = [n for n in numbers if str(n) not in cache
or now - cache[str(n)].get("fetched_at", 0) > max_age_min * 60]
for i in range(0, len(need), STUB_BATCH):
jobs.append((repo, need[i:i + STUB_BATCH]))
done = [0]
def fetch(job):
repo, batch = job
host, owner, name = split_repo(repo)
aliases = " ".join(
f'n{n}: issueOrPullRequest(number:{n}){{ __typename '
f'... on Issue{{ number title state createdAt body author{{login}} }} '
f'... on PullRequest{{ number title state isDraft createdAt body author{{login}} }} }}'
for n in batch)
q = f'query {{ repository(owner:"{owner}", name:"{name}") {{ {aliases} }} }}'
try:
data = graphql(q, host=host)
except GhError as e:
log(f"stub resolve failed for {repo}: {e}")
return repo, {}
rep = (data or {}).get("repository") or {}
out = {}
for n in batch:
s = rep.get(f"n{n}")
if s:
out[str(n)] = {"fetched_at": now, "is_pr": s["__typename"] == "PullRequest",
"title": s.get("title"), "state": s.get("state"),
"draft": s.get("isDraft", False), "created": s.get("createdAt"),
"author": _login(s.get("author")), "body": (s.get("body") or "")[:SUM_BODY_CHARS]}
else:
out[str(n)] = {"fetched_at": now, "missing": True}
done[0] += len(batch)
progress("stubs", done[0], sum(len(b) for _, b in jobs), repo)
return repo, out
if jobs:
with ThreadPoolExecutor(max_workers=min(FETCH_PARALLEL, len(jobs))) as pool:
for repo, part in pool.map(fetch, jobs):
caches[repo].update(part)
for repo in {r for r, _ in jobs}:
path = _cache_path("stubs", repo)
with open(path, "w") as f:
json.dump(caches[repo], f)
secure(path)
out = {}
for repo, numbers in by_repo.items():
want = {str(n) for n in numbers}
out[repo] = {int(k): v for k, v in caches[repo].items() if k in want}
return out
# --------------------------------------------------------------------------
# graph model
# --------------------------------------------------------------------------
FENCE_RE = re.compile(r"```.*?```", re.S)
REF_RE = re.compile(r"(?<![\w/])(?:(?P<repo>[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+))?#(?P<num>\d+)\b")
URL_RE = re.compile(r"https?://(?P<host>[A-Za-z0-9.-]+)/(?P<repo>[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)/(?:issues|pull)/(?P<num>\d+)")
MENTION_RE = re.compile(r"(?<![\w/`])@(?P<login>[A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))(?![\w-])")
# lines that are pasted kernel logs / stack traces: "#14" there is a build number, not an issue
NOISE_LINE_RE = re.compile(
r"^\s*(?:\[\s*\d+\.\d+\]|#\d+\s+0x[0-9a-f]+|.*\bPID:\s*\d+|.*\bTainted:|.*\bNot tainted\b"
r"|.*\bHardware name:|.*\bCall Trace\b|.*\bRIP:|.*\bWARNING:.*\bat\b|.*\bBUG:"
r"|.*\bPLATFORM\s+--|.*\bFSTYP\s+--|.*\bLinux/\w+ .*\d+\.\d+\.\d+)")
# "#N" with a tiny N is usually an ordinal ("overwrite #5", "attempt #2") unless a
# reference word precedes it or the repo is spelled out.
SMALL_REF = 20
REF_WORDS = {"pr", "prs", "issue", "issues", "pull", "see", "in", "of", "to", "by", "and", "with", "on",
"fixes", "fix", "fixed", "closes", "close", "resolves", "resolved", "than", "from", "at",
"ref", "refs", "cf", "via", "per", "like", "vs", "for", "as", "after", "before", "since"}
def _clean_lines(text):
text = FENCE_RE.sub(" ", text or "")
return [l for l in text.splitlines() if not NOISE_LINE_RE.match(l)]
def _plausible_small_ref(line, m, is_url=False):
if not is_url and m.group("repo"):
return True
words = re.findall(r"[A-Za-z0-9_]+", line[:m.start()])
if not words:
return is_url # a bare URL line is fine; a bare "#3" at line start is an ordinal
return words[-1].lower() in REF_WORDS
SNIPPET_CHARS = 160
def snippet(line, start, end):
"""The sentence-ish context around line[start:end], collapsed to one line of ~SNIPPET_CHARS."""
line = line.strip().lstrip("> ").strip()
if len(line) <= SNIPPET_CHARS:
return re.sub(r"\s+", " ", line)
a = max(0, start - SNIPPET_CHARS // 2)
b = min(len(line), end + SNIPPET_CHARS // 2)