-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
2318 lines (2034 loc) · 60.9 KB
/
main.go
File metadata and controls
2318 lines (2034 loc) · 60.9 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
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
)
var version = "dev"
const (
defaultGroqModel = "llama-3.3-70b-versatile"
groqAPIURL = "https://api.groq.com/openai/v1/chat/completions"
groqAPIKeyConfig = "gitpilot.groq-api-key"
groqModelConfig = "gitpilot.groq-model"
initConfigKey = "gitpilot.initialized"
keychainService = "gitpilot"
keychainAccount = "groq-api-key"
colorReset = "\033[0m"
colorDim = "\033[38;5;245m"
colorBorder = "\033[38;5;240m"
colorAccent = "\033[38;5;111m"
colorInfo = "\033[38;5;117m"
colorSuccess = "\033[38;5;114m"
colorWarn = "\033[38;5;221m"
colorError = "\033[38;5;203m"
colorStrong = "\033[1m"
maxAIContextChars = 16000
maxCommitRequestTokens = 1400
maxGroupingRequestTokens = 1200
maxDiffExcerptChars = 3500
minDiffExcerptChars = 600
diffHeadLines = 24
diffTailLines = 14
maxSemanticItems = 12
maxSampleLines = 8
estimatedCharsPerToken = 4
maxGroqAttempts = 4
)
type FileChange struct {
FileName string
Status string
Diff string
}
type chatCompletionRequest struct {
Model string `json:"model"`
Temperature float64 `json:"temperature"`
MaxTokens int `json:"max_tokens,omitempty"`
Messages []chatMessage `json:"messages"`
}
type chatMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type chatCompletionResponse struct {
Choices []struct {
Message chatMessage `json:"message"`
} `json:"choices"`
Error *struct {
Message string `json:"message"`
} `json:"error,omitempty"`
}
type CommitPlan struct {
Label string
Changes []FileChange
}
type CommitInfo struct {
Hash string
Subject string
}
type commitGroupProposal struct {
Label string `json:"label"`
Files []string `json:"files"`
}
type commitRunSummary struct {
Mode string
Committed []string
Skipped []string
Failed []string
}
func printWelcome() {
printPanel([]string{
colorStrong + "Git Pilot" + colorReset,
colorDim + "AI-assisted Git workflow for structured commits and push approvals" + colorReset,
"",
colorDim + "Commands: auth, init, status, diff, commit, push, pull, pr, config, version, help, exit" + colorReset,
})
}
func printSection(title string) {
fmt.Printf("\n%s──%s %s%s%s\n", colorBorder, colorReset, colorStrong, title, colorReset)
}
func printSuccess(message string) {
fmt.Printf("%s●%s %s%s%s\n", colorSuccess, colorReset, colorSuccess, message, colorReset)
}
func printWarning(message string) {
fmt.Printf("%s●%s %s%s%s\n", colorWarn, colorReset, colorWarn, message, colorReset)
}
func printError(message string) {
fmt.Printf("%s●%s %s%s%s\n", colorError, colorReset, colorError, message, colorReset)
}
func printInfo(message string) {
fmt.Printf("%s●%s %s%s%s\n", colorInfo, colorReset, colorInfo, message, colorReset)
}
func printPanel(lines []string) {
expanded := make([]string, 0, len(lines))
for _, line := range lines {
parts := strings.Split(line, "\n")
expanded = append(expanded, parts...)
}
width := 0
for _, line := range expanded {
if len(stripANSI(line)) > width {
width = len(stripANSI(line))
}
}
if width < 24 {
width = 24
}
fmt.Printf("%s╭%s╮%s\n", colorBorder, strings.Repeat("─", width+2), colorReset)
for _, line := range expanded {
padding := width - len(stripANSI(line))
fmt.Printf("%s│%s %s%s %s│%s\n", colorBorder, colorReset, line, strings.Repeat(" ", padding), colorBorder, colorReset)
}
fmt.Printf("%s╰%s╯%s\n", colorBorder, strings.Repeat("─", width+2), colorReset)
}
func stripANSI(text string) string {
var builder strings.Builder
inEscape := false
for _, r := range text {
if r == '\033' {
inEscape = true
continue
}
if inEscape {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
inEscape = false
}
continue
}
builder.WriteRune(r)
}
return builder.String()
}
func styleStatus(status string) string {
switch {
case strings.Contains(status, "?"):
return colorInfo + "new " + colorReset
case strings.Contains(status, "A"):
return colorSuccess + "added " + colorReset
case strings.Contains(status, "M"):
return colorWarn + "modified" + colorReset
case strings.Contains(status, "D"):
return colorError + "deleted " + colorReset
case strings.Contains(status, "R"):
return colorAccent + "renamed " + colorReset
default:
return colorDim + status + colorReset
}
}
func renderChoice(index int, title, description string) string {
return fmt.Sprintf("%s[%d]%s %s%s%s\n %s%s%s", colorAccent, index, colorReset, colorStrong, title, colorReset, colorDim, description, colorReset)
}
func readCommand() []string {
reader := bufio.NewReader(os.Stdin)
fmt.Printf("%s%sgitpilot%s %s›%s ", colorAccent, colorStrong, colorReset, colorBorder, colorReset)
line, err := reader.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
printError("Failed to read command: " + err.Error())
return nil
}
line = strings.TrimSpace(line)
if line == "" {
return nil
}
return strings.Fields(line)
}
func runInteractive() {
for {
args := readCommand()
if len(args) == 0 {
continue
}
if args[0] == "exit" {
fmt.Println("Goodbye!")
break
}
executeCommand(args)
}
}
func executeCommand(args []string) {
switch args[0] {
case "init":
executeInit()
case "status":
executeStatus()
case "diff":
executeDiff()
case "commit":
executeCommit(args[1:])
case "push":
if err := executePush(); err != nil {
fmt.Println("❌ Push failed:", err)
}
case "pull":
executePull()
case "auth":
executeAuth(args[1:])
case "config":
executeConfig(args[1:])
case "pr":
executePR(args[1:])
case "help":
printHelp()
case "version":
fmt.Printf("gitpilot %s (%s/%s)\n", version, runtime.GOOS, runtime.GOARCH)
default:
printError("Invalid command. Type 'help'")
}
}
func runGitCommand(args ...string) (string, error) {
cmd := exec.Command("git", args...)
output, err := cmd.CombinedOutput()
if err != nil {
return string(output), fmt.Errorf("git %s: %w", strings.Join(args, " "), err)
}
return string(output), nil
}
func getChangedFiles() ([]FileChange, error) {
output, err := runGitCommand("status", "--porcelain")
if err != nil {
return nil, err
}
// Preserve leading spaces because porcelain status uses them as data,
// e.g. " M main.go" for unstaged modifications.
lines := strings.Split(strings.TrimRight(output, "\n"), "\n")
if len(lines) == 1 && lines[0] == "" {
return nil, nil
}
var changes []FileChange
seen := make(map[string]struct{})
for _, line := range lines {
if len(line) < 4 {
continue
}
status := strings.TrimSpace(line[:2])
path := strings.TrimSpace(line[3:])
if strings.Contains(path, " -> ") {
parts := strings.Split(path, " -> ")
path = strings.TrimSpace(parts[len(parts)-1])
}
if _, ok := seen[path]; ok {
continue
}
seen[path] = struct{}{}
diff, diffErr := getDiffForFile(path, status)
if diffErr != nil {
printWarning("Skipping file: " + path)
continue
}
changes = append(changes, FileChange{
FileName: path,
Status: status,
Diff: diff,
})
}
return changes, nil
}
func getDiffForFile(fileName, status string) (string, error) {
if strings.Contains(status, "?") {
return runDiffAllowExitCodeOne("diff", "--no-index", "--", "/dev/null", fileName)
}
var sections []string
if stagedDiff, err := runDiffAllowExitCodeOne("diff", "--cached", "--", fileName); err == nil && strings.TrimSpace(stagedDiff) != "" {
sections = append(sections, stagedDiff)
}
if workingDiff, err := runDiffAllowExitCodeOne("diff", "--", fileName); err == nil && strings.TrimSpace(workingDiff) != "" {
sections = append(sections, workingDiff)
}
if len(sections) == 0 {
return "", errors.New("no diff available")
}
return strings.Join(sections, "\n"), nil
}
func runDiffAllowExitCodeOne(args ...string) (string, error) {
cmd := exec.Command("git", args...)
output, err := cmd.CombinedOutput()
if err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 && len(output) > 0 {
return string(output), nil
}
return "", err
}
return string(output), nil
}
func filterChanges(changes []FileChange, targets []string) ([]FileChange, error) {
if len(targets) == 0 {
return changes, nil
}
lookup := make(map[string]FileChange, len(changes))
for _, change := range changes {
lookup[change.FileName] = change
}
var filtered []FileChange
for _, target := range targets {
change, ok := lookup[target]
if !ok {
return nil, fmt.Errorf("file %q has no detected changes", target)
}
filtered = append(filtered, change)
}
return filtered, nil
}
func executeInit() {
printSection("Init")
if _, err := runGitCommand("rev-parse", "--is-inside-work-tree"); err != nil {
printError("Current directory is not a Git repository.")
return
}
branch, _ := runGitCommand("branch", "--show-current")
remoteName := getDefaultRemoteName()
model := strings.TrimSpace(getGroqModel())
if _, err := runGitCommand("config", "--get", groqModelConfig); err != nil {
if err := setGitConfig(groqModelConfig, defaultGroqModel); err != nil {
printError("Failed to save default Groq model: " + err.Error())
return
}
model = defaultGroqModel
}
if _, err := runGitCommand("config", "--get", initConfigKey); err != nil {
if err := setGitConfig(initConfigKey, "true"); err != nil {
printError("Failed to save Git Pilot initialization state: " + err.Error())
return
}
}
printPanel([]string{
colorStrong + "Repository ready for Git Pilot" + colorReset,
colorDim + "Branch" + colorReset + " " + strings.TrimSpace(branch),
colorDim + "Remote" + colorReset + " " + remoteName,
colorDim + "Model" + colorReset + " " + model,
})
if _, err := getGroqAPIKey(); err != nil {
printWarning("Groq API key is not configured yet.")
fmt.Println("Set GROQ_API_KEY or run: config groq-key <your-key>")
return
}
printSuccess("Groq API key detected.")
}
func executeStatus() {
printSection("Repository Status")
output, err := runGitCommand("status")
if err != nil {
printWarning("Git returned an error.")
}
fmt.Println(output)
}
func executeDiff() {
printSection("Changed Files")
changes, err := getChangedFiles()
if err != nil {
printError(err.Error())
return
}
if len(changes) == 0 {
fmt.Println("No changes detected.")
return
}
lines := []string{
fmt.Sprintf("%s%d file(s) changed%s", colorStrong, len(changes), colorReset),
}
for index, change := range changes {
lines = append(lines, fmt.Sprintf("%s%2d%s %s %s", colorDim, index+1, colorReset, styleStatus(change.Status), change.FileName))
}
printPanel(lines)
}
func executeCommit(args []string) {
printSection("Commit Session")
changes, err := getChangedFiles()
if err != nil {
printError(err.Error())
return
}
if len(changes) == 0 {
fmt.Println("No changes detected.")
return
}
apiKey, err := getGroqAPIKey()
if err != nil {
printError(err.Error())
fmt.Println("Set GROQ_API_KEY or run: config groq-key <your-key>")
return
}
model := getGroqModel()
mode := ""
targets := []string(nil)
if len(args) > 0 {
mode = args[0]
targets = args[1:]
} else {
mode = promptCommitMode()
if mode == "" {
printWarning("Commit cancelled.")
return
}
}
plans, err := buildCommitPlans(apiKey, model, mode, changes, targets)
if err != nil {
printError(err.Error())
return
}
summary := commitRunSummary{Mode: mode}
printInfo("Planned commits: " + strconv.Itoa(len(plans)))
for index, plan := range plans {
printSection(fmt.Sprintf("Commit %d of %d", index+1, len(plans)))
printPanel([]string{
colorStrong + plan.Label + colorReset,
colorDim + strconv.Itoa(len(plan.Changes)) + " file(s) in this commit" + colorReset,
"",
formatFilesForDisplay(plan.Changes),
})
printInfo("Generating AI commit message...")
message, err := generateCommitMessage(apiKey, model, plan.Changes)
if err != nil {
printError("AI generation failed: " + err.Error())
summary.Failed = append(summary.Failed, plan.Label)
continue
}
printCommitPreview(plan, message)
if !approveCommit(plan, message) {
printWarning("Commit skipped.")
summary.Skipped = append(summary.Skipped, plan.Label)
continue
}
if err := performCommit(mode, plan.Changes, message); err != nil {
printError("Commit failed: " + err.Error())
summary.Failed = append(summary.Failed, plan.Label)
continue
}
printSuccess("Commit created.")
summary.Committed = append(summary.Committed, fmt.Sprintf("%s -> %s", plan.Label, message))
}
printCommitSummary(summary)
if len(summary.Committed) > 0 {
promptPushAfterCommits()
}
}
func promptCommitMode() string {
reader := bufio.NewReader(os.Stdin)
for {
printSection("Commit Mode")
fmt.Println("How do you want to split these commits?")
fmt.Println(renderChoice(1, "File wise", "One commit per changed file."))
fmt.Println(renderChoice(2, "Group wise", "AI groups related files into logical commit categories."))
fmt.Printf("%sSelect mode%s %s(1/2)%s: ", colorStrong, colorReset, colorDim, colorReset)
answer, err := reader.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
printError("Failed to read choice: " + err.Error())
return ""
}
switch strings.TrimSpace(answer) {
case "1":
return "file"
case "2":
return "group"
case "":
if errors.Is(err, io.EOF) {
return ""
}
default:
printWarning("Please choose 1 or 2.")
}
}
}
func buildCommitPlans(apiKey, model, mode string, changes []FileChange, targets []string) ([]CommitPlan, error) {
switch mode {
case "group":
if len(targets) > 0 {
groupChanges, err := filterChanges(changes, targets)
if err != nil {
return nil, err
}
return []CommitPlan{{
Label: "group: " + formatFileList(groupChanges),
Changes: groupChanges,
}}, nil
}
return buildGroupedCommitPlans(apiKey, model, changes)
case "categories":
return buildGroupedCommitPlans(apiKey, model, changes)
case "all":
groupChanges, err := filterChanges(changes, targets)
if err != nil {
return nil, err
}
return []CommitPlan{{
Label: "group: " + formatFileList(groupChanges),
Changes: groupChanges,
}}, nil
case "file":
fileChanges := changes
var err error
if len(targets) > 0 {
fileChanges, err = filterChanges(changes, targets)
}
if err != nil {
return nil, err
}
plans := make([]CommitPlan, 0, len(fileChanges))
for _, change := range fileChanges {
plans = append(plans, CommitPlan{
Label: "file: " + change.FileName,
Changes: []FileChange{change},
})
}
return plans, nil
default:
return nil, errors.New("unknown commit mode. Use: commit, commit file <file...>, or commit group <file...>")
}
}
func printCommitPreview(plan CommitPlan, message string) {
printPanel([]string{
colorStrong + "Commit Preview" + colorReset,
colorDim + "Target" + colorReset + " " + plan.Label,
colorDim + "Files" + colorReset + " " + formatFileList(plan.Changes),
colorDim + "Message" + colorReset + " " + colorAccent + message + colorReset,
})
}
func approveCommit(plan CommitPlan, message string) bool {
reader := bufio.NewReader(os.Stdin)
fmt.Printf("Approve commit for %s? [y/N]: ", plan.Label)
answer, err := reader.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
printError("Failed to read approval: " + err.Error())
return false
}
answer = strings.TrimSpace(strings.ToLower(answer))
return answer == "y" || answer == "yes"
}
func promptYesNo(prompt string) bool {
reader := bufio.NewReader(os.Stdin)
fmt.Print(prompt)
answer, err := reader.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
printError("Failed to read approval: " + err.Error())
return false
}
answer = strings.TrimSpace(strings.ToLower(answer))
return answer == "y" || answer == "yes"
}
func performCommit(mode string, changes []FileChange, message string) error {
if len(changes) == 0 {
return errors.New("no changes to commit")
}
if len(changes) > 1 && mode == "all" {
if _, err := runGitCommand("add", "-A"); err != nil {
return err
}
_, err := runGitCommand("commit", "-m", message)
return err
}
paths := make([]string, 0, len(changes))
for _, change := range changes {
paths = append(paths, change.FileName)
}
addArgs := append([]string{"add", "-A", "--"}, paths...)
if _, err := runGitCommand(addArgs...); err != nil {
return err
}
commitArgs := append([]string{"commit", "--only", "-m", message, "--"}, paths...)
_, err := runGitCommand(commitArgs...)
return err
}
func buildGroupedCommitPlans(apiKey, model string, changes []FileChange) ([]CommitPlan, error) {
content, err := generateCommitGroups(apiKey, model, changes)
if err != nil {
return nil, err
}
proposals, err := parseCommitGroups(content)
if err != nil {
return nil, err
}
lookup := make(map[string]FileChange, len(changes))
for _, change := range changes {
lookup[change.FileName] = change
}
used := make(map[string]struct{})
var plans []CommitPlan
for _, proposal := range proposals {
if len(proposal.Files) == 0 {
continue
}
var group []FileChange
for _, file := range proposal.Files {
change, ok := lookup[file]
if !ok {
continue
}
if _, seen := used[file]; seen {
continue
}
used[file] = struct{}{}
group = append(group, change)
}
if len(group) == 0 {
continue
}
label := proposal.Label
if strings.TrimSpace(label) == "" {
label = formatFileList(group)
}
plans = append(plans, CommitPlan{
Label: label,
Changes: group,
})
}
for _, change := range changes {
if _, seen := used[change.FileName]; seen {
continue
}
plans = append(plans, CommitPlan{
Label: "remaining: " + change.FileName,
Changes: []FileChange{change},
})
}
if len(plans) == 0 {
return nil, errors.New("AI did not produce any valid commit groups")
}
return plans, nil
}
func generateCommitGroups(apiKey, model string, changes []FileChange) (string, error) {
payload := chatCompletionRequest{
Model: model,
Temperature: 0.1,
MaxTokens: 500,
Messages: []chatMessage{
{
Role: "system",
Content: "You group changed file paths into logical git commits. Use only path, status, and area metadata; do not assume diff contents. Return JSON only. " +
`Use this schema: [{"label":"short category label","files":["path1","path2"]}]. ` +
"Each file must appear at most once.",
},
{
Role: "user",
Content: buildGroupingPrompt(changes),
},
},
}
payload = limitChatPayload(payload, maxGroupingRequestTokens)
return sendGroqChat(apiKey, payload)
}
func buildGroupingPrompt(changes []FileChange) string {
var builder strings.Builder
builder.WriteString("Group these changed files into logical commits from the file graph only.\n")
builder.WriteString("Use directory structure, path names, extensions, status, and inferred area. Keep unrelated paths separate.\n\n")
builder.WriteString(buildChangedFilesGraph(changes))
return builder.String()
}
func buildChangedFilesGraph(changes []FileChange) string {
var builder strings.Builder
builder.WriteString("Changed file graph:\n")
for _, change := range changes {
builder.WriteString(formatGraphPath(change.FileName))
builder.WriteString(" [")
builder.WriteString(change.Status)
builder.WriteString(", ")
builder.WriteString(classifyFileArea(change.FileName))
builder.WriteString("]")
builder.WriteString("\n")
}
return builder.String()
}
func formatGraphPath(path string) string {
parts := strings.Split(filepath.ToSlash(path), "/")
if len(parts) == 0 {
return "- " + path
}
var builder strings.Builder
for index, part := range parts {
if part == "" {
continue
}
if builder.Len() == 0 {
builder.WriteString("- ")
} else {
builder.WriteString(" > ")
}
builder.WriteString(part)
if index == len(parts)-1 {
builder.WriteString(" (")
builder.WriteString(path)
builder.WriteString(")")
}
}
return builder.String()
}
func parseCommitGroups(content string) ([]commitGroupProposal, error) {
cleaned := strings.TrimSpace(content)
cleaned = strings.TrimPrefix(cleaned, "```json")
cleaned = strings.TrimPrefix(cleaned, "```")
cleaned = strings.TrimSuffix(cleaned, "```")
cleaned = strings.TrimSpace(cleaned)
var proposals []commitGroupProposal
if err := json.Unmarshal([]byte(cleaned), &proposals); err != nil {
return nil, fmt.Errorf("failed to parse AI commit groups: %w", err)
}
return proposals, nil
}
func printCommitSummary(summary commitRunSummary) {
printSection("Commit Session Summary")
lines := []string{
colorDim + "Mode" + colorReset + " " + summary.Mode,
colorSuccess + "Committed" + colorReset + " " + strconv.Itoa(len(summary.Committed)),
colorWarn + "Skipped" + colorReset + " " + strconv.Itoa(len(summary.Skipped)),
colorError + "Failed" + colorReset + " " + strconv.Itoa(len(summary.Failed)),
}
if len(summary.Committed) > 0 {
lines = append(lines, "", colorStrong+"Created"+colorReset)
for _, item := range summary.Committed {
lines = append(lines, " + "+item)
}
}
if len(summary.Skipped) > 0 {
lines = append(lines, "", colorStrong+"Skipped"+colorReset)
for _, item := range summary.Skipped {
lines = append(lines, " - "+item)
}
}
if len(summary.Failed) > 0 {
lines = append(lines, "", colorStrong+"Failed"+colorReset)
for _, item := range summary.Failed {
lines = append(lines, " x "+item)
}
}
printPanel(lines)
}
func promptPushAfterCommits() {
printSection("Push")
if !promptYesNo("Push committed changes now? [y/N]: ") {
printWarning("Push skipped.")
return
}
if err := executePush(); err != nil {
printError("Push failed: " + err.Error())
}
}
func formatFileList(changes []FileChange) string {
names := make([]string, 0, len(changes))
for _, change := range changes {
names = append(names, change.FileName)
}
return strings.Join(names, ", ")
}
func formatFilesForDisplay(changes []FileChange) string {
lines := make([]string, 0, len(changes))
for _, change := range changes {
lines = append(lines, fmt.Sprintf(" %s %s", styleStatus(change.Status), change.FileName))
}
return strings.Join(lines, "\n")
}
func generateCommitMessage(apiKey, model string, changes []FileChange) (string, error) {
prompt := buildCommitPrompt(changes)
payload := chatCompletionRequest{
Model: model,
Temperature: 0.15,
MaxTokens: 200,
Messages: []chatMessage{
{
Role: "system",
Content: "You write high-signal git commit subjects. Reply with exactly one imperative conventional commit subject. " +
"Allowed prefixes: feat:, fix:, docs:, style:, refactor:, perf:, test:, build:, ci:, chore:, revert:. " +
"Choose the prefix from the actual changed area and intent. Use a concrete object and action from the provided summaries. " +
"Never use vague words like update, changes, stuff, misc, null, handle, or file unless they are part of a real API name. " +
"No quotes, no markdown, no bullet points, max 72 characters.",
},
{
Role: "user",
Content: prompt,
},
},
}
payload = limitChatPayload(payload, maxCommitRequestTokens)
message, err := sendGroqChat(apiKey, payload)
if err != nil {
return "", err
}
message = sanitizeCommitMessage(message)
if isUsableCommitMessage(message) {
return message, nil
}
payload.Messages = append(payload.Messages,
chatMessage{Role: "assistant", Content: message},
chatMessage{Role: "user", Content: "That subject is too vague or malformed. Generate one specific conventional commit subject using the file summaries and changed symbols. Do not include null, generic filler, or explanations."},
)
payload = limitChatPayload(payload, maxCommitRequestTokens)
message, err = sendGroqChat(apiKey, payload)
if err != nil {
return "", err
}
message = sanitizeCommitMessage(message)
if isUsableCommitMessage(message) {
return message, nil
}
return fallbackCommitMessage(changes), nil
}
func buildCommitPrompt(changes []FileChange) string {
var builder strings.Builder
builder.WriteString("Generate a git commit message for these changes.\n")
builder.WriteString("Summarize the main behavior change, not the implementation trivia.\n\n")
builder.WriteString("Prefix selection guidance:\n")
builder.WriteString("- feat: new user-facing behavior or capability\n")
builder.WriteString("- fix: bug fix or error handling correction\n")
builder.WriteString("- docs: documentation-only changes\n")
builder.WriteString("- refactor: internal restructuring without behavior change\n")
builder.WriteString("- test: tests only\n")
builder.WriteString("- build: build, packaging, release, dependency, or installer changes\n")
builder.WriteString("- ci: workflow or automation changes\n")
builder.WriteString("- chore: maintenance that does not fit the above\n\n")
builder.WriteString(buildManagedChangeContext(changes, maxAIContextChars))
return builder.String()
}
func sanitizeCommitMessage(message string) string {
message = strings.TrimSpace(message)
message = strings.TrimPrefix(message, "```")
message = strings.TrimSuffix(message, "```")
message = strings.TrimSpace(message)
lines := strings.Split(message, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
line = strings.TrimPrefix(line, "- ")
line = strings.TrimPrefix(line, "* ")
line = strings.Trim(line, `"'`)
if line != "" {
message = line
break
}
}
if len(message) > 72 {
message = strings.TrimSpace(message[:72])
}
return message
}
func isUsableCommitMessage(message string) bool {
if message == "" || !hasConventionalPrefix(message) {
return false
}
lower := strings.ToLower(message)
badFragments := []string{
": null",
" null ",
"undefined",
"todo",