-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
226 lines (179 loc) · 5.07 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
package main
import (
"context"
"fmt"
"os"
"path"
"time"
goenv "github.com/Netflix/go-env"
"github.com/google/go-github/v57/github"
gh "github.com/kmesiab/go-github-diff"
"github.com/mkideal/cli"
)
const (
DefaultFilePerms = 0o644
DefaultOpenAIModel = "gpt-3.5-turbo"
)
type argT struct {
URL string `cli:"*url" usage:"The GitHub pull request URL"`
ApiKey string `cli:"key" env:"OPENAI_API_KEY" usage:"Your OpenAI API key. Leave this blank to use environment variable OPENAI_API_KEY"`
CompletionModel string `cli:"model" env:"CADRE_COMPLETION_MODEL" usage:"The OpenAI API model to use for code reviews."`
}
type ReviewedDiff struct {
Diff gh.GitDiff `json:"diff"`
Review string `json:"review"`
Model string `json:"model"`
Error error `json:"error"`
}
func main() {
os.Exit(cli.Run(new(argT), func(ctx *cli.Context) error {
argv := ctx.Argv().(*argT)
printGreeting()
mergedArgs, err := coalesceConfiguration(argv)
if err != nil {
return fmt.Errorf("couldn't figure out the configuration. %s", err)
}
if mergedArgs.ApiKey == "" {
return fmt.Errorf(
"no API key provided, either pass it with the `--key` flag " +
"or set the OPENAI_API_KEY environment variable")
}
fmt.Printf("📡 Getting pull request from GitHub...\n")
parsedDiffFiles, err := processPullRequest(mergedArgs.URL, &GithubDiffClient{})
if err != nil {
return err
}
fmt.Printf("\n⌛ Processing %d diff files. This may take a while...\n\n", len(parsedDiffFiles))
reviews, err := getCodeReviews(
parsedDiffFiles,
argv.CompletionModel,
mergedArgs.ApiKey,
Prompt,
&OpenAICompletionService{},
)
if err != nil {
return err
}
saveReviews(reviews)
fmt.Println("Done! 🏁")
return nil
}))
}
func saveReviews(reviews []ReviewedDiff) {
for _, review := range reviews {
if review.Error != nil {
fmt.Printf("⚠️ couldn't get the review for %s: %s\n",
path.Base(review.Diff.FilePathNew),
review.Error,
)
continue
}
filename := path.Base(review.Diff.FilePathNew) + ".md"
// Ensure the directory exists
dir := path.Dir(filename)
// If it doesn't exist, create it
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, DefaultFilePerms); err != nil {
fmt.Printf("⚠️ couldn't create directory for %s: %s\n", dir, err)
continue
}
}
// Save the review to disk
err := saveReviewToFile(filename, review.Review)
if err != nil {
fmt.Printf("⚠️ couldn't save the review for %s: %s\n",
filename,
err,
)
continue
}
fmt.Printf("💾 Saved review to %s\n", filename)
}
}
func getCodeReviews(diffs []*gh.GitDiff, model, apiKey, prompt string, svc CompletionServiceInterface) ([]ReviewedDiff, error) {
reviewChan := make(chan ReviewedDiff)
var reviews []ReviewedDiff
for _, diff := range diffs {
go func(d *gh.GitDiff) {
fmt.Printf("🤖 Getting code review for %s\n", path.Base(d.FilePathNew))
review, err := svc.GetCompletion(d.DiffContents, model, apiKey, prompt)
rDiff := ReviewedDiff{
Error: err,
Diff: *d,
Review: review,
Model: model,
}
reviewChan <- rDiff
}(diff)
}
for range diffs {
review := <-reviewChan
reviews = append(reviews, review)
}
close(reviewChan)
return reviews, nil
}
func processPullRequest(prURL string, ghClient GithubDiffClientInterface) ([]*gh.GitDiff, error) {
pullRequestUrl, err := ghClient.ParsePullRequestURL(prURL)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
client := github.NewClient(nil)
diffString, err := ghClient.GetPullRequest(ctx, pullRequestUrl, client)
if err != nil {
return nil, err
}
ignoreList := []string{
".github",
".gitignore",
".travis.yml",
"LICENSE",
".md",
".mod",
".sum",
}
parsedDiff := ghClient.ParseGitDiff(diffString, ignoreList)
return parsedDiff, nil
}
func saveReviewToFile(filename, reviewContent string) error {
// Check if the file already exists
if _, err := os.Stat(filename); err == nil {
return fmt.Errorf("file %s already exists, not overwriting", filename)
}
// Write the review content to the file
err := os.WriteFile(filename, []byte(reviewContent), DefaultFilePerms)
if err != nil {
return fmt.Errorf("failed to write review to file: %s", err)
}
return nil
}
func coalesceConfiguration(cliArgs *argT) (*argT, error) {
envArgs := &argT{}
// Unmarshal environment variables into the envArgs struct
_, err := goenv.UnmarshalFromEnviron(envArgs)
if err != nil {
return nil, err
}
// Default to the command line overriding
// the environment variables
if cliArgs.ApiKey == "" {
cliArgs.ApiKey = envArgs.ApiKey
}
// If no model is provided, use the default model
if cliArgs.CompletionModel == "" {
cliArgs.CompletionModel = DefaultOpenAIModel
}
return cliArgs, nil
}
func printGreeting() {
fmt.Println(`
_____ ___ ____________ _____
/ __ \ / _ \| _ \ ___ \ ___|
| / \// /_\ \ | | | |_/ / |__
| | | _ | | | | /| __|
| \__/\| | | | |/ /| |\ \| |___
\____/\_| |_/___/ \_| \_\____/
`)
}