-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutil.go
More file actions
184 lines (165 loc) · 5.35 KB
/
util.go
File metadata and controls
184 lines (165 loc) · 5.35 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
package main
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/cli/go-gh/v2/pkg/api"
"github.com/joho/godotenv"
openai "github.com/sashabaranov/go-openai"
"math"
"os"
"os/exec"
"strconv"
"strings"
)
const MaxDiffLength = 30000 // set to 30k since large model has maximum context length is 32768 tokens.
func getGitDiff() (string, error) {
cmd := exec.Command("git", "diff")
output, err := cmd.Output()
diff := strings.TrimSpace(string(output))
if diff == "" {
cmd = exec.Command("git", "diff", "--staged")
output, err = cmd.Output()
if err != nil {
return "", err
}
diff = strings.TrimSpace(string(output))
}
runes := []rune(diff)
size := len(runes)
if size > MaxDiffLength {
runes = runes[:MaxDiffLength]
return string(runes), fmt.Errorf("the total length was %d and only first 30k were used", size)
}
return string(output), nil
}
func calculateTimeSaved(numCommits int, wordCount int) float64 {
// Assuming an average typing speed of 40 words per minute
wordsPerMinute := 40.0
hoursSaved := float64(wordCount) / wordsPerMinute / 60
return math.Round(hoursSaved*10) / 10
}
func getCommitStats() (int, int, error) {
cmd := exec.Command("git", "log", "--oneline")
stdout, err := cmd.StdoutPipe()
if err != nil {
return 0, 0, err
}
if err := cmd.Start(); err != nil {
return 0, 0, err
}
defer cmd.Wait()
cmd = exec.Command("wc", "-lw")
cmd.Stdin = stdout
output, err := cmd.Output()
if err != nil {
return 0, 0, err
}
fields := strings.Fields(string(output))
numLines, err := strconv.Atoi(fields[0])
if err != nil {
return 0, 0, err
}
numWords, err := strconv.Atoi(fields[1])
if err != nil {
return numLines, 0, err
}
return numLines, numWords, nil
}
func getDiffPrompt(diff string) []azopenai.ChatMessage {
prompt := os.Getenv("PROMPT_OVERRIDE")
if prompt == "" {
prompt = `You will examine and explain the given code changes and write a commit message in Conventional Commits format.
The first line of the commit message should be a 20 word Title summary include a type, optional scope, subject in text, seperated by a newline and the following body.
The types should be one of:
- fix: for a bug fix
- feat: for a new feature
- perf: for a performance improvement
- revert: to revert a previous commit
The body will explain the code change. Body will be formatted in well structured beautifully rendered and use relevant emojis
if no code changes are detected, you will reply with no code change detected message.`
}
messages := []azopenai.ChatMessage{
{Role: to.Ptr(azopenai.ChatRoleSystem), Content: to.Ptr(prompt)},
{Role: to.Ptr(azopenai.ChatRoleUser), Content: to.Ptr(diff)},
{Role: to.Ptr(azopenai.ChatRoleSystem), Content: to.Ptr("Commit message as follows:")},
}
return messages
}
func getPrompt(message string) []azopenai.ChatMessage {
messages := []azopenai.ChatMessage{
{Role: to.Ptr(azopenai.ChatRoleSystem), Content: to.Ptr(message)},
}
return messages
}
func getChatCompletionResponse(messages []azopenai.ChatMessage) (string, error) {
err := godotenv.Load()
if err != nil {
fmt.Errorf(".env file not found: %v", err)
}
keyCredential, err := azopenai.NewKeyCredential(os.Getenv("OPENAI_API_KEY"))
if err != nil {
fmt.Errorf("export OPENAI_API_KEY=<api_key> #execute this in your terminal and try again")
return "", fmt.Errorf("error creating Azure OpenAI client: %v", err)
}
url := os.Getenv("OPENAI_URL")
model := os.Getenv("OPENAI_MODEL")
var client *azopenai.Client
if strings.Contains(url, "azure") {
clientOptions := &azopenai.ClientOptions{
ClientOptions: policy.ClientOptions{
APIVersion: "2024-12-01-preview",
},
}
client, err = azopenai.NewClientWithKeyCredential(url, keyCredential, clientOptions)
if err != nil {
return "", fmt.Errorf("error creating Azure OpenAI client: %v", err)
}
} else {
client, err = azopenai.NewClientForOpenAI(url, keyCredential, nil)
if err != nil {
return "", fmt.Errorf("error creating Azure OpenAI client: %v", err)
}
}
if model == "" {
model = openai.GPT4
}
resp, err := client.GetChatCompletions(
context.Background(),
azopenai.ChatCompletionsOptions{
Messages: messages,
Deployment: model,
},
nil,
)
if err != nil {
return "", fmt.Errorf("Completion error: %v", err)
}
//for _, choice := range resp.Choices {
// fmt.Fprintf(os.Stderr, "Content[%d]: %s\n", *choice.Index, *choice.Message.Content)
//}
return *resp.Choices[0].Message.Content, nil
}
func getUserName() {
client, err := api.DefaultRESTClient()
if err != nil {
fmt.Println(err)
return
}
response := struct{ Login string }{}
err = client.Get("user", &response)
if err != nil {
fmt.Println(err)
return
}
}
var patterns = []string{"```bash", "```plaintext","```diff", "```", "```python", "```javascript", "```go", "```java", "```csharp", "```ruby", "```php", "```html", "```css", "```json", "```xml", "```yaml", "```md", "```markdown", "```sql", "```shell", "```powershell", "```dockerfile", "```makefile", "```ini", "```apacheconf", "```nginx", "```git", "```vim", "```vimscrip"}
func formatResponse(response string) string {
for _, pattern := range patterns {
response = strings.TrimPrefix(response, pattern)
response = strings.TrimSuffix(response, pattern)
}
return response
}