-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1794 lines (1561 loc) · 68.6 KB
/
app.py
File metadata and controls
1794 lines (1561 loc) · 68.6 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
"""Commit Explorer — Interactive TUI for exploring git repository history."""
import asyncio
import os
import re
import shutil
import sys
import tempfile
from abc import ABC, abstractmethod
from datetime import datetime, timezone, timedelta
from typing import NamedTuple, Optional
from urllib.parse import quote
import webbrowser
from dotenv import load_dotenv
from rich.markup import escape
from rich.text import Text
from textual import on, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.screen import Screen
from textual.containers import Horizontal, ScrollableContainer, Vertical
from textual.widget import Widget
from textual.widgets import (
Button,
Footer,
Header,
Input,
Label,
ListItem,
ListView,
LoadingIndicator,
Select,
Static,
)
load_dotenv(override=True)
# ── Types ─────────────────────────────────────────────────────────────────────
class CommitInfo(NamedTuple):
sha: str
short_sha: str
message: str
author: str
author_email: str
date: str # ISO format
parents: list[str]
class FileChange(NamedTuple):
filename: str
status: str # added, modified, removed, renamed, etc.
additions: int
deletions: int
class CommitDetail(NamedTuple):
info: CommitInfo
stats: dict[str, int]
files: list[FileChange]
refs: list[str] # issue refs
linked_prs: list[dict] # simplified PR info
class RepoInfo(NamedTuple):
description: str
created_at: str
default_branch: str
language: str
stars: int
forks: int
open_issues: int
branches: Optional[int]
total_commits: Optional[int]
class ConflictFile(NamedTuple):
filename: str
conflict_text: str # raw text containing <<<<<<< / ======= / >>>>>>> markers
class PRMetadata(NamedTuple):
provider: str # "github" or "gitlab"
owner: str
repo: str
number: int
title: str
state: str # open / closed / merged
author: str
base: str # base branch name
head: str # head branch name
url: str # original PR/MR URL
head_clone_url: str # clone URL for the head repo (may be a fork)
head_owner: str # owner of the head repo (may differ from base owner)
description: str # PR/MR body text
class BranchComparison(NamedTuple):
base: str
target: str
stat_summary: str # shortstat line
file_changes: list # list[FileChange]
unique_commits: list # list[CommitInfo]
conflicts: list # list[ConflictFile]
shallow_warning: bool
full_diff: str # full git diff output for export
full_log: str # full git log --stat -p output for export
# ── Providers (URL builders only) ─────────────────────────────────────────────
class GitProvider(ABC):
@property
@abstractmethod
def name(self) -> str:
pass
@abstractmethod
def clone_url(self, owner: str, repo: str) -> str:
"""Return the git clone URL."""
pass
@abstractmethod
def commit_url(self, owner: str, repo: str, sha: str) -> str:
"""Return a browser URL for the given commit."""
pass
class GitHubProvider(GitProvider):
@property
def name(self) -> str:
return "GitHub"
def clone_url(self, owner: str, repo: str) -> str:
token = os.getenv("GITHUB_TOKEN", "")
creds = f"{token}@" if token else ""
return f"https://{creds}github.com/{quote(owner, safe='')}/{quote(repo, safe='')}.git"
def commit_url(self, owner: str, repo: str, sha: str) -> str:
return f"https://github.com/{owner}/{repo}/commit/{sha}"
class GitLabProvider(GitProvider):
def __init__(self) -> None:
base = os.getenv("GITLAB_URL", "https://gitlab.com").rstrip("/")
if "/api/" in base:
base = base.split("/api/")[0]
self._host = base
@property
def name(self) -> str:
return "GitLab"
def clone_url(self, owner: str, repo: str) -> str:
token = os.getenv("GITLAB_TOKEN", "")
creds = f"oauth2:{token}@" if token else ""
host_no_scheme = re.sub(r'^https?://', '', self._host)
scheme = "https://" if self._host.startswith("https") else "http://"
return f"{scheme}{creds}{host_no_scheme}/{quote(owner, safe='')}/{quote(repo, safe='')}.git"
def commit_url(self, owner: str, repo: str, sha: str) -> str:
return f"{self._host}/{owner}/{repo}/-/commit/{sha}"
class AzureDevOpsProvider(GitProvider):
def __init__(self) -> None:
self._org = os.getenv("AZURE_DEVOPS_ORG", "")
@property
def name(self) -> str:
return "Azure DevOps"
def clone_url(self, owner: str, repo: str) -> str:
token = os.getenv("AZURE_DEVOPS_TOKEN", "")
creds = f":{token}@" if token else ""
return f"https://{creds}dev.azure.com/{self._org}/{quote(owner, safe='')}/{quote(repo, safe='')}/_git/{quote(repo, safe='')}"
def commit_url(self, owner: str, repo: str, sha: str) -> str:
return f"https://dev.azure.com/{self._org}/{owner}/_git/{repo}/commit/{sha}"
# ── Git Backend (Dulwich) ──────────────────────────────────────────────────────
class _GitBackend:
"""Bare-clone git backend using Dulwich. Stores the clone in a temp dir."""
_PER_PAGE = 30
def __init__(self) -> None:
self._tmpdir: Optional[str] = None
self._commits: list[CommitInfo] = []
self._graph_data: list[tuple[CommitInfo, list]] = []
self._shown: int = 0
@property
def all_commits(self) -> list[CommitInfo]:
return self._commits
@property
def graph_data(self) -> list[tuple[CommitInfo, list]]:
return self._graph_data
@property
def shown(self) -> int:
return self._shown
def has_more(self) -> bool:
return self._shown < len(self._graph_data)
def next_page(self) -> list[tuple[CommitInfo, list]]:
end = min(self._shown + self._PER_PAGE, len(self._graph_data))
page = self._graph_data[self._shown:end]
self._shown = end
return page
async def load(self, url: str, depth: Optional[int] = None) -> None:
self.cleanup()
self._tmpdir = tempfile.mkdtemp(prefix="cex-")
def _do_clone() -> None:
import io
import os
import urllib3
import ssl
from dulwich import porcelain
# Check if SSL verification should be disabled
disable_ssl_verify = os.getenv("GIT_SSL_NO_VERIFY", "").lower() in ("1", "true", "yes")
# Setup clone kwargs
clone_kwargs = {}
if disable_ssl_verify:
# Disable warnings about unverified requests
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Create a custom pool manager that doesn't verify certificates
# and pass it through to the GitClient
pool_manager = urllib3.PoolManager(
cert_reqs=ssl.CERT_NONE,
assert_hostname=False
)
clone_kwargs['pool_manager'] = pool_manager
porcelain.clone(
url,
target=self._tmpdir,
depth=depth,
bare=True,
filter_spec="blob:none", # skip file contents — commits+trees only
errstream=io.BytesIO(),
**clone_kwargs
)
await asyncio.to_thread(_do_clone)
self._graph_data = await asyncio.to_thread(_build_graph_from_git, self._tmpdir)
self._commits = [c for c, _ in self._graph_data]
self._shown = 0
def _extract_commits(self) -> list[CommitInfo]:
from dulwich.repo import Repo
from dulwich.walk import ORDER_DATE
repo = Repo(self._tmpdir)
heads: list[bytes] = []
for ref, sha in repo.refs.as_dict().items():
if ref.startswith(b"refs/heads/") or ref.startswith(b"refs/remotes/"):
heads.append(sha)
if not heads:
try:
heads = [repo.head()]
except Exception:
pass
if not heads:
return []
commits: list[CommitInfo] = []
seen: set[str] = set()
for entry in repo.get_walker(include=list(set(heads)), order=ORDER_DATE):
c = entry.commit
sha = c.id.decode()
if sha in seen:
continue
seen.add(sha)
parents = [p.decode() for p in c.parents]
msg = c.message.decode("utf-8", errors="replace").strip().split("\n")[0]
author_raw = c.author.decode("utf-8", errors="replace")
m = re.match(r"^(.*?)\s*<(.*)>$", author_raw)
author = m.group(1).strip() if m else author_raw
email = m.group(2).strip() if m else ""
dt = datetime.fromtimestamp(
c.author_time,
tz=timezone(timedelta(seconds=c.author_timezone)),
)
commits.append(CommitInfo(
sha=sha, short_sha=sha[:7],
message=msg, author=author, author_email=email,
date=dt.isoformat(), parents=parents,
))
return commits
def get_detail(self, sha: str) -> "CommitDetail":
import difflib
from dulwich.repo import Repo
from dulwich.diff_tree import tree_changes, CHANGE_ADD, CHANGE_DELETE, CHANGE_RENAME
repo = Repo(self._tmpdir)
c = repo[sha.encode()]
parents = [p.decode() for p in c.parents]
msg_full = c.message.decode("utf-8", errors="replace").strip()
author_raw = c.author.decode("utf-8", errors="replace")
m = re.match(r"^(.*?)\s*<(.*)>$", author_raw)
author = m.group(1).strip() if m else author_raw
email = m.group(2).strip() if m else ""
dt = datetime.fromtimestamp(
c.author_time,
tz=timezone(timedelta(seconds=c.author_timezone)),
)
info = CommitInfo(
sha=sha, short_sha=sha[:7],
message=msg_full.split("\n")[0],
author=author, author_email=email,
date=dt.isoformat(), parents=parents,
)
parent_tree = None
if parents:
try:
parent_tree = repo[parents[0].encode()].tree
except Exception:
pass
files: list[FileChange] = []
total_add = total_del = 0
try:
for change in tree_changes(repo.object_store, parent_tree, c.tree):
if change.type == CHANGE_ADD:
status = "added"
filename = change.new.path.decode("utf-8", errors="replace")
elif change.type == CHANGE_DELETE:
status = "removed"
filename = change.old.path.decode("utf-8", errors="replace")
elif change.type == CHANGE_RENAME:
status = "renamed"
filename = change.new.path.decode("utf-8", errors="replace")
else:
status = "modified"
filename = (change.new.path or change.old.path).decode("utf-8", errors="replace")
add = del_ = 0
try:
old_data = repo.object_store[change.old.sha].data if change.old.sha else b""
new_data = repo.object_store[change.new.sha].data if change.new.sha else b""
for line in difflib.unified_diff(
old_data.splitlines(True), new_data.splitlines(True)
):
if line.startswith(b"+") and not line.startswith(b"+++"):
add += 1
elif line.startswith(b"-") and not line.startswith(b"---"):
del_ += 1
except Exception:
pass
total_add += add
total_del += del_
files.append(FileChange(filename=filename, status=status,
additions=add, deletions=del_))
except Exception:
pass
return CommitDetail(
info=info,
stats={"additions": total_add, "deletions": total_del, "total": len(files)},
files=files,
refs=[],
linked_prs=[],
)
def get_repo_info(self) -> "RepoInfo":
from dulwich.repo import Repo
r = Repo(self._tmpdir)
try:
default_branch = r.refs.get_symrefs().get(b"HEAD", b"refs/heads/main")
default_branch = default_branch.decode().removeprefix("refs/heads/")
except Exception:
default_branch = "main"
branch_count = sum(
1 for ref in r.refs.as_dict()
if ref.startswith(b"refs/heads/") or ref.startswith(b"refs/remotes/")
)
return RepoInfo(
description="",
created_at="",
default_branch=default_branch,
language="",
stars=0,
forks=0,
open_issues=0,
branches=branch_count,
total_commits=len(self._commits),
)
def fetch_all(self) -> None:
"""Fetch all remote refs into the existing bare clone."""
import subprocess
r = subprocess.run(
["git", "--git-dir", self._tmpdir, "fetch", "--all", "--quiet"],
capture_output=True,
)
if r.returncode != 0:
raise RuntimeError(r.stderr.decode("utf-8", errors="replace").strip())
def compare_branches(self, base: str, target: str) -> "BranchComparison":
"""Fetch remotes and compare two branches. Returns a BranchComparison.
base and target may be bare branch names (resolved to origin/) or
already-qualified refs like 'pr-head/main'.
"""
import subprocess
self.fetch_all()
base_ref = base if "/" in base and not base.startswith("refs/") and base.split("/")[0] in ("origin", "pr-head") else f"origin/{base}"
target_ref = target if "/" in target and not target.startswith("refs/") and target.split("/")[0] in ("origin", "pr-head") else f"origin/{target}"
# Shallow clone detection
shallow_warning = False
try:
r = subprocess.run(
["git", "--git-dir", self._tmpdir, "rev-parse", "--is-shallow-repository"],
capture_output=True, encoding="utf-8", errors="replace", timeout=10,
)
if r.stdout.strip() == "true":
shallow_warning = True
except Exception:
pass
# Per-file list using --name-status (tree-only — works with filter=blob:none)
r_ns = subprocess.run(
["git", "--git-dir", self._tmpdir, "diff",
base_ref, target_ref, "--name-status", "--no-color", "-z"],
capture_output=True, encoding="utf-8", errors="replace", timeout=30,
)
file_changes: list[FileChange] = []
STATUS_MAP = {"A": "added", "D": "removed", "M": "modified",
"R": "renamed", "C": "copied", "T": "modified",
"U": "modified", "X": "modified"}
ns_output = r_ns.stdout
ns_tokens = [t for t in ns_output.split("\x00") if t]
i = 0
while i < len(ns_tokens):
token = ns_tokens[i]
if not token:
i += 1
continue
code = token[0].upper()
if code in ("R", "C") and i + 2 < len(ns_tokens):
fname = ns_tokens[i + 2]
i += 3
elif i + 1 < len(ns_tokens):
fname = ns_tokens[i + 1]
i += 2
else:
i += 1
continue
status = STATUS_MAP.get(code, "modified")
file_changes.append(FileChange(filename=fname, status=status,
additions=0, deletions=0))
# Fetch blobs for the two ref tips so --stat / full diff work
def _ref_remote_and_branch(ref: str) -> tuple[str, str]:
for prefix in ("origin/", "pr-head/"):
if ref.startswith(prefix):
return prefix.rstrip("/"), ref[len(prefix):]
return "origin", ref
for _remote, _branch in {_ref_remote_and_branch(base_ref),
_ref_remote_and_branch(target_ref)}:
try:
subprocess.run(
["git", "--git-dir", self._tmpdir,
"-c", "fetch.promisor=true",
"fetch", "--filter=blob:none", _remote, _branch],
capture_output=True, timeout=60,
)
except Exception:
pass
# Shortstat summary (needs blobs for line counts)
r_short = subprocess.run(
["git", "--git-dir", self._tmpdir, "diff",
base_ref, target_ref, "--shortstat", "--no-color"],
capture_output=True, encoding="utf-8", errors="replace", timeout=30,
)
stat_summary = r_short.stdout.strip()
if not stat_summary and file_changes:
stat_summary = f"{len(file_changes)} file(s) changed"
# Back-fill +/- counts from --stat if blobs were fetched
r_stat = subprocess.run(
["git", "--git-dir", self._tmpdir, "diff",
base_ref, target_ref, "--stat", "--no-color"],
capture_output=True, encoding="utf-8", errors="replace", timeout=30,
)
stat_by_file: dict[str, tuple[int, int]] = {}
for sline in r_stat.stdout.splitlines():
sline = sline.strip()
if not sline or "|" not in sline:
continue
fname_s, bar = sline.split("|", 1)
fname_s = fname_s.strip()
bar = bar.strip()
if not fname_s or "changed" in bar:
continue
stat_by_file[fname_s] = (bar.count("+"), bar.count("-"))
# Apply counts to file_changes
file_changes = [
FileChange(filename=fc.filename, status=fc.status,
additions=stat_by_file.get(fc.filename, (0, 0))[0],
deletions=stat_by_file.get(fc.filename, (0, 0))[1])
for fc in file_changes
]
# Unique commits in target not in base
r_log = subprocess.run(
["git", "--git-dir", self._tmpdir, "log",
f"{base_ref}..{target_ref}",
"--format=%H%x00%s%x00%aN%x00%aE%x00%ad%x00%P",
"--date=short", "--no-color"],
capture_output=True, encoding="utf-8", errors="replace", timeout=30,
)
unique_commits: list[CommitInfo] = []
for line in r_log.stdout.splitlines():
line = line.strip()
if not line:
continue
fields = line.split("\x00")
sha = fields[0] if len(fields) > 0 else ""
if not sha:
continue
unique_commits.append(CommitInfo(
sha=sha, short_sha=sha[:7],
message=fields[1] if len(fields) > 1 else "",
author=fields[2] if len(fields) > 2 else "",
author_email=fields[3] if len(fields) > 3 else "",
date=fields[4] if len(fields) > 4 else "",
parents=fields[5].split() if len(fields) > 5 and fields[5] else [],
))
# Full diff for export (untruncated)
r_diff = subprocess.run(
["git", "--git-dir", self._tmpdir, "diff",
base_ref, target_ref, "--no-color"],
capture_output=True, encoding="utf-8", errors="replace", timeout=60,
)
full_diff = r_diff.stdout
# Full log with per-commit stats for export (use default medium format so --stat interleaves correctly)
r_full_log = subprocess.run(
["git", "--git-dir", self._tmpdir, "log",
f"{base_ref}..{target_ref}",
"--stat", "--no-color", "--date=iso"],
capture_output=True, encoding="utf-8", errors="replace", timeout=60,
)
full_log = r_full_log.stdout
# Conflict detection (shallow repos may lack merge-base)
conflicts: list[ConflictFile] = []
if not shallow_warning:
conflicts = self.detect_conflicts(base, target)
return BranchComparison(
base=base, target=target,
stat_summary=stat_summary,
file_changes=file_changes,
unique_commits=unique_commits,
conflicts=conflicts,
shallow_warning=shallow_warning,
full_diff=full_diff,
full_log=full_log,
)
def detect_conflicts(self, base: str, target: str) -> "list[ConflictFile]":
"""Detect merge conflicts between two remote branches."""
import subprocess
base_ref = f"origin/{base}"
target_ref = f"origin/{target}"
# Try git merge-tree --write-tree (git >= 2.38)
try:
r = subprocess.run(
["git", "--git-dir", self._tmpdir, "-c", "core.bare=true",
"merge-tree", "--write-tree", "--no-messages", "--name-only",
base_ref, target_ref],
capture_output=True, encoding="utf-8", errors="replace", timeout=30,
)
if r.returncode == 0:
return []
if r.returncode == 1:
# First line = merged tree SHA, rest = conflicted filenames
lines = r.stdout.strip().splitlines()
if not lines:
return []
tree_sha = lines[0].strip()
conflict_filenames = [l.strip() for l in lines[1:] if l.strip()]
conflicts: list[ConflictFile] = []
for fname in conflict_filenames:
blob_r = subprocess.run(
["git", "--git-dir", self._tmpdir, "cat-file", "blob",
f"{tree_sha}:{fname}"],
capture_output=True, encoding="utf-8", errors="replace", timeout=10,
)
if blob_r.returncode == 0:
conflicts.append(ConflictFile(filename=fname,
conflict_text=blob_r.stdout))
return conflicts
except Exception:
pass
# Fallback: classic git merge-tree
try:
mb_r = subprocess.run(
["git", "--git-dir", self._tmpdir, "merge-base", base_ref, target_ref],
capture_output=True, encoding="utf-8", errors="replace", timeout=30,
)
if mb_r.returncode != 0:
return []
merge_base = mb_r.stdout.strip()
if not merge_base:
return []
mt_r = subprocess.run(
["git", "--git-dir", self._tmpdir, "merge-tree",
merge_base, base_ref, target_ref],
capture_output=True, encoding="utf-8", errors="replace", timeout=30,
)
return _parse_classic_merge_tree(mt_r.stdout)
except Exception:
return []
def cleanup(self) -> None:
if self._tmpdir:
shutil.rmtree(self._tmpdir, ignore_errors=True)
self._tmpdir = None
self._commits = []
self._graph_data = []
self._shown = 0
# ── Helpers ───────────────────────────────────────────────────────────────────
def _parse_classic_merge_tree(output: str) -> "list[ConflictFile]":
"""Parse output from classic `git merge-tree <base> <ours> <theirs>`.
Sections look like:
changed in both
base 100644 <sha> path/to/file
our 100644 <sha> path/to/file
their 100644 <sha> path/to/file
@@@ -1,3 -1,3 +1,9 @@@
context
+<<<<<<< .our
+ours
+=======
+theirs
+>>>>>>> .their
"""
conflicts: list[ConflictFile] = []
current_file = ""
in_diff = False
diff_lines: list[str] = []
has_conflict = False
SECTION_HEADERS = (
"changed in both", "added in both", "removed in both",
"added in remote", "removed in remote",
"added in local", "removed in local",
)
def _flush() -> None:
nonlocal current_file, in_diff, diff_lines, has_conflict
if current_file and has_conflict and diff_lines:
content = []
for dl in diff_lines:
if dl.startswith("+"):
content.append(dl[1:])
elif dl.startswith(" "):
content.append(dl[1:])
conflicts.append(ConflictFile(
filename=current_file,
conflict_text="\n".join(content),
))
current_file = ""
in_diff = False
diff_lines = []
has_conflict = False
for line in output.splitlines():
stripped = line.strip()
if any(stripped.startswith(h) for h in SECTION_HEADERS):
_flush()
elif stripped.startswith("base ") or stripped.startswith("our ") or stripped.startswith("their "):
# " base 100644 sha path/to/file" — last token is filename
parts = stripped.split()
if len(parts) >= 4 and not current_file:
current_file = parts[-1]
elif stripped.startswith("@@@") or stripped.startswith("@@"):
in_diff = True
diff_lines = []
elif in_diff:
diff_lines.append(line)
if stripped.startswith("+<<<<<<<") or stripped.startswith("<<<<<<< "):
has_conflict = True
_flush()
return conflicts
def _add_fork_remote(tmpdir: str, fork_url: str, branch: str) -> None:
"""Add 'pr-head' remote pointing at a fork and fetch the given branch."""
import subprocess
subprocess.run(
["git", "--git-dir", tmpdir, "remote", "remove", "pr-head"],
capture_output=True,
)
r = subprocess.run(
["git", "--git-dir", tmpdir, "remote", "add", "pr-head", fork_url],
capture_output=True, encoding="utf-8", errors="replace",
)
if r.returncode != 0:
raise RuntimeError(f"remote add failed: {r.stderr.strip()}")
r = subprocess.run(
["git", "--git-dir", tmpdir, "fetch", "--filter=blob:none",
"pr-head", branch],
capture_output=True, encoding="utf-8", errors="replace", timeout=120,
)
if r.returncode != 0:
raise RuntimeError(f"fetch fork failed: {r.stderr.strip()}")
def _resolve_pr_url(url: str) -> "PRMetadata":
"""Parse a GitHub PR or GitLab MR URL and fetch metadata via the provider API."""
import urllib.request
import json
url = url.strip().rstrip("/")
# GitHub: https://github.com/{owner}/{repo}/pull/{N}
gh_m = re.match(
r"https?://github\.com/([^/]+)/([^/]+)/pull/(\d+)", url
)
if gh_m:
owner, repo, number = gh_m.group(1), gh_m.group(2), int(gh_m.group(3))
token = os.getenv("GITHUB_TOKEN", "")
api_url = f"https://api.github.com/repos/{owner}/{repo}/pulls/{number}"
req = urllib.request.Request(api_url, headers={
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
**(({"Authorization": f"Bearer {token}"}) if token else {}),
})
with urllib.request.urlopen(req, timeout=15) as resp:
data = json.loads(resp.read())
merged = data.get("merged", False)
state = "merged" if merged else data.get("state", "unknown")
token = os.getenv("GITHUB_TOKEN", "")
head_repo = data["head"].get("repo") or {}
head_owner = head_repo.get("owner", {}).get("login", owner)
head_repo_name = head_repo.get("name", repo)
creds = f"{token}@" if token else ""
head_clone_url = f"https://{creds}github.com/{quote(head_owner, safe='')}/{quote(head_repo_name, safe='')}.git"
return PRMetadata(
provider="github", owner=owner, repo=repo, number=number,
title=data.get("title", ""),
state=state,
author=data.get("user", {}).get("login", ""),
base=data["base"]["ref"],
head=data["head"]["ref"],
url=url,
head_clone_url=head_clone_url,
head_owner=head_owner,
description=data.get("body") or "",
)
# GitLab: https://gitlab.com/{owner}/{repo}/-/merge_requests/{N}
# or https://gitlab.com/{owner}/{repo}/merge_requests/{N}
gl_m = re.match(
r"(https?://[^/]+)/([^/]+(?:/[^/]+)*?)(?:/-)?/merge_requests/(\d+)", url
)
if gl_m:
host, path, number = gl_m.group(1), gl_m.group(2), int(gl_m.group(3))
parts = path.split("/")
owner, repo = "/".join(parts[:-1]), parts[-1]
token = os.getenv("GITLAB_TOKEN", "")
project_id = quote(path, safe="")
api_url = f"{host}/api/v4/projects/{project_id}/merge_requests/{number}"
req = urllib.request.Request(api_url, headers={
**(({"PRIVATE-TOKEN": token}) if token else {}),
})
with urllib.request.urlopen(req, timeout=15) as resp:
data = json.loads(resp.read())
state = data.get("state", "unknown")
gl_token = os.getenv("GITLAB_TOKEN", "")
source_ns = data.get("source_namespace", {}) or {}
head_owner = source_ns.get("full_path", path.rsplit("/", 1)[0])
head_repo_name = data.get("source_project_id", "") # fallback
source_http = data.get("source", {}) or {}
head_clone_url = source_http.get("http_url_to_repo", "")
if not head_clone_url:
creds = f"oauth2:{gl_token}@" if gl_token else ""
host_no_scheme = re.sub(r'^https?://', '', host)
scheme = "https://" if host.startswith("https") else "http://"
head_clone_url = f"{scheme}{creds}{host_no_scheme}/{quote(head_owner, safe='')}/{quote(path.rsplit('/', 1)[-1], safe='')}.git"
return PRMetadata(
provider="gitlab", owner=owner, repo=repo, number=number,
title=data.get("title", ""),
state=state,
author=data.get("author", {}).get("username", ""),
base=data["target_branch"],
head=data["source_branch"],
url=url,
head_clone_url=head_clone_url,
head_owner=head_owner,
description=data.get("description") or "",
)
raise ValueError(
f"Unsupported URL format: {url!r}\n"
"Supported: github.com/.../pull/N or gitlab.com/.../merge_requests/N"
)
def _write_export(result: "BranchComparison", pr_meta: "Optional[PRMetadata]" = None) -> str:
"""Write a BranchComparison to a detailed .txt file in the CWD. Returns the file path."""
now = datetime.now()
date_str = now.strftime("%Y%m%d-%H%M%S")
if pr_meta:
owner_safe = pr_meta.owner.replace("/", "-")
repo_safe = pr_meta.repo.replace("/", "-")
filename = f"compare-{owner_safe}-{repo_safe}-pr{pr_meta.number}-{date_str}.txt"
else:
base_safe = result.base.replace("/", "-")
target_safe = result.target.replace("/", "-")
filename = f"compare-{base_safe}-{target_safe}-{date_str}.txt"
SEP = "=" * 72
sep = "-" * 72
lines = [SEP]
if pr_meta:
lines += [
f"PR/MR Review: {pr_meta.url}",
f"Title: {pr_meta.title}",
f"Author: {pr_meta.author} | State: {pr_meta.state}",
]
if pr_meta.description.strip():
lines.append("")
lines.append("Description:")
for dl in pr_meta.description.strip().splitlines():
lines.append(f" {dl}")
lines += [
f"Compare: origin/{result.base} \u2192 origin/{result.target}",
f"Generated: {now.strftime('%Y-%m-%d %H:%M:%S')}",
]
if result.shallow_warning:
lines.append("WARNING: Shallow clone \u2014 commit log and conflict results may be incomplete")
lines += ["", SEP, ""]
# ── Diff Summary ──────────────────────────────────────────────────────────
lines.append("DIFF SUMMARY")
lines.append(sep)
lines.append(result.stat_summary if result.stat_summary else "No differences.")
lines.append("")
# ── Changed Files ─────────────────────────────────────────────────────────
lines.append(f"CHANGED FILES ({len(result.file_changes)})")
lines.append(sep)
if result.file_changes:
col_w = max(len(fc.filename) for fc in result.file_changes) + 2
for fc in result.file_changes:
status_label = fc.status.upper()
lines.append(
f" {status_label:<10} {fc.filename:<{col_w}} +{fc.additions} -{fc.deletions}"
)
else:
lines.append(" No file changes.")
lines.append("")
# ── Commit Log ────────────────────────────────────────────────────────────
lines.append(f"COMMIT LOG ({len(result.unique_commits)} commits in origin/{result.target} not in origin/{result.base})")
lines.append(sep)
if result.full_log.strip():
lines.append(result.full_log.rstrip())
elif result.unique_commits:
for c in result.unique_commits:
lines.append(f"commit {c.sha}")
lines.append(f"Author: {c.author} <{c.author_email}>")
lines.append(f"Date: {c.date}")
lines.append(f"")
lines.append(f" {c.message}")
lines.append("")
else:
lines.append(" No unique commits.")
lines.append("")
# ── Full Diff ─────────────────────────────────────────────────────────────
lines.append("FULL DIFF")
lines.append(sep)
if result.full_diff.strip():
lines.append(result.full_diff.rstrip())
else:
lines.append("No differences.")
lines.append("")
# ── Conflicts ─────────────────────────────────────────────────────────────
lines.append("CONFLICTS")
lines.append(sep)
if not result.conflicts:
lines.append("Clean merge \u2014 no conflicts detected")
else:
for cf in result.conflicts:
lines.append(f"File: {cf.filename}")
lines.append(sep)
lines.append(cf.conflict_text.rstrip())
lines.append("")
lines.append("")
with open(filename, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
return filename
def fmt_date(iso: str) -> str:
try:
iso = iso.replace("Z", "+00:00")
dt = datetime.fromisoformat(iso)
return dt.strftime("%Y-%m-%d %H:%M")
except (ValueError, TypeError):
return iso[:16]
# ── Graph Builder ─────────────────────────────────────────────────────────────
def _build_graph_from_git(tmpdir: str) -> list[tuple[CommitInfo, list[Text]]]:
"""Run `git log --graph --color=always` on the cloned bare repo and parse
the ANSI-coloured output into (CommitInfo, graph_lines) pairs.
Each commit line is identified by a NUL-delimited marker injected via
--format so we can cleanly separate graph-prefix characters from commit
metadata without any regex fragility.
"""
import subprocess
# \x01 (SOH) marks commit lines; %x00 tells git to output NUL field separators.
# Neither appears in graph characters (*, |, \, /, space).
MARKER = "\x01"
fmt = f"{MARKER}%H%x00%s%x00%aN%x00%aE%x00%ad%x00%P"
proc = subprocess.run(
[
"git", "--git-dir", tmpdir,
"log", "--graph", "--color=always",
f"--format={fmt}",
"--date=short",
"--all",
],
capture_output=True,
encoding="utf-8",
errors="replace",
)
output: list[tuple[CommitInfo, list[Text]]] = []
current_commit: Optional[CommitInfo] = None
current_lines: list[Text] = []
for raw in proc.stdout.splitlines():
if MARKER in raw:
graph_part, data = raw.split(MARKER, 1)
fields = data.split("\x00")
sha = fields[0] if len(fields) > 0 else ""
subject = fields[1] if len(fields) > 1 else ""
author = fields[2] if len(fields) > 2 else ""
email = fields[3] if len(fields) > 3 else ""
date = fields[4] if len(fields) > 4 else ""
parents = fields[5].split() if len(fields) > 5 and fields[5] else []
if not sha:
continue
if current_commit is not None:
output.append((current_commit, current_lines))
current_commit = CommitInfo(
sha=sha, short_sha=sha[:7],
message=subject, author=author, author_email=email,
date=date, parents=parents,
)
current_lines = [Text.from_ansi(graph_part)]
else:
if current_commit is not None:
current_lines.append(Text.from_ansi(raw))
if current_commit is not None:
output.append((current_commit, current_lines))