-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitmaster_flash.py
More file actions
2416 lines (2167 loc) · 108 KB
/
Copy pathgitmaster_flash.py
File metadata and controls
2416 lines (2167 loc) · 108 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
"""gitmaster_flash — fast terminal (TUI) overview of every Git repo below the
current directory, so you can tidy up many repos quickly.
Green = clean and in sync with the configured remote; red/yellow = needs
attention (modified/deleted/untracked files, merge conflicts, stashes, commits
ahead/behind). Problem repos sort to the top.
Keys (all shown in the footer, nothing to memorize; case-insensitive — f == F):
↑/↓ select a repo
→ expand (shows files with M/D/U/C and stashes)
← collapse
⏎ quit and cd into the repo in your terminal
(needs the shell wrapper `gmf` from gmf.zsh — a child process cannot
change the parent shell's working directory)
F/… open the repo in a configured app (see config.json)
C commit helper: suggests what to commit and what to .gitignore
P safely push the current branch to the private sync remote
L safely fast-forward the current branch from the private sync remote
G guarded GitHub push (preview + typed confirmation; branch only, no tags)
H explain the Git safety rules
U apply the latest stash (git stash pop, with confirmation)
S view the latest stash as a diff (read-only, scrollable)
D drop the latest stash (git stash drop, with confirmation)
R reload everything incl. `git fetch --all` (shows progress)
Q quit
Non-interactive: with --list / --json (or no TTY) it prints the overview as text
or JSON (machine-readable). Exit code 1 if any repo needs attention.
Two machines: `--diff HOST` compares this machine's repos with another one over
ssh and prints only the differences (read-only, never changes anything). The only
requirement is that `ssh HOST` works — gitmaster_flash does NOT need to be
installed there: the script is piped over stdin, so both sides always run the
exact same version. Remotes live in .git/config and are never carried by git
itself, so they drift silently between machines — that is what this finds.
Try it risk-free: `gitmaster_flash.py --demo` builds a throwaway sandbox of fake
repos in every state and opens the UI on it (also used for the README screenshots).
Config: ~/.config/gitmaster_flash/config.json (created on first run). Configurable:
app keys, the sync-remote match, scan exclusions, and UI language (en/de).
"""
from __future__ import annotations
import argparse
import concurrent.futures
import curses
import hashlib
import json
import os
import posixpath
import shlex
import stat
import subprocess
import sys
import tempfile
import unicodedata
import urllib.parse
from dataclasses import dataclass, field
from pathlib import Path
__version__ = "0.9.2"
CONFIG_PATH = Path.home() / ".config" / "gitmaster_flash" / "config.json"
# Defaults; die geschriebene config.json darf einzelne Schlüssel überschreiben.
# Bewusst generisch gehalten: eigene Editoren/Remote-Namen setzt man in der Config.
DEFAULT_CONFIG = {
# Taste -> App zum Öffnen des Repo-Ordners (macOS `open -a`). Die Taste
# erscheint automatisch im Footer ("E Editor"). Beispiel für weitere:
# "Z": {"name": "Zed", "path": "/Applications/Zed.app"} (freie Taste waehlen)
"apps": {
"E": {"name": "Editor", "path": "/Applications/Visual Studio Code.app"},
},
# Woran der Sync-Remote erkannt wird: Remote-Name ODER Host in der URL.
"sync_remote_names": ["origin"],
"sync_remote_hosts": [],
# Ordner, in die der Repo-Scan gar nicht erst hineinschaut (Tempo).
"skip_dirs": ["node_modules", "Library", ".Trash", "venv", ".venv", "__pycache__"],
# UI-Sprache: "en", "de" oder null = automatisch aus $LANG (Fallback en).
"lang": None,
# Timeout in Sekunden für einzelne git-Aufrufe (fetch darf länger).
"git_timeout": 10,
"fetch_timeout": 30,
}
# Muster für die Commit-Hilfe: Dateien, die typischerweise in .gitignore gehören.
# (basename_oder_teil, ist_verzeichnis, gitignore_zeile)
IGNORE_RULES = [
("node_modules", True, "node_modules/"),
("__pycache__", True, "__pycache__/"),
(".venv", True, ".venv/"),
("venv", True, "venv/"),
("dist", True, "dist/"),
("build", True, "build/"),
(".idea", True, ".idea/"),
(".pytest_cache", True, ".pytest_cache/"),
(".mypy_cache", True, ".mypy_cache/"),
(".ruff_cache", True, ".ruff_cache/"),
(".DS_Store", False, ".DS_Store"),
("Thumbs.db", False, "Thumbs.db"),
(".env", False, ".env"),
]
IGNORE_SUFFIXES = {".pyc": "*.pyc", ".log": "*.log", ".tmp": "*.tmp"}
# ---------------------------------------------------------------------------
# i18n — kleine Übersetzungsschicht (Englisch = Basis, Deutsch optional)
# ---------------------------------------------------------------------------
UI_LANG = "en" # von main() gesetzt; Tests nutzen die englische Basis.
TR = {
# Fortschritt / Kopf
"reading": {"en": "Reading repos", "de": "Lese Repos"},
"fetching": {"en": "Fetching from remote", "de": "Hole Stand vom Remote (fetch)"},
"hdr_repos": {"en": "repos", "de": "Repos"},
# --diff (two machines)
"diff_here": {"en": "here", "de": "hier"},
"diff_same": {"en": "No differences to {h}.", "de": "Kein Unterschied zu {h}."},
"diff_need_host": {"en": "--diff needs a host, e.g. --diff mymac",
"de": "--diff braucht einen Host, z.B. --diff meinmac"},
"diff_ssh_failed": {"en": "Cannot reach {h}: {e}", "de": "{h} nicht erreichbar: {e}"},
"diff_version": {
"en": "! version differs: {a} {va} vs {b} {vb} — compare with care",
"de": "! Version verschieden: {a} {va} vs. {b} {vb} — Vergleich mit Vorsicht lesen"},
# {m}/{a}/{b} kommen vorformatiert aus _loc(): "hier" bleibt nackt,
# Hostnamen bekommen "auf"/"on" — deshalb steht die Praeposition NICHT im Text.
"diff_on": {"en": "on {m}", "de": "auf {m}"},
"diff_only_on": {"en": "only {m}: {rel}", "de": "nur {m}: {rel}"},
"diff_remote_missing": {
"en": "DRIFT {rel}: remote '{r}' only {m} (git never transfers remotes)",
"de": "DRIFT {rel}: Remote '{r}' nur {m} (Git uebertraegt Remotes nie)"},
"diff_remote_state": {
"en": "DRIFT {rel}: {r} is {aa} ahead/{ab} behind {a}, {ba}/{bb} {b}",
"de": "DRIFT {rel}: {r} {a} {aa} voraus/{ab} zurueck, {b} {ba}/{bb}"},
"diff_sync_even": {
"en": "SYNC {rel}: {r} {aa} ahead/{ab} behind on both machines",
"de": "SYNC {rel}: {r} auf beiden Rechnern {aa} voraus/{ab} zurueck"},
"diff_branch": {"en": "local {rel}: [{ba}] {a}, [{bb}] {b}",
"de": "lokal {rel}: [{ba}] {a}, [{bb}] {b}"},
"diff_dirty": {"en": "local {rel}: {n} changed/new file(s) {m}",
"de": "lokal {rel}: {n} geaenderte/neue Datei(en) {m}"},
"diff_repo_field": {
"en": "DRIFT {rel}: {field} is {va} {a}, {vb} {b}",
"de": "DRIFT {rel}: {field} {a}={va}, {b}={vb}"},
"diff_remote_security": {
"en": "DRIFT {rel}: security/endpoint identity for {r} differs",
"de": "DRIFT {rel}: Sicherheit/Ziel-Identität für {r} unterscheidet sich"},
"hdr_review": {"en": "{n} to review", "de": "{n} zu prüfen"},
"hdr_clean": {"en": "all clean ✔", "de": "alles sauber ✔"},
# Repo-Zeile
"clean_synced": {"en": "✔ clean & synced", "de": "✔ sauber & synchron"},
"no_sync_remote": {"en": "no sync remote", "de": "kein Sync-Remote"},
"branch_not_on": {"en": "branch '{b}' not on {r}", "de": "Branch '{b}' nicht auf {r}"},
"detached": {"en": "detached HEAD", "de": "detached HEAD"},
"error_prefix": {"en": "ERROR: {e}", "de": "FEHLER: {e}"},
"conflict_n": {"en": "conflict:{n}", "de": "Konflikt:{n}"},
# Detailzeilen
"conflict_label": {"en": "C=conflict ", "de": "C=Konflikt "},
"stash_row_hint": {"en": "(U pop · S preview · D drop)",
"de": "(U anwenden · S Vorschau · D verwerfen)"},
"no_changes": {"en": "(no changes)", "de": "(keine Änderungen)"},
# Footer
"f1": {"en": " ↑/↓ select · → expand · ← collapse · ⏎ cd & quit · P sync push · L sync pull",
"de": " ↑/↓ wählen · → aufklappen · ← zuklappen · ⏎ cd & Exit · P Sync-Push · L Sync-Pull"},
"f2": {"en": " {apps} · C commit · U stash pop · R fetch all · G GitHub push",
"de": " {apps} · C Commit · U Stash pop · R fetch all · G GitHub-Push"},
"f3": {"en": " Q quit · S stash preview · D stash drop · H Git help",
"de": " Q Beenden · S Stash-Vorschau · D Stash verwerfen · H Git-Hilfe"},
"yesno": {"en": " (Y/N)", "de": " (J/N)"},
# Apps
"app_not_found": {"en": "App not found: {p} (edit config.json)",
"de": "App nicht gefunden: {p} (config.json anpassen)"},
"app_opened": {"en": "Opened {name}: {rel}", "de": "{name} geöffnet: {rel}"},
"app_open_failed": {"en": "Failed to open {name}: {e}",
"de": "{name} öffnen fehlgeschlagen: {e}"},
"cd_hint": {"en": "(Tip: install the `gmf` shell wrapper from gmf.zsh, "
"then you land there automatically.)",
"de": "(Tipp: Shell-Wrapper `gmf` aus gmf.zsh installieren, "
"dann landet man automatisch dort.)"},
# Stash
"no_stash": {"en": "No stash in this repo.", "de": "Kein Stash in diesem Repo."},
"resolve_conflicts_first": {
"en": "Resolve the merge conflicts first (open the repo with an app key), "
"then press U again.",
"de": "Erst die Merge-Konflikte auflösen (App-Taste öffnet das Repo), "
"dann erneut U drücken."},
"confirm_pop": {"en": "Apply latest stash in '{rel}' (git stash pop)?",
"de": "Neuesten Stash in '{rel}' anwenden (git stash pop)?"},
"cancelled": {"en": "Cancelled.", "de": "Abgebrochen."},
"stash_applied": {"en": "Stash applied in {rel}.", "de": "Stash angewendet in {rel}."},
"stash_conflict": {
"en": "Stash created {n} merge conflict(s) — the stash is kept. "
"Open the repo with an app key and resolve.",
"de": "Stash erzeugte {n} Merge-Konflikt(e) — Stash bleibt erhalten. "
"Repo mit einer App-Taste öffnen und auflösen."},
"stash_pop_failed": {"en": "stash pop failed: {e}", "de": "stash pop fehlgeschlagen: {e}"},
"empty_diff": {"en": "(empty diff)", "de": "(leerer Diff)"},
"stash_preview_failed": {"en": "Stash preview failed: {e}",
"de": "Stash-Vorschau fehlgeschlagen: {e}"},
"stash_preview_empty": {
"en": "(stash exists, but Git produced no displayable patch)",
"de": "(Stash vorhanden, aber Git erzeugte keinen darstellbaren Patch)"},
"stash_preview_title": {"en": "Stash preview · {rel} · {s}",
"de": "Stash-Vorschau · {rel} · {s}"},
"confirm_drop": {"en": "Drop latest stash in '{rel}' PERMANENTLY "
"(git stash drop)? Cannot be undone.",
"de": "Neuesten Stash in '{rel}' ENDGÜLTIG verwerfen "
"(git stash drop)? Nicht rückgängig machbar."},
"drop_cancelled": {"en": "Cancelled — stash kept.",
"de": "Abgebrochen — Stash bleibt erhalten."},
"stash_dropped": {"en": "Stash dropped in {rel}.", "de": "Stash verworfen in {rel}."},
"stash_drop_failed": {"en": "stash drop failed: {e}",
"de": "stash drop fehlgeschlagen: {e}"},
# Pager
"pager_footer": {"en": " ↑/↓ scroll · Q/Esc close · line {a}-{b} / {n}",
"de": " ↑/↓ scrollen · Q/Esc schließen · Zeile {a}-{b} / {n}"},
# Commit-Hilfe
"commit_title": {"en": "Commit helper · {rel} — review, then ⏎",
"de": "Commit-Hilfe · {rel} — Vorschlag prüfen, dann ⏎"},
"to_gitignore": {"en": "→ .gitignore ({p})", "de": "→ .gitignore ({p})"},
"do_commit": {"en": "✔ commit", "de": "✔ committen"},
"do_skip": {"en": "✘ skip", "de": "✘ auslassen"},
"commit_footer": {"en": " ␣ commit on/off · i gitignore on/off · ⏎ next · Esc cancel",
"de": " ␣ committen an/aus · i gitignore an/aus · ⏎ weiter · Esc abbrechen"},
"commit_cancelled": {"en": "Commit helper cancelled.", "de": "Commit-Hilfe abgebrochen."},
"nothing_selected": {"en": "Nothing selected.", "de": "Nichts ausgewählt."},
"commit_in": {"en": "Commit in {rel}", "de": "Commit in {rel}"},
"new_in_gitignore": {"en": "New in .gitignore:", "de": "Neu in .gitignore:"},
"to_commit_n": {"en": "To commit: {n} file(s)", "de": "Zu committen: {n} Datei(en)"},
"recent_msgs": {"en": "Recent commit messages (style reference):",
"de": "Letzte Commit-Messages (Stil-Vorlage):"},
"commit_msg_prompt": {"en": "Commit message: ", "de": "Commit-Message: "},
"empty_msg": {"en": "Empty message — cancelled.", "de": "Leere Message — abgebrochen."},
"git_add_failed": {"en": "git add failed: {e}", "de": "git add fehlgeschlagen: {e}"},
"commit_failed": {"en": "Commit failed: {e}", "de": "Commit fehlgeschlagen: {e}"},
"commit_conflicts": {
"en": "Commit helper is blocked while merge conflicts exist.",
"de": "Die Commit-Hilfe ist gesperrt, solange Merge-Konflikte bestehen."},
"committed_in": {"en": "Committed in {rel}.", "de": "Committet in {rel}."},
"confirm_push": {"en": "Push {n} commit(s) to {r} now?",
"de": "Jetzt {n} Commit(s) zu {r} pushen?"},
"committed_pushed": {"en": "Committed & pushed ({r}).", "de": "Committet & gepusht ({r})."},
"push_failed": {"en": "Push failed (Git exit code {code}).",
"de": "Push fehlgeschlagen (Git-Exit-Code {code})."},
"pull_failed": {"en": "Fast-forward failed (Git exit code {code}).",
"de": "Fast-forward fehlgeschlagen (Git-Exit-Code {code})."},
"nothing_to_commit": {"en": "Nothing to commit in this repo.",
"de": "Nichts zu committen in diesem Repo."},
# Sichere Push-/Pull-Hilfe
"no_sync_for_action": {"en": "No sync remote is configured for this repository.",
"de": "Für dieses Repo ist kein Sync-Remote konfiguriert."},
"public_simple_block": {
"en": "The sync remote is public. Use G for the guarded GitHub preview.",
"de": "Der Sync-Remote ist öffentlich. Nutze G für die geschützte GitHub-Vorschau."},
"transfer_fetch_failed": {"en": "Fetch from {r} failed (Git exit code {code}).",
"de": "Fetch von {r} fehlgeschlagen (Git-Exit-Code {code})."},
"transfer_inspect_failed": {
"en": "Git could not inspect the branch safely; no transfer was attempted.",
"de": "Git konnte den Branch nicht sicher prüfen; es wurde nichts übertragen."},
"remote_url_mismatch": {
"en": "{r} has multiple or differing fetch/push targets; transfer is blocked.",
"de": "{r} hat mehrere oder abweichende Fetch-/Push-Ziele; Transfer ist gesperrt."},
"transfer_changed": {
"en": "Branch, files, index, remote, or target changed after approval; review again.",
"de": "Branch, Dateien, Index, Remote oder Ziel änderten sich nach der Freigabe; erneut prüfen."},
"transfer_dirty": {"en": "Working tree is not clean — commit, ignore, or stash first.",
"de": "Arbeitsbaum ist nicht sauber — erst committen, ignorieren oder stashen."},
"transfer_detached": {"en": "Detached HEAD — use the terminal for this special case.",
"de": "Detached HEAD — diesen Sonderfall im Terminal bearbeiten."},
"transfer_missing": {"en": "Branch '{b}' does not exist on {r}; creating remote branches is blocked here.",
"de": "Branch '{b}' existiert nicht auf {r}; neue Remote-Branches sind hier gesperrt."},
"transfer_divergent": {"en": "Local and {r} have diverged ({a} ahead, {b} behind); no automatic reconciliation.",
"de": "Lokal und {r} sind divergiert ({a} voraus, {b} zurück); kein automatischer Abgleich."},
"transfer_behind": {"en": "Local branch is {n} commit(s) behind {r}; pull first.",
"de": "Der lokale Branch ist {n} Commit(s) hinter {r}; zuerst pullen."},
"nothing_to_push": {"en": "Nothing to push to {r}.", "de": "Nichts zu {r} zu pushen."},
"nothing_to_pull": {"en": "Nothing to pull from {r}.", "de": "Nichts von {r} zu pullen."},
"confirm_sync_push": {"en": "Push {n} commit(s) to the private sync remote {r}?",
"de": "{n} Commit(s) zum privaten Sync-Remote {r} pushen?"},
"confirm_sync_pull": {"en": "Fast-forward {n} commit(s) from the private sync remote {r}?",
"de": "{n} Commit(s) per Fast-forward vom privaten Sync-Remote {r} holen?"},
"sync_pushed": {"en": "Pushed current branch to {r} (no tags).",
"de": "Aktuellen Branch zu {r} gepusht (keine Tags)."},
"sync_pulled": {"en": "Fast-forwarded current branch from {r}.",
"de": "Aktuellen Branch per Fast-forward von {r} geholt."},
"no_github": {"en": "No GitHub remote in this repository.",
"de": "Dieses Repo hat keinen GitHub-Remote."},
"many_github": {"en": "Several GitHub remotes ({names}); use the terminal to choose deliberately.",
"de": "Mehrere GitHub-Remotes ({names}); bitte im Terminal bewusst auswählen."},
"github_preview": {"en": "GitHub push preview · {rel} → {r}/{b}",
"de": "GitHub-Push-Vorschau · {rel} → {r}/{b}"},
"github_type": {"en": "Type '{phrase}' to publish this branch only: ",
"de": "Zum Veröffentlichen nur dieses Branches '{phrase}' eingeben: "},
"github_cancelled": {"en": "GitHub push cancelled — nothing was published.",
"de": "GitHub-Push abgebrochen — nichts wurde veröffentlicht."},
"github_pushed": {"en": "Published current branch to {r}; no tags were sent.",
"de": "Aktuellen Branch zu {r} veröffentlicht; keine Tags übertragen."},
"github_changed": {"en": "Remote or outgoing files changed after the preview; review again.",
"de": "Remote oder ausgehende Dateien änderten sich nach der Vorschau; bitte erneut prüfen."},
"preview_branch_only": {
"en": "Branch only: approved OID + target lease, no tags or new remote branch.",
"de": "Nur Branch: freigegebene OID + Ziel-Lease, keine Tags/neuen Remote-Branches."},
"preview_privacy": {
"en": "Review every outgoing commit and file name; this is not an automatic privacy approval.",
"de": "Jeden ausgehenden Commit und Dateinamen prüfen; dies ist keine automatische Privacy-Freigabe."},
"outgoing_commits": {"en": "Outgoing commits:", "de": "Ausgehende Commits:"},
"changed_files": {"en": "Changed files:", "de": "Geänderte Dateien:"},
"none_label": {"en": "(none)", "de": "(keine)"},
"git_help_title": {"en": "Safe Git actions", "de": "Sichere Git-Aktionen"},
"git_help_body": {
"en": "P Push only the current branch to the private sync remote.\n"
" Requires a clean tree, fetches first, and rejects behind/divergent history.\n\n"
"L Pull only from the private sync remote by fast-forward.\n"
" Never merges or rebases and refuses dirty/divergent repositories.\n\n"
"G Guarded GitHub push. Shows outgoing commits and file names first.\n"
" Requires typing PUSH <remote>; pins source and target OIDs and sends no tags.\n"
" New or unrelated GitHub branches remain terminal-only special cases.\n\n"
"R Fetches all remotes in all repositories; it does not change working trees.",
"de": "P Nur den aktuellen Branch zum privaten Sync-Remote pushen.\n"
" Verlangt einen sauberen Tree, fetcht zuerst und blockiert Rückstand/Divergenz.\n\n"
"L Nur per Fast-forward vom privaten Sync-Remote holen.\n"
" Führt nie Merge oder Rebase aus und verweigert dirty/divergente Repos.\n\n"
"G Geschützter GitHub-Push mit Vorschau von Commits und Dateinamen.\n"
" Verlangt PUSH <Remote>; pinnt Quell-/Ziel-OID und sendet keine Tags.\n"
" Neue oder unverbundene GitHub-Branches bleiben Terminal-Sonderfälle.\n\n"
"R Fetcht alle Remotes aller Repos; Working Trees bleiben unverändert."},
# main
"not_a_dir": {"en": "Not a directory: {p}", "de": "Kein Ordner: {p}"},
"git_timeout": {"en": "git timeout", "de": "git-Timeout"},
"demo_built": {"en": "Demo sandbox: {p}\n(fake repos; delete the folder when done)",
"de": "Demo-Sandbox: {p}\n(Fake-Repos; Ordner danach löschen)"},
}
def t(key: str, **kw) -> str:
entry = TR.get(key, {})
s = entry.get(UI_LANG) or entry.get("en") or key
return s.format(**kw) if kw else s
def resolve_lang(cfg: dict, override: str | None = None) -> str:
if override in ("en", "de"):
return override
v = (cfg.get("lang") or "").lower()
if v in ("en", "de"):
return v
env = (os.environ.get("LC_ALL") or os.environ.get("LANG") or "").lower()
return "de" if env.startswith("de") else "en"
# ---------------------------------------------------------------------------
# Konfiguration
# ---------------------------------------------------------------------------
def load_config() -> dict:
"""Config laden; fehlt sie, mit Defaults anlegen (selbsterklärender Start)."""
cfg = json.loads(json.dumps(DEFAULT_CONFIG)) # tiefe Kopie
if CONFIG_PATH.exists():
try:
cfg.update(json.loads(CONFIG_PATH.read_text()))
except (json.JSONDecodeError, OSError) as exc:
print(f"Warning: cannot read {CONFIG_PATH} ({exc}) — using defaults.",
file=sys.stderr)
else:
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
CONFIG_PATH.write_text(json.dumps(DEFAULT_CONFIG, indent=2, ensure_ascii=False) + "\n")
# App-Tasten intern immer groß (Tastendruck wird ebenfalls großgezogen).
cfg["apps"] = {k.upper(): v for k, v in cfg.get("apps", {}).items()}
return cfg
# ---------------------------------------------------------------------------
# Git-Datensammlung (reine Logik, testbar)
# ---------------------------------------------------------------------------
@dataclass
class RepoStatus:
path: Path
rel: str # Pfad relativ zum Scan-Start (Anzeigename)
branch: str = "?"
remote: str | None = None # Name des erkannten Sync-Remotes (z.B. origin)
remote_state: str = "ok" # ok | no-remote | no-branch | detached | error
ahead: int = 0
behind: int = 0
# Zusatz-Info: Stand gegenüber dem *konfigurierten Upstream*, falls das ein
# ANDERER Remote als der Sync-Remote ist (typisch: github). So werden Commits
# sichtbar, die zwar auf dem Sync-Remote, aber nie z.B. zu GitHub gepusht wurden.
upstream: str | None = None # z.B. "github/main"
upstream_ahead: int = 0
upstream_behind: int = 0
remotes: list = field(default_factory=list) # RemoteStatus, GitHub immer zuletzt
modified: int = 0
deleted: int = 0
untracked: int = 0
conflicts: int = 0 # ungemergte Dateien (Merge-Konflikt, z.B. nach stash pop)
files: list = field(default_factory=list) # [(Buchstabe M/D/U/C, Pfad), ...]
stashes: list = field(default_factory=list) # ["stash@{0} WIP ...", ...]
error: str = ""
@property
def dirty(self) -> bool:
return bool(self.modified or self.deleted or self.untracked or self.conflicts)
@property
def clean_and_synced(self) -> bool:
return (not self.dirty and not self.stashes and self.ahead == 0
and self.behind == 0 and self.remote_state == "ok")
def severity(self) -> int:
"""Sortierschlüssel: Problematisches nach oben."""
if self.error:
return 0
if self.dirty or self.stashes:
return 1
if self.ahead or self.behind:
return 2
if self.remote_state != "ok":
return 3
return 4
@dataclass
class RemoteStatus:
"""Anzeigezustand eines Remotes für den aktuellen Branch.
URLs bleiben absichtlich aus UI/JSON heraus. `public` wird ausschließlich aus
der URL-Klasse abgeleitet; dadurch kann auch ein Remote namens `origin`
verständlich und mit der GitHub-Sicherheitsstufe behandelt werden.
"""
name: str
public: bool = False
mixed_public: bool = False
is_sync: bool = False
branch_exists: bool = False
ahead: int = 0
behind: int = 0
fetch_fingerprint: str = ""
push_fingerprints: list[str] = field(default_factory=list)
target_mismatch: bool = False
multiple_pushurls: bool = False
@property
def transfer_safe(self) -> bool:
return not (self.mixed_public or self.target_mismatch or self.multiple_pushurls)
def badge(self) -> str:
arrows = ""
if self.ahead:
arrows += f"↑{self.ahead}"
if self.behind:
arrows += f"↓{self.behind}"
if not self.branch_exists:
arrows = "?"
return f"{arrows} {self.name}" if arrows else self.name
@dataclass
class TransferCheck:
"""Deterministischer Preflight für genau einen Branch und einen Remote."""
reason: str
ahead: int = 0
behind: int = 0
remote_ref: str = ""
commits: list[str] = field(default_factory=list)
files: list[str] = field(default_factory=list)
branch: str = ""
head_oid: str = ""
index_oid: str = ""
worktree_fingerprint: str = ""
fetch_fingerprint: str = ""
push_fingerprint: str = ""
target_oid: str = ""
@property
def ready(self) -> bool:
return self.reason == "ready"
def approval_signature(self) -> tuple:
return (self.branch, self.head_oid, self.index_oid, self.worktree_fingerprint,
self.fetch_fingerprint, self.push_fingerprint, self.target_oid,
tuple(self.commits), tuple(self.files), self.ahead, self.behind)
@dataclass(frozen=True)
class RemoteTarget:
host: str
repo_id: str
fingerprint: str
@dataclass
class RemoteConfig:
name: str
fetch_urls: list[str]
push_urls: list[str]
fetch_targets: list[RemoteTarget]
push_targets: list[RemoteTarget]
@property
def transfer_safe(self) -> bool:
return (len(self.fetch_targets) == 1 and len(self.push_targets) == 1
and self.fetch_targets[0] == self.push_targets[0])
# Zwei-Buchstaben-Codes, die einen ungemergten Zustand (Merge-Konflikt) bedeuten.
# git status meldet solche Dateien z.B. nach einem `stash pop` mit Konflikt.
UNMERGED_CODES = {"DD", "AU", "UD", "UA", "DU", "AA", "UU"}
def parse_porcelain(output: str) -> tuple[int, int, int, int, list]:
"""NUL-getrenntes ``git status --porcelain=v1 -z`` auswerten.
-> (modified, deleted, untracked, conflicts, dateien).
Vereinfachung fürs Auge: Konflikt = C, Untracked = U, Gelöschtes = D, jede
andere Änderung (modified/added/renamed/…) = M. Konflikte werden ZUERST
geprüft, sonst würde z.B. `UD` fälschlich als Löschung zählen.
``-z`` ist für die Commit-Hilfe entscheidend: Ohne diese Option setzt Git
Pfade mit Umlauten oder Steuerzeichen in Anführungszeichen und maskiert sie.
Diese Anzeigeform ist kein gültiger Pfad für ein späteres ``git add``.
Rename-/Copy-Einträge besitzen bei ``-z`` ein zweites Feld mit dem alten
Namen; für Anzeige und Staging brauchen wir den ersten, neuen Namen.
"""
m = d = u = c = 0
files = []
fields = output.split("\0")
i = 0
while i < len(fields):
record = fields[i]
i += 1
if not record:
continue
xy, path = record[:2], record[3:]
if "R" in xy or "C" in xy:
# Bei -z folgt nach dem Zielpfad noch der Quellpfad.
i += 1
if xy in UNMERGED_CODES:
c += 1
files.append(("C", path))
elif xy == "??":
u += 1
files.append(("U", path))
elif "D" in xy:
d += 1
files.append(("D", path))
else:
m += 1
files.append(("M", path))
return m, d, u, c, files
def suggested_ignore(path: str) -> str | None:
"""Liefert die passende .gitignore-Zeile, wenn die Datei typischer Müll ist."""
parts = path.rstrip("/").split("/")
basename = parts[-1]
for name, is_dir, pattern in IGNORE_RULES:
if is_dir and name in parts:
return pattern
if not is_dir and basename == name:
return pattern
for suffix, pattern in IGNORE_SUFFIXES.items():
if basename.endswith(suffix):
return pattern
return None
class CommitSafetyError(RuntimeError):
pass
def _path_signature(path: Path) -> tuple | None:
try:
info = path.lstat()
except FileNotFoundError:
return None
return (info.st_dev, info.st_ino, stat.S_IFMT(info.st_mode), info.st_mode,
info.st_size, info.st_mtime_ns)
def update_gitignore_atomic(repo: Path, patterns: list[str]) -> bool:
"""Append unique rules without following symlinks or overwriting a raced target."""
repo = repo.resolve()
target = repo / ".gitignore"
before = _path_signature(target)
existing_text = ""
if before is not None:
info = target.lstat()
if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode):
raise CommitSafetyError("target is not a regular file")
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
try:
fd = os.open(target, flags)
except OSError as e:
raise CommitSafetyError(str(e)) from e
try:
with os.fdopen(fd, "r") as f:
existing_text = f.read()
except (OSError, UnicodeError) as e:
raise CommitSafetyError(str(e)) from e
existing = set(existing_text.splitlines())
new_lines = [pattern for pattern in patterns if pattern not in existing]
if not new_lines:
return False
updated = existing_text
if updated and not updated.endswith("\n"):
updated += "\n"
updated += "\n".join(new_lines) + "\n"
fd, tmp_name = tempfile.mkstemp(prefix=".gitignore.gmf.", dir=repo)
tmp = Path(tmp_name)
try:
mode = stat.S_IMODE(target.lstat().st_mode) if before is not None else 0o644
os.fchmod(fd, mode)
with os.fdopen(fd, "w") as f:
f.write(updated)
f.flush()
os.fsync(f.fileno())
if _path_signature(target) != before:
raise CommitSafetyError("target changed during update")
os.replace(tmp, target)
finally:
try:
tmp.unlink()
except FileNotFoundError:
pass
return True
def _real_index_signature(repo: Path, timeout: int) -> tuple | None:
index_r = _required_git(repo, "rev-parse", "--git-path", "index", timeout=timeout)
index = Path(index_r.stdout.strip())
if not index.is_absolute():
index = repo / index
signature = _path_signature(index)
if signature is None:
return None
try:
content_hash = hashlib.sha256(index.read_bytes()).hexdigest()
except OSError as e:
raise CommitSafetyError("cannot read Git index: %s" % e) from e
return signature + (content_hash,)
def has_unmerged_entries(repo: Path, timeout: int) -> bool:
diff = _required_git(repo, "diff", "--name-only", "--diff-filter=U", "-z",
timeout=timeout)
index = _required_git(repo, "ls-files", "-u", "-z", timeout=timeout)
return bool(diff.stdout or index.stdout)
def commit_selected(repo: Path, paths: list[str], message: str, timeout: int) -> subprocess.CompletedProcess:
"""Commit exactly paths through a temporary index; preserve the user's index bytes."""
if not paths:
raise CommitSafetyError("no approved paths")
if has_unmerged_entries(repo, timeout):
raise CommitSafetyError("merge conflicts exist")
real_before = _real_index_signature(repo, timeout)
approved = set(paths)
with tempfile.TemporaryDirectory(prefix="gmf-index-") as temp:
index_path = str(Path(temp) / "index")
env = dict(os.environ, GIT_INDEX_FILE=index_path)
_required_git(repo, "read-tree", "HEAD", timeout=timeout, env=env)
staged = run_git(repo, "add", "--", *paths, timeout=timeout, env=env)
if staged.returncode != 0:
return staged
names = _required_git(repo, "diff", "--cached", "--name-only", "-z", "--",
timeout=timeout, env=env)
actual = {path for path in names.stdout.split("\0") if path}
if actual != approved:
raise CommitSafetyError("temporary index differs from approved paths")
tree_before = _required_git(repo, "write-tree", timeout=timeout, env=env).stdout.strip()
if has_unmerged_entries(repo, timeout):
raise CommitSafetyError("merge conflicts appeared before commit")
if _real_index_signature(repo, timeout) != real_before:
raise CommitSafetyError("Git index changed during approval")
# Stage once more and compare the complete tree to catch worktree races.
_required_git(repo, "add", "--", *paths, timeout=timeout, env=env)
tree_after = _required_git(repo, "write-tree", timeout=timeout, env=env).stdout.strip()
if tree_after != tree_before:
raise CommitSafetyError("approved files changed during commit preparation")
result = run_git(repo, "commit", "-m", message, timeout=timeout, env=env)
if _real_index_signature(repo, timeout) != real_before:
raise CommitSafetyError("Git changed the real index unexpectedly")
return result
def stash_preview(repo: Path, timeout: int) -> tuple[bool, str]:
"""Return a complete stash patch, including untracked and binary contents."""
r = run_git(repo, "stash", "show", "-p", "--binary", "--include-untracked",
"stash@{0}", timeout=timeout)
if r.returncode != 0:
detail = (r.stderr or "Git exit %d" % r.returncode).strip()[:240]
return False, detail
return True, r.stdout
def run_git(repo: Path, *args: str, timeout: int = 10,
env: dict | None = None) -> subprocess.CompletedProcess:
return subprocess.run(
["git", "-C", str(repo), *args],
capture_output=True, text=True, timeout=timeout, env=env,
)
class GitReadError(RuntimeError):
pass
def _required_git(repo: Path, *args: str, timeout: int = 10,
env: dict | None = None) -> subprocess.CompletedProcess:
r = run_git(repo, *args, timeout=timeout, env=env)
if r.returncode != 0:
raise GitReadError("git %s failed (exit %d)" % (args[0], r.returncode))
return r
def find_repos(root: Path, skip_dirs: list[str]) -> list[Path]:
"""Alle Git-Repos unterhalb von root finden.
In ein gefundenes Repo wird nicht weiter hinabgestiegen (verschachtelte
Repos wären ohnehin Submodule o.ä. und verlangsamen den Scan nur).
"""
skip = set(skip_dirs)
repos: list[Path] = []
for dirpath, dirnames, filenames in os.walk(root):
# .git kann Ordner (normales Repo) oder Datei (Worktree/Submodul) sein.
if ".git" in dirnames or ".git" in filenames:
repos.append(Path(dirpath))
dirnames[:] = []
continue
dirnames[:] = [d for d in dirnames if d not in skip and d != ".git"]
return sorted(repos)
def _normal_host(host: str) -> str:
host = host.strip().rstrip(".").lower()
try:
return host.encode("idna").decode("ascii")
except UnicodeError:
return host
def canonical_remote_target(url: str, repo: Path | None = None) -> RemoteTarget:
"""Credential-free host/repository identity for URL, SCP, and local syntax."""
raw = url.strip()
host = "local"
port = None
path = raw
if "://" not in raw and ":" in raw and not raw.startswith(("/", "./", "../", "~")):
hostpart, path = raw.split(":", 1)
if "/" not in hostpart:
host = _normal_host(hostpart.rsplit("@", 1)[-1])
elif urllib.parse.urlsplit(raw).scheme:
parsed = urllib.parse.urlsplit(raw)
if parsed.scheme == "file":
path = urllib.parse.unquote(parsed.path)
else:
host = _normal_host(parsed.hostname or "")
port = parsed.port
path = urllib.parse.unquote(parsed.path)
if host == "local":
local = Path(path).expanduser()
if not local.is_absolute() and repo is not None:
local = repo / local
repo_id = str(local.resolve(strict=False))
canonical = "local:" + repo_id
else:
repo_id = posixpath.normpath("/" + path.lstrip("/"))
if repo_id.endswith(".git"):
repo_id = repo_id[:-4]
default_port = ((raw.startswith("ssh://") and port == 22)
or (raw.startswith("https://") and port == 443)
or (raw.startswith("http://") and port == 80))
authority = host if not port or default_port else f"{host}:{port}"
canonical = authority + ":" + repo_id
fingerprint = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:20]
return RemoteTarget(host, repo_id, fingerprint)
def read_remote_configs(repo: Path, cfg: dict) -> dict[str, RemoteConfig]:
"""Read every effective fetch/push target; any Git read error is fatal."""
t_ = cfg["git_timeout"]
names_r = _required_git(repo, "remote", timeout=t_)
result = {}
for name in [line for line in names_r.stdout.splitlines() if line]:
fetch_r = _required_git(repo, "remote", "get-url", "--all", "--", name,
timeout=t_)
push_r = _required_git(repo, "remote", "get-url", "--push", "--all", "--", name,
timeout=t_)
fetch_urls = [line for line in fetch_r.stdout.splitlines() if line]
push_urls = [line for line in push_r.stdout.splitlines() if line]
if not fetch_urls or not push_urls:
raise GitReadError("remote target is empty")
result[name] = RemoteConfig(
name, fetch_urls, push_urls,
[canonical_remote_target(url, repo) for url in fetch_urls],
[canonical_remote_target(url, repo) for url in push_urls],
)
return result
def detect_sync_remote(repo: Path, cfg: dict,
configs: dict[str, RemoteConfig] | None = None) -> str | None:
"""Sync remote by configured name, then by exact normalized hostname."""
configs = configs if configs is not None else read_remote_configs(repo, cfg)
for name in cfg["sync_remote_names"]:
if name in configs:
return name
wanted = {_normal_host(host) for host in cfg["sync_remote_hosts"]}
for name, remote in configs.items():
if any(target.host in wanted for target in remote.fetch_targets + remote.push_targets):
return name
return None
def remote_urls(repo: Path, cfg: dict) -> dict[str, list[str]]:
"""Compatibility helper: all effective URLs, while reads remain fail-closed."""
return {name: list(dict.fromkeys(remote.fetch_urls + remote.push_urls))
for name, remote in read_remote_configs(repo, cfg).items()}
def is_github_url(url: str) -> bool:
"""Only an exact github.com host receives the public-push classification."""
return canonical_remote_target(url).host == "github.com"
def collect_remote_statuses(repo: Path, branch: str, sync_remote: str | None,
cfg: dict,
configs: dict[str, RemoteConfig] | None = None) -> list[RemoteStatus]:
"""Alle Remotes samt Branch-Delta lesen; öffentliche Remotes immer zuletzt."""
states: list[RemoteStatus] = []
configs = configs if configs is not None else read_remote_configs(repo, cfg)
for name, remote in configs.items():
targets = remote.fetch_targets + remote.push_targets
public_classes = {target.host == "github.com" for target in targets}
state = RemoteStatus(
name=name,
public=True in public_classes,
mixed_public=len(public_classes) > 1,
is_sync=name == sync_remote,
fetch_fingerprint=(remote.fetch_targets[0].fingerprint
if len(remote.fetch_targets) == 1 else ""),
push_fingerprints=[target.fingerprint for target in remote.push_targets],
target_mismatch=not remote.transfer_safe,
multiple_pushurls=len(remote.push_targets) != 1,
)
if branch not in ("?", "(detached)"):
ref = f"refs/remotes/{name}/{branch}"
r = run_git(repo, "show-ref", "--verify", "--quiet", ref,
timeout=cfg["git_timeout"])
if r.returncode not in (0, 1):
raise GitReadError("git show-ref failed (exit %d)" % r.returncode)
state.branch_exists = r.returncode == 0
if state.branch_exists:
r = _required_git(repo, "rev-list", "--left-right", "--count",
f"HEAD...{ref}", timeout=cfg["git_timeout"])
values = r.stdout.split()
if len(values) != 2:
raise GitReadError("git rev-list returned malformed output")
state.ahead, state.behind = map(int, values)
states.append(state)
# Sync-Remote zuerst; GitHub unabhängig vom tatsächlichen Namen ganz rechts.
states.sort(key=lambda r: (r.public, not r.is_sync, r.name.lower()))
return states
def inspect_transfer(repo: Path, remote: str, branch: str, action: str,
timeout: int = 10) -> TransferCheck:
"""Prüft Push/Pull, ohne etwas zu verändern.
Bewusst eng: sauberer Tree, vorhandener Remote-Branch und verwandte,
fast-forward-fähige History. Neue Branches und Divergenzen gehören ins
Terminal, wo der Mensch den Sonderfall ausdrücklich auflöst.
"""
if branch in ("?", "(detached)"):
return TransferCheck("detached")
cfg = {**DEFAULT_CONFIG, "git_timeout": timeout}
try:
configs = read_remote_configs(repo, cfg)
remote_cfg = configs.get(remote)
if remote_cfg is None or not remote_cfg.transfer_safe:
return TransferCheck("remote-unsafe")
branch_r = _required_git(repo, "symbolic-ref", "--short", "-q", "HEAD",
timeout=timeout)
current_branch = branch_r.stdout.strip()
if current_branch != branch:
return TransferCheck("inspect-failed")
head = _required_git(repo, "rev-parse", "--verify", "HEAD", timeout=timeout).stdout.strip()
index_oid = _required_git(repo, "write-tree", timeout=timeout).stdout.strip()
dirty = _required_git(repo, "status", "--porcelain=v1", "-z", timeout=timeout)
except (GitReadError, ValueError):
return TransferCheck("inspect-failed")
worktree_fingerprint = hashlib.sha256(dirty.stdout.encode("utf-8")).hexdigest()
if dirty.stdout:
return TransferCheck("dirty")
ref = f"refs/remotes/{remote}/{branch}"
exists = run_git(repo, "show-ref", "--verify", "--quiet", ref, timeout=timeout)
if exists.returncode == 1:
return TransferCheck("missing-branch", remote_ref=ref)
if exists.returncode != 0:
return TransferCheck("inspect-failed", remote_ref=ref)
try:
target_oid = _required_git(repo, "rev-parse", "--verify", ref,
timeout=timeout).stdout.strip()
except GitReadError:
return TransferCheck("inspect-failed", remote_ref=ref)
delta = run_git(repo, "rev-list", "--left-right", "--count",
f"{head}...{target_oid}", timeout=timeout)
if delta.returncode != 0 or len(delta.stdout.split()) != 2:
return TransferCheck("inspect-failed", remote_ref=ref)
ahead_s, behind_s = delta.stdout.split()
ahead, behind = int(ahead_s), int(behind_s)
if ahead and behind:
return TransferCheck("divergent", ahead=ahead, behind=behind, remote_ref=ref)
if action == "push":
if behind:
return TransferCheck("behind", ahead=ahead, behind=behind, remote_ref=ref)
if not ahead:
return TransferCheck("nothing-push", remote_ref=ref)
commits_r = run_git(repo, "log", "--oneline", "--no-decorate",
f"{target_oid}..{head}", timeout=timeout)
files_r = run_git(repo, "diff", "--name-status", f"{target_oid}..{head}",
timeout=timeout)
if commits_r.returncode != 0 or files_r.returncode != 0:
return TransferCheck("inspect-failed", ahead, behind, ref)
return TransferCheck(
"ready", ahead=ahead, behind=behind, remote_ref=ref,
commits=[line for line in commits_r.stdout.splitlines() if line.strip()],
files=[line for line in files_r.stdout.splitlines() if line.strip()],
branch=current_branch, head_oid=head, index_oid=index_oid,
worktree_fingerprint=worktree_fingerprint,
fetch_fingerprint=remote_cfg.fetch_targets[0].fingerprint,
push_fingerprint=remote_cfg.push_targets[0].fingerprint,
target_oid=target_oid,
)
if action == "pull":
if ahead:
return TransferCheck("nothing-pull", ahead, behind, ref)
if not behind:
return TransferCheck("nothing-pull", remote_ref=ref)
return TransferCheck(
"ready", ahead=ahead, behind=behind, remote_ref=ref,
branch=current_branch, head_oid=head, index_oid=index_oid,
worktree_fingerprint=worktree_fingerprint,
fetch_fingerprint=remote_cfg.fetch_targets[0].fingerprint,
push_fingerprint=remote_cfg.push_targets[0].fingerprint,
target_oid=target_oid,
)
raise ValueError(f"unknown transfer action: {action}")
def safe_push_args(remote: str, branch: str, source_oid: str,
target_oid: str) -> tuple[str, ...]:
"""Push approved OID only, leased to the approved target OID, without tags."""
lease = f"--force-with-lease=refs/heads/{branch}:{target_oid}"
return ("push", "--porcelain", "--no-follow-tags", lease, "--", remote,
f"{source_oid}:refs/heads/{branch}")
def safe_pull_args(target_oid: str) -> tuple[str, ...]:
"""Pull ohne Fetch-Konfigurationsmagie: nur lokaler Fast-forward-Merge."""
return ("merge", "--ff-only", "--", target_oid)
def upstream_delta(repo: Path, sync_remote: str | None,
cfg: dict) -> tuple[str | None, int, int]:
"""Stand gegenüber dem konfigurierten Upstream, WENN dieser ein anderer
Remote als der Sync-Remote ist (typisch: github).
-> (upstream_ref oder None, ahead, behind). None, wenn kein (fremder) Upstream
gesetzt ist oder dessen Tracking-Ref fehlt. Basis ist der letzte fetch-Stand
dieses Remotes (wir fetchen hier NICHT übers Netz nach — wie in einem Editor).
"""
t_ = cfg["git_timeout"]
r = run_git(repo, "rev-parse", "--abbrev-ref", "@{upstream}", timeout=t_)
if r.returncode != 0:
return None, 0, 0
up = r.stdout.strip() # z.B. "github/main"
up_remote = up.split("/", 1)[0]
if not up or up_remote == sync_remote:
return None, 0, 0 # kein Upstream oder == Sync-Remote (schon gezeigt)
r = run_git(repo, "rev-list", "--left-right", "--count", f"HEAD...{up}", timeout=t_)
if r.returncode != 0:
return None, 0, 0 # Tracking-Ref (noch) nicht lokal vorhanden
ahead, behind = r.stdout.split()
return up, int(ahead), int(behind)
def collect_status(repo: Path, root: Path, cfg: dict, fetch: bool = False) -> RepoStatus:
"""Kompletten Zustand eines Repos einsammeln (läuft parallel in Threads)."""
rel = str(repo.relative_to(root)) if repo != root else repo.name
# macOS liefert Dateinamen je nach Herkunft in NFD ("ö" = "o" + kombinierender
# Punkt = 2 Codepoints) oder NFC (1 Codepoint). Fuer die Anzeige zaehlt aber die
# Zahl der Terminal-Zellen: bei NFD verrechnet sich len() und die Spalten hinter