-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-commit-completion.plugin.zsh
More file actions
2196 lines (1906 loc) · 83.5 KB
/
git-commit-completion.plugin.zsh
File metadata and controls
2196 lines (1906 loc) · 83.5 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
# Save original PATH at the start of the script
typeset -g _ORIGINAL_PATH="$PATH"
# Debug log function with timestamp
_debug_log() {
PATH="$_ORIGINAL_PATH" /bin/date +"[%H:%M:%S] $1" >> /tmp/git-completion-debug.log
}
# Function to manage state changes
_set_suggestion_state() {
local new_state="$1"
local error_msg="$2"
typeset -g _SUGGESTION_STATE="$new_state"
if [[ -n "$error_msg" ]]; then
typeset -g _SUGGESTION_ERROR="$error_msg"
else
typeset -g _SUGGESTION_ERROR=""
fi
_debug_log "State changed to: $_SUGGESTION_STATE${error_msg:+ ($error_msg)}"
}
# Global state variables
typeset -g _CONFIG_FILE="${HOME}/.git-suggest-config"
typeset -g _COMMIT_SUGGESTION=""
typeset -g _CACHED_STAGED_DIFF=""
# Suggestion states
typeset -g _SUGGESTION_STATE="UNCONFIGURED" # UNCONFIGURED, LOADING, ERROR, READY
typeset -g _SUGGESTION_ERROR=""
_debug_log "Initial state setup - State: $_SUGGESTION_STATE, Diff cached: ${_CACHED_STAGED_DIFF:+yes}"
# Function to update staged diff when files are staged
_update_staged_diff() {
_debug_log "Starting diff update"
if git rev-parse --is-inside-work-tree &>/dev/null; then
_debug_log "Checking for staged changes..."
local new_diff
# Debug git status
local git_status=$(git status --porcelain)
_debug_log "Git status: $git_status"
# Get both staged changes and new files
new_diff=$(git diff --staged)
_debug_log "Standard diff result: ${new_diff:+exists}"
local new_files=$(git diff --staged --name-status | grep '^A' || true)
_debug_log "Staged files status: $new_files"
if [[ -n "$new_files" ]]; then
_debug_log "New files detected: $new_files"
# For new files, get their content
while IFS= read -r line; do
if [[ "$line" =~ ^A[[:space:]]+(.+)$ ]]; then
local file="${BASH_REMATCH[1]}"
_debug_log "Getting content for new file: $file"
if [[ -n "$file" && -f "$file" ]]; then
new_diff+=$'\n'"New file: $file"$'\n'
local file_content=$(git show ":${file}" 2>/dev/null || cat "$file" 2>/dev/null)
_debug_log "File content length: ${#file_content}"
new_diff+="$file_content"
else
_debug_log "File not found or empty path: $file"
fi
fi
done <<< "$new_files"
fi
# Debug the current state
_debug_log "Final diff length: ${#new_diff}"
if [[ -z "$new_diff" ]]; then
_debug_log "No staged changes detected"
typeset -g _CACHED_STAGED_DIFF=""
return 1
fi
_debug_log "Current cached diff: ${_CACHED_STAGED_DIFF:+exists}"
_debug_log "New diff: ${new_diff:+exists}"
if [[ "$new_diff" != "$_CACHED_STAGED_DIFF" ]]; then
typeset -g _CACHED_STAGED_DIFF="$new_diff"
_debug_log "Updated cached diff: ${_CACHED_STAGED_DIFF:+exists}"
fi
fi
}
# Function to generate test suggestions
_generate_commit_suggestions() {
_debug_log "=== Starting suggestion generation ==="
_debug_log "Current state: $_SUGGESTION_STATE"
_debug_log "Current diff cache: ${_CACHED_STAGED_DIFF:+exists}"
if [[ -z "$SUGGEST_PROVIDER" ]]; then
_set_suggestion_state "UNCONFIGURED"
_debug_log "State change -> UNCONFIGURED (no provider)"
return 1
fi
# Validate provider-specific configuration
case $SUGGEST_PROVIDER in
"openai"|"anthropic"|"grok")
if [[ -z "$SUGGEST_LLM_TOKEN" ]]; then
_set_suggestion_state "ERROR" "No API token configured for $SUGGEST_PROVIDER"
_debug_log "State change -> ERROR (no token)"
return 1
fi
;;
"local")
if [[ -z "$SUGGEST_LLM_PATH" ]]; then
_set_suggestion_state "ERROR" "No model path configured"
_debug_log "State change -> ERROR (no path)"
return 1
fi
;;
esac
_debug_log "Diff content length: ${#_CACHED_STAGED_DIFF}"
if [[ -n "$_CACHED_STAGED_DIFF" ]]; then
_debug_log "Diff preview: $(echo "$_CACHED_STAGED_DIFF" | head -n 1)"
fi
if [[ -z "$_CACHED_STAGED_DIFF" ]]; then
_set_suggestion_state "ERROR" "No staged changes detected"
_debug_log "State change -> ERROR (no diff)"
return 1
fi
_set_suggestion_state "LOADING"
_debug_log "Calling LLM provider"
local suggestion
suggestion=$(_llm_generate_suggestion "$_CACHED_STAGED_DIFF")
local result=$?
if [[ $result -ne 0 || -z "$suggestion" ]]; then
_set_suggestion_state "ERROR" "Failed to generate suggestion"
_debug_log "LLM generation failed"
_debug_log "State immediately after error: $_SUGGESTION_STATE"
return 1
fi
# Only set READY state after successful generation
_set_suggestion_state "READY"
_debug_log "Successfully generated suggestion"
# Return just the suggestion without formatting
echo "$suggestion"
}
# Hook function to run after git commands
_git_command_hook() {
local cmd="$1"
_debug_log "Command received: $cmd" # Log the exact command
# Debug pattern matching
if [[ "$cmd" =~ ^git[[:space:]]+ ]]; then
_debug_log "Git command detected: $cmd"
fi
if [[ "$cmd" =~ ^ga[[:space:]]+ ]]; then
_debug_log "Ga alias detected: $cmd"
fi
# More explicit pattern matching for git add commands
if [[ "$cmd" =~ ^(git[[:space:]]+add|ga|git[[:space:]]+reset)[[:space:]]+ || "$cmd" =~ git[[:space:]]+add.*[[:space:]]+ ]]; then
_debug_log "Git add command detected: $cmd"
typeset -g _LAST_GIT_COMMAND="$cmd"
fi
}
# Function to run after command completion
_post_git_command() {
if [[ -n "$_LAST_GIT_COMMAND" ]]; then
_debug_log "Processing completed git command: $_LAST_GIT_COMMAND"
# Debug git status
local git_status=$(git status --porcelain)
_debug_log "Git status after command: $git_status"
_debug_log "Running diff update"
_update_staged_diff
_debug_log "After update - Diff cached: ${_CACHED_STAGED_DIFF:+yes}"
# If we have staged changes, start generating a suggestion in the background
if [[ -n "$_CACHED_STAGED_DIFF" ]]; then
_debug_log "Starting background suggestion generation after git add"
# Clear existing suggestion when starting new generation
# TODO: We might not have to do this since global vars are not a thing
typeset -g _COMMIT_SUGGESTION=""
_set_suggestion_state "LOADING"
local parent_pid=$$
_debug_log "Parent PID: $parent_pid"
# Create temporary files
local tmp_file="/tmp/git-suggestion-temp-diff-${parent_pid}"
local suggestion_state_file="/tmp/git-suggestion-state-${parent_pid}"
local suggestion_file="/tmp/git-suggestion-${parent_pid}"
local plugin_path="${0:A}"
echo "$_CACHED_STAGED_DIFF" > "$tmp_file"
# Use a helper function to safely background the process
_run_background_suggestion "$tmp_file" "$suggestion_file" "$suggestion_state_file" "$plugin_path"
fi
# Clear the last command
typeset -g _LAST_GIT_COMMAND=""
fi
}
# Add both hooks
autoload -U add-zsh-hook
add-zsh-hook preexec _git_command_hook
add-zsh-hook precmd _post_git_command
# Function to show suggestion
_show_suggestion() {
print -P "" # New line
_debug_log "Current state when showing suggestion: $_SUGGESTION_STATE"
_debug_log "Current suggestion: ${_COMMIT_SUGGESTION:+exists}"
case $_SUGGESTION_STATE in
"UNCONFIGURED")
if [[ -n "$SUGGEST_LLM_TOKEN" ]]; then
print -P "%F{yellow}⚠ Configuration detected in environment but no provider set. Run %F{green}git-suggest-config%f%F{yellow} to complete setup.%f"
else
print -P "%F{yellow}⚠ LLM not configured. Run %F{green}git-suggest-config%f%F{yellow} to set up.%f"
fi
;;
"LOADING")
print -P "%F{blue}⟳ Generating commit suggestion... (Press Tab to check if ready)%f"
;;
"ERROR")
print -P "%F{red}✖ Error generating suggestion: $_SUGGESTION_ERROR%f"
;;
"READY")
if [[ -n "$_COMMIT_SUGGESTION" ]]; then
print -P "%F{green}Suggested commit message:%f\n$_COMMIT_SUGGESTION"
rm -f "/tmp/git-suggestion-state-${$}"
rm -f "/tmp/git-suggestion-${$}"
else
print -P "%F{yellow}No suggestion available%f"
fi
;;
esac
}
# Format the complete message for acceptance
_format_complete_message() {
echo "$_COMMIT_SUGGESTION" | awk '
BEGIN { first = 1 }
/^Suggested commit message:/ { next }
/^$/ { if (!first) printf "\n"; next }
/^feat/ { first = 0; printf "%s", $0; next }
/^-/ { printf "\n%s", $0; next }
{ print $0 }
' | sed '/^$/d'
}
# Add at the top with other global variables
typeset -g _ORIGINAL_TAB_BINDING=""
typeset -g _TAB_BINDING_CHANGED=0
# Function to restore binding
_restore_tab_binding() {
if [[ $_TAB_BINDING_CHANGED -eq 1 ]]; then
bindkey '^I' complete-word
_TAB_BINDING_CHANGED=0
_debug_log "Restored original Tab binding"
fi
}
# Add SIGINT trap
_handle_interrupt() {
_restore_tab_binding
# Restore original SIGINT behavior
trap - INT
# Send SIGINT to the current process
kill -INT $$
}
# Set up the trap
trap '_handle_interrupt' INT
# Update the quote handler
_git_commit_quote_handler() {
# Insert the quote first
zle self-insert
local current_buffer="$BUFFER"
_debug_log "Buffer after quote: '$current_buffer'"
# Check for git commit command
if [[ "$current_buffer" =~ "(git commit|gc) -m \"$" ]]; then
_debug_log "✓ Git commit command detected"
if [[ $_TAB_BINDING_CHANGED -eq 0 ]]; then
_ORIGINAL_TAB_BINDING=$(bindkey '^I')
bindkey '^I' accept-suggestion
_TAB_BINDING_CHANGED=1
_debug_log "Temporarily bound Tab to accept-suggestion for git commit"
fi
# Check for any completed background job (success or error)
local suggestion_file="/tmp/git-suggestion-${$}"
local state_file="/tmp/git-suggestion-state-${$}"
local error_file="${suggestion_file%.tmp}.error"
if [[ -f "$state_file" ]]; then
local bg_state=$(cat "$state_file")
if [[ "$bg_state" == "READY" && -f "$suggestion_file" ]]; then
_debug_log "Existing suggestion found"
_COMMIT_SUGGESTION=$(cat "$suggestion_file")
_set_suggestion_state "READY"
rm -f "$suggestion_file" "$state_file" "$error_file"
_debug_log "Loaded and cleaned up suggestion files"
elif [[ "$bg_state" == "ERROR" ]]; then
local error_msg="Failed to generate suggestion"
if [[ -f "$error_file" ]]; then
error_msg=$(cat "$error_file")
fi
_set_suggestion_state "ERROR" "$error_msg"
rm -f "$suggestion_file" "$state_file" "$error_file"
_debug_log "Loaded error state: $error_msg"
fi
fi
# Use existing suggestion if available
if [[ "$_SUGGESTION_STATE" == "READY" && -n "$_COMMIT_SUGGESTION" ]]; then
_debug_log "Using existing suggestion"
_show_suggestion
else
_debug_log "No cached suggestion available"
_show_suggestion
fi
# # Get and show suggestion
# _COMMIT_SUGGESTION=$(_generate_commit_suggestions)
# _show_suggestion "$_COMMIT_SUGGESTION"
# Run in current shell to preserve state
# _generate_commit_suggestions > >(read -r suggestion; typeset -g _COMMIT_SUGGESTION="$suggestion")
# # If we don't have a suggestion yet, generate one
# if [[ "$_SUGGESTION_STATE" != "READY" ]]; then
# _debug_log "No suggestion ready, generating one now"
# _set_suggestion_state "LOADING"
# _show_suggestion
# # Generate the suggestion
# _generate_commit_suggestions
# else
# _debug_log "Suggestion already available"
# _show_suggestion
# fi
# Force display update
zle reset-prompt
fi
}
# Add the preexec hook
add-zsh-hook preexec _restore_tab_binding
# Accept suggestion function
_accept_suggestion() {
# Check for completed background job if in LOADING state
if [[ "$_SUGGESTION_STATE" == "LOADING" ]]; then
local suggestion_file="/tmp/git-suggestion-${$}"
local state_file="/tmp/git-suggestion-state-${$}"
local error_file="${suggestion_file%.tmp}.error"
if [[ -f "$state_file" ]]; then
local bg_state=$(cat "$state_file")
if [[ "$bg_state" == "READY" && -f "$suggestion_file" ]]; then
_COMMIT_SUGGESTION=$(cat "$suggestion_file")
_set_suggestion_state "READY"
rm -f "$suggestion_file" "$state_file" "$error_file"
_debug_log "Loaded completed suggestion from background job"
elif [[ "$bg_state" == "ERROR" ]]; then
local error_msg="Failed to generate suggestion"
if [[ -f "$error_file" ]]; then
error_msg=$(cat "$error_file")
fi
_set_suggestion_state "ERROR" "$error_msg"
rm -f "$suggestion_file" "$state_file" "$error_file"
_debug_log "Loaded error state from background job: $error_msg"
fi
fi
fi
if [[ -n "$_COMMIT_SUGGESTION" && "$_SUGGESTION_STATE" == "READY" ]]; then
# Get the complete formatted message
local formatted_message
formatted_message=$(_format_complete_message)
# Update buffer with full message
BUFFER="${BUFFER}${formatted_message}"
CURSOR=${#BUFFER}
zle reset-prompt
elif [[ "$_SUGGESTION_STATE" == "LOADING" ]]; then
print -P "%F{blue}⟳ Still generating... Press Tab again to check.%f"
zle reset-prompt
elif [[ "$_SUGGESTION_STATE" == "ERROR" ]]; then
print -P "%F{red}✖ Error: $_SUGGESTION_ERROR%f"
if [[ "$_SUGGESTION_ERROR" == *"API key"* || "$_SUGGESTION_ERROR" == *"token"* ]]; then
print -P "%F{yellow}Run %F{green}git-suggest-config%f%F{yellow} to fix your API configuration.%f"
elif [[ "$_SUGGESTION_ERROR" == *"No staged changes"* ]]; then
print -P "%F{yellow}Stage some changes with %F{green}git add%f%F{yellow} first.%f"
else
print -P "%F{yellow}Run %F{green}git-suggest-config%f%F{yellow} to check your configuration.%f"
fi
zle reset-prompt
elif [[ "$_SUGGESTION_STATE" == "UNCONFIGURED" ]]; then
if [[ -n "$SUGGEST_LLM_TOKEN" ]]; then
print -P "%F{yellow}⚠ Token found in environment but no provider configured.%f"
print -P "%F{yellow}Run %F{green}git-suggest-config%f%F{yellow} to complete setup, or set SUGGEST_PROVIDER env var.%f"
else
print -P "%F{yellow}⚠ LLM not configured. Run %F{green}git-suggest-config%f%F{yellow} to set up.%f"
fi
zle reset-prompt
fi
}
# Create and bind the widgets
zle -N self-insert-quote _git_commit_quote_handler
zle -N accept-suggestion _accept_suggestion
# Bind keys
bindkey '"' self-insert-quote
bindkey '^I' accept-suggestion # Tab key
bindkey '^[[C' accept-suggestion # Right arrow
_debug_log "Git commit suggestion system loaded at $(date)"
# Configuration management functions with multi-provider support
_load_config() {
_debug_log "=== Loading multi-provider configuration ==="
if [[ -f "$_CONFIG_FILE" ]]; then
# Source the config file to load variables
source "$_CONFIG_FILE"
# Use SUGGEST_ACTIVE_PROVIDER if available, fallback to SUGGEST_PROVIDER
local active_provider="${SUGGEST_ACTIVE_PROVIDER:-$SUGGEST_PROVIDER}"
# Set the appropriate token based on active provider
case "$active_provider" in
"openai")
[[ -n "$SUGGEST_OPENAI_TOKEN" ]] && export SUGGEST_LLM_TOKEN="$SUGGEST_OPENAI_TOKEN"
;;
"anthropic")
[[ -n "$SUGGEST_ANTHROPIC_TOKEN" ]] && export SUGGEST_LLM_TOKEN="$SUGGEST_ANTHROPIC_TOKEN"
;;
"grok")
[[ -n "$SUGGEST_GROK_TOKEN" ]] && export SUGGEST_LLM_TOKEN="$SUGGEST_GROK_TOKEN"
;;
"local")
# Local LLM uses path instead of token
[[ -n "$SUGGEST_LOCAL_PATH" ]] && export SUGGEST_LLM_PATH="$SUGGEST_LOCAL_PATH"
;;
esac
# Ensure SUGGEST_PROVIDER is set for backward compatibility
[[ -n "$active_provider" ]] && export SUGGEST_PROVIDER="$active_provider"
_debug_log "Loaded config - Active Provider: $active_provider, Token: ${SUGGEST_LLM_TOKEN:+set}"
_debug_log "Available providers: OpenAI:${SUGGEST_OPENAI_TOKEN:+✓} Anthropic:${SUGGEST_ANTHROPIC_TOKEN:+✓} Grok:${SUGGEST_GROK_TOKEN:+✓} Local:${SUGGEST_LOCAL_PATH:+✓}"
# Set initial state based on configuration
local has_valid_config=false
case "$active_provider" in
"openai"|"anthropic"|"grok")
[[ -n "$SUGGEST_LLM_TOKEN" ]] && has_valid_config=true
;;
"local")
[[ -n "$SUGGEST_LLM_PATH" ]] && has_valid_config=true
;;
esac
if $has_valid_config; then
_set_suggestion_state "READY"
_debug_log "Initial state set to READY (config valid)"
else
_set_suggestion_state "UNCONFIGURED"
_debug_log "Initial state set to UNCONFIGURED (missing config for active provider)"
fi
return 0
fi
_set_suggestion_state "UNCONFIGURED"
_debug_log "No configuration file found at $_CONFIG_FILE"
return 1
}
# Function to save configuration with multi-provider support
_save_config() {
local provider="$1"
local token="$2"
local model_path="$3"
# Restore PATH before running commands
PATH="$_ORIGINAL_PATH"
# Convert relative path to absolute path for local LLM
if [[ "$provider" == "local" && -n "$model_path" ]]; then
# Get absolute path
model_path="$(cd "$(dirname "$model_path")" && pwd)/$(basename "$model_path")"
_debug_log "Converted path to absolute: $model_path"
fi
# Load existing configuration to preserve other provider tokens
local existing_openai=""
local existing_anthropic=""
local existing_grok=""
local existing_local=""
if [[ -f "$_CONFIG_FILE" ]]; then
existing_openai=$(grep "SUGGEST_OPENAI_TOKEN=" "$_CONFIG_FILE" 2>/dev/null | cut -d'"' -f2)
existing_anthropic=$(grep "SUGGEST_ANTHROPIC_TOKEN=" "$_CONFIG_FILE" 2>/dev/null | cut -d'"' -f2)
existing_grok=$(grep "SUGGEST_GROK_TOKEN=" "$_CONFIG_FILE" 2>/dev/null | cut -d'"' -f2)
existing_local=$(grep "SUGGEST_LOCAL_PATH=" "$_CONFIG_FILE" 2>/dev/null | cut -d'"' -f2)
fi
# Set the new token/path for the specified provider
case $provider in
"openai")
existing_openai="$token"
;;
"anthropic")
existing_anthropic="$token"
;;
"grok")
existing_grok="$token"
;;
"local")
existing_local="$model_path"
;;
esac
# Create enhanced config content with all providers
cat > "$_CONFIG_FILE" << EOF
# Git Commit Suggestions Configuration
# Multi-provider support - Generated on $(date)
# Active provider
SUGGEST_ACTIVE_PROVIDER="$provider"
# Legacy variable for backward compatibility
SUGGEST_PROVIDER="$provider"
EOF
# Add all provider tokens (only if they exist)
[[ -n "$existing_openai" ]] && echo "SUGGEST_OPENAI_TOKEN=\"$existing_openai\"" >> "$_CONFIG_FILE"
[[ -n "$existing_anthropic" ]] && echo "SUGGEST_ANTHROPIC_TOKEN=\"$existing_anthropic\"" >> "$_CONFIG_FILE"
[[ -n "$existing_grok" ]] && echo "SUGGEST_GROK_TOKEN=\"$existing_grok\"" >> "$_CONFIG_FILE"
[[ -n "$existing_local" ]] && echo "SUGGEST_LOCAL_PATH=\"$existing_local\"" >> "$_CONFIG_FILE"
# Add legacy token variable for backward compatibility
case $provider in
"openai"|"anthropic"|"grok")
echo "SUGGEST_LLM_TOKEN=\"$token\"" >> "$_CONFIG_FILE"
;;
"local")
echo "SUGGEST_LLM_PATH=\"$model_path\"" >> "$_CONFIG_FILE"
;;
esac
chmod 600 "$_CONFIG_FILE" # Secure the file since it contains tokens
_debug_log "Multi-provider configuration saved to $_CONFIG_FILE"
}
# Helper function for typewriter text animation
_animate_text() {
local text="$1"
local delay="${2:-0.03}"
for (( i=0; i<${#text}; i++ )); do
echo -n "${text:$i:1}"
sleep "$delay"
done
echo ""
}
# Enhanced configuration function with improved onboarding
_git_suggest_config() {
# Restore PATH at the start of the function
PATH="$_ORIGINAL_PATH"
# Animated GAT ASCII art header (just the art, not everything)
echo ""
echo " ╔═══════════════════════════════════════════════════════════╗"
echo " ║ ║"
sleep 0.2
echo " ║ ████████ █████████ ████████ ║"
sleep 0.2
echo " ║ ██ ██ ██ ██ ║"
sleep 0.2
echo " ║ ██ ████ █████████ ██ ║"
sleep 0.2
echo " ║ ██ ██ ██ ██ ██ ║"
sleep 0.2
echo " ║ ████████ ██ ██ ██ ║"
echo " ║ ║"
echo " ║ 🤖 Git AI Tool - Smart Commit Messages ║"
echo " ║ ║"
echo " ╚═══════════════════════════════════════════════════════════╝"
echo ""
# Dramatic pause before showing the rest
sleep 0.7
# Check if this is first-time setup
local is_first_time=false
local has_config=false
if [[ ! -f "$_CONFIG_FILE" && -z "$SUGGEST_PROVIDER" && -z "$SUGGEST_LLM_TOKEN" ]]; then
is_first_time=true
else
has_config=true
fi
# Welcome message for first-time users (no animation)
if $is_first_time; then
echo "🚀 Welcome to Git Commit Suggestions!"
echo "====================================="
echo ""
echo "This plugin generates AI-powered commit messages based on your staged changes."
echo "Let's get you set up with an AI provider to start generating suggestions!"
echo ""
else
echo "🔧 Git Commit Suggestions Configuration"
echo "======================================="
echo ""
fi
# Show current configuration if it exists (no animation)
if $has_config; then
echo "📋 Current Configuration:"
echo "========================"
# Determine current provider and status
local current_provider=""
local current_status=""
local token_preview=""
if [[ -n "$SUGGEST_PROVIDER" ]]; then
current_provider="$SUGGEST_PROVIDER"
elif [[ -f "$_CONFIG_FILE" ]]; then
# Load from config file
local temp_provider=$(grep "SUGGEST_PROVIDER=" "$_CONFIG_FILE" 2>/dev/null | cut -d'"' -f2)
[[ -n "$temp_provider" ]] && current_provider="$temp_provider"
fi
if [[ -n "$SUGGEST_LLM_TOKEN" ]]; then
token_preview="${SUGGEST_LLM_TOKEN:0:8}...${SUGGEST_LLM_TOKEN: -4}"
current_status="✅ Active"
elif [[ -f "$_CONFIG_FILE" ]]; then
local temp_token=$(grep "SUGGEST_LLM_TOKEN=" "$_CONFIG_FILE" 2>/dev/null | cut -d'"' -f2)
if [[ -n "$temp_token" ]]; then
token_preview="${temp_token:0:8}...${temp_token: -4}"
current_status="✅ Active"
fi
fi
if [[ -n "$current_provider" ]]; then
case "$current_provider" in
"openai")
echo " 🤖 Provider: OpenAI API (GPT-3.5-turbo)"
;;
"anthropic")
echo " 🧠 Provider: Anthropic API (Claude-3-haiku)"
;;
"local")
echo " 🏠 Provider: Local LLM"
;;
"grok")
echo " ⚡ Provider: Grok API (xAI)"
;;
*)
echo " ❓ Provider: $current_provider"
;;
esac
if [[ -n "$token_preview" ]]; then
echo " 🔑 Token: $token_preview"
fi
echo " 📊 Status: $current_status"
else
echo " ⚠️ No valid configuration found"
fi
echo ""
fi
# Auto-detect existing API keys in environment
local detected_openai=""
local detected_anthropic=""
local detected_grok=""
local has_detections=false
if [[ -n "$OPENAI_API_KEY" ]]; then
detected_openai="$OPENAI_API_KEY"
has_detections=true
fi
if [[ -n "$ANTHROPIC_API_KEY" ]]; then
detected_anthropic="$ANTHROPIC_API_KEY"
has_detections=true
fi
if [[ -n "$GROK_API_KEY" ]]; then
detected_grok="$GROK_API_KEY"
has_detections=true
fi
# Show auto-detected keys (no animation)
if $has_detections; then
echo "🔍 Auto-detected API keys in your environment:"
[[ -n "$detected_openai" ]] && echo " ✅ OpenAI API key found (${detected_openai:0:8}...)"
[[ -n "$detected_anthropic" ]] && echo " ✅ Anthropic API key found (${detected_anthropic:0:8}...)"
[[ -n "$detected_grok" ]] && echo " ✅ Grok API key found (${detected_grok:0:8}...)"
echo ""
echo "🚀 QUICK SETUP:"
echo "0. ⚡ Configure ALL detected providers at once (recommended!)"
echo ""
fi
# Menu with recommendations and current config indicators (no animation)
echo "Choose your AI provider:"
echo ""
# OpenAI option with current config indicator
echo -n "1. 🤖 OpenAI API (GPT-3.5-turbo)"
if [[ "$current_provider" == "openai" && "$current_status" == "✅ Active" ]]; then
echo " 🟢 CURRENTLY ACTIVE"
else
echo ""
fi
echo " • Speed: ~2-3 seconds"
echo " • Cost: ~\$0.001 per commit"
echo " • Quality: Excellent"
[[ -n "$detected_openai" ]] && echo " 🔍 Auto-detected key available!"
echo ""
# Anthropic option with current config indicator
echo -n "2. 🧠 Anthropic API (Claude-3-haiku)"
if [[ "$current_provider" == "anthropic" && "$current_status" == "✅ Active" ]]; then
echo " 🟢 CURRENTLY ACTIVE"
else
echo " ⭐ RECOMMENDED"
fi
echo " • Speed: ~1-2 seconds (fastest)"
echo " • Cost: ~\$0.0001 per commit (cheapest)"
echo " • Quality: Excellent + concise"
[[ -n "$detected_anthropic" ]] && echo " 🔍 Auto-detected key available!"
echo ""
# Grok option with current config indicator
echo -n "3. ⚡ Grok API (xAI)"
if [[ "$current_provider" == "grok" && "$current_status" == "✅ Active" ]]; then
echo " 🟢 CURRENTLY ACTIVE"
else
echo " 🆕 NEW!"
fi
echo " • Speed: ~1-3 seconds"
echo " • Cost: ~\$0.0005 per commit"
echo " • Quality: Excellent + real-time context"
[[ -n "$detected_grok" ]] && echo " 🔍 Auto-detected key available!"
echo ""
# Local LLM option with current config indicator
echo -n "4. 🏠 Local LLM (coming soon)"
if [[ "$current_provider" == "local" && "$current_status" == "✅ Active" ]]; then
echo " 🟢 CURRENTLY ACTIVE"
else
echo ""
fi
echo " • Speed: Variable"
echo " • Cost: Free (after setup)"
echo " • Quality: Depends on model"
echo ""
# Show quick switching options for configured providers
local configured_providers=($(_get_configured_providers))
if [[ ${#configured_providers[@]} -gt 1 ]]; then
echo "⚡ Quick Switch (no re-entry needed):"
local switch_options=()
for provider in "${configured_providers[@]}"; do
if [[ "$provider" != "$current_provider" ]]; then
case "$provider" in
"openai") echo " s1. 🤖 Switch to OpenAI" && switch_options+=("s1:openai") ;;
"anthropic") echo " s2. 🧠 Switch to Anthropic" && switch_options+=("s2:anthropic") ;;
"grok") echo " s3. ⚡ Switch to Grok" && switch_options+=("s3:grok") ;;
"local") echo " s4. 🏠 Switch to Local LLM" && switch_options+=("s4:local") ;;
esac
fi
done
echo ""
fi
echo "5. 📋 View current configuration"
echo "6. 🗑️ Clear configuration"
echo ""
# Coffee support section
echo "─────────────────────────────────────────────────────────────────"
echo "☕ Enjoying this plugin? Buy the creator a coffee!"
echo " 💖 https://buymeacoffee.com/ngattusohw"
echo " ⭐ Star the repo: https://github.com/ngattusohw/git-commit-suggestions"
echo "─────────────────────────────────────────────────────────────────"
echo ""
local menu_options="1-6"
if $has_detections; then
menu_options="0-6"
fi
if [[ ${#configured_providers[@]} -gt 1 ]]; then
if $has_detections; then
menu_options="0-6, s1-s4"
else
menu_options="1-6, s1-s4"
fi
fi
read "choice?Select option ($menu_options): "
case $choice in
0)
echo ""
echo "🚀 Auto-configuring ALL detected providers..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
local setup_count=0
local setup_providers=()
# Configure OpenAI if detected
if [[ -n "$detected_openai" ]]; then
echo ""
echo "🤖 Setting up OpenAI..."
echo "🧪 Testing API key..."
if _test_openai_key "$detected_openai"; then
_save_config "openai" "$detected_openai"
echo "✅ OpenAI configured successfully!"
setup_count=$((setup_count + 1))
setup_providers+=("OpenAI")
else
echo "❌ OpenAI API key test failed"
echo "🔍 Testing with verbose output..."
_test_openai_key "$detected_openai" "true" # Show verbose error details
fi
fi
# Configure Anthropic if detected
if [[ -n "$detected_anthropic" ]]; then
echo ""
echo "🧠 Setting up Anthropic..."
echo "🧪 Testing API key..."
if _test_anthropic_key "$detected_anthropic"; then
_save_config "anthropic" "$detected_anthropic"
echo "✅ Anthropic configured successfully!"
setup_count=$((setup_count + 1))
setup_providers+=("Anthropic")
else
echo "❌ Anthropic API key test failed"
echo "🔍 Testing with verbose output..."
_test_anthropic_key "$detected_anthropic" "true" # Show verbose error details
fi
fi
# Configure Grok if detected
if [[ -n "$detected_grok" ]]; then
echo ""
echo "⚡ Setting up Grok..."
echo "🧪 Testing API key..."
if _test_grok_key "$detected_grok"; then
_save_config "grok" "$detected_grok"
echo "✅ Grok configured successfully!"
setup_count=$((setup_count + 1))
setup_providers+=("Grok")
else
echo "❌ Grok API key test failed"
echo "🔍 Testing with verbose output..."
_test_grok_key "$detected_grok" "true" # Show verbose error details
fi
fi
echo ""
if [[ $setup_count -gt 0 ]]; then
echo "🎉 AMAZING! $setup_count provider(s) configured successfully!"
echo "✅ Configured: ${setup_providers[*]}"
echo ""
echo "🚀 You can now:"
echo " • Use any provider for commit suggestions"
echo " • Switch between providers instantly: git-suggest-switch <provider>"
echo " • Run git-suggest-config to change active provider"
echo ""
# Set the last configured provider as active (prefer Anthropic if available)
local preferred_provider=""
for provider in "anthropic" "grok" "openai"; do
if [[ " ${setup_providers[*]} " =~ " ${provider^} " ]]; then
preferred_provider="$provider"
break
fi
done
if [[ -n "$preferred_provider" ]]; then
echo "🎯 Setting $preferred_provider as your active provider (recommended for best performance/cost)"
_switch_provider "$preferred_provider"
fi
_show_success_message "Multi-Provider Setup"
else
echo "❌ No providers could be configured. Please check your API keys."
return 1
fi
return 0
;;
1)
echo ""
echo "🤖 Setting up OpenAI API..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━"
local token=""
if [[ -n "$detected_openai" ]]; then
echo "🔍 Found OpenAI API key in environment: ${detected_openai:0:8}..."
read "use_detected?Use this key? (y/n): "
if [[ "$use_detected" == "y" ]]; then
token="$detected_openai"
echo "✅ Using auto-detected OpenAI key"
fi
fi
if [[ -z "$token" ]]; then
echo ""
echo "📝 Get your API key from: https://platform.openai.com/api-keys"
echo "💡 Tip: Look for 'sk-' followed by a long string"
read "token?Enter OpenAI API token: "
fi
if [[ -n "$token" ]]; then
echo "🧪 Testing API key..."
if _test_openai_key "$token" "true"; then # Always use verbose mode
_save_config "openai" "$token"
echo "✅ OpenAI configured successfully!"
_show_success_message "OpenAI"
else
echo ""
echo "💡 Please check your key and try again."
return 1
fi
else
echo "❌ No API key provided."
return 1
fi
;;
2)
echo ""
echo "🧠 Setting up Anthropic API..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━"
local token=""
if [[ -n "$detected_anthropic" ]]; then
echo "🔍 Found Anthropic API key in environment: ${detected_anthropic:0:8}..."
read "use_detected?Use this key? (y/n): "
if [[ "$use_detected" == "y" ]]; then
token="$detected_anthropic"
echo "✅ Using auto-detected Anthropic key"
fi
fi
if [[ -z "$token" ]]; then
echo ""
echo "📝 Get your API key from: https://console.anthropic.com/"
echo "💡 Tip: Look for 'sk-ant-' followed by a long string"
read "token?Enter Anthropic API token: "
fi
if [[ -n "$token" ]]; then
echo "🧪 Testing API key..."
if _test_anthropic_key "$token" "true"; then # Always use verbose mode
_save_config "anthropic" "$token"
echo "✅ Anthropic configured successfully!"
_show_success_message "Anthropic"
else
echo ""
echo "💡 Please check your key and try again."
return 1
fi
else
echo "❌ No API key provided."
return 1
fi
;;
3)
echo ""
echo "⚡ Setting up Grok API..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━"