-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
1737 lines (1510 loc) · 74.1 KB
/
Copy pathgui.py
File metadata and controls
1737 lines (1510 loc) · 74.1 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
"""
GitFollow GUI - Desktop interface for GitFollow.
Run: python gui.py or double-click GitFollow.exe
"""
import colorsys
import queue
import time
import tkinter as tk
from tkinter import scrolledtext, messagebox
import importlib
import json
import logging
import os
import sys
import threading
import webbrowser
from pathlib import Path
from datetime import datetime, timezone
# ── Paths ─────────────────────────────────────────────────────────────────────
if getattr(sys, "frozen", False):
BASE_DIR = Path(sys.executable).parent
else:
BASE_DIR = Path(__file__).parent
ENV_FILE = BASE_DIR / ".env"
STATE_FILE = BASE_DIR / "data" / "state.json"
# ── CA bundle sanity check ────────────────────────────────────────────────────
# Some installers (e.g. PostgreSQL) set CURL_CA_BUNDLE / REQUESTS_CA_BUNDLE /
# SSL_CERT_FILE machine-wide, pointing at their own cert bundle. If that path
# later goes missing, `requests` refuses every call with
# "Could not find a suitable TLS CA certificate bundle". Drop any such
# dangling env var so requests falls back to certifi's bundled certs.
for _ca_var in ("REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE", "SSL_CERT_FILE"):
_ca_path = os.environ.get(_ca_var)
if _ca_path and not Path(_ca_path).is_file():
os.environ.pop(_ca_var, None)
VERSION = "2.3.6"
# ── GitHub Dark Dimmed color tokens ───────────────────────────────────────────
C_BG = "#22272e" # canvas-default
C_SURFACE = "#2d333b" # canvas-subtle
C_SIDEBAR = "#1c2128" # canvas-inset (sidebar)
C_SIDEBAR_H = "#2d333b" # sidebar hover
C_SIDEBAR_S = "#2d333b" # sidebar selected
C_ACCENT = "#539bf5" # accent-fg
C_SUCCESS = "#57ab5a" # success-fg
C_DANGER = "#e5534b" # danger-fg
C_WARNING = "#c69026" # attention-fg
C_TEXT = "#adbac7" # fg-default
C_TEXT2 = "#768390" # fg-muted
C_MUTED = "#636e7b" # fg-subtle
C_SEP = "#444c56" # border-default
C_TERM_BG = "#1c2128" # canvas-inset (terminal)
C_TERM_FG = "#adbac7" # fg-default
F_APP = ("Segoe UI", 12, "bold")
F_H1 = ("Segoe UI", 17, "bold")
F_H2 = ("Segoe UI", 12, "bold")
F_UI = ("Segoe UI", 10)
F_BOLD = ("Segoe UI", 10, "bold")
F_SM = ("Segoe UI", 9)
F_XS = ("Segoe UI", 8)
F_NUM = ("Segoe UI", 26, "bold")
F_MONO = ("Consolas", 9)
F_NAV = ("Segoe UI", 10)
# ── Helpers ───────────────────────────────────────────────────────────────────
def load_env() -> dict:
env = {}
if ENV_FILE.exists():
for line in ENV_FILE.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, _, v = line.partition("=")
env[k.strip()] = v.strip()
return env
def save_env(env: dict):
ENV_FILE.write_text(
"\n".join(f"{k}={v}" for k, v in env.items() if v.strip()) + "\n",
encoding="utf-8",
)
def load_state() -> dict:
if STATE_FILE.exists():
try:
return json.loads(STATE_FILE.read_text(encoding="utf-8"))
except Exception:
pass
return {
"following": {},
"quality_cache": {},
"stats": {"followed": 0, "unfollowed": 0, "mutual": 0},
}
def _darken(hex_color: str, amount: float) -> str:
"""Return a darkened version of a hex color."""
hex_c = hex_color.lstrip("#")
r, g, b = (int(hex_c[i:i+2], 16) / 255 for i in (0, 2, 4))
h, s, v = colorsys.rgb_to_hsv(r, g, b)
r2, g2, b2 = colorsys.hsv_to_rgb(h, s, max(0.0, v - amount))
return "#{:02x}{:02x}{:02x}".format(int(r2 * 255), int(g2 * 255), int(b2 * 255))
# ── Rounded button (Canvas-based) ─────────────────────────────────────────────
class RoundedButton(tk.Canvas):
"""Pill-shaped button drawn on a Canvas for rounded corners."""
def __init__(self, parent, text, command,
width=130, height=34, radius=8,
bg=C_ACCENT, fg="white", font=F_BOLD, **kwargs):
super().__init__(
parent, width=width, height=height,
bg=parent.cget("bg"), highlightthickness=0, **kwargs
)
self._text = text
self._orig_cmd = command
self._command = command
self._orig_bg = bg
self._bg = bg
self._hover_bg = _darken(bg, 0.12)
self._fg = fg
self._radius = radius
self._font = font
self._btn_w = width
self._btn_h = height
self._disabled = False
self._hovering = False
self._draw()
self.bind("<Enter>", self._on_enter)
self.bind("<Leave>", self._on_leave)
self.bind("<Button-1>", self._on_click)
def _rounded_rect(self, color: str):
self.delete("all")
w, h, r = self._btn_w, self._btn_h, self._radius
c = color
self.create_arc(0, 0, 2*r, 2*r, start=90, extent=90, fill=c, outline=c)
self.create_arc(w-2*r, 0, w, 2*r, start=0, extent=90, fill=c, outline=c)
self.create_arc(0, h-2*r, 2*r, h, start=180, extent=90, fill=c, outline=c)
self.create_arc(w-2*r, h-2*r, w, h, start=270, extent=90, fill=c, outline=c)
self.create_rectangle(r, 0, w-r, h, fill=c, outline=c)
self.create_rectangle(0, r, w, h-r, fill=c, outline=c)
self.create_text(w // 2, h // 2, text=self._text,
fill=self._fg, font=self._font)
def _draw(self):
if self._disabled:
self._rounded_rect(C_MUTED)
elif self._hovering:
self._rounded_rect(self._hover_bg)
else:
self._rounded_rect(self._bg)
def _on_enter(self, _e=None):
if not self._disabled:
self._hovering = True
self.config(cursor="hand2")
self._draw()
def _on_leave(self, _e=None):
self._hovering = False
self.config(cursor="")
self._draw()
def _on_click(self, _e=None):
if self._command and not self._disabled:
self._command()
def config_state(self, disabled: bool):
self._disabled = disabled
self._hovering = False
self._command = None if disabled else self._orig_cmd
self._bg = C_MUTED if disabled else self._orig_bg
self._draw()
# ── Tooltip ────────────────────────────────────────────────────────────────────
class Tooltip:
"""Dark floating tooltip on hover."""
def __init__(self, widget: tk.Widget, text: str):
self._win = None
self._text = text
widget.bind("<Enter>", self._show)
widget.bind("<Leave>", self._hide)
widget.bind("<Button>", self._hide)
def _show(self, event=None):
if self._win:
return
w = event.widget
x = w.winfo_rootx() + w.winfo_width() + 8
y = w.winfo_rooty() + (w.winfo_height() // 2) - 14
self._win = tw = tk.Toplevel(w)
tw.wm_overrideredirect(True)
tw.wm_attributes("-topmost", True)
tw.wm_geometry(f"+{x}+{y}")
tk.Label(
tw, text=self._text, justify="left", wraplength=260,
bg=C_SURFACE, fg=C_TEXT, font=F_SM, padx=12, pady=8,
).pack()
def _hide(self, event=None):
if self._win:
self._win.destroy()
self._win = None
def _tip(parent, text: str, bg=C_BG) -> tk.Label:
"""Small inline ? label with a hover tooltip."""
lbl = tk.Label(parent, text="?", font=("Segoe UI", 8, "bold"),
fg=C_MUTED, bg=bg, cursor="question_arrow", width=2)
Tooltip(lbl, text)
return lbl
def _relative_time(iso_str: str) -> str:
"""Return a human-readable relative time string from an ISO timestamp."""
if not iso_str:
return "unknown"
try:
dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))
diff = datetime.now(timezone.utc) - dt
total_seconds = int(diff.total_seconds())
if total_seconds < 60:
return "just now"
if total_seconds < 3600:
return f"{total_seconds // 60}m ago"
if total_seconds < 86400:
return f"{total_seconds // 3600}h ago"
days = diff.days
if days < 30:
return f"{days}d ago"
if days < 365:
return f"{days // 30}mo ago"
return f"{days // 365}y ago"
except Exception:
return "unknown"
# ── Log handler ────────────────────────────────────────────────────────────────
class _GUILogHandler(logging.Handler):
def __init__(self, callback):
super().__init__()
self.callback = callback
def emit(self, record):
try:
self.callback(self.format(record) + "\n")
except Exception:
pass
# ── App ────────────────────────────────────────────────────────────────────────
MAX_LOG_LINES = 2000 # keep the last N lines in the output terminal
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("GitFollow")
self.geometry("960x640")
self.resizable(True, True)
self.minsize(960, 640)
self.configure(bg=C_SIDEBAR)
_icon = BASE_DIR / "assets" / "icon.ico"
if _icon.exists():
try:
self.iconbitmap(str(_icon))
except Exception:
pass
self._running = False
self._stop_requested_early = False # stop clicked before _gf_module was set
self._pages = {}
self._nav_frames = {}
self._current_page = None
self._log_queue = queue.Queue()
self._log_line_count = 0
self.protocol("WM_DELETE_WINDOW", self._on_close)
self._build_ui()
self.after(50, self._poll_log_queue)
self.after(100, self._on_open)
# ── Shell ──────────────────────────────────────────────────────────────────
def _build_ui(self):
# Left sidebar
self._sidebar = tk.Frame(self, bg=C_SIDEBAR, width=190)
self._sidebar.pack(side="left", fill="y")
self._sidebar.pack_propagate(False)
# Right content pane
self._pane = tk.Frame(self, bg=C_BG)
self._pane.pack(side="left", fill="both", expand=True)
self._build_sidebar()
self._build_setup_page()
self._build_dashboard_page()
self._build_run_page()
self._build_people_page()
self._build_settings_page()
# Status bar (pinned to bottom of pane)
tk.Frame(self._pane, bg=C_SEP, height=1).pack(side="bottom", fill="x")
bar = tk.Frame(self._pane, bg=C_SURFACE, height=30)
bar.pack(side="bottom", fill="x")
bar.pack_propagate(False)
self._status_var = tk.StringVar(value="Ready")
tk.Label(bar, textvariable=self._status_var,
bg=C_SURFACE, fg=C_MUTED, font=F_SM).pack(side="left", padx=16, pady=6)
self._show_page("setup")
# ── Sidebar ────────────────────────────────────────────────────────────────
def _build_sidebar(self):
# App branding
brand = tk.Frame(self._sidebar, bg=C_SIDEBAR, height=60)
brand.pack(fill="x")
brand.pack_propagate(False)
tk.Label(brand, text="GitFollow", bg=C_SIDEBAR, fg="white",
font=F_APP).pack(side="left", padx=18, pady=18)
tk.Label(brand, text=f"v{VERSION}", bg=C_SIDEBAR, fg=C_MUTED,
font=F_XS).pack(side="left", pady=22)
tk.Frame(self._sidebar, bg=C_SEP, height=1).pack(fill="x")
tk.Label(self._sidebar, text="MENU", bg=C_SIDEBAR, fg=C_MUTED,
font=("Segoe UI", 8, "bold")).pack(anchor="w", padx=18, pady=(12, 2))
for key, icon, label in [
("setup", "checkmark.circle", "Setup"),
("dashboard", "chart.bar", "Dashboard"),
("run", "play.circle", "Run"),
("people", "person.2", "People"),
("settings", "gearshape", "Settings"),
]:
self._nav_item(key, label)
# Spacer + license note
tk.Frame(self._sidebar, bg=C_SIDEBAR).pack(fill="both", expand=True)
tk.Label(self._sidebar, text="MIT License",
bg=C_SIDEBAR, fg=C_MUTED, font=F_XS).pack(side="bottom", pady=14)
def _nav_item(self, key: str, label: str):
frame = tk.Frame(self._sidebar, bg=C_SIDEBAR, cursor="hand2")
frame.pack(fill="x", padx=8, pady=1)
# Accent bar (shown when selected)
bar = tk.Frame(frame, bg=C_SIDEBAR, width=3)
bar.pack(side="left", fill="y")
inner = tk.Label(frame, text=f" {label}", bg=C_SIDEBAR, fg=C_MUTED,
font=F_NAV, anchor="w", padx=10, pady=8)
inner.pack(fill="x", side="left", expand=True)
def click(_e=None, k=key):
self._show_page(k)
def enter(_e=None):
if self._current_page != key:
frame.config(bg=C_SIDEBAR_H)
inner.config(bg=C_SIDEBAR_H)
bar.config(bg=C_SIDEBAR_H)
def leave(_e=None):
if self._current_page != key:
frame.config(bg=C_SIDEBAR)
inner.config(bg=C_SIDEBAR)
bar.config(bg=C_SIDEBAR)
for w in (frame, inner, bar):
w.bind("<Button-1>", click)
w.bind("<Enter>", enter)
w.bind("<Leave>", leave)
self._nav_frames[key] = (frame, inner, bar)
def _show_page(self, name: str):
self._current_page = name
for pg in self._pages.values():
pg.pack_forget()
self._pages[name].pack(fill="both", expand=True)
for key, (frame, inner, bar) in self._nav_frames.items():
if key == name:
frame.config(bg=C_SIDEBAR_S)
inner.config(bg=C_SIDEBAR_S, fg=C_TEXT,
font=("Segoe UI", 10, "bold"))
bar.config(bg=C_ACCENT)
else:
frame.config(bg=C_SIDEBAR)
inner.config(bg=C_SIDEBAR, fg=C_MUTED, font=F_NAV)
bar.config(bg=C_SIDEBAR)
# ── Page scaffold ──────────────────────────────────────────────────────────
def _page_header(self, page: tk.Frame, title: str, subtitle: str = "") -> tk.Frame:
"""White header bar. Returns the right-side actions frame."""
hdr = tk.Frame(page, bg=C_SURFACE)
hdr.pack(fill="x")
left = tk.Frame(hdr, bg=C_SURFACE)
left.pack(side="left", fill="y")
tk.Label(left, text=title, bg=C_SURFACE, fg=C_TEXT,
font=F_H1).pack(anchor="w", padx=24, pady=(18, 0))
if subtitle:
tk.Label(left, text=subtitle, bg=C_SURFACE, fg=C_MUTED,
font=F_SM).pack(anchor="w", padx=24, pady=(1, 16))
else:
tk.Frame(left, height=18, bg=C_SURFACE).pack()
right = tk.Frame(hdr, bg=C_SURFACE)
right.pack(side="right", fill="y", padx=22, pady=18)
tk.Frame(page, bg=C_SEP, height=1).pack(fill="x")
return right
def _card(self, parent, **pack_kw) -> tk.Frame:
"""Surface card with a hairline border for definition against the page bg."""
card = tk.Frame(parent, bg=C_SURFACE,
highlightthickness=1, highlightbackground=C_SEP)
card.pack(**pack_kw)
return card
# ── Setup page ─────────────────────────────────────────────────────────────
def _build_setup_page(self):
page = tk.Frame(self._pane, bg=C_BG)
self._pages["setup"] = page
self._page_header(page, "Setup", "Verify your environment before running.")
content = tk.Frame(page, bg=C_BG)
content.pack(fill="both", expand=True, padx=20, pady=20)
card = self._card(content, fill="x")
checks = [
("python", "Python 3.8+",
"GitFollow requires Python 3.8 or newer."),
("requests", "requests library installed",
"Handles all GitHub API calls. Run 'pip install requests' if missing."),
("token", "GH_TOKEN configured",
"Your GitHub Personal Access Token. Set it in the Settings tab."),
("username", "GH_USERNAME configured",
"Your GitHub username. Set it in the Settings tab."),
("data_dir", "data/ directory exists",
"Stores state.json which tracks follows and quality check results."),
]
self._check_icons = {}
for key, label, tooltip in checks:
row = tk.Frame(card, bg=C_SURFACE)
row.pack(fill="x", padx=20, pady=5)
dot = tk.Label(row, text="●", font=("Segoe UI", 13),
bg=C_SURFACE, fg=C_MUTED, width=2)
dot.pack(side="left")
tk.Label(row, text=label, font=F_UI,
bg=C_SURFACE, fg=C_TEXT).pack(side="left", padx=(4, 0))
_tip(row, tooltip, bg=C_SURFACE).pack(side="left", padx=(8, 0))
self._check_icons[key] = dot
tk.Frame(card, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=(8, 0))
btn_row = tk.Frame(card, bg=C_SURFACE)
btn_row.pack(fill="x", padx=20, pady=14)
RoundedButton(btn_row, "Re-check", self._run_checks,
width=100, height=32).pack(side="left", padx=(0, 8))
self._test_conn_btn = RoundedButton(
btn_row, "Test Connection", self._test_connection,
width=130, height=32, bg=C_TEXT2,
)
self._test_conn_btn.pack(side="left", padx=(0, 8))
Tooltip(self._test_conn_btn,
"Makes a live call to the GitHub API to confirm GH_TOKEN is valid "
"and GH_USERNAME matches the token's account.")
RoundedButton(btn_row, "Auto-fix", self._autofix,
width=100, height=32, bg=C_SUCCESS).pack(side="left", padx=(0, 8))
RoundedButton(btn_row, "Create Token",
lambda: webbrowser.open(
"https://github.com/settings/tokens/new"
"?scopes=user%3Afollow&description=GitFollow"
),
width=120, height=32, bg=C_TEXT2).pack(side="left")
self._setup_msg = tk.Label(card, text="", font=F_SM, bg=C_SURFACE,
wraplength=850, justify="left")
self._setup_msg.pack(anchor="w", padx=20, pady=(0, 14))
def _run_checks(self):
self._set_status("Running checks...")
results = {}
results["python"] = sys.version_info >= (3, 8)
try:
import requests # noqa
results["requests"] = True
except ImportError:
results["requests"] = False
merged = {**load_env(), **os.environ}
results["token"] = bool(merged.get("GH_TOKEN", "").strip())
results["username"] = bool(merged.get("GH_USERNAME", "").strip())
results["data_dir"] = (BASE_DIR / "data").exists()
for key, ok in results.items():
self._check_icons[key].config(fg=C_SUCCESS if ok else C_DANGER)
all_ok = all(results.values())
self._setup_msg.config(
text="All checks passed. You are ready to run." if all_ok
else "Fix the failing items above, then click Re-check.",
fg=C_SUCCESS if all_ok else C_DANGER,
)
self._set_status("Checks complete." if all_ok else "Some checks failed.")
def _test_connection(self):
env = {**load_env(), **os.environ}
token = env.get("GH_TOKEN", "").strip()
user = env.get("GH_USERNAME", "").strip()
if not token or not user:
messagebox.showerror(
"Missing credentials",
"Set GH_TOKEN and GH_USERNAME in the Settings tab first.",
)
return
self._test_conn_btn.config_state(disabled=True)
self._setup_msg.config(text="Testing connection to GitHub...", fg=C_MUTED)
self._set_status("Testing GitHub connection...")
def _fetch():
try:
import requests
resp = requests.get(
"https://api.github.com/user",
headers={"Authorization": f"token {token}",
"Accept": "application/vnd.github.v3+json"},
timeout=10,
)
if resp.status_code == 200:
login = resp.json().get("login", "")
if login.lower() == user.lower():
msg, ok = f"Connected as {login} — token is valid and ready to use.", True
else:
msg, ok = (
f"Token is valid but belongs to '{login}', not '{user}'. "
"Update GH_USERNAME in Settings.", False,
)
elif resp.status_code == 401:
msg, ok = "401 Unauthorized — GH_TOKEN is invalid, expired, or revoked.", False
else:
msg, ok = f"GitHub API returned HTTP {resp.status_code}.", False
except Exception as e:
msg, ok = f"Connection failed: {e}", False
self.after(0, lambda: self._test_connection_done(msg, ok))
threading.Thread(target=_fetch, daemon=True).start()
def _test_connection_done(self, msg: str, ok: bool):
self._test_conn_btn.config_state(disabled=False)
self._setup_msg.config(text=msg, fg=C_SUCCESS if ok else C_DANGER)
self._set_status("Connection test complete.")
def _autofix(self):
import subprocess as sp
fixed = []
# In a frozen exe, requests is already bundled — pip cannot help here
if not getattr(sys, "frozen", False):
try:
import requests # noqa
except ImportError:
try:
no_win = getattr(sp, "CREATE_NO_WINDOW", 0)
sp.check_call(
[sys.executable, "-m", "pip", "install", "requests", "-q"],
creationflags=no_win,
)
fixed.append("Installed requests")
except Exception as e:
messagebox.showerror("Auto-fix failed", str(e))
return
data_dir = BASE_DIR / "data"
if not data_dir.exists():
data_dir.mkdir(parents=True)
fixed.append("Created data/ directory")
if not ENV_FILE.exists():
ENV_FILE.write_text("GH_TOKEN=\nGH_USERNAME=\n", encoding="utf-8")
fixed.append("Created .env - open Settings to fill in credentials")
messagebox.showinfo(
"Auto-fix",
("Fixed:\n " + "\n ".join(fixed)) if fixed else "Nothing needed fixing.",
)
self._run_checks()
# ── Dashboard page ─────────────────────────────────────────────────────────
def _build_dashboard_page(self):
page = tk.Frame(self._pane, bg=C_BG)
self._pages["dashboard"] = page
hdr_right = self._page_header(page, "Dashboard", "Live statistics.")
self._dash_ts = tk.Label(hdr_right, text="", font=F_SM,
bg=C_SURFACE, fg=C_MUTED)
self._dash_ts.pack(side="right", padx=(0, 12), anchor="center")
RoundedButton(hdr_right, "Refresh", self._refresh_dashboard,
width=90, height=30, font=F_SM).pack(side="right", padx=(0, 10))
RoundedButton(hdr_right, "Clear Cache", self._clear_cache,
width=100, height=30, font=F_SM, bg=C_WARNING).pack(side="right", padx=(0, 10))
content = tk.Frame(page, bg=C_BG)
content.pack(fill="both", expand=True, padx=20, pady=20)
grid = tk.Frame(content, bg=C_BG)
grid.pack(fill="x")
card_defs = [
("following", "FOLLOWING", "Your current total following count on GitHub."),
("followers", "FOLLOWERS", "Your current total follower count on GitHub."),
("mutual", "MUTUAL FOLLOWS", "Accounts currently marked as mutual in state.json (they follow you back)."),
("followed", "TOTAL FOLLOWED", "Total accounts followed through GitFollow across all runs."),
("unfollowed", "TOTAL UNFOLLOWED", "Total accounts unfollowed through GitFollow across all runs."),
("cached", "CACHED CHECKS", "Quality check results stored locally to avoid re-checking."),
]
tk.Label(grid, text="CURRENT", font=("Segoe UI", 8, "bold"),
bg=C_BG, fg=C_MUTED).grid(
row=0, column=0, columnspan=3, sticky="w", pady=(0, 6))
tk.Label(grid, text="ALL-TIME", font=("Segoe UI", 8, "bold"),
bg=C_BG, fg=C_MUTED).grid(
row=2, column=0, columnspan=3, sticky="w", pady=(16, 6))
self._stat_vars = {}
for i, (key, label, tooltip) in enumerate(card_defs):
col = i % 3
row = 1 if i < 3 else 3
card = tk.Frame(grid, bg=C_SURFACE,
highlightthickness=1, highlightbackground=C_SEP)
card.grid(row=row, column=col,
padx=(0 if col == 0 else 10, 0),
sticky="nsew")
# Mutual follows gets a status accent (reciprocated = good) —
# the other five are plain counters, not a categorical set, so
# they stay neutral rather than each getting an arbitrary hue.
if key == "mutual":
tk.Frame(card, bg=C_SUCCESS, width=3).pack(side="left", fill="y")
inner = tk.Frame(card, bg=C_SURFACE, padx=20, pady=16)
inner.pack(side="left", fill="both", expand=True)
top_row = tk.Frame(inner, bg=C_SURFACE)
top_row.pack(fill="x")
tk.Label(top_row, text=label, font=("Segoe UI", 8),
bg=C_SURFACE, fg=C_MUTED).pack(side="left")
_tip(top_row, tooltip, bg=C_SURFACE).pack(side="right")
var = tk.StringVar(value="--")
self._stat_vars[key] = var
tk.Label(inner, textvariable=var, font=F_NUM,
bg=C_SURFACE, fg=C_TEXT).pack(anchor="w", pady=(8, 0))
for col in range(3):
grid.columnconfigure(col, weight=1)
tk.Label(content,
text="Following / Followers fetched live from the GitHub API. "
"Other stats read from local state.json.",
font=F_XS, bg=C_BG, fg=C_MUTED,
wraplength=700, justify="left",
).pack(anchor="w", pady=(14, 0))
def _refresh_dashboard(self):
state = load_state()
stats = state.get("stats", {})
cache = state.get("quality_cache", {})
# Compute current mutual count directly from state (not the lifetime counter,
# which never decrements when someone unfollows you).
current_mutual = sum(
1 for v in state.get("following", {}).values() if v.get("mutual")
)
self._stat_vars["mutual"].set(f"{current_mutual:,}")
self._stat_vars["followed"].set(f"{stats.get('followed', 0):,}")
self._stat_vars["unfollowed"].set(f"{stats.get('unfollowed', 0):,}")
self._stat_vars["cached"].set(f"{len(cache):,}")
self._stat_vars["following"].set("...")
self._stat_vars["followers"].set("...")
self._dash_ts.config(text="Fetching...")
self._set_status("Fetching live counts from GitHub...")
def _fetch():
env = {**load_env(), **os.environ}
token = env.get("GH_TOKEN", "").strip()
user = env.get("GH_USERNAME", "").strip()
if not token or not user:
self.after(0, lambda: (
self._stat_vars["following"].set("--"),
self._stat_vars["followers"].set("--"),
self._dash_ts.config(text="Set credentials in Settings"),
self._set_status("Credentials not configured."),
))
return
try:
import requests
resp = requests.get(
f"https://api.github.com/users/{user}",
headers={"Authorization": f"token {token}",
"Accept": "application/vnd.github.v3+json"},
timeout=10,
)
if resp.status_code == 200:
data = resp.json()
f_ing = data.get("following", 0)
f_ers = data.get("followers", 0)
ts = datetime.now().strftime("%H:%M:%S")
self.after(0, lambda: (
self._stat_vars["following"].set(f"{f_ing:,}"),
self._stat_vars["followers"].set(f"{f_ers:,}"),
self._dash_ts.config(text=f"Updated {ts}"),
self._set_status("Dashboard refreshed."),
))
elif resp.status_code == 401:
self.after(0, lambda: (
self._stat_vars["following"].set("--"),
self._stat_vars["followers"].set("--"),
self._dash_ts.config(text="Auth error (401)"),
self._set_status("401 Unauthorized — token is invalid or expired. Update GH_TOKEN in Settings."),
))
else:
self.after(0, lambda: (
self._stat_vars["following"].set("Err"),
self._stat_vars["followers"].set("Err"),
self._dash_ts.config(text=f"API error {resp.status_code}"),
self._set_status(f"GitHub API returned {resp.status_code}."),
))
except Exception as e:
self.after(0, lambda: (
self._dash_ts.config(text="Network error"),
self._set_status(f"Error: {e}"),
))
threading.Thread(target=_fetch, daemon=True).start()
def _clear_cache(self):
state = load_state()
count = len(state.get("quality_cache", {}))
if count == 0:
messagebox.showinfo("Clear Cache", "Cache is already empty.")
return
if not messagebox.askyesno(
"Clear Cache",
f"Remove {count:,} cached quality-check results?\n"
"All accounts will be re-evaluated on the next run.",
):
return
state["quality_cache"] = {}
STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
STATE_FILE.write_text(json.dumps(state, indent=2), encoding="utf-8")
self._stat_vars["cached"].set("0")
self._set_status(f"Cleared {count:,} cached entries.")
# ── Run page ───────────────────────────────────────────────────────────────
def _build_run_page(self):
page = tk.Frame(self._pane, bg=C_BG)
self._pages["run"] = page
self._page_header(page, "Run", "Execute follow or unfollow passes locally.")
content = tk.Frame(page, bg=C_BG)
content.pack(fill="both", expand=True, padx=20, pady=20)
# Action buttons card
card = self._card(content, fill="x", pady=(0, 12))
btn_area = tk.Frame(card, bg=C_SURFACE, padx=20, pady=16)
btn_area.pack(fill="x")
self._btn_follow = RoundedButton(
btn_area, "Run Follow", lambda: self._start_run("follow"),
width=130, height=36,
)
self._btn_follow.pack(side="left", padx=(0, 10))
Tooltip(self._btn_follow,
"Searches GitHub for active developers meeting your quality criteria "
"and follows up to FOLLOW_LIMIT of them.")
self._btn_unfollow = RoundedButton(
btn_area, "Run Unfollow", lambda: self._start_run("unfollow"),
width=130, height=36, bg=C_TEXT2,
)
self._btn_unfollow.pack(side="left", padx=(0, 10))
Tooltip(self._btn_unfollow,
"Immediately unfollows every current non-reciprocator (except "
"whitelisted accounts). If Quality Unfollow is enabled in Settings, "
"also scans existing follows for quality and unfollows failures "
"(first run is slow; subsequent runs use the cache).")
self._btn_stop = RoundedButton(
btn_area, "Stop", self._stop_run,
width=80, height=36, bg=C_DANGER,
)
self._btn_stop.pack(side="left")
self._btn_stop.config_state(disabled=True)
clear_lbl = tk.Label(btn_area, text="Clear Log", font=F_SM,
fg=C_ACCENT, bg=C_SURFACE, cursor="hand2")
clear_lbl.pack(side="right")
clear_lbl.bind("<Button-1>", lambda _e: self._clear_log())
# Terminal card
term = tk.Frame(content, bg=C_TERM_BG,
highlightthickness=1, highlightbackground=C_SEP)
term.pack(fill="both", expand=True)
# Minimal header bar — no dots
chrome = tk.Frame(term, bg=C_SURFACE)
chrome.pack(fill="x")
tk.Label(chrome, text="Output", font=F_MONO,
bg=C_SURFACE, fg=C_MUTED).pack(side="left", padx=14, pady=6)
tk.Frame(term, bg=C_SEP, height=1).pack(fill="x")
self._log = scrolledtext.ScrolledText(
term, font=F_MONO, state="disabled",
bg=C_TERM_BG, fg=C_TERM_FG, insertbackground=C_TERM_FG,
relief="flat", borderwidth=0, selectbackground="#264f78",
)
self._log.pack(fill="both", expand=True, padx=4, pady=(0, 4))
def _start_run(self, mode: str):
if self._running:
messagebox.showinfo("Already running", "A run is already in progress.")
return
env = load_env()
merged = {**env, **os.environ}
if not merged.get("GH_TOKEN") or not merged.get("GH_USERNAME"):
messagebox.showerror(
"Missing credentials",
"GH_TOKEN and GH_USERNAME must be set.\nGo to the Settings tab.",
)
return
if mode == "unfollow":
env["FOLLOW_LIMIT"] = "0"
env.pop("FOLLOW_ONLY", None)
os.environ.pop("FOLLOW_ONLY", None)
# QUALITY_UNFOLLOW is whatever was saved in Settings (env, from .env);
# clear any stale process-level override left by a previous run.
os.environ.pop("QUALITY_UNFOLLOW", None)
# A manual button click is a deliberate, immediate action — the
# UNFOLLOW_HOURS grace period exists for the unattended/scheduled
# run so freshly-followed accounts get a chance to follow back
# before then. Clicking Run Unfollow by hand should act now.
env["UNFOLLOW_HOURS"] = "0"
else:
env["FOLLOW_ONLY"] = "true"
env.pop("QUALITY_UNFOLLOW", None)
os.environ.pop("QUALITY_UNFOLLOW", None)
os.environ.pop("FOLLOW_LIMIT", None)
env["STATE_FILE"] = str(STATE_FILE)
os.environ.update(env)
self._running = True
self._btn_follow.config_state(disabled=True)
self._btn_unfollow.config_state(disabled=True)
self._btn_stop.config_state(disabled=False)
self._set_status(f"Running {mode}...")
self._log_write(
f"\n{'=' * 60}\n"
f" GitFollow - {mode.title()} Run - "
f"{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')} UTC\n"
f"{'=' * 60}\n\n"
)
handler = _GUILogHandler(self._log_write)
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s"))
def _worker():
root_log = logging.getLogger()
root_log.setLevel(logging.INFO)
# Remove any StreamHandlers that write to stderr/stdout — these are
# None in a windowed exe and will suppress our handler via handleError.
for h in root_log.handlers[:]:
if isinstance(h, logging.StreamHandler) and not isinstance(h, _GUILogHandler):
root_log.removeHandler(h)
root_log.addHandler(handler)
try:
import gitfollow as _gf
importlib.reload(_gf)
_gf.stop_event.clear()
self._gf_module = _gf
# Honour a stop that was requested during the module reload
if self._stop_requested_early:
self._stop_requested_early = False
_gf.stop_event.set()
_gf.main()
except Exception as e:
self._log_write(f"\nERROR: {e}\n")
finally:
root_log.removeHandler(handler)
self._gf_module = None
self.after(0, self._run_done)
threading.Thread(target=_worker, daemon=True).start()
def _stop_run(self):
gf = getattr(self, "_gf_module", None)
if gf:
gf.stop_event.set()
else:
# Module not yet assigned (clicked Stop during reload) — flag it so
# the worker honours the request once the module is ready.
self._stop_requested_early = True
self._btn_stop.config_state(disabled=True)
self._set_status("Stop requested — finishing current operation...")
self._log_write("\n Stop requested — will halt after current operation.\n")
def _run_done(self):
self._running = False
self._btn_follow.config_state(disabled=False)
self._btn_unfollow.config_state(disabled=False)
self._btn_stop.config_state(disabled=True)
self._log_write(
f"\n{'=' * 60}\n"
f" Run complete - {datetime.now(timezone.utc).strftime('%H:%M:%S')} UTC\n"
f"{'=' * 60}\n"
)
self._set_status("Run complete.")
self._refresh_dashboard()
def _log_write(self, text: str):
self._log_queue.put(text)
def _poll_log_queue(self):
messages = []
try:
while True:
messages.append(self._log_queue.get_nowait())
except queue.Empty:
pass
if messages:
combined = "".join(messages)
new_lines = combined.count("\n")
self._log.config(state="normal")
self._log.insert(tk.END, combined)
self._log_line_count += new_lines
# Prune oldest lines to keep the widget bounded
if self._log_line_count > MAX_LOG_LINES:
excess = self._log_line_count - MAX_LOG_LINES
self._log.delete("1.0", f"{excess + 1}.0")
self._log_line_count = MAX_LOG_LINES
self._log.see(tk.END)
self._log.config(state="disabled")
self.after(50, self._poll_log_queue)
def _clear_log(self):
self._log.config(state="normal")
self._log.delete("1.0", tk.END)
self._log.config(state="disabled")
self._log_line_count = 0
# ── People page ────────────────────────────────────────────────────────────
def _build_people_page(self):
page = tk.Frame(self._pane, bg=C_BG)
self._pages["people"] = page
hdr_right = self._page_header(page, "People", "Browse following and followers.")
self._people_refresh_btn = RoundedButton(
hdr_right, "Refresh", self._load_people,
width=90, height=30, font=F_SM,
)
self._people_refresh_btn.pack(side="right")
# Sub-tab bar
self._people_tab_var = "following"
self._people_tab_btns = {}
tab_bar = tk.Frame(page, bg=C_SURFACE)
tab_bar.pack(fill="x")
for key, label in [("following", "Following"), ("followers", "Followers")]:
btn = tk.Label(tab_bar, text=label, font=F_BOLD,
cursor="hand2", bg=C_SURFACE, padx=20, pady=10)
btn.pack(side="left")
btn.bind("<Button-1>", lambda _e, k=key: self._switch_people_tab(k))
self._people_tab_btns[key] = btn
tk.Frame(page, bg=C_SEP, height=1).pack(fill="x")
# Action bar pinned to bottom
tk.Frame(page, bg=C_SEP, height=1).pack(side="bottom", fill="x")
action_bar = tk.Frame(page, bg=C_SURFACE)
action_bar.pack(side="bottom", fill="x")
self._people_sel_var = tk.StringVar(value="")
tk.Label(action_bar, textvariable=self._people_sel_var,
font=F_SM, bg=C_SURFACE, fg=C_MUTED).pack(side="left", padx=16, pady=10)