-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
563 lines (486 loc) · 14.8 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
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
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"strings"
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const ApiModel = "gpt-4o" // 128k context window
type GPTRequest struct {
Messages []GPTMessage `json:"messages"`
MaxTokens int `json:"max_tokens"`
Model string `json:"model"`
}
type GPTMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type GPTResponse struct {
Choices []GPTChoice `json:"choices"`
Error interface{} `json:"error"`
}
type GPTChoice struct {
Message GPTMessage `json:"message"`
}
const CommitMessagePrompt = `
Generate a git commit message based on the output of a diff command.
The commit message should be a detailed but brief overview of the changes.
Return only the text for the commit message.
Here is the diff output:
%s
`
const AdditionalCommitMessagePrompt = `
The following extra context has been added by the user. Take it into account when generating the commit message.
%s
`
const BranchNamePrompt = `
Generate a branch name from a commit message. The branch name should be in a valid format, e.g. feat/branch-name-of-feature.
It should be prefixed with "feat/", "fix/", "perf/", "docs/", "style/", "refactor/", "test/", "chore/" or "bug/".
Here is the commit message:
%s
Only respond with the branch name, nothing else.
`
func main() {
// Initialize Cobra
var rootCmd = &cobra.Command{Use: "gitpilotai"}
rootCmd.AddCommand(configCmd)
rootCmd.AddCommand(generateCmd)
rootCmd.AddCommand(branchCmd)
rootCmd.AddCommand(prCmd)
cobra.OnInitialize(initConfig)
if err := rootCmd.Execute(); err != nil {
color.Red(err.Error())
os.Exit(1)
}
}
func initConfig() {
viper.SetConfigType("env")
viper.SetConfigName(".gitpilotai")
viper.AddConfigPath("$HOME")
// Attempt to read the configuration file
configErr := viper.ReadInConfig()
homeDir, err := os.UserHomeDir()
if err != nil {
color.Red("Error finding home directory: %v", err)
os.Exit(1)
}
envFilePath := homeDir + "/.gitpilotai.env"
viper.AutomaticEnv() // Enable reading of environment variables
// Check if the OPENAI_API_KEY environment variable is set
envVar := viper.GetString("OPENAI_API_KEY")
if configErr != nil { // Config file not found
if envVar == "" {
// Environment variable not set, create or open the config file and write the variable
envFile, err := os.OpenFile(envFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
color.Red("Error opening or creating .gitpilotai.env file: %v", err)
os.Exit(1)
}
defer envFile.Close()
if _, err := envFile.WriteString("OPENAI_API_KEY=\n"); err != nil {
color.Red("Error writing to .gitpilotai.env file: %v", err)
os.Exit(1)
}
color.Red("OPENAI_API_KEY environment variable not set and was added to .gitpilotai.env. Please set it.")
os.Exit(1)
} else {
// Environment variable is set but config file does not exist, write it to the file
envFile, err := os.OpenFile(envFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
color.Red("Error opening or creating .gitpilotai.env file: %v", err)
os.Exit(1)
}
defer envFile.Close()
// Remove all contents from the file
if err := envFile.Truncate(0); err != nil {
color.Red("Error truncating .gitpilotai.env file: %v", err)
return
}
if _, err := envFile.Seek(0, 0); err != nil {
color.Red("Error seeking in .gitpilotai.env file: %v", err)
return
}
if _, err := envFile.WriteString("OPENAI_API_KEY=\n"); err != nil {
color.Red("Error writing to .gitpilotai.env file: %v", err)
return
}
viper.Set("OPENAI_API_KEY", envVar)
}
} else {
// Config file exists, load the variable from the file
if envVar == "" {
// If the environment variable is still not set, load it from the file
envFile, err := os.Open(envFilePath)
if err != nil {
color.Red("Error opening .gitpilotai.env file: %v", err)
os.Exit(1)
}
defer envFile.Close()
scanner := bufio.NewScanner(envFile)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "OPENAI_API_KEY=") {
envVar = strings.TrimPrefix(line, "OPENAI_API_KEY=")
viper.Set("OPENAI_API_KEY", envVar)
break
}
}
if err := scanner.Err(); err != nil {
color.Red("Error reading .gitpilotai.env file: %v", err)
os.Exit(1)
}
} else {
envFile, err := os.OpenFile(envFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
color.Red("Error opening or creating .gitpilotai.env file: %v", err)
os.Exit(1)
}
defer envFile.Close()
// Remove all contents from the file
if err := envFile.Truncate(0); err != nil {
color.Red("Error truncating .gitpilotai.env file: %v", err)
return
}
if _, err := envFile.Seek(0, 0); err != nil {
color.Red("Error seeking in .gitpilotai.env file: %v", err)
return
}
_, err = envFile.WriteString("OPENAI_API_KEY=" + envVar + "\n")
if err != nil {
color.Red("Error writing to .gitpilotai.env file: %v", err)
os.Exit(1)
}
viper.Set("OPENAI_API_KEY", envVar)
}
}
}
var configCmd = &cobra.Command{
Use: "config",
Short: "Configure the API key",
Run: func(cmd *cobra.Command, args []string) {
color.Green("Config initialized.")
},
}
var generateCmd = &cobra.Command{
Use: "generate",
Short: "Generate commit messages based on git diff",
Run: func(cmd *cobra.Command, args []string) {
gitMessage := ""
if len(args) > 0 {
gitMessage = strings.Join(args, " ")
color.Blue("Received git message: %s", gitMessage)
}
if !hasGitChanges() {
color.Yellow("No changes detected in the Git repository.")
return
}
if err := stageFiles(); err != nil {
color.Red("Error staging files: %v", err)
os.Exit(1)
}
diff := getGitDiff()
if diff == "" {
color.Yellow("No diff found.")
return
}
commitMessage, err := GenerateDiff(diff, gitMessage)
if err != nil {
color.Red("Error generating commit message: %v", err)
os.Exit(1)
}
color.Cyan("%s\n", commitMessage)
if err := commitChanges(commitMessage); err != nil {
color.Red("Error committing changes: %v", err)
os.Exit(1)
}
currentBranch, err := detectCurrentBranch()
if err != nil {
color.Red("Error detecting current branch: %v", err)
os.Exit(1)
}
if err := pushChanges(currentBranch); err != nil {
color.Red("Error pushing changes: %v", err)
os.Exit(1)
}
},
}
var branchCmd = &cobra.Command{
Use: "branch",
Short: "Generate a new branch and commit messages based on git diff",
Run: func(cmd *cobra.Command, args []string) {
currentBranch, err := detectCurrentBranch()
if err != nil {
color.Red("Error detecting current branch: %v", err)
os.Exit(1)
}
if currentBranch != "main" && currentBranch != "master" {
color.Red("You must be on the main branch to create a new branch.")
os.Exit(1)
}
gitMessage := ""
if len(args) > 0 {
gitMessage = strings.Join(args, " ")
color.Blue("Received git message: %s", gitMessage)
}
// Add files
if !hasGitChanges() {
color.Yellow("No changes detected in the Git repository.")
return
}
if err := stageFiles(); err != nil {
color.Red("Error staging files: %v", err)
os.Exit(1)
}
diff := getGitDiff()
if diff == "" {
color.Yellow("No diff found.")
return
}
// Generate commit message
commitMessage, err := GenerateDiff(diff, gitMessage)
if err != nil {
color.Red("Error generating commit message: %v", err)
os.Exit(1)
}
// Create branch
branchName := generateBranchNameFromCommitMessage(commitMessage)
// Switch to new branch
err = checkoutNewBranchLocally(branchName)
if err != nil {
color.Red("Error checking out new branch: %v", err)
os.Exit(1)
}
// Commit changes
if err := commitChanges(commitMessage); err != nil {
color.Red("Error committing changes: %v", err)
os.Exit(1)
}
if err := pushChanges(branchName); err != nil {
color.Red("Error pushing changes: %v", err)
os.Exit(1)
}
},
}
var prCmd = &cobra.Command{
Use: "pr",
Short: "Open a pull request",
Run: func(cmd *cobra.Command, args []string) {
if err := openPullRequest(); err != nil {
color.Red("Error opening pull request: %v", err)
os.Exit(1)
}
},
}
func hasGitChanges() bool {
out, err := exec.Command("git", "status", "--porcelain").Output()
if err != nil {
color.Red("Error checking git status: %v", err)
os.Exit(1)
}
return len(out) > 0
}
func getGitDiff() string {
stagedDiffCmd := exec.Command("git", "diff", "--staged")
stagedDiff, err := stagedDiffCmd.Output()
if err != nil {
color.Red("Error getting staged git diff: %v", err)
os.Exit(1)
}
unstagedDiffCmd := exec.Command("git", "diff")
unstagedDiff, err := unstagedDiffCmd.Output()
if err != nil {
color.Red("Error getting unstaged git diff: %v", err)
os.Exit(1)
}
totalDiff := strings.TrimSpace(string(stagedDiff)) + "\n" + strings.TrimSpace(string(unstagedDiff))
return totalDiff
}
func GenerateDiff(diff string, gitMessage string) (string, error) {
prompt := fmt.Sprintf(CommitMessagePrompt, diff)
if gitMessage != "" {
prompt += fmt.Sprintf(AdditionalCommitMessagePrompt, gitMessage)
}
commitMessage, err := makeOpenAPIRequestFromPrompt(prompt)
if err != nil {
color.Red("Error generating commit message: %v", err)
os.Exit(1)
}
// Strip commitMessage of any quotes
commitMessage = strings.ReplaceAll(commitMessage, "\"", "")
return commitMessage, nil
}
func makeOpenAIRequest(body []byte) (string, error) {
req, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewBuffer(body))
if err != nil {
color.Red("Error creating request: %v", err)
os.Exit(1)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+viper.GetString("OPENAI_API_KEY"))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
color.Red("Error sending request to OpenAI: %v", err)
os.Exit(1)
}
defer resp.Body.Close()
var apiResp GPTResponse
if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil {
color.Red("Error decoding API response: %v", err)
os.Exit(1)
}
if apiResp.Error != nil {
color.Red("Error from API: %s", apiResp.Error)
os.Exit(1)
}
if len(apiResp.Choices) > 0 {
return apiResp.Choices[0].Message.Content, nil
}
color.Red("No response from API")
os.Exit(1)
return "", nil
}
func commitChanges(commitMessage string) error {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Are you sure you want to commit the changes? (y/n): ")
fmt.Printf("%s\n", commitMessage)
confirmation, _ := reader.ReadString('\n')
confirmation = strings.TrimSpace(confirmation)
if confirmation != "y" && confirmation != "Y" {
color.Yellow("Commit canceled.")
return nil
}
cmd := exec.Command("git", "commit", "-m", commitMessage)
if out, err := cmd.CombinedOutput(); err != nil {
color.Red("git commit failed: %s, %v", out, err)
os.Exit(1)
}
color.Green("Changes committed successfully.")
return nil
}
func pushChanges(branchName string) error {
// Check if the branch exists locally
cmd := exec.Command("git", "rev-parse", "--verify", branchName)
if err := cmd.Run(); err != nil {
color.Red("branch %s does not exist locally", branchName)
os.Exit(1)
}
// Check if the branch exists remotely
cmd = exec.Command("git", "ls-remote", "--exit-code", "--heads", "origin", branchName)
if err := cmd.Run(); err == nil {
// Branch exists remotely, perform a normal push
cmd = exec.Command("git", "push", "origin", branchName)
} else {
// Branch does not exist remotely, set the upstream and push
cmd = exec.Command("git", "push", "--set-upstream", "origin", branchName)
}
if out, err := cmd.CombinedOutput(); err != nil {
color.Red("git push failed: %s, %v", out, err)
os.Exit(1)
}
color.Green("Changes pushed successfully to branch %s.\n", branchName)
return nil
}
func stageFiles() error {
// List the files to be staged
cmd := exec.Command("git", "status", "--porcelain")
out, err := cmd.Output()
if err != nil {
color.Red("Error listing files: %v", err)
os.Exit(1)
}
fmt.Println("Files to be staged:")
fmt.Println(string(out))
// Ask for confirmation
reader := bufio.NewReader(os.Stdin)
fmt.Print("Are you sure you want to stage these changes? (y/n): ")
confirmation, _ := reader.ReadString('\n')
confirmation = strings.TrimSpace(confirmation)
if confirmation != "y" && confirmation != "Y" {
color.Yellow("Staging canceled.")
return nil
}
// Stage the files
cmd = exec.Command("git", "add", ".")
if out, err := cmd.CombinedOutput(); err != nil {
color.Red("Error staging files: %s, %v", out, err)
os.Exit(1)
}
color.Green("Files staged successfully.")
return nil
}
func detectCurrentBranch() (string, error) {
cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
out, err := cmd.Output()
if err != nil {
color.Red("error detecting current branch: %v", err)
os.Exit(1)
}
return strings.TrimSpace(string(out)), nil
}
func generateBranchNameFromCommitMessage(commitMessage string) string {
prompt := fmt.Sprintf(BranchNamePrompt, commitMessage)
branch, err := makeOpenAPIRequestFromPrompt(prompt)
if err != nil {
color.Red("Error generating branch name: %v", err)
os.Exit(1)
}
return branch
}
func makeOpenAPIRequestFromPrompt(prompt string) (string, error) {
requestBody, err := json.Marshal(GPTRequest{
Model: ApiModel,
Messages: []GPTMessage{{Role: "user", Content: prompt}},
MaxTokens: 1000,
})
if err != nil {
color.Red("error marshaling request body: %v", err)
os.Exit(1)
}
response, err := makeOpenAIRequest(requestBody)
if err != nil {
color.Red("Error generating branch name: %v", err)
os.Exit(1)
}
return response, nil
}
func checkoutNewBranchLocally(branchName string) error {
cmd := exec.Command("git", "checkout", "-b", branchName)
if out, err := cmd.CombinedOutput(); err != nil {
color.Red("error checking out new branch: %s, %v", out, err)
os.Exit(1)
}
color.Green("Switched to new branch %s\n", branchName)
return nil
}
func openPullRequest() error {
repoURL, err := exec.Command("git", "config", "--get", "remote.origin.url").Output()
if err != nil {
color.Red("error retrieving repository URL: %v", err)
os.Exit(1)
}
repoURLStr := strings.TrimSpace(string(repoURL))
repoURLStr = strings.TrimSuffix(repoURLStr, ".git")
repoURLStr = strings.Replace(repoURLStr, "git@", "https://", 1)
currentBranchCmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
currentBranchOutput, err := currentBranchCmd.Output()
if err != nil {
color.Red("error retrieving current branch name: %v", err)
os.Exit(1)
}
branchName := strings.TrimSpace(string(currentBranchOutput))
prURL := fmt.Sprintf("%s/compare/%s", repoURLStr, branchName)
cmd := exec.Command("open", prURL)
if out, err := cmd.CombinedOutput(); err != nil {
color.Red("error opening pull request: %s, %v", out, err)
os.Exit(1)
}
return nil
}