-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-branches-graph
More file actions
executable file
·868 lines (732 loc) · 34.2 KB
/
git-branches-graph
File metadata and controls
executable file
·868 lines (732 loc) · 34.2 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
#!/usr/bin/env python3
"""
git_branches_graph.py
---------------------
Visualise relationships between Git branches.
The script:
1. Verifies it is executed inside a Git working tree.
2. Collects branch names either automatically (`git branch --format '%(refname:short)'`)
or from explicit user-supplied lists (CLI parameters or standard input).
Leading markers produced by `git branch` such as “* ” or “+ ” are stripped.
• Use --all/-a flag to include remote branches (similar to `git branch --all`)
• Use --tags/-T/--include-tags to include Git tags in addition to branches
3. For every pair of branches it finds their *nearest common ancestor* via
`git merge-base`.
• If the ancestor **commit** is pointed-to by an existing branch, that branch
name is used as the node label.
• Otherwise the commit is referred to by its shortest unique abbreviation
(`git rev-parse --short=<n>` is attempted, falling back to 7 chars).
4. Produces a simple *directed* graph where each common-ancestor node points to
the two (or more) branch tips that diverge from it.
5. Supports five output formats selectable with `--format`:
• mermaid (default) – “graph LR; A --> B;”
• dot/graphviz – “digraph { A -> B }”
• csv – “from,to”
• png – Renders to PNG via Graphviz
• html – Interactive HTML with pan/zoom using Mermaid
6. Prints to STDOUT, making it easy to pipe into `dot -Tpng`, `mmdc`, etc.
• Use --browser with HTML format to serve locally and open in browser
IMPORTANT NOTE about --all flag:
When multiple branches (local and/or remote) point to the same commit, only one
branch name will be shown in the graph for that commit. This is because the graph
uses commits as nodes, not branches. For example, if both 'master' and
'origin/master' point to commit abc123, the graph will show only one of these
branch names (typically the last one alphabetically) as the label for that node.
EXPERIMENTAL --cluster-same-commit flag:
This experimental feature groups branches pointing to the same commit into visual
clusters (subgraphs in Mermaid, clusters in Graphviz). This allows you to see ALL
branch names even when multiple branches point to the same commit. The branches are
grouped together in a box/cluster, making it clear they reference the same commit.
Note: This feature may produce more complex graphs and is still being refined.
Example
-------
# Auto-detect local branches and print Mermaid
./git_branches_graph.py
# Provide explicit branch names
./git_branches_graph.py feature/login bugfix/email --format dot
# Read branch names from STDIN (could be `git branch` output)
git branch | ./git_branches_graph.py --stdin -f csv
# Include remote branches in the graph
./git_branches_graph.py --all
# [EXPERIMENTAL] Show all branches in clusters when they point to same commit
./git_branches_graph.py --all --cluster-same-commit
# Generate interactive HTML with pan/zoom
./git_branches_graph.py --format html --output graph.html
# Open HTML directly in browser (serves on local server)
./git_branches_graph.py --format html --browser
"""
from __future__ import annotations
import argparse
import itertools
import os
import shlex
import subprocess
import sys
import http.server
import socketserver
import threading
import webbrowser
from pathlib import Path
from typing import Dict, Iterable, List, Set, Tuple
from collections import deque
# Repository path selected by --repo option; set in main()
GIT_REPO: Path | None = None
# --------------------------------------------------------------------------- #
# Helpers #
# --------------------------------------------------------------------------- #
def run_git(*args: str) -> str:
"""Run a git command (optionally inside --repo path) and return stdout stripped."""
cmd = ["git"]
if GIT_REPO is not None:
cmd += ["-C", str(GIT_REPO)]
cmd += list(args)
try:
out = subprocess.check_output(cmd, text=True)
except subprocess.CalledProcessError as exc:
sys.stderr.write(f"error: {' '.join(cmd)} failed: {exc}\n")
sys.exit(2)
return out.strip()
# --- new helper ----------------------------------------------------------- #
def _try_git_rev_parse(ref: str) -> str | None:
"""
Run `git rev-parse <ref>` but **do NOT exit** when it fails.
Returns the SHA (stripped) or None when the ref does not exist.
IMPORTANT: We suppress stderr to avoid confusing error messages when checking
if refs exist (which is expected to fail for many refs we try).
WHY THIS FUNCTION EXISTS:
- The main run_git() helper exits on failure, but we need to *test* if refs exist
- When resolving branch names, we try multiple ref paths until one works
- Each failed attempt would spam stderr with "fatal: ambiguous argument..." messages
- These errors confused users who thought something was broken
HOW IT WORKS:
- Runs git rev-parse to convert a ref to its SHA
- Suppresses stderr with DEVNULL to hide expected failures
- Returns None on failure instead of exiting
- This allows the calling code to try multiple ref paths silently
EXAMPLE: For 'origin/master', we might try:
1. refs/remotes/origin/master (succeeds, returns SHA)
2. refs/heads/origin/master (fails silently, returns None)
3. origin/master (would succeed but we already found it)
"""
cmd = ["git"]
if GIT_REPO is not None:
cmd += ["-C", str(GIT_REPO)]
cmd += ["rev-parse", ref]
try:
# Suppress stderr to avoid git error messages when refs don't exist
# This is critical - without stderr=DEVNULL, users see confusing errors
return subprocess.check_output(cmd, text=True, stderr=subprocess.DEVNULL).strip()
except subprocess.CalledProcessError:
# This is expected - many refs we try won't exist
return None
def resolve_name_to_commit(name: str) -> str:
"""
Resolve *name* to a commit SHA giving priority to the correct ref type.
The caller may pass a display-name ending with ' (tag)' produced by
--include-tags. That suffix is stripped before resolution and the
`refs/tags/…` namespace is tried first.
EDGE CASES HANDLED:
1. Remote branches like 'origin/master' need to be resolved as 'refs/remotes/origin/master'
not 'refs/remotes/origin/master' or 'refs/heads/origin/master'
2. Special case: 'origin' alone (refs/remotes/origin/HEAD) should be filtered out earlier
3. Tags are marked with ' (tag)' suffix and prioritized in refs/tags/ namespace
WHY THESE EDGE CASES MATTER:
- Git stores refs in different namespaces: heads/ for local, remotes/ for remote branches
- A name like 'origin/master' could theoretically exist as:
* refs/heads/origin/master (local branch with '/' in name)
* refs/remotes/origin/master (remote tracking branch - most common)
- Without proper ordering, we'd resolve to the wrong ref or fail entirely
- The original code tried refs/heads/origin/master first, causing "unknown revision" errors
HOW WE RESOLVE NAMES:
1. Tags marked with ' (tag)' suffix get priority in refs/tags/ namespace
2. Names with '/' are assumed to be remote branches (refs/remotes/) first
3. Then try as local branch (refs/heads/)
4. Then try as-is (could be full ref or SHA)
5. Finally try tags as fallback (unless already tried)
"""
is_tag = False
if name.endswith(" (tag)"):
base = name[:-6].rstrip() # strip trailing ' (tag)'
is_tag = True
else:
base = name
search_order: list[str] = []
if is_tag:
search_order.append(f"refs/tags/{base}") # tag first when user marked it
# WHY: Names containing '/' are almost always remote branches (origin/master)
# HOW: Check refs/remotes/ namespace first for these names
# This fixes the main issue where 'origin/master' was being checked as
# 'refs/heads/origin/master' (doesn't exist) instead of 'refs/remotes/origin/master'
if '/' in base and not base.startswith('refs/'):
# This looks like a remote branch (e.g., 'origin/master')
# Try it as a remote ref first
search_order.append(f"refs/remotes/{base}")
# always try branches / remotes in standard order
search_order += [
f"refs/heads/{base}",
base, # Try as-is (might already be a full ref or a commit SHA)
]
if not is_tag:
search_order.append(f"refs/tags/{base}") # tag last as generic fall-back
for ref in search_order:
sha = _try_git_rev_parse(ref)
if sha:
return sha
sys.stderr.write(f"fatal: could not resolve '{name}' to a commit\n")
sys.exit(1)
def ensure_git_repo() -> None:
"""Abort if we are not inside a git repository."""
try:
inside = run_git("rev-parse", "--is-inside-work-tree")
except SystemExit:
raise
except Exception:
inside = "false"
if inside != "true":
sys.stderr.write("fatal: not a git repository (or any of the parent directories)\n")
sys.exit(1)
def strip_branch_marker(name: str) -> str:
"""Remove markers such as '* ' or '+ ' added by `git branch` output."""
return name.lstrip("*+ ").strip()
def abbreviate_commit(commit: str) -> str:
"""Return shortest unique abbreviation; fall back to 7 chars."""
try:
return run_git("rev-parse", "--short", commit)
except Exception:
return commit[:7]
# --------------------------------------------------------------------------- #
# Graph computation #
# --------------------------------------------------------------------------- #
def collect_branches(use_stdin: bool, explicit: List[str], include_all: bool = False, include_tags: bool = False) -> List[str]:
"""
Collect branch names from various sources.
EDGE CASES HANDLED:
1. 'origin' without a branch name is refs/remotes/origin/HEAD - we filter this out
as it's not a real branch but a symbolic ref to the default remote branch
2. git branch output may include markers like '* ' or '+ ' which we strip
3. When --all is used, we get both local branches and remote branches like 'origin/master'
WHY THESE EDGE CASES EXIST:
- Git's 'branch --all' includes refs/remotes/origin/HEAD which appears as just 'origin'
- This causes errors later when we try to resolve 'origin' as refs/heads/origin
- Users don't expect to see 'origin' as a standalone branch in the graph
HOW WE HANDLE THEM:
- Strip git branch markers (* for current branch, + for worktree branch)
- Filter out bare remote names (no '/' character) that are known remotes
- This preserves actual branches named 'origin' while removing HEAD refs
"""
if use_stdin:
names = [strip_branch_marker(line) for line in sys.stdin.read().splitlines() if line.strip()]
elif explicit:
names = [strip_branch_marker(n) for n in explicit]
else:
# All local branches (or all branches if include_all is True)
if include_all:
raw = run_git("branch", "--all", "--format=%(refname:short)").splitlines()
else:
raw = run_git("branch", "--format=%(refname:short)").splitlines()
# Filter out problematic entries:
# - 'origin' alone is refs/remotes/origin/HEAD (symbolic ref to default branch)
# - Any other single remote name without '/' could be similar
names = []
for r in raw:
cleaned = strip_branch_marker(r).strip()
if cleaned:
# WHY: 'git branch --all' includes refs/remotes/origin/HEAD as 'origin'
# This is not a real branch, just a pointer to the default remote branch
# HOW: Skip entries that look like bare remote names (no slash)
# We check against known remote names to avoid filtering legitimate local branches
if include_all and '/' not in cleaned and cleaned in ['origin', 'upstream']:
continue
names.append(cleaned)
if include_tags:
tag_raw = run_git("tag", "--list").splitlines()
# mark them so they stay distinguishable in the graph
tag_names = [f"{t.strip()} (tag)" for t in tag_raw if t.strip()]
names += tag_names
if not names:
sys.stderr.write("error: no branches detected / specified\n")
sys.exit(1)
return sorted(set(names))
def map_branches_to_commits(branches: Iterable[str]) -> Dict[str, str]:
# OLD: return {br: run_git("rev-parse", br) for br in branches}
return {br: resolve_name_to_commit(br) for br in branches}
def common_ancestor(a_commit: str, b_commit: str) -> str | None:
"""
Return the merge-base of two commits or None if the commits have no
common ancestor (git exits with status 1 in that case).
"""
cmd: List[str] = ["git"]
if GIT_REPO is not None:
cmd += ["-C", str(GIT_REPO)]
cmd += ["merge-base", a_commit, b_commit]
try:
return subprocess.check_output(cmd, text=True).strip()
except subprocess.CalledProcessError:
# unrelated histories
return None
def build_graph(branch_commits: Dict[str, str], cluster_same_commit: bool = False) -> Tuple[Set[Tuple[str, str]], Dict[str, str], Dict[str, List[str]]]:
"""
Discover all common-ancestor vertices (recursively) and build the full edge
set. New ancestors discovered during the process are themselves compared
with every other vertex until no new vertices appear.
Returns:
edges: Set[(parent_label, child_label)]
node_labels: Map commit_sha -> chosen label
commit_branches: Map commit_sha -> list of branch names (for clustering)
"""
# Track all branches pointing to each commit
commit_branches: Dict[str, List[str]] = {}
for br, sha in branch_commits.items():
commit_branches.setdefault(sha, []).append(br)
# Initial labels (branch names for tips)
if cluster_same_commit:
# Use commit SHA as label when clustering
node_labels: Dict[str, str] = {sha: sha for sha in branch_commits.values()}
else:
# Use last branch name as label (original behavior)
node_labels: Dict[str, str] = {sha: br for br, sha in branch_commits.items()}
vertices: List[str] = list(branch_commits.values()) # queue-like list
edges: Set[Tuple[str, str]] = set()
idx = 0 # index of vertex to start pairing from
while idx < len(vertices):
current_subset = vertices[idx:]
idx = len(vertices) # next iteration will start where new vertices begin
# Compare every unordered pair within the current subset and all previous vertices
for sha1 in vertices:
for sha2 in current_subset:
if sha1 >= sha2: # ensure each unordered pair processed once
continue
anc = common_ancestor(sha1, sha2)
if not anc:
continue # unrelated histories
# register ancestor label (once)
if anc not in node_labels:
node_labels[anc] = abbreviate_commit(anc)
vertices.append(anc) # newly discovered, will be processed in later rounds
# add edges ancestor -> child (skip self-referential edges)
if node_labels[anc] != node_labels[sha1]:
edges.add((node_labels[anc], node_labels[sha1]))
if node_labels[anc] != node_labels[sha2]:
edges.add((node_labels[anc], node_labels[sha2]))
return edges, node_labels, commit_branches
# --------------------------------------------------------------------------- #
# Transitive reduction #
# --------------------------------------------------------------------------- #
def transitive_reduction(edges: Set[Tuple[str, str]]) -> Set[Tuple[str, str]]:
"""
Perform transitive reduction on a DAG represented by *edges*.
Removes every edge (u, v) for which an alternative path u ~~> v exists.
"""
# Build adjacency list
adj: Dict[str, Set[str]] = {}
for u, v in edges:
adj.setdefault(u, set()).add(v)
def reachable(src: str, dst: str, skip_edge: Tuple[str, str]) -> bool:
"""DFS reachability ignoring *skip_edge*."""
stack = [src]
seen = {src}
while stack:
u = stack.pop()
for w in adj.get(u, ()):
if (u, w) == skip_edge:
continue
if w == dst:
return True
if w not in seen:
seen.add(w)
stack.append(w)
return False
reduced: Set[Tuple[str, str]] = set()
for edge in edges:
u, v = edge
if not reachable(u, v, edge):
reduced.add(edge)
return reduced
# --------------------------------------------------------------------------- #
# Output renderers #
# --------------------------------------------------------------------------- #
def render_mermaid(edges: Set[Tuple[str, str]], node_labels: Dict[str, str] = None,
commit_branches: Dict[str, List[str]] = None, cluster_same_commit: bool = False) -> str:
lines = ["graph LR"]
if cluster_same_commit and commit_branches and node_labels:
# Track which commits we've already rendered in subgraphs
rendered_commits = set()
subgraph_counter = 0
# Create subgraphs for commits with multiple branches
for sha, branches in commit_branches.items():
if len(branches) > 1 and sha in node_labels:
subgraph_counter += 1
lines.append(f" subgraph cluster_{subgraph_counter}[\" \"]")
for branch in sorted(branches):
lines.append(f" {shlex.quote(branch)}[{shlex.quote(branch)}]")
lines.append(" end")
rendered_commits.add(sha)
# Render edges, using branch names for multi-branch commits
for parent, child in sorted(edges):
# Determine actual nodes to connect
parent_branches = []
child_branches = []
# Find branches for parent
for sha, branches in commit_branches.items():
if node_labels.get(sha) == parent:
parent_branches = branches if len(branches) > 1 else [parent]
break
if not parent_branches:
parent_branches = [parent]
# Find branches for child
for sha, branches in commit_branches.items():
if node_labels.get(sha) == child:
child_branches = branches if len(branches) > 1 else [child]
break
if not child_branches:
child_branches = [child]
# Connect all combinations
for p in parent_branches:
for c in child_branches:
lines.append(f" {shlex.quote(p)} --> {shlex.quote(c)}")
else:
# Original behavior
for parent, child in sorted(edges):
lines.append(f" {shlex.quote(parent)} --> {shlex.quote(child)}")
return "\n".join(lines)
def render_png(edges: Set[Tuple[str, str]], node_labels: Dict[str, str] = None,
commit_branches: Dict[str, List[str]] = None, cluster_same_commit: bool = False) -> bytes:
"""Render PNG via Graphviz `dot`."""
dot_src = render_dot(edges, node_labels, commit_branches, cluster_same_commit)
try:
# Pass graphviz DOT source as bytes and receive binary PNG data.
png_data = subprocess.check_output(
["dot", "-Tpng"],
input=dot_src.encode(),
)
except FileNotFoundError:
sys.stderr.write("error: graphviz `dot` executable not found. Install graphviz.\n")
sys.exit(2)
except subprocess.CalledProcessError as exc:
sys.stderr.write(f"error: dot failed: {exc}\n")
sys.exit(2)
return png_data
def render_dot(edges: Set[Tuple[str, str]], node_labels: Dict[str, str] = None,
commit_branches: Dict[str, List[str]] = None, cluster_same_commit: bool = False) -> str:
lines = ["digraph G {"]
lines.append(' rankdir="LR";') # Left to right layout like Mermaid
if cluster_same_commit and commit_branches and node_labels:
subgraph_counter = 0
# Create clusters for commits with multiple branches
for sha, branches in commit_branches.items():
if len(branches) > 1 and sha in node_labels:
subgraph_counter += 1
lines.append(f' subgraph cluster_{subgraph_counter} {{')
lines.append(' style="rounded,filled";')
lines.append(' fillcolor="lightgray";')
lines.append(f' label="";')
for branch in sorted(branches):
lines.append(f' "{branch}";')
lines.append(' }')
# Render edges
for parent, child in sorted(edges):
# Find branches for parent and child
parent_branches = []
child_branches = []
for sha, branches in commit_branches.items():
if node_labels.get(sha) == parent:
parent_branches = branches if len(branches) > 1 else [parent]
if node_labels.get(sha) == child:
child_branches = branches if len(branches) > 1 else [child]
if not parent_branches:
parent_branches = [parent]
if not child_branches:
child_branches = [child]
# Connect branches
for p in parent_branches:
for c in child_branches:
lines.append(f' "{p}" -> "{c}";')
else:
# Original behavior
for parent, child in sorted(edges):
lines.append(f' "{parent}" -> "{child}";')
lines.append("}")
return "\n".join(lines)
def render_csv(edges: Set[Tuple[str, str]]) -> str:
lines = ["from,to"]
lines += [f"{parent},{child}" for parent, child in sorted(edges)]
return "\n".join(lines)
def render_html(mermaid_content: str, template_path: str = "/home/gw-t490/d/25Q2/code/mermaid_html_template_with_zoom_and_panning.html") -> str:
"""Render HTML with embedded Mermaid diagram using the template."""
try:
# Read the template
template = Path(template_path).read_text()
# Find where to insert the Mermaid content
# The template has a placeholder diagram, we need to replace it
# Look for the mermaid div content
start_marker = '<div id="diagramContainer" class="mermaid">'
end_marker = '</div>'
start_idx = template.find(start_marker)
if start_idx == -1:
raise ValueError("Could not find mermaid container in template")
# Find the closing tag for this specific div
start_idx += len(start_marker)
end_idx = template.find(end_marker, start_idx)
if end_idx == -1:
raise ValueError("Could not find closing tag for mermaid container")
# Replace the content between the markers
html = template[:start_idx] + "\n " + mermaid_content + "\n " + template[end_idx:]
return html
except Exception as e:
sys.stderr.write(f"error: failed to render HTML: {e}\n")
sys.exit(2)
def serve_and_open_html(html_content: str, port: int = 0) -> None:
"""Start a local HTTP server and open the HTML in a browser."""
import tempfile
# Create a temporary directory for serving
with tempfile.TemporaryDirectory() as tmpdir:
html_path = Path(tmpdir) / "graph.html"
html_path.write_text(html_content)
# Find an available port
with socketserver.TCPServer(("", port), http.server.SimpleHTTPRequestHandler) as httpd:
actual_port = httpd.server_address[1]
url = f"http://localhost:{actual_port}/graph.html"
# Change to temporary directory for serving
os.chdir(tmpdir)
# Open browser in a separate thread
def open_browser():
import time
time.sleep(0.5) # Give server time to start
webbrowser.open(url)
browser_thread = threading.Thread(target=open_browser)
browser_thread.daemon = True
browser_thread.start()
print(f"Serving at {url}")
print("Press Ctrl+C to stop the server")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nServer stopped")
# --------------------------------------------------------------------------- #
# CLI #
# --------------------------------------------------------------------------- #
def parse_args(argv: List[str] | None = None) -> argparse.Namespace:
p = argparse.ArgumentParser(
description="Produce a simple graph (Mermaid, Graphviz, CSV) showing common ancestors of Git branches."
)
group = p.add_mutually_exclusive_group()
group.add_argument(
"-s", "--stdin",
action="store_true",
help="Read branch names from standard input (one per line, accepts raw `git branch` output)."
)
group.add_argument(
"-l", "--list",
metavar="LIST",
help="Comma-separated list of branch / tag names to include "
"(mutually exclusive with --stdin / --list-file / positional branches)."
)
group.add_argument(
"-L", "--list-file",
metavar="FILE",
help="Path to a text file containing branch / tag names (one per line). "
"Mutually exclusive with --stdin / --list / positional branches."
)
p.add_argument(
"branches",
nargs="*",
help="Branch names to include. If omitted all local branches are used.",
)
p.add_argument(
"-a",
"--all",
action="store_true",
help="Include remote branches in addition to local branches.",
)
p.add_argument(
"-T", "--tags", "--include-tags",
dest="include_tags",
action="store_true",
help="Include Git tags in addition to branches."
)
p.add_argument(
"-r",
"--repo",
default=".",
help="Path to a git repository to inspect (default: current directory).",
)
p.add_argument(
"-f",
"--format",
choices=("mermaid", "dot", "csv", "png", "html"),
default="mermaid",
help="Output format (default: mermaid).",
)
p.add_argument(
"-o",
"--output",
help="Write output to given file path. "
"When --format png and this flag is omitted the script "
"auto-creates graph.png / graph.<n>.png in the CWD.",
)
p.add_argument(
"-C",
"--cluster-same-commit",
action="store_true",
help="[EXPERIMENTAL] Group branches pointing to the same commit into clusters/subgraphs. "
"Shows all branch names instead of just one per commit.",
)
p.add_argument(
"-B",
"--browser",
action="store_true",
help="When using HTML format, start a local server and open in browser.",
)
p.add_argument(
"--no-transitive-reduction", "--full-graph",
dest="no_transitive_reduction",
action="store_true",
help="Skip transitive-reduction and keep every discovered edge "
"(graph may contain redundant paths)."
)
return p.parse_args(argv)
def _name_exists(name: str) -> bool:
"""
Return True if *name* exists as a branch, remote branch, loose ref or tag.
EDGE CASES HANDLED:
1. Remote branches like 'origin/master' should be checked as 'refs/remotes/origin/master'
2. Local branches are checked as 'refs/heads/branch-name'
3. Tags are checked as 'refs/tags/tag-name'
4. The name might already be a full ref or commit SHA
WHY THIS FUNCTION NEEDS SPECIAL HANDLING:
- Used by --list and --list-file options to validate user-provided branch names
- Must handle the same remote branch resolution issues as resolve_name_to_commit
- The original code checked refs/remotes/origin/master as refs/heads/origin/master
- This caused spurious "fatal: ambiguous argument" errors in stderr
HOW IT WORKS:
- Detects likely remote branches (contain '/' but aren't already full refs)
- Tries refs/remotes/ namespace first for these
- Falls back to standard order: local branches, as-is, then tags
- Uses _try_git_rev_parse to suppress error messages during checking
EXAMPLE RESOLUTION:
- 'master' → refs/heads/master (local branch)
- 'origin/master' → refs/remotes/origin/master (remote branch)
- 'v1.0' → refs/tags/v1.0 (tag)
- 'abc123' → abc123 (commit SHA)
"""
# WHY: Names with '/' are likely remote branches (origin/feature)
# HOW: Check refs/remotes/ first to avoid checking non-existent refs/heads/origin/feature
# This prevents the stderr errors that were confusing users
if '/' in name and not name.startswith('refs/'):
if _try_git_rev_parse(f"refs/remotes/{name}"):
return True
# Standard resolution order
for ref in (
f"refs/heads/{name}", # Local branch
name, # Already a full ref or commit SHA?
f"refs/tags/{name}", # Git tag
):
if _try_git_rev_parse(ref):
return True
return False
def main(argv: List[str] | None = None) -> None:
args = parse_args(argv)
# ---- choose exactly one source of names ---------------------------------
sources_used = sum((
bool(args.stdin),
bool(args.list),
bool(args.list_file),
bool(args.branches),
))
if sources_used > 1:
sys.stderr.write(
"error: --stdin, --list, --list-file and positional branch names "
"are mutually exclusive\n"
)
sys.exit(1)
# ------------------------------------------------------------------------
if args.list or args.list_file:
if args.list:
raw_names = [n.strip() for n in args.list.split(",") if n.strip()]
else: # --list-file
raw_names = [
ln.strip() for ln in Path(args.list_file).expanduser().read_text().splitlines()
if ln.strip()
]
# keep only names that exist (branch first, tag second)
filtered = [n for n in raw_names if _name_exists(n)]
# honour --include-tags switch (adds *labelled* tag nodes)
if args.include_tags:
tag_names = [
f"{t.strip()} (tag)"
for t in run_git("tag", "--list").splitlines()
if t.strip()
]
filtered.extend(tag_names)
if not filtered:
sys.stderr.write("error: no valid branches / tags found\n")
sys.exit(1)
branches = sorted(set(filtered))
else:
# original paths: stdin / positional / auto-detect
branches = collect_branches(
args.stdin,
args.branches,
args.all,
args.include_tags,
)
# If --browser is specified, default to HTML format unless explicitly overridden
if args.browser and args.format == "mermaid": # mermaid is the default
args.format = "html"
# If the first positional argument looks like a directory that is a git
# repository, treat it as the --repo path (for convenience).
if args.repo == "." and args.branches:
candidate_repo = Path(args.branches[0]).expanduser().resolve()
if candidate_repo.is_dir() and (candidate_repo / ".git").exists():
args.repo = str(candidate_repo)
args.branches = args.branches[1:]
global GIT_REPO
GIT_REPO = Path(args.repo).expanduser().resolve()
if not GIT_REPO.exists():
sys.stderr.write(f"fatal: path '{GIT_REPO}' does not exist\n")
sys.exit(1)
ensure_git_repo()
branch_commits = map_branches_to_commits(branches)
edges, node_labels, commit_branches = build_graph(branch_commits, args.cluster_same_commit)
if not args.no_transitive_reduction:
edges = transitive_reduction(edges)
def write_text(text: str) -> None:
if args.output:
Path(args.output).expanduser().write_text(text + "\n")
else:
sys.stdout.write(text + "\n")
if args.format == "mermaid":
write_text(render_mermaid(edges, node_labels, commit_branches, args.cluster_same_commit))
elif args.format == "dot":
write_text(render_dot(edges, node_labels, commit_branches, args.cluster_same_commit))
elif args.format == "csv":
write_text(render_csv(edges))
elif args.format == "html":
# Generate Mermaid content first
mermaid_content = render_mermaid(edges, node_labels, commit_branches, args.cluster_same_commit)
html_content = render_html(mermaid_content)
if args.browser:
# Serve and open in browser
serve_and_open_html(html_content)
else:
# Write to file or stdout
write_text(html_content)
else: # png
png_bytes = render_png(edges, node_labels, commit_branches, args.cluster_same_commit)
# Determine output path
if args.output:
out_path = Path(args.output).expanduser()
else:
suffix = ""
i = 0
while True:
candidate = Path(f"graph{suffix}.png")
if not candidate.exists():
out_path = candidate
break
i += 1
suffix = f".{i}"
out_path.write_bytes(png_bytes)
sys.stderr.write(f"INFO: created file '{out_path}' ({len(png_bytes)} bytes)\n")
if __name__ == "__main__":
main()