-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
253 lines (220 loc) · 7.53 KB
/
main.go
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
package main
import (
"fmt"
"log"
"os"
"os/exec"
"strings"
"github.com/Codexiaoyi/ai-git/pkg/ai"
"github.com/Codexiaoyi/ai-git/pkg/git"
"github.com/spf13/cobra"
)
var (
config *ai.Config
)
func main() {
cfg, err := ai.LoadConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err)
os.Exit(1)
}
config = cfg
var rootCmd = &cobra.Command{
Use: "ai-git [command]",
Short: "AI-assisted git commands",
Long: "AI-git is a git wrapper with AI capabilities for certain commands",
DisableFlagParsing: true,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Help()
return
}
if err == nil || strings.Contains(err.Error(), "flag needs an argument") {
// Handle specific commands
switch args[0] {
case "commit":
var message string
var all bool
cmd.Flags().StringVarP(&message, "message", "m", "", "Auto generate commit message")
cmd.Flags().BoolVarP(&all, "all", "a", false, "Auto add all to stage")
err := cmd.Flags().Parse(args)
if err != nil && strings.Contains(err.Error(), "flag needs an argument") && message == "" {
handleCommit(*config, all)
return
}
case "checkout":
var newBranch string
cmd.Flags().StringVarP(&newBranch, "newBranch", "b", "", "Auto generate branch name")
err := cmd.Flags().Parse(args)
if err != nil && strings.Contains(err.Error(), "flag needs an argument") && newBranch == "" {
handleCheckout(*config)
return
}
}
}
// Fallback to standard git
gitCmd := exec.Command("git", args...)
gitCmd.Stdin = os.Stdin
gitCmd.Stdout = os.Stdout
gitCmd.Stderr = os.Stderr
if err := gitCmd.Run(); err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
os.Exit(exitError.ExitCode())
}
fmt.Fprintf(os.Stderr, "Error executing git command: %v\n", err)
os.Exit(1)
}
},
}
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func handleCommit(config ai.Config, addAll bool) {
// Get detailed git changes information
changes, err := git.GetChanges()
if err != nil {
log.Fatalf("Error getting git changes: %v", err)
}
// No changes to commit
if len(changes.Modified) == 0 && len(changes.Added) == 0 && len(changes.Deleted) == 0 && len(changes.Unknown) == 0 {
fmt.Println("No changes to commit")
return
}
// Format changes for the prompt
formattedChanges := git.FormatChangesForPrompt(changes)
// Create prompt
prompt := fmt.Sprintf("Generate a concise git commit message based on these changes:\n\n%s, just give me the shortly commit message, you can add emojis.", formattedChanges)
// Generate commit message using AI
message, err := ai.GenerateCommitMessage(prompt, config)
if err != nil {
log.Fatalf("Error generating commit message: %v", err)
}
// Write the AI-generated message to a temporary file for editing
tempFile, err := os.CreateTemp("", "ai-git-commit-msg-*.txt")
if err != nil {
log.Fatalf("Error creating temporary file: %v", err)
}
defer os.Remove(tempFile.Name()) // Clean up file when done
// Write AI-generated message to the file
fmt.Fprintf(tempFile, "%s\n\n# AI-generated commit message. Save and close the editor to confirm the commit.\n#Or clear the file to cancel the commit.\n# Lines starting with # will be ignored.", message)
tempFile.Close()
// Open the temporary file in the user's default editor
editor := os.Getenv("AI_GIT_EDITOR")
if editor == "" {
editor = os.Getenv("EDITOR")
if editor == "" {
editor = "vim" // Default to vim if no editor is set
}
}
// Run the editor
editCmd := exec.Command(editor, tempFile.Name())
editCmd.Stdin = os.Stdin
editCmd.Stdout = os.Stdout
editCmd.Stderr = os.Stderr
if err := editCmd.Run(); err != nil {
log.Fatalf("Error opening editor: %v", err)
}
// Read the edited message
editedMessageBytes, err := os.ReadFile(tempFile.Name())
if err != nil {
log.Fatalf("Error reading edited message: %v", err)
}
// Process the edited message - remove comment lines
lines := strings.Split(string(editedMessageBytes), "\n")
var finalLines []string
for _, line := range lines {
if !strings.HasPrefix(strings.TrimSpace(line), "#") {
finalLines = append(finalLines, line)
}
}
message = strings.TrimSpace(strings.Join(finalLines, "\n"))
// If the message is empty, cancel the commit
if message == "" {
fmt.Println("Commit message is empty. Commit cancelled.")
return
}
arg := "-m"
if addAll {
arg = "-am"
}
// Execute git commit with the edited message
commitCmd := exec.Command("git", "commit", arg, message)
commitCmd.Stdout = os.Stdout
commitCmd.Stderr = os.Stderr
if err := commitCmd.Run(); err != nil {
log.Fatalf("Error executing git commit: %v", err)
}
}
func handleCheckout(config ai.Config) {
// Get detailed git changes information
changes, err := git.GetChanges()
if err != nil {
log.Fatalf("Error getting git changes: %v", err)
}
// Format changes for the prompt
formattedChanges := git.FormatChangesForPrompt(changes)
// Create prompt
prompt := fmt.Sprintf("Generate a concise git branch name based on these changes:\n\n%s\n\nPlease generate a branch name that follows git branch naming conventions (lowercase, hyphen-separated, descriptive). Just give me the branch name, no explanation needed.", formattedChanges)
// Generate branch name using AI
branchName, err := ai.GenerateBranchName(prompt, config)
if err != nil {
log.Fatalf("Error generating branch name: %v", err)
}
// Clean up the branch name
branchName = strings.TrimSpace(branchName)
branchName = strings.ToLower(branchName)
branchName = strings.ReplaceAll(branchName, " ", "-")
// Write the AI-generated branch name to a temporary file for editing
tempFile, err := os.CreateTemp("", "ai-git-branch-name-*.txt")
if err != nil {
log.Fatalf("Error creating temporary file: %v", err)
}
defer os.Remove(tempFile.Name()) // Clean up file when done
// Write AI-generated branch name to the file
fmt.Fprintf(tempFile, "%s\n\n# AI-generated branch name. Save and close the editor to confirm.\n# Or clear the file to cancel.\n# Lines starting with # will be ignored.", branchName)
tempFile.Close()
// Open the temporary file in the user's default editor
editor := os.Getenv("AI_GIT_EDITOR")
if editor == "" {
editor = os.Getenv("EDITOR")
if editor == "" {
editor = "vim" // Default to vim if no editor is set
}
}
// Run the editor
editCmd := exec.Command(editor, tempFile.Name())
editCmd.Stdin = os.Stdin
editCmd.Stdout = os.Stdout
editCmd.Stderr = os.Stderr
if err := editCmd.Run(); err != nil {
log.Fatalf("Error opening editor: %v", err)
}
// Read the edited branch name
editedNameBytes, err := os.ReadFile(tempFile.Name())
if err != nil {
log.Fatalf("Error reading edited branch name: %v", err)
}
// Process the edited branch name - remove comment lines
lines := strings.Split(string(editedNameBytes), "\n")
var finalLines []string
for _, line := range lines {
if !strings.HasPrefix(strings.TrimSpace(line), "#") {
finalLines = append(finalLines, line)
}
}
branchName = strings.TrimSpace(strings.Join(finalLines, "\n"))
// If the branch name is empty, cancel the operation
if branchName == "" {
fmt.Println("Branch name is empty. Operation cancelled.")
return
}
// Execute git checkout -b with the branch name
checkoutCmd := exec.Command("git", "checkout", "-b", branchName)
checkoutCmd.Stdout = os.Stdout
checkoutCmd.Stderr = os.Stderr
if err := checkoutCmd.Run(); err != nil {
log.Fatalf("Error executing git checkout -b: %v", err)
}
}