-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitcoach.py
More file actions
executable file
·3348 lines (2836 loc) · 111 KB
/
Copy pathgitcoach.py
File metadata and controls
executable file
·3348 lines (2836 loc) · 111 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
"""gitcoach: opinionated Git helpers for solo developers."""
from __future__ import annotations
import argparse
import datetime as dt
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Iterable
class GitCoachError(Exception):
"""Raised for expected gitcoach usage/runtime errors."""
class UserCancelled(Exception):
"""Raised when a user cancels an interactive prompt."""
PROFILE_PRESETS: dict[str, dict[str, bool | str]] = {
"solo-safe": {
"guard_commit_main": True,
"guard_push_main": True,
"guard_force_push": True,
"guard_push_dirty": True,
"commit_untracked_policy": "ask",
},
"fast": {
"guard_commit_main": False,
"guard_push_main": False,
"guard_force_push": False,
"guard_push_dirty": False,
"commit_untracked_policy": "allow",
},
"strict": {
"guard_commit_main": True,
"guard_push_main": True,
"guard_force_push": True,
"guard_push_dirty": True,
"commit_untracked_policy": "block",
},
}
CONFIG_DEFAULTS: dict[str, bool | str] = {
"main_branch": "main",
"dev_branch": "dev",
"save_tracked_only": True,
"workflow_profile": "solo-safe",
**PROFILE_PRESETS["solo-safe"],
}
CONFIG_BOOL_KEYS = {
"save_tracked_only",
"guard_commit_main",
"guard_push_main",
"guard_force_push",
"guard_push_dirty",
}
CONFIG_STRING_KEYS = {
"main_branch",
"dev_branch",
"workflow_profile",
"commit_untracked_policy",
}
MASCOT_NAME = "GitCoach"
# Centralized interactive copy so wording stays consistent.
INTERACTIVE_COPY = {
"app_title": f"What would you like {MASCOT_NAME} to help with?",
"app_subtitle": f"Pick a goal first. {MASCOT_NAME} will handle the Git steps with you.",
"goal_prompt": "Choose a task",
"why_title": f"Why this helps ({MASCOT_NAME})",
"next_steps_title": f"Try this next in {MASCOT_NAME}",
"cancelled": f"[info] No problem, cancelled. {MASCOT_NAME} is here when you're ready.",
"doctor_cancelled": f"[info] No problem, cancelled. You can reopen Doctor anytime.",
"undo_cancelled": f"[info] No problem, cancelled. You can keep going safely.",
"profile_title": "Safety profile settings",
"doctor_menu_title": "Doctor options",
"undo_menu_title": "Undo & recovery options",
"more_menu_title": "More options (advanced)",
"ignore_menu_title": ".gitignore helper",
"confirm_loop_main": "Want to do another task?",
"confirm_loop_undo": "Want to do another undo/recovery task?",
"confirm_loop_doctor": "Want to do another Doctor task?",
"confirm_loop_advanced": "Want to do another advanced task?",
"confirm_apply_ignore": "Apply these patterns now?",
"confirm_risky_local": f"{MASCOT_NAME} tip: this changes local history/worktree. Continue?",
"workflow_guide_title": f"Simple workflow with {MASCOT_NAME}",
}
GOAL_START_WORK = "Start work on a new branch"
GOAL_SAVE_CHANGES = "Save my changes (commit)"
GOAL_SHARE_GITHUB = "Share my work to GitHub (sync + push)"
GOAL_SYNC_ONLY = "Get latest remote updates (sync only)"
GOAL_UNDO = "Undo or recover changes"
GOAL_DOCTOR = "Fix identity or contribution issues"
GOAL_STATUS = "Check repo status"
GOAL_IGNORE = "Handle untracked files (.gitignore)"
GOAL_SAFETY = "Adjust safety settings"
GOAL_BASICS = "Quick guide (beginner flow)"
GOAL_MORE = "More options (advanced)"
GOAL_EXIT = "Exit"
INTERACTIVE_MAIN_ACTIONS = [
GOAL_START_WORK,
GOAL_SAVE_CHANGES,
GOAL_SHARE_GITHUB,
GOAL_SYNC_ONLY,
GOAL_UNDO,
GOAL_DOCTOR,
GOAL_STATUS,
GOAL_IGNORE,
GOAL_SAFETY,
GOAL_BASICS,
GOAL_MORE,
GOAL_EXIT,
]
INTERACTIVE_GOAL_HELP: dict[str, list[str]] = {
GOAL_START_WORK: [
f"Use when: you're starting a feature or fix.",
f"Why: keeps main clean, and {MASCOT_NAME} can carry local changes if needed.",
],
GOAL_SAVE_CHANGES: [
"Use when: you want a safe checkpoint in Git.",
f"Why: {MASCOT_NAME} helps stage, quality-check, and commit clearly.",
],
GOAL_SHARE_GITHUB: [
"Use when: your local commits are ready to publish.",
f"Why: {MASCOT_NAME} syncs first, then pushes to reduce rejection errors.",
],
GOAL_SYNC_ONLY: [
"Use when: your branch may be behind remote updates.",
"Why: brings remote commits into your local branch without publishing.",
],
GOAL_UNDO: [
"Use when: you staged/committed/restored the wrong thing.",
f"Why: guided recovery options are safer than panic reset commands.",
],
GOAL_DOCTOR: [
"Use when: GitHub contributions are missing or identity is wrong.",
f"Why: Doctor scans identity and can rewrite commit emails safely.",
],
GOAL_STATUS: [
"Use when: you're not sure what state your branch is in.",
"Why: shows staged/unstaged/untracked plus ahead/behind in one snapshot.",
],
GOAL_IGNORE: [
"Use when: random files keep showing up in status.",
f"Why: suggests and applies .gitignore patterns from current files.",
],
GOAL_SAFETY: [
"Use when: you want stricter or faster Git behavior.",
f"Why: switch workflow profiles (solo-safe/fast/strict) cleanly.",
],
GOAL_BASICS: [
"Use when: you want the simplest recommended flow.",
f"Why: {MASCOT_NAME} gives a short beginner-safe sequence to follow.",
],
}
DOCTOR_MENU_ACTIONS = [
"Scan identity issues",
"Scan folder for identity issues",
"Set git identity (name/email)",
"Fix email history",
"Promote branch to main",
"Back to main menu",
]
UNDO_MENU_ACTIONS = [
"Unstage all staged files",
"Discard unstaged tracked changes",
"Undo last commit (keep changes staged)",
"Undo last commit (keep changes unstaged)",
"Revert a commit (safe history)",
"Restore one file to HEAD",
"Back to main menu",
]
PROFILE_MENU_ACTIONS = [
"Show current profile",
"Set profile: solo-safe",
"Set profile: fast",
"Set profile: strict",
"Back to main menu",
]
IGNORE_MENU_ACTIONS = [
"Preview untracked + suggestions",
"Apply all suggested patterns",
"Pick suggested patterns to apply",
"Add one custom ignore pattern",
"Back to main menu",
]
MORE_MENU_ACTIONS = [
"Switch branch directly",
"Sync current branch (no push)",
"Push current branch only",
"Draft commit message",
"Ship dev -> main",
"Doctor tools",
"Undo / rollback tools",
"Workflow profile settings",
"Install safety guards",
"Init repo defaults",
"Recent actions log",
"Back to main menu",
]
def safe_input(prompt: str) -> str:
try:
return input(prompt)
except EOFError as err:
raise UserCancelled from err
except KeyboardInterrupt as err:
print("")
raise UserCancelled from err
def is_interactive_tty() -> bool:
return sys.stdin.isatty() and sys.stdout.isatty()
def color_enabled() -> bool:
if not sys.stdout.isatty():
return False
if os.getenv("NO_COLOR"):
return False
term = os.getenv("TERM", "")
return term.lower() not in {"", "dumb"}
def style_text(text: str, *, color: str | None = None, bold: bool = False, dim: bool = False) -> str:
if not color_enabled():
return text
color_codes = {
"red": "31",
"green": "32",
"yellow": "33",
"blue": "34",
"magenta": "35",
"cyan": "36",
"gray": "90",
}
parts: list[str] = []
if bold:
parts.append("1")
if dim:
parts.append("2")
if color and color in color_codes:
parts.append(color_codes[color])
if not parts:
return text
return f"\033[{';'.join(parts)}m{text}\033[0m"
def print_rule(char: str = "-", width: int = 70) -> None:
print(style_text(char * width, color="gray", dim=True))
def print_box(title: str, lines: list[str]) -> None:
width = max(52, len(title) + 6, *(len(line) + 4 for line in lines)) if lines else max(52, len(title) + 6)
top = "+" + "-" * (width - 2) + "+"
print(style_text(top, color="cyan"))
print(style_text(f"| {title.ljust(width - 4)} |", color="cyan", bold=True))
print(style_text(top, color="cyan"))
for line in lines:
print(f"| {line.ljust(width - 4)} |")
print(style_text(top, color="cyan"))
def prompt_label(text: str) -> str:
return style_text(text, color="blue", bold=True)
def can_use_gum() -> bool:
if os.getenv("GITCOACH_NO_GUM"):
return False
return is_interactive_tty() and shutil.which("gum") is not None
def choose_option_with_gum(prompt: str, options: list[str], *, allow_cancel: bool = True) -> str:
# Pass options as argv so gum keeps stdin connected to the user's TTY.
# Capturing only stdout lets us read the selected value while still rendering UI.
result = subprocess.run(
["gum", "filter", "--placeholder", prompt, *options],
check=False,
text=True,
stdout=subprocess.PIPE,
)
if result.returncode != 0:
if allow_cancel:
raise UserCancelled
detail = (result.stderr or result.stdout or "").strip()
raise GitCoachError(detail or "No selection made.")
picked = (result.stdout or "").strip()
if not picked:
if allow_cancel:
raise UserCancelled
raise GitCoachError("No selection made.")
if picked not in options:
if allow_cancel:
raise UserCancelled
raise GitCoachError("Invalid selection.")
return picked
def run(
cmd: list[str],
*,
check: bool = True,
capture: bool = True,
cwd: Path | None = None,
) -> subprocess.CompletedProcess[str]:
result = subprocess.run(
cmd,
check=False,
text=True,
capture_output=capture,
cwd=str(cwd) if cwd else None,
)
if check and result.returncode != 0:
stdout = (result.stdout or "").strip()
stderr = (result.stderr or "").strip()
detail = stderr or stdout or f"exit code {result.returncode}"
raise GitCoachError(f"Command failed: {' '.join(cmd)}\n{detail}")
return result
def git(*args: str, check: bool = True, capture: bool = True) -> subprocess.CompletedProcess[str]:
return run(["git", *args], check=check, capture=capture)
def ensure_git_repo() -> None:
try:
git("rev-parse", "--git-dir")
except GitCoachError as err:
raise GitCoachError("Not inside a Git repository.") from err
def repo_has_commits() -> bool:
result = git("rev-parse", "--verify", "HEAD", check=False)
return result.returncode == 0
def current_branch() -> str:
result = git("rev-parse", "--abbrev-ref", "HEAD")
return result.stdout.strip()
def branch_exists(name: str) -> bool:
result = git("show-ref", "--verify", f"refs/heads/{name}", check=False)
return result.returncode == 0
def remote_exists(name: str) -> bool:
result = git("remote", "get-url", name, check=False)
return result.returncode == 0
def get_remote_url(name: str) -> str | None:
result = git("remote", "get-url", name, check=False)
value = result.stdout.strip()
return value if result.returncode == 0 and value else None
def infer_github_repo_slug(remote_url: str) -> str | None:
value = remote_url.strip()
patterns = [
r"^git@github\.com:(?P<slug>.+?)(?:\.git)?$",
r"^https?://github\.com/(?P<slug>.+?)(?:\.git)?$",
r"^ssh://git@github\.com/(?P<slug>.+?)(?:\.git)?$",
]
for pattern in patterns:
match = re.match(pattern, value)
if not match:
continue
slug = match.group("slug").strip("/")
if slug.count("/") == 1:
return slug
return None
def get_config(key: str) -> str | None:
result = git("config", "--get", key, check=False)
value = result.stdout.strip()
return value if value else None
def get_global_config(key: str) -> str | None:
result = run(["git", "config", "--global", "--get", key], check=False)
value = (result.stdout or "").strip()
return value if result.returncode == 0 and value else None
def git_in_repo(
repo: Path,
*args: str,
check: bool = True,
capture: bool = True,
) -> subprocess.CompletedProcess[str]:
return run(["git", "-C", str(repo), *args], check=check, capture=capture)
def find_git_repos(root: Path, max_depth: int = 3) -> list[Path]:
root = root.resolve()
if not root.exists() or not root.is_dir():
raise GitCoachError(f"Path does not exist or is not a directory: {root}")
repos: list[Path] = []
for current, dirs, _files in os.walk(root):
current_path = Path(current)
depth = len(current_path.relative_to(root).parts)
if depth > max_depth:
dirs[:] = []
continue
if ".git" in dirs:
repos.append(current_path)
dirs[:] = []
continue
if current_path == root and current_path.joinpath(".git").exists():
repos.append(current_path)
dirs[:] = []
return sorted(set(repos))
def collect_history_emails_for_repo(repo: Path) -> dict[str, int]:
result = git_in_repo(repo, "log", "--all", "--format=%ae%n%ce", check=False)
if result.returncode != 0:
return {}
counts: dict[str, int] = {}
for raw in (result.stdout or "").splitlines():
email = raw.strip()
if not email:
continue
counts[email] = counts.get(email, 0) + 1
return counts
def summarize_repo_identity(
repo: Path,
target_email: str | None,
) -> tuple[str, str | None, int, int]:
local_email = (git_in_repo(repo, "config", "--get", "user.email", check=False).stdout or "").strip() or None
effective_email = local_email or get_global_config("user.email")
counts = collect_history_emails_for_repo(repo)
total_entries = sum(counts.values())
mismatch = 0
if target_email:
mismatch = sum(count for email, count in counts.items() if email.lower() != target_email.lower())
return (repo.name, effective_email, total_entries, mismatch)
def list_local_branches() -> list[str]:
result = git("for-each-ref", "--format=%(refname:short)", "refs/heads", check=False)
return [line.strip() for line in result.stdout.splitlines() if line.strip()]
def list_remotes() -> list[str]:
result = git("remote", check=False)
return [line.strip() for line in result.stdout.splitlines() if line.strip()]
def current_upstream() -> str | None:
result = git("rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}", check=False)
value = result.stdout.strip()
if result.returncode != 0 or not value:
return None
return value
def branch_upstream(branch: str) -> str | None:
result = git(
"rev-parse",
"--abbrev-ref",
"--symbolic-full-name",
f"{branch}@{{upstream}}",
check=False,
)
value = (result.stdout or "").strip()
if result.returncode != 0 or not value:
return None
return value
def status_counts() -> tuple[int, int, int]:
staged = 0
unstaged = 0
untracked = 0
for raw in git("status", "--porcelain").stdout.splitlines():
line = raw.rstrip("\n")
if not line:
continue
if line.startswith("??"):
untracked += 1
continue
if len(line) >= 1 and line[0] != " ":
staged += 1
if len(line) >= 2 and line[1] != " ":
unstaged += 1
return staged, unstaged, untracked
def has_staged_changes() -> bool:
for raw in git("status", "--porcelain").stdout.splitlines():
if raw and not raw.startswith("??") and raw[0] != " ":
return True
return False
def has_unstaged_changes() -> bool:
for raw in git("status", "--porcelain").stdout.splitlines():
if raw and not raw.startswith("??") and len(raw) > 1 and raw[1] != " ":
return True
return False
def has_untracked_files() -> bool:
return bool(git("ls-files", "--others", "--exclude-standard").stdout.strip())
def worktree_dirty() -> bool:
return bool(git("status", "--porcelain", check=False).stdout.strip())
def has_parent_commit() -> bool:
result = git("rev-parse", "--verify", "HEAD~1", check=False)
return result.returncode == 0
def changed_tracked_files() -> list[str]:
files: set[str] = set()
for args in (("diff", "--name-only"), ("diff", "--cached", "--name-only")):
result = git(*args, check=False)
for line in (result.stdout or "").splitlines():
name = line.strip()
if name:
files.add(name)
return sorted(files)
def recent_commit_choices(limit: int = 30) -> list[tuple[str, str]]:
result = git("log", f"-n{limit}", "--pretty=format:%h%x09%s", check=False)
choices: list[tuple[str, str]] = []
for line in (result.stdout or "").splitlines():
parts = line.split("\t", 1)
if not parts or not parts[0].strip():
continue
sha = parts[0].strip()
summary = parts[1].strip() if len(parts) > 1 else ""
choices.append((sha, f"{sha} {summary}".strip()))
return choices
def create_safety_stash(label: str) -> str | None:
result = git("stash", "push", "-u", "-m", label, check=False)
output = ((result.stdout or "") + "\n" + (result.stderr or "")).strip()
if "No local changes to save" in output:
return None
ref = git("stash", "list", "-n", "1", "--format=%gd", check=False).stdout.strip()
return ref or "stash@{0}"
def unique_branch_name(base: str) -> str:
if not branch_exists(base):
return base
for i in range(2, 100):
candidate = f"{base}-{i}"
if not branch_exists(candidate):
return candidate
return f"{base}-{dt.datetime.now().strftime('%Y%m%d-%H%M%S')}"
def suggest_feature_branch_from_message(message: str) -> str:
subject = message.strip().splitlines()[0].strip() if message.strip() else "work"
summary = subject.split(": ", 1)[1] if ": " in subject else subject
slug = re.sub(r"[^a-zA-Z0-9]+", "-", summary.strip().lower()).strip("-")
if not slug:
slug = "work"
return f"feature/{slug[:48]}"
def checkout_branch_with_changes(branch: str, *, autostash: bool = True) -> bool:
"""Checkout existing branch or create it while carrying local changes.
Returns True when a temporary stash was used.
"""
if not branch_exists(branch):
git("checkout", "-b", branch, capture=False)
return False
attempt = run(["git", "checkout", branch], check=False, capture=False)
if attempt.returncode == 0:
return False
if not autostash:
raise GitCoachError(
f"Could not switch to {branch} with local changes. "
"Retry with --autostash."
)
stash_ref = create_safety_stash(f"gitcoach-branch-switch-{dt.datetime.now().strftime('%Y%m%d-%H%M%S')}")
git("checkout", branch, capture=False)
if stash_ref:
pop = run(["git", "stash", "pop"], check=False, capture=False)
if pop.returncode != 0:
print("[warn] Stash pop had conflicts. Resolve and continue.")
else:
print("[ok] Restored local changes after branch switch.")
return True
def ahead_behind(upstream: str) -> tuple[int, int]:
result = git("rev-list", "--left-right", "--count", f"{upstream}...HEAD", check=False)
if result.returncode != 0:
return (0, 0)
parts = result.stdout.strip().split()
if len(parts) != 2:
return (0, 0)
behind = int(parts[0])
ahead = int(parts[1])
return ahead, behind
def ahead_behind_refs(local_ref: str, upstream_ref: str) -> tuple[int, int]:
result = git("rev-list", "--left-right", "--count", f"{upstream_ref}...{local_ref}", check=False)
if result.returncode != 0:
return (0, 0)
parts = result.stdout.strip().split()
if len(parts) != 2:
return (0, 0)
behind = int(parts[0])
ahead = int(parts[1])
return ahead, behind
def ensure_clean_worktree() -> None:
result = git("status", "--porcelain")
if result.stdout.strip():
raise GitCoachError("Working tree is not clean. Commit/stash changes first.")
def parse_config_bool(raw: str, default: bool) -> bool:
lowered = raw.strip().lower()
if lowered in {"1", "true", "yes", "on"}:
return True
if lowered in {"0", "false", "no", "off"}:
return False
return default
def normalize_commit_untracked_policy(value: str) -> str:
lowered = value.strip().lower()
if lowered in {"allow", "off", "false", "no"}:
return "allow"
if lowered in {"block", "deny", "strict", "true", "on"}:
return "block"
return "ask"
def repo_file_path(name: str) -> Path:
top = run(["git", "rev-parse", "--show-toplevel"], check=False)
root = (top.stdout or "").strip()
if top.returncode == 0 and root:
return Path(root) / name
return Path(name)
def load_gitcoach_config() -> dict[str, bool | str]:
path = repo_file_path(".gitcoach.yml")
parsed: dict[str, str] = {}
if path.exists():
for raw in path.read_text(encoding="utf-8", errors="ignore").splitlines():
line = raw.strip()
if not line or line.startswith("#") or ":" not in line:
continue
key, value = line.split(":", 1)
parsed[key.strip()] = value.strip().strip("'").strip('"')
profile = str(parsed.get("workflow_profile", CONFIG_DEFAULTS["workflow_profile"])).strip().lower()
if profile not in PROFILE_PRESETS:
profile = str(CONFIG_DEFAULTS["workflow_profile"])
config: dict[str, bool | str] = dict(CONFIG_DEFAULTS)
config.update(PROFILE_PRESETS[profile])
config["workflow_profile"] = profile
for key in CONFIG_STRING_KEYS:
if key in parsed and parsed[key]:
config[key] = parsed[key]
for key in CONFIG_BOOL_KEYS:
if key in parsed:
config[key] = parse_config_bool(parsed[key], bool(config[key]))
policy_raw = str(parsed.get("commit_untracked_policy", config["commit_untracked_policy"]))
config["commit_untracked_policy"] = normalize_commit_untracked_policy(policy_raw)
return config
def save_gitcoach_config(config: dict[str, bool | str]) -> None:
normalized = dict(CONFIG_DEFAULTS)
profile = str(config.get("workflow_profile", normalized["workflow_profile"])).strip().lower()
if profile not in PROFILE_PRESETS:
profile = str(CONFIG_DEFAULTS["workflow_profile"])
normalized.update(PROFILE_PRESETS[profile])
normalized["workflow_profile"] = profile
for key in CONFIG_STRING_KEYS:
value = config.get(key)
if value not in {None, ""}:
normalized[key] = str(value)
for key in CONFIG_BOOL_KEYS:
value = config.get(key)
if isinstance(value, bool):
normalized[key] = value
elif isinstance(value, str):
normalized[key] = parse_config_bool(value, bool(normalized[key]))
normalized["commit_untracked_policy"] = normalize_commit_untracked_policy(
str(config.get("commit_untracked_policy", normalized["commit_untracked_policy"]))
)
lines = [
f"main_branch: {normalized['main_branch']}",
f"dev_branch: {normalized['dev_branch']}",
f"save_tracked_only: {str(normalized['save_tracked_only']).lower()}",
f"workflow_profile: {normalized['workflow_profile']}",
f"guard_commit_main: {str(normalized['guard_commit_main']).lower()}",
f"guard_push_main: {str(normalized['guard_push_main']).lower()}",
f"guard_force_push: {str(normalized['guard_force_push']).lower()}",
f"guard_push_dirty: {str(normalized['guard_push_dirty']).lower()}",
f"commit_untracked_policy: {normalized['commit_untracked_policy']}",
]
repo_file_path(".gitcoach.yml").write_text("\n".join(lines) + "\n", encoding="utf-8")
def apply_profile(profile: str) -> dict[str, bool | str]:
profile_name = profile.strip().lower()
if profile_name not in PROFILE_PRESETS:
supported = ", ".join(sorted(PROFILE_PRESETS))
raise GitCoachError(f"Unknown profile: {profile}. Choose one of: {supported}")
config = load_gitcoach_config()
config["workflow_profile"] = profile_name
config.update(PROFILE_PRESETS[profile_name])
save_gitcoach_config(config)
return config
def git_dir_path() -> Path:
return Path(git("rev-parse", "--git-dir").stdout.strip())
def actions_log_path() -> Path:
return git_dir_path() / ".gitcoach-actions.jsonl"
def log_action(action: str, details: dict[str, object] | None = None) -> None:
try:
entry: dict[str, object] = {
"timestamp": dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z"),
"action": action,
"branch": (git("rev-parse", "--abbrev-ref", "HEAD", check=False).stdout or "").strip() or "(unknown)",
}
if details:
clean_details: dict[str, object] = {}
for key, value in details.items():
if isinstance(value, (str, int, float, bool)) or value is None:
clean_details[key] = value
elif isinstance(value, (list, tuple, set)):
clean_details[key] = list(value)
else:
clean_details[key] = str(value)
entry["details"] = clean_details
path = actions_log_path()
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(entry, sort_keys=True) + "\n")
except Exception:
# Logging should never block the main action.
return
def read_recent_actions(limit: int = 20) -> list[dict[str, object]]:
path = actions_log_path()
if not path.exists():
return []
entries: list[dict[str, object]] = []
for raw in path.read_text(encoding="utf-8", errors="ignore").splitlines():
line = raw.strip()
if not line:
continue
try:
parsed = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(parsed, dict):
entries.append(parsed)
return entries[-limit:]
def install_safety_hooks(*, force: bool = False) -> tuple[list[str], list[str]]:
config = load_gitcoach_config()
block_commit_main = bool(config["guard_commit_main"])
block_push_main = bool(config["guard_push_main"])
block_force_push = bool(config["guard_force_push"])
block_push_dirty = bool(config["guard_push_dirty"])
block_commit_untracked = str(config["commit_untracked_policy"]) == "block"
hook_dir = Path(git("rev-parse", "--git-path", "hooks").stdout.strip())
hook_dir.mkdir(parents=True, exist_ok=True)
pre_commit = hook_dir / "pre-commit"
pre_push = hook_dir / "pre-push"
marker = "gitcoach guard hook"
pre_commit_body = f"""#!/bin/sh
# gitcoach guard hook
BLOCK_COMMIT_MAIN="{1 if block_commit_main else 0}"
BLOCK_COMMIT_UNTRACKED="{1 if block_commit_untracked else 0}"
branch="$(git rev-parse --abbrev-ref HEAD)"
if [ "$BLOCK_COMMIT_MAIN" = "1" ]; then
if [ "$branch" = "main" ] || [ "$branch" = "master" ]; then
if [ -z "${{GITCOACH_ALLOW_MAIN_COMMIT:-}}" ]; then
echo "[gitcoach] Commit blocked on $branch."
echo "[gitcoach] Use a feature branch, or bypass once with GITCOACH_ALLOW_MAIN_COMMIT=1."
exit 1
fi
fi
fi
if [ "$BLOCK_COMMIT_UNTRACKED" = "1" ]; then
if [ -n "$(git ls-files --others --exclude-standard)" ]; then
if [ -z "${{GITCOACH_ALLOW_UNTRACKED_COMMIT:-}}" ]; then
echo "[gitcoach] Commit blocked: untracked files detected."
echo "[gitcoach] Add/ignore those files, or bypass once with GITCOACH_ALLOW_UNTRACKED_COMMIT=1."
exit 1
fi
fi
fi
exit 0
"""
pre_push_body = f"""#!/bin/sh
# gitcoach guard hook
BLOCK_PUSH_MAIN="{1 if block_push_main else 0}"
BLOCK_FORCE_PUSH="{1 if block_force_push else 0}"
BLOCK_PUSH_DIRTY="{1 if block_push_dirty else 0}"
zero="0000000000000000000000000000000000000000"
if [ "$BLOCK_PUSH_DIRTY" = "1" ]; then
if [ -n "$(git status --porcelain)" ]; then
if [ -z "${{GITCOACH_ALLOW_DIRTY_PUSH:-}}" ]; then
echo "[gitcoach] Push blocked: working tree has local changes."
echo "[gitcoach] Commit/stash first, or bypass once with GITCOACH_ALLOW_DIRTY_PUSH=1."
exit 1
fi
fi
fi
while read local_ref local_sha remote_ref remote_sha
do
case "$remote_ref" in
refs/heads/main|refs/heads/master)
if [ "$BLOCK_PUSH_MAIN" = "1" ]; then
if [ -z "${{GITCOACH_ALLOW_MAIN_PUSH:-}}" ]; then
echo "[gitcoach] Push blocked to ${{remote_ref#refs/heads/}}."
echo "[gitcoach] Push from dev/feature branches and merge intentionally."
echo "[gitcoach] Bypass once with GITCOACH_ALLOW_MAIN_PUSH=1."
exit 1
fi
fi
;;
esac
if [ "$local_sha" = "$zero" ]; then
continue
fi
if [ "$remote_sha" = "$zero" ]; then
continue
fi
if ! git merge-base --is-ancestor "$remote_sha" "$local_sha" >/dev/null 2>&1; then
if [ "$BLOCK_FORCE_PUSH" = "1" ]; then
if [ -z "${{GITCOACH_ALLOW_FORCE_PUSH:-}}" ]; then
echo "[gitcoach] Non-fast-forward push blocked on ${{remote_ref#refs/heads/}}."
echo "[gitcoach] Bypass once with GITCOACH_ALLOW_FORCE_PUSH=1."
exit 1
fi
fi
fi
done
exit 0
"""
installed: list[str] = []
skipped: list[str] = []
for hook_path, body in ((pre_commit, pre_commit_body), (pre_push, pre_push_body)):
if hook_path.exists():
existing = hook_path.read_text(encoding="utf-8", errors="ignore")
if marker not in existing and not force:
skipped.append(hook_path.name)
continue
hook_path.write_text(body, encoding="utf-8")
hook_path.chmod(0o755)
installed.append(hook_path.name)
return installed, skipped
def slugify_feature_name(value: str) -> str:
slug = re.sub(r"[^a-zA-Z0-9]+", "-", value.strip().lower()).strip("-")
if not slug:
raise GitCoachError("Feature name must contain letters or numbers.")
return slug
def write_default_config(main_branch: str, dev_branch: str) -> None:
path = repo_file_path(".gitcoach.yml")
if path.exists():
return
config = dict(CONFIG_DEFAULTS)
config["main_branch"] = main_branch
config["dev_branch"] = dev_branch
save_gitcoach_config(config)
def pick_main_branch(preferred: str) -> str:
if branch_exists(preferred):
return preferred
for candidate in ("main", "master"):
if branch_exists(candidate):
return candidate
return preferred
def prompt_text(prompt: str, *, default: str | None = None, required: bool = False) -> str:
while True:
suffix = f" [{default}]" if default else ""
value = safe_input(f"{prompt_label(prompt)}{suffix}: ").strip()
if value:
return value
if default is not None:
return default
if not required:
return ""
print("[warn] Value is required.")
def prompt_confirm(prompt: str, *, default: bool = False) -> bool:
hint = "Y/n" if default else "y/N"
while True:
raw = safe_input(f"{prompt_label(prompt)} [{hint}]: ").strip().lower()
if not raw:
return default
if raw in {"y", "yes"}:
return True
if raw in {"n", "no"}:
return False
print("[warn] Enter y or n.")
def interactive_fix_suggestions(error_text: str) -> list[str]:
text = error_text.lower()
suggestions: list[str] = []
if "working tree is not clean" in text:
suggestions.extend(
[
GOAL_SAVE_CHANGES,
GOAL_UNDO,
GOAL_START_WORK,
]
)
elif "no staged tracked changes to commit" in text:
suggestions.extend(
[
f"Edit files first, then choose: {GOAL_SAVE_CHANGES}.",