-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_repository_manager.py
More file actions
2321 lines (1930 loc) · 105 KB
/
git_repository_manager.py
File metadata and controls
2321 lines (1930 loc) · 105 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
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
import re
import json
import subprocess
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import threading
from datetime import datetime
import hashlib
import time
import functools
import sys
import atexit
import traceback
import uuid
# ----------------------------------------------------------------------------------
# Diagnostic / Logging Utilities (added to investigate rapid restart issue)
# ----------------------------------------------------------------------------------
APP_BASE_DIR = Path(getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))))
LOG_FILE = APP_BASE_DIR / "manager_debug.log"
LOCK_FILE = APP_BASE_DIR / "git_repository_manager.lock"
def _safe_log(msg: str):
"""Append a timestamped line to the debug log (best-effort)."""
try:
LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
with LOG_FILE.open("a", encoding="utf-8") as f:
f.write(f"{datetime.utcnow().isoformat()}Z | {msg}\n")
except Exception:
pass
def _install_global_exception_hook():
def _hook(exc_type, exc, tb):
_safe_log("UNCAUGHT_EXCEPTION: " + ''.join(traceback.format_exception(exc_type, exc, tb)))
# Show a message box if GUI is up (avoid infinite recursion if Tk not ready)
try:
root = tk._default_root # type: ignore
if root:
messagebox.showerror("Fatal Error", f"{exc_type.__name__}: {exc}")
except Exception:
pass
sys.excepthook = _hook
def _acquire_single_instance_lock():
"""Create a lock file to prevent multiple concurrent instances (helps rule out spawn loops)."""
try:
if LOCK_FILE.exists():
# If stale (older than 1 day) remove it
try:
if time.time() - LOCK_FILE.stat().st_mtime > 86400:
LOCK_FILE.unlink(missing_ok=True)
else:
_safe_log("Another instance detected (lock file present). Exiting early.")
# Provide a small delay so a flashing console is observable if run non-windowed
time.sleep(0.35)
sys.exit(0)
except Exception:
# If we cannot access the lock file reliably, continue but log
_safe_log("Lock file access issue; proceeding anyway.")
LOCK_FILE.write_text(f"pid={os.getpid()} guid={uuid.uuid4()} time={datetime.utcnow().isoformat()}Z")
atexit.register(lambda: LOCK_FILE.exists() and LOCK_FILE.unlink())
except Exception as e:
_safe_log(f"Failed to establish lock: {e}")
_install_global_exception_hook()
# _acquire_single_instance_lock()
_safe_log(f"PROCESS_START | frozen={getattr(sys,'frozen',False)} | pid={os.getpid()} | cwd={os.getcwd()}")
# ----------------------------------------------------------------------------------
# Silent Git command helper (prevents flashing consoles on Windows)
# ----------------------------------------------------------------------------------
def run_git(cmd, cwd):
"""
Run a git command silently (no console window) and return CompletedProcess.
Mirrors prior parameters: capture_output=True, text mode, utf-8, replace errors.
"""
creationflags = 0
startupinfo = None
if os.name == 'nt':
# Suppress console window for child processes
creationflags = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
try:
startupinfo = subprocess.STARTUPINFO() # type: ignore[attr-defined]
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW # type: ignore[attr-defined]
except Exception:
startupinfo = None
try:
result = subprocess.run(
cmd,
cwd=cwd,
capture_output=True,
text=True,
encoding='utf-8',
errors='replace',
startupinfo=startupinfo,
creationflags=creationflags
)
return result
except Exception as e:
_safe_log(f"GIT_CMD_FAIL | cmd={cmd} | cwd={cwd} | error={e}")
raise
# Global benchmarking configuration
BENCHMARKING_ENABLED = True # Set to False to disable all benchmarks
def benchmark(func=None, *, print_args=False):
"""
Decorator to benchmark method execution time.
Args:
func: The function being decorated
print_args: Whether to print function arguments in the benchmark output
Usage:
@benchmark
def my_method(self):
pass
@benchmark(print_args=True)
def my_method_with_args(self, arg1, arg2):
pass
"""
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
if not BENCHMARKING_ENABLED:
return f(*args, **kwargs)
start_time = time.perf_counter()
try:
result = f(*args, **kwargs)
end_time = time.perf_counter()
execution_time = end_time - start_time
# Format the function name and class name if it's a method
if args and hasattr(args[0], '__class__'):
func_name = f"{args[0].__class__.__name__}.{f.__name__}"
else:
func_name = f.__name__
# Format arguments if requested
args_str = ""
if print_args and len(args) > 1: # Skip 'self' argument
args_repr = [repr(arg) for arg in args[1:]]
kwargs_repr = [f"{k}={repr(v)}" for k, v in kwargs.items()]
all_args = args_repr + kwargs_repr
if all_args:
args_str = f" with args({', '.join(all_args)})"
print(f"🚀 BENCHMARK: {func_name}{args_str} took {execution_time:.4f} seconds")
return result
except Exception as e:
end_time = time.perf_counter()
execution_time = end_time - start_time
func_name = f"{args[0].__class__.__name__}.{f.__name__}" if args and hasattr(args[0], '__class__') else f.__name__
print(f"❌ BENCHMARK: {func_name} failed after {execution_time:.4f} seconds - {str(e)}")
raise
return wrapper
if func is None:
return decorator
else:
return decorator(func)
def toggle_benchmarking():
"""Toggle benchmarking on/off"""
global BENCHMARKING_ENABLED
BENCHMARKING_ENABLED = not BENCHMARKING_ENABLED
status = "ENABLED" if BENCHMARKING_ENABLED else "DISABLED"
print(f"📊 Benchmarking {status}")
def time_operation(operation_name: str):
"""Context manager for timing specific operations"""
class TimerContext:
def __init__(self, name: str):
self.name = name
self.start_time = None
def __enter__(self):
self.start_time = time.perf_counter()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if BENCHMARKING_ENABLED:
end_time = time.perf_counter()
execution_time = end_time - self.start_time
if exc_type is None:
print(f"⏱️ {self.name} took {execution_time:.4f} seconds")
else:
print(f"❌ {self.name} failed after {execution_time:.4f} seconds")
return TimerContext(operation_name)
def benchmark_method(obj, method_name, *args, **kwargs):
"""Benchmark any method call on demand"""
if not BENCHMARKING_ENABLED:
return getattr(obj, method_name)(*args, **kwargs)
method = getattr(obj, method_name)
class_name = obj.__class__.__name__ if hasattr(obj, '__class__') else 'Unknown'
start_time = time.perf_counter()
try:
result = method(*args, **kwargs)
end_time = time.perf_counter()
execution_time = end_time - start_time
print(f"🚀 MANUAL BENCHMARK: {class_name}.{method_name} took {execution_time:.4f} seconds")
return result
except Exception as e:
end_time = time.perf_counter()
execution_time = end_time - start_time
print(f"❌ MANUAL BENCHMARK: {class_name}.{method_name} failed after {execution_time:.4f} seconds - {str(e)}")
raise
class GitCommit:
def __init__(self, commit_sha: str, message: str = "", author: str = "",
date: str = "", repo_path: str = ""):
self.commit_sha = commit_sha
self.message = message
self.author = author
self.date = date
self.repo_path = repo_path
self.branch_names: List[str] = [] # Multiple branch heads can point to same commit
def add_branch_name(self, name: str):
"""Add a branch name that points to this commit"""
if name not in self.branch_names:
self.branch_names.append(name)
def get_branch_names_display(self) -> str:
"""Get branch names formatted for display"""
return "; ".join(self.branch_names) if self.branch_names else ""
class GitBranch:
def __init__(self, name: str, commit_sha: str, commit_message: str = "", author: str = "",
date: str = "", is_remote: bool = False, repo_path: str = ""):
self.name = name
self.commit_sha = commit_sha
self.commit_message = commit_message
self.author = author
self.date = date
self.is_remote = is_remote
self.repo_path = repo_path
self._commit_info_loaded = False
def load_commit_info_if_needed(self):
"""Load commit information only when needed"""
if not self._commit_info_loaded and self.repo_path:
commit_info = self._get_commit_info()
self.commit_message = commit_info.get('message', '')
self.author = commit_info.get('author', '')
self.date = commit_info.get('date', '')
self._commit_info_loaded = True
def _get_commit_info(self) -> Dict[str, str]:
"""Get detailed commit information"""
try:
cmd = ["git", "show", "--format=%an|%ad|%s", "--date=short", "--no-patch", self.commit_sha]
result = subprocess.run(cmd, cwd=self.repo_path, capture_output=True, text=True)
if result.returncode == 0:
output_lines = result.stdout.strip().split('\n')
if output_lines and output_lines[0]:
parts = output_lines[0].split('|', 2)
if len(parts) >= 3:
return {
'author': parts[0].strip(),
'date': parts[1].strip(),
'message': parts[2].strip()
}
elif len(parts) == 2:
return {
'author': parts[0].strip(),
'date': parts[1].strip(),
'message': ''
}
except Exception as e:
print(f"Error getting commit info for {self.commit_sha}: {e}")
return {'author': '', 'date': '', 'message': ''}
def to_dict(self) -> dict:
"""Serialize branch to dictionary"""
return {
"name": self.name,
"commit_sha": self.commit_sha,
"commit_message": self.commit_message,
"author": self.author,
"date": self.date,
"is_remote": self.is_remote,
"repo_path": self.repo_path,
"_commit_info_loaded": self._commit_info_loaded
}
@classmethod
def from_dict(cls, data: dict) -> 'GitBranch':
"""Deserialize branch from dictionary"""
branch = cls(
name=data.get("name", ""),
commit_sha=data.get("commit_sha", ""),
commit_message=data.get("commit_message", ""),
author=data.get("author", ""),
date=data.get("date", ""),
is_remote=data.get("is_remote", False),
repo_path=data.get("repo_path", "")
)
branch._commit_info_loaded = data.get("_commit_info_loaded", False)
return branch
class GitRepository:
def __init__(self, path: str, is_submodule: bool = False):
self.path = path
self.name = os.path.basename(path)
self.is_submodule = is_submodule
self.local_branches: List[GitBranch] = []
self.remote_branches: List[GitBranch] = []
self.submodules: List['GitRepository'] = []
self._branches_loaded = False
self._submodules_loaded = False
self._last_hash = None # For change detection
def get_repo_hash(self) -> str:
"""Get hash representing current state of repository"""
try:
# Get the latest commit hash and refs info for change detection
result = run_git(["git", "rev-parse", "HEAD"], self.path)
head_hash = result.stdout.strip() if result.returncode == 0 else ""
# Get all refs for comprehensive change detection
result = run_git(["git", "show-ref"], self.path)
refs_hash = hashlib.md5(result.stdout.encode()).hexdigest() if result.returncode == 0 else ""
return hashlib.md5(f"{head_hash}:{refs_hash}".encode()).hexdigest()
except Exception:
return ""
def has_changes(self) -> bool:
"""Check if repository has changes since last scan"""
current_hash = self.get_repo_hash()
if self._last_hash is None or self._last_hash != current_hash:
self._last_hash = current_hash
return True
return False
# @benchmark
def load_branches_if_needed(self):
"""Load branches, but check for changes first"""
if not self._branches_loaded or self.has_changes():
self.load_branches()
@benchmark
def load_branches(self):
"""Load local and remote branches from the git repository"""
try:
# Get local branches with full info
self.local_branches = self._get_branches(local=True)
# Get remote branches with full info
self.remote_branches = self._get_branches(local=False)
# Load submodules if this is not a submodule itself
if not self.is_submodule and not self._submodules_loaded:
self.load_submodules()
self._branches_loaded = True
# Update hash after successful load
self._last_hash = self.get_repo_hash()
except Exception as e:
print(f"Error loading branches for {self.path}: {e}")
except Exception as e:
print(f"Error loading branches for {self.path}: {e}")
def load_submodules(self):
"""Load submodules from the git repository"""
if self._submodules_loaded:
return
try:
# Get submodule list using git command
result = run_git(["git", "submodule", "status"], self.path)
if result.returncode == 0 and result.stdout:
for line in result.stdout.split('\n'):
line = line.strip()
if line:
# Parse submodule status line
# Format: " 160000 commit_sha path (tag)"
parts = line.split()
if len(parts) >= 2:
submodule_path = parts[1] if not parts[0].startswith('-') else parts[1]
full_submodule_path = os.path.join(self.path, submodule_path)
if os.path.exists(full_submodule_path):
submodule = GitRepository(full_submodule_path, is_submodule=True)
# Don't load branches immediately for submodules
self.submodules.append(submodule)
self._submodules_loaded = True
except Exception as e:
print(f"Error loading submodules for {self.path}: {e}")
def get_current_branch_commits(self, limit: int = 20) -> Tuple[str, List[GitCommit]]:
"""Get current branch name and its last N commits with branch information"""
try:
# Get current branch name
result = run_git(["git", "symbolic-ref", "--short", "HEAD"], self.path)
current_branch = result.stdout.strip() if result.returncode == 0 else "HEAD"
# Get the last N commits from current branch
result = run_git(["git", "log", f"-{limit}", "--format=%H|%an|%ad|%s", "--date=short"], self.path)
commits = []
if result.returncode == 0 and result.stdout:
# Parse commits
for line in result.stdout.split('\n'):
line = line.strip()
if not line:
continue
parts = line.split('|', 3)
if len(parts) >= 4:
commit_sha = parts[0]
author = parts[1]
date = parts[2]
message = parts[3]
commit = GitCommit(
commit_sha=commit_sha,
message=message,
author=author,
date=date,
repo_path=self.path
)
commits.append(commit)
# Now get branch information for each commit
self._add_branch_info_to_commits(commits)
return current_branch, commits
except Exception as e:
print(f"Error getting current branch commits for {self.path}: {e}")
return "unknown", []
def _add_branch_info_to_commits(self, commits: List[GitCommit]):
"""Add branch name information to commits"""
try:
# Get all branch heads (local and remote) that point to commits
result = run_git(["git", "for-each-ref", "--format=%(refname:short)|%(objectname)", "refs/heads/", "refs/remotes/"], self.path)
if result.returncode == 0 and result.stdout:
# Create a mapping of commit SHA to branch names
commit_to_branches = {}
for line in result.stdout.split('\n'):
line = line.strip()
if not line:
continue
parts = line.split('|', 1)
if len(parts) >= 2:
branch_name = parts[0]
commit_sha = parts[1]
# Keep remote branch names with origin path, but skip origin/HEAD
if branch_name == 'origin/HEAD':
continue # Skip origin/HEAD
if commit_sha not in commit_to_branches:
commit_to_branches[commit_sha] = []
commit_to_branches[commit_sha].append(branch_name)
# Add branch information to commits
for commit in commits:
if commit.commit_sha in commit_to_branches:
for branch_name in commit_to_branches[commit.commit_sha]:
commit.add_branch_name(branch_name)
except Exception as e:
print(f"Error adding branch info to commits: {e}")
def _get_branches(self, local: bool = True) -> List[GitBranch]:
"""Get branches from git repository with full commit info"""
branches = []
try:
# Get branch info with commit details in one command
if local:
cmd = ["git", "for-each-ref", "--format=%(refname:short)|%(objectname)|%(authorname)|%(authordate:short)|%(subject)", "refs/heads/"]
else:
cmd = ["git", "for-each-ref", "--format=%(refname:short)|%(objectname)|%(authorname)|%(authordate:short)|%(subject)", "refs/remotes/"]
result = run_git(cmd, self.path)
if result.returncode != 0:
return branches
if result.stdout:
for line in result.stdout.split('\n'):
line = line.strip()
if not line:
continue
# Parse the formatted output: name|sha|author|date|message
parts = line.split('|', 4)
if len(parts) >= 5:
branch_name = parts[0]
commit_sha = parts[1]
author = parts[2]
date = parts[3]
message = parts[4]
# For remote branches, clean up the name
if not local and '/' in branch_name:
# Remove 'origin/' prefix for display
display_name = '/'.join(branch_name.split('/')[1:]) if '/' in branch_name else branch_name
else:
display_name = branch_name
# Create branch with full commit info loaded
branch = GitBranch(
name=display_name,
commit_sha=commit_sha,
commit_message=message,
author=author,
date=date,
is_remote=not local,
repo_path=self.path
)
branch._commit_info_loaded = True # Mark as loaded since we have the info
branches.append(branch)
except Exception as e:
print(f"Error getting branches: {e}")
return branches
def to_dict(self) -> dict:
"""Serialize repository to dictionary"""
return {
"path": self.path,
"name": self.name,
"is_submodule": self.is_submodule,
"local_branches": [branch.to_dict() for branch in self.local_branches],
"remote_branches": [branch.to_dict() for branch in self.remote_branches],
"submodules": [submodule.to_dict() for submodule in self.submodules],
"_branches_loaded": self._branches_loaded,
"_submodules_loaded": self._submodules_loaded,
"_last_hash": self._last_hash
}
@classmethod
def from_dict(cls, data: dict) -> 'GitRepository':
"""Deserialize repository from dictionary"""
repo = cls(data.get("path", ""), data.get("is_submodule", False))
repo.name = data.get("name", "")
repo.local_branches = [GitBranch.from_dict(b) for b in data.get("local_branches", [])]
repo.remote_branches = [GitBranch.from_dict(b) for b in data.get("remote_branches", [])]
repo.submodules = [cls.from_dict(s) for s in data.get("submodules", [])]
repo._branches_loaded = data.get("_branches_loaded", False)
repo._submodules_loaded = data.get("_submodules_loaded", False)
repo._last_hash = data.get("_last_hash", None)
return repo
class FolderNode:
def __init__(self, path: str, name: str, level: int = 0):
self.path = path
self.name = name
self.level = level
self.children: List['FolderNode'] = []
self.repositories: List[GitRepository] = []
self.has_repositories = False
def add_repository(self, repo: GitRepository):
self.repositories.append(repo)
self.has_repositories = True
# Mark all parent nodes as having repositories
self._mark_parents_with_repos()
def _mark_parents_with_repos(self):
# This would be implemented with parent references
pass
class GitRepositoryManager:
def __init__(self):
self.root = tk.Tk()
self.root.title("Git Repository Manager")
self.root.geometry("1200x800")
# Data
self.selected_folder = ""
self.repositories: Dict[str, GitRepository] = {}
self.folder_tree: Dict[str, FolderNode] = {}
self.current_commits: List[GitCommit] = []
self.filtered_commits: List[GitCommit] = []
self.current_branches: List[GitBranch] = []
self.filtered_branches: List[GitBranch] = []
self.current_branch_name = ""
# Settings
self.repo_filter_regex = ""
self.branch_filter_user = ""
self.branch_filter_message = ""
self.show_commit_sha = tk.BooleanVar(value=True)
self.show_commit_message = tk.BooleanVar(value=True)
self.show_author = tk.BooleanVar(value=True)
self.show_date = tk.BooleanVar(value=True)
self.sort_column = "date" # Initially sort by date
self.sort_reverse = True # Most recent first
# Performance / filtering
self._filter_pending_id = None # for debounce of branch filter operations
self._filter_debounce_ms = 220 # delay after last keystroke before heavy filtering
self._during_filter = False # flag to suppress branch reloads while filtering
# New filter options
self.match_case = tk.BooleanVar(value=False)
self.match_whole_word = tk.BooleanVar(value=False)
self.use_regex = tk.BooleanVar(value=False)
self.search_scope = tk.StringVar(value="remote and local")
# Colors for different levels (base palette)
self.level_colors = ["#8B0000", "#0000CD", "#008B8B", "#8B008B", "#FF8C00", "#228B22"]
# If system is using dark mode, slightly lighten the palette for better contrast
try:
if self._is_system_dark_mode():
# Lighten by ~28% towards white
self.level_colors = [self._lighten_hex(c, 0.28) for c in self.level_colors]
except Exception:
# Non-fatal: if detection fails, keep base colors
pass
self.setup_ui()
self.load_settings()
def _lighten_hex(self, hex_color: str, amount: float) -> str:
"""Return a lighter hex color moved `amount` (0..1) towards white.
Examples: amount=0.2 -> 20% closer to white.
"""
try:
if not hex_color:
return hex_color
s = hex_color.lstrip('#')
if len(s) != 6:
return hex_color
r = int(s[0:2], 16)
g = int(s[2:4], 16)
b = int(s[4:6], 16)
def lighten(c):
return int(c + (255 - c) * float(amount))
nr = max(0, min(255, lighten(r)))
ng = max(0, min(255, lighten(g)))
nb = max(0, min(255, lighten(b)))
return f"#{nr:02X}{ng:02X}{nb:02X}"
except Exception:
return hex_color
def _is_system_dark_mode(self) -> bool:
"""Attempt to detect whether the OS is currently using a dark theme.
Supports macOS (via `defaults`), Windows (registry), and a best-effort for some Linux desktops.
Returns True if dark mode is detected, otherwise False.
"""
try:
import platform
system = platform.system()
if system == 'Darwin':
# macOS: `defaults read -g AppleInterfaceStyle` returns 'Dark' when in dark mode
try:
p = subprocess.run(['defaults', 'read', '-g', 'AppleInterfaceStyle'], capture_output=True, text=True)
out = (p.stdout or p.stderr or '').strip()
return 'Dark' in out
except Exception:
return False
elif system == 'Windows':
try:
import winreg
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize') as key:
# AppsUseLightTheme == 0 means dark mode for apps
val, _ = winreg.QueryValueEx(key, 'AppsUseLightTheme')
return int(val) == 0
except Exception:
return False
else:
# Linux / other: best-effort using gsettings (GNOME) or environment variables
try:
p = subprocess.run(['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], capture_output=True, text=True)
out = (p.stdout or p.stderr or '').strip().lower()
if 'dark' in out:
return True
except Exception:
pass
# Fallback: check GTK_THEME env for '-dark' suffix
try:
gtk_theme = os.environ.get('GTK_THEME', '')
if gtk_theme and 'dark' in gtk_theme.lower():
return True
except Exception:
pass
return False
except Exception:
return False
def setup_ui(self):
"""Setup the user interface"""
# Main frame
main_frame = ttk.Frame(self.root)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Top frame for folder selection and filters
top_frame = ttk.Frame(main_frame)
top_frame.pack(fill=tk.X, pady=(0, 10))
# Folder selection
folder_frame = ttk.Frame(top_frame)
folder_frame.pack(fill=tk.X, pady=(0, 5))
ttk.Label(folder_frame, text="Selected Folder:").pack(side=tk.LEFT)
self.folder_label = ttk.Label(folder_frame, text="No folder selected")
self.folder_label.pack(side=tk.LEFT, padx=(5, 0))
ttk.Button(folder_frame, text="Select Folder", command=self.select_folder).pack(side=tk.RIGHT)
ttk.Button(folder_frame, text="Rescan", command=self.rescan_folder).pack(side=tk.RIGHT, padx=(0, 5))
# Repository filter
filter_frame = ttk.Frame(top_frame)
filter_frame.pack(fill=tk.X, pady=(0, 5))
ttk.Label(filter_frame, text="Repository Filter (Regex):").pack(side=tk.LEFT)
self.repo_filter_entry = ttk.Entry(filter_frame, width=30)
self.repo_filter_entry.pack(side=tk.LEFT, padx=(5, 0))
self.repo_filter_entry.bind('<KeyRelease>', self.on_repo_filter_change)
# Branch filters
commit_filter_frame = ttk.Frame(top_frame)
commit_filter_frame.pack(fill=tk.X)
ttk.Label(commit_filter_frame, text="Commit Filter - User:").pack(side=tk.LEFT)
self.branch_user_entry = ttk.Entry(commit_filter_frame, width=20)
self.branch_user_entry.pack(side=tk.LEFT, padx=(5, 10))
self.branch_user_entry.bind('<KeyRelease>', self.on_branch_filter_change)
ttk.Label(commit_filter_frame, text="Message:").pack(side=tk.LEFT)
self.branch_message_entry = ttk.Entry(commit_filter_frame, width=20)
self.branch_message_entry.pack(side=tk.LEFT, padx=(5, 0))
self.branch_message_entry.bind('<KeyRelease>', self.on_branch_filter_change)
# New filter options frame
filter_options_frame = ttk.Frame(top_frame)
filter_options_frame.pack(fill=tk.X, pady=(5, 0))
# Checkboxes for filter options
self.match_case_cb = ttk.Checkbutton(filter_options_frame, text="Match case",
variable=self.match_case, command=self.on_filter_option_change)
self.match_case_cb.pack(side=tk.LEFT, padx=(0, 10))
self.match_whole_word_cb = ttk.Checkbutton(filter_options_frame, text="Match whole word only",
variable=self.match_whole_word, command=self.on_filter_option_change)
self.match_whole_word_cb.pack(side=tk.LEFT, padx=(0, 10))
self.use_regex_cb = ttk.Checkbutton(filter_options_frame, text="Regular expression",
variable=self.use_regex, command=self.on_filter_option_change)
self.use_regex_cb.pack(side=tk.LEFT, padx=(0, 20))
# Search scope combo box
ttk.Label(filter_options_frame, text="Only search in:").pack(side=tk.LEFT, padx=(0, 5))
self.search_scope_combo = ttk.Combobox(filter_options_frame, textvariable=self.search_scope,
values=["remote and local", "remote", "local"],
state="readonly", width=15)
self.search_scope_combo.pack(side=tk.LEFT)
self.search_scope_combo.bind('<<ComboboxSelected>>', self.on_search_scope_change)
# Main content frame with paned window for resizable separator
content_frame = ttk.Frame(main_frame)
content_frame.pack(fill=tk.BOTH, expand=True)
# Create PanedWindow for vertical separator
self.paned_window = ttk.PanedWindow(content_frame, orient=tk.HORIZONTAL)
self.paned_window.pack(fill=tk.BOTH, expand=True)
# Left pane - Repository tree
left_frame = ttk.Frame(self.paned_window)
self.paned_window.add(left_frame, weight=1)
ttk.Label(left_frame, text="Repositories").pack(anchor=tk.W)
# Tree view for repositories
tree_frame = ttk.Frame(left_frame)
tree_frame.pack(fill=tk.BOTH, expand=True)
self.repo_tree = ttk.Treeview(tree_frame)
self.repo_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Configure color tags for different levels
self.repo_tree.tag_configure("folder", foreground="#696969")
self.repo_tree.tag_configure("submodule", foreground="#FF6347") # Tomato color for submodules
for i, color in enumerate(self.level_colors):
self.repo_tree.tag_configure(f"repo_level_{i}", foreground=color)
repo_scrollbar = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=self.repo_tree.yview)
repo_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.repo_tree.configure(yscrollcommand=repo_scrollbar.set)
# Bind events
self.repo_tree.bind('<Button-3>', self.on_tree_right_click)
self.repo_tree.bind('<<TreeviewSelect>>', self.on_tree_select)
# Right pane - Commit details
right_frame = ttk.Frame(self.paned_window)
self.paned_window.add(right_frame, weight=2)
# Current branch label
self.current_branch_label = ttk.Label(right_frame, text="No repository selected", font=("TkDefaultFont", 10, "bold"))
self.current_branch_label.pack(anchor=tk.W, pady=(0, 5))
# Remove the old branch display options since we'll use header context menu
# Commit list
ttk.Label(right_frame, text="Recent Commits").pack(anchor=tk.W)
commit_frame = ttk.Frame(right_frame)
commit_frame.pack(fill=tk.BOTH, expand=True)
# Create treeview with columns (SHA moved to front, Name now shows branch heads)
columns = ("sha", "name", "message", "author", "date")
self.branch_tree = ttk.Treeview(commit_frame, columns=columns, show="headings")
# Configure columns with SHA first, Name now shows branch heads
self.branch_tree.heading("sha", text="SHA", command=lambda: self.sort_commits("sha"))
self.branch_tree.heading("name", text="Branch Heads", command=lambda: self.sort_commits("name"))
self.branch_tree.heading("message", text="Message", command=lambda: self.sort_commits("message"))
self.branch_tree.heading("author", text="Author", command=lambda: self.sort_commits("author"))
self.branch_tree.heading("date", text="Date", command=lambda: self.sort_commits("date"))
# Set column widths (SHA first)
self.branch_tree.column("sha", width=80)
self.branch_tree.column("name", width=150)
self.branch_tree.column("message", width=300)
self.branch_tree.column("author", width=120)
self.branch_tree.column("date", width=100)
self.branch_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Bind right-click to branch tree headers for column visibility
self.branch_tree.bind('<Button-3>', self.on_branch_header_right_click)
commit_scrollbar = ttk.Scrollbar(commit_frame, orient=tk.VERTICAL, command=self.branch_tree.yview)
commit_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.branch_tree.configure(yscrollcommand=commit_scrollbar.set)
# Context menu for repository tree
self.context_menu = tk.Menu(self.root, tearoff=0)
self.context_menu.add_command(label="Open in File Explorer", command=self.open_in_explorer)
# Context menu for commit headers
self.branch_header_menu = tk.Menu(self.root, tearoff=0)
self.branch_header_menu.add_checkbutton(label="SHA", variable=self.show_commit_sha,
command=self.on_column_visibility_change)
self.branch_header_menu.add_checkbutton(label="Branch Heads", state="disabled") # Branch Heads always visible
self.branch_header_menu.add_checkbutton(label="Message", variable=self.show_commit_message,
command=self.on_column_visibility_change)
self.branch_header_menu.add_checkbutton(label="Author", variable=self.show_author,
command=self.on_column_visibility_change)
self.branch_header_menu.add_checkbutton(label="Date", variable=self.show_date,
command=self.on_column_visibility_change)
# Add menu bar for debugging/benchmarking
self.setup_menu_bar()
def setup_menu_bar(self):
"""Setup the menu bar with debugging options"""
menubar = tk.Menu(self.root)
self.root.config(menu=menubar)
# Debug menu
debug_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Debug", menu=debug_menu)
debug_menu.add_command(label="Toggle Benchmarking", command=self.toggle_benchmarking)
debug_menu.add_separator()
debug_menu.add_command(label="Profile Repository Loading", command=self.profile_repo_loading)
debug_menu.add_command(label="Profile Branch Filtering", command=self.profile_branch_filtering)
def toggle_benchmarking(self):
"""Toggle benchmarking on/off"""
toggle_benchmarking()
def profile_repo_loading(self):
"""Profile repository loading performance"""
if not self.repositories:
messagebox.showwarning("No Data", "Please scan repositories first")
return
print(f"\n📊 PROFILING REPOSITORY LOADING ({len(self.repositories)} repositories)")
print("=" * 60)
slow_repos = []
total_time = 0
for repo_path, repo in self.repositories.items():
with time_operation(f"Loading branches for {os.path.basename(repo_path)}"):
start = time.perf_counter()
repo.load_branches_if_needed()
end = time.perf_counter()
duration = end - start
total_time += duration
if duration > 0.1: # More than 100ms
slow_repos.append((repo_path, duration))
print(f"\n📈 SUMMARY:")
print(f"Total time: {total_time:.3f}s")
print(f"Average per repo: {total_time/len(self.repositories):.3f}s")
if slow_repos:
print(f"\n⚠️ SLOW REPOSITORIES (>100ms):")
for repo_path, duration in sorted(slow_repos, key=lambda x: x[1], reverse=True):
print(f" {os.path.basename(repo_path)}: {duration:.3f}s")
else:
print("\n✅ All repositories loaded quickly (<100ms)")
def profile_branch_filtering(self):
"""Profile branch filtering performance"""
if not self.branch_filter_user and not self.branch_filter_message:
messagebox.showwarning("No Filters", "Please set branch filters first")
return
print(f"\n📊 PROFILING BRANCH FILTERING")
print("=" * 60)
# Test the current filtering operation
self.update_repository_tree_with_branch_filter()
def select_folder(self):
"""Open folder selection dialog"""
folder = filedialog.askdirectory(title="Select folder to scan for Git repositories")
if folder:
self.selected_folder = folder
self.folder_label.config(text=folder)
self.scan_repositories()
def rescan_folder(self):
"""Rescan the selected folder"""
if self.selected_folder:
self.scan_repositories()
else:
messagebox.showwarning("Warning", "Please select a folder first")
def scan_repositories(self):
"""Scan the selected folder for Git repositories"""
if not self.selected_folder:
return
self.root.config(cursor="wait")
self.root.update()
# Run scanning in a separate thread to prevent UI freezing
threading.Thread(target=self._scan_repositories_thread, daemon=True).start()
def _scan_repositories_thread(self):
"""Thread function for scanning repositories"""
try:
self.repositories.clear()
self.folder_tree.clear()
repo_count = 0
skipped_dirs = {'.svn', '.hg', 'node_modules', '__pycache__', '.venv', 'venv'}
# Walk through directory tree with optimizations
for root, dirs, files in os.walk(self.selected_folder, topdown=True):
# Skip common non-repository directories for performance (but keep .git)
dirs[:] = [d for d in dirs if d not in skipped_dirs]
# Check for regular git repository
if '.git' in dirs:
# This is a regular git repository
repo = GitRepository(root, is_submodule=False)
# Load all branches immediately during scan
repo.load_branches()
self.repositories[root] = repo
repo_count += 1
# Continue scanning subdirectories to find submodules
# but exclude .git directory itself
dirs[:] = [d for d in dirs if d != '.git']
# Update UI every 5 repositories for progress feedback
if repo_count % 5 == 0:
self.root.after(0, lambda c=repo_count: self._update_scan_progress(c))