-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
225 lines (177 loc) · 5.46 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
package main
import (
config "HaseFlrn/ollama_commit/cmd"
lib "HaseFlrn/ollama_commit/lib/config"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"strings"
)
func main() {
arg := os.Args
if len(arg) <= 1 {
conf := lib.GetConfig()
llmCommit(conf)
os.Exit(0)
} else if len(arg) > 1 && arg[1] == "config" {
config.Config()
os.Exit(0)
} else {
fmt.Println("Invalid usage. Please run `ollama_commit` without any arguments or `config`.")
os.Exit(1)
}
}
func llmCommit(config lib.Config) {
checkPrerequisites()
result := isGitRepo()
if !result {
fmt.Println("This is not a git repository. Please run this command in a git repository.")
os.Exit(1)
}
diff := getGitDiff()
// Build the prompt
prompt := buildPrompt(diff)
// Build the commit message
fmt.Println("Building commit message...")
commitMessage := askOllama(prompt, config)
fmt.Printf("Commit Message:\n\n%v\n", commitMessage)
if !promptConfirmation() {
fmt.Println("Exiting...")
os.Exit(0)
}
// Commit the changes to the repo
commitChanges(commitMessage)
}
func checkPrerequisites() {
if !commandExists("git") {
fmt.Println("Git is not installed. Please install Git and try again.")
os.Exit(1)
}
if !commandExists("ollama") {
fmt.Println("Ollama is not installed. Please install Ollama and try again.")
os.Exit(1)
}
if !isOllamaServerRunning() {
fmt.Println("Ollama is not running! Please start by `ollama serve`")
os.Exit(1)
}
}
func isOllamaServerRunning() bool {
_, err := http.Get("http://127.0.0.1:11434/")
return err == nil
}
func commandExists(cmd string) bool {
_, err := exec.LookPath(cmd)
return err == nil
}
func isGitRepo() bool {
_, err := exec.Command("git", "rev-parse", "--is-inside-work-tree", "&>/dev/null").Output()
return err != nil
}
func getGitDiff() string {
r, err := exec.Command("git", "diff", "--cached").Output()
if err != nil {
log.Fatal(err)
}
if len(r) == 0 {
fmt.Print("No changes to commit. Make sure you add the changes to the staging area before running this command.\n")
os.Exit(0)
}
return string(r)
}
func promptConfirmation() bool {
fmt.Println("\n--------------------------------")
fmt.Print("Do you want to continue? (y/n): ")
var response string
fmt.Scanln(&response)
response = strings.ToLower(response)
response = strings.TrimSpace(response)
return response == "y" || response == "yes"
}
func buildPrompt(diff string) string {
base := `You are a seasoned developer, writing your commit message.
Your answer must convey the following commit message format exactly:
<type>([scope]): <description>
[optional body]
With <type> being one of the following:
[ 'build', 'chore', 'ci', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'style', 'test' ]
Whith scope being an field that is used to specify the module that the commit is related to.
With <description> being a short and concise description of the changes made.
With [optional body] being a more detailed description of the changes made. If it is used, it must be separated from the description by a empty line.
You must create a concise and descriptive commit message based on the following diff:
%v
Only answer with the commit message as plain text and do not describe your reasoning.
If there are a lot of changes, you are allowed to use bullet points as description body.
- DO NOT LIE.
- DO NOT HALLUCINATE.
- DO NOT ADD ANY NUMBERS OR SPECIAL CHARACTERS.
- DO NOT ADD A FULL STOP AT THE END.
- RESPOND ONLY WITH THE COMMIT MESSAGE.`
prompt := fmt.Sprintf(base, diff)
return prompt
}
type OllamaResponse struct {
Model string `json:"model"`
Created_At string `json:"created_at"`
Response string `json:"response"`
Done bool `json:"done"`
Done_Reason string `json:"done_reason"`
Context []int `json:"context"`
Total_Duration int `json:"total_duration"`
Load_Duration int `json:"load_duration"`
Prompt_Eval_Count int `json:"prompt_eval_count"`
Prompt_Eval_Duration int `json:"prompt_eval_duration"`
Eval_Count int `json:"eval_count"`
Eval_Duration int `json:"eval_duration"`
}
func askOllama(prompt string, config lib.Config) string {
_, err := http.Get("http://localhost:11434/")
if err != nil {
fmt.Println("Ollama is not running. Please start Ollama and try again.")
os.Exit(1)
}
// TODO: Make model configurable
requestData := map[string]interface{}{
"model": config.Model,
"prompt": prompt,
"stream": false,
"options": map[string]float32{
"temperature": config.Temperature,
},
}
jsonData, err := json.Marshal(requestData)
if err != nil {
fmt.Println("Error while marshalling JSON data.")
os.Exit(1)
}
path := fmt.Sprintf("http://localhost:%d/api/generate", config.Ollama_Port)
r, _ := http.NewRequest("POST", path, bytes.NewBuffer(jsonData))
r.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(r)
if err != nil {
fmt.Println("Error while sending request to Ollama.")
os.Exit(1)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var ollamaResponse OllamaResponse
err = json.Unmarshal(body, &ollamaResponse)
if err != nil {
fmt.Printf("Error while unmarshalling JSON data. %v\n", err)
os.Exit(1)
}
return ollamaResponse.Response
}
func commitChanges(commitMessage string) {
// Commit the changes to the repo
_, err := exec.Command("git", "commit", "-m", commitMessage).Output()
if err != nil {
log.Fatal(err)
}
}