-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
309 lines (256 loc) · 7.24 KB
/
main.go
File metadata and controls
309 lines (256 loc) · 7.24 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
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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strings"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textarea"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
type OllamaResponse struct {
Model string `json:"model"`
CreatedAt string `json:"created_at"`
Message struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"message"`
Done bool `json:"done"`
}
type OllamaRequest struct {
Model string `json:"model"`
Messages []OllamaMessage `json:"messages"`
Stream bool `json:"stream"`
}
type OllamaMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type Text struct {
Text string
}
type Error struct {
Error string `json:"error"`
}
type model struct {
textarea textarea.Model
spinner spinner.Model
quitting bool
err error
commit string
spinning bool
waiting bool
initialized bool
editing bool
}
type errMsg struct {
err error
}
type commitMsg struct {
commit string
}
type commitDoneMsg struct {
err error
}
func (m model) Init() tea.Cmd {
return tea.Batch(
m.spinner.Tick, generateCommit(), textarea.Blink,
)
}
func initialModel() model {
ta := textarea.New()
ta.Placeholder = "Write your commit message..."
ta.FocusedStyle.CursorLine = lipgloss.NewStyle()
s := spinner.New()
s.Spinner = spinner.Dot
s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("260"))
return model{
spinner: s,
spinning: true,
textarea: ta,
}
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
m.textarea, cmd = m.textarea.Update(msg)
m.spinner, cmd = m.spinner.Update(msg)
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.textarea.SetWidth(msg.Width)
m.textarea.SetHeight(strings.Count(m.commit, "\n") + 3)
m.initialized = true
return m, nil
case tea.KeyMsg:
if msg.Type == tea.KeyCtrlS && m.commit != "" {
m.editing = false
m.commit = m.textarea.Value()
return m, commitCode(m.commit)
}
switch msg.String() {
case "ctrl+c":
m.quitting = true
return m, tea.Quit
case "e":
if m.waiting {
m.textarea.SetHeight(strings.Count(m.commit, "\n") + 3)
m.editing = true
m.waiting = false
m.textarea.Focus()
m.textarea.SetValue(m.commit)
return m, cmd
}
return m, nil
case "enter":
if m.commit != "" && m.waiting {
m.editing = false
return m, commitCode(m.commit)
}
default:
return m, nil
}
case errMsg:
m.err = msg.err
m.spinning = false
m.quitting = true
return m, nil
case commitMsg:
var cmd tea.Cmd
m.spinning = false
m.commit = msg.commit
m.waiting = true
return m, cmd
case commitDoneMsg:
return m, tea.Quit
}
return m, cmd
}
func (m model) View() string {
if m.err != nil {
return fmt.Sprintf("\n %s", m.err.Error())
}
if m.spinning {
return fmt.Sprintf("\n %s Generating Commit...\n", m.spinner.View())
}
if m.commit != "" && m.waiting {
return fmt.Sprintf("%s\n\n Press Enter to Commit or e to Edit or Ctrl+C to Cancel", m.commit)
}
if m.commit != "" && !m.waiting && m.editing {
return fmt.Sprintf("%s\n Press Ctrl+S to Commit or Ctrl+C to Cancel", m.textarea.View())
}
return ""
}
func main() {
p := tea.NewProgram(initialModel())
if _, err := p.Run(); err != nil {
fmt.Printf(err.Error())
os.Exit(1)
}
}
func isGitRepo() bool {
cmd := exec.Command("git", "rev-parse", "--is-inside-work-tree")
err := cmd.Run()
return err == nil
}
func getOllamaURL() string {
url := os.Getenv("OLLAMA_URL")
if url == "" {
return "http://localhost:11434"
}
return url
}
func generateCommit() tea.Cmd {
return func() tea.Msg {
if !isGitRepo() {
return errMsg{err: errors.New("Not inside a Git repository. Run `git init` first.")}
}
client := &http.Client{}
c := exec.Command("git", "diff", "--staged")
diffOutput, err := c.Output()
if err != nil {
return errMsg{err: err}
}
if len(diffOutput) <= 0 {
return errMsg{err: errors.New("No staged changes found. Please stage changes using `git add .` or `git add <file>`")}
}
prompt := fmt.Sprintf(
"You are an AI commit assistant. Based on the following Git diff, generate a high-quality, conventional commit message with the following structure:\n\n1. A single-line header:\n type: <short summary>\n - Use a valid conventional commit type (e.g., feat, fix, refactor, docs, test, chore, style, ci)\n - Write the summary in the imperative mood (e.g., 'add support for X')\n\n2. A bullet point list describing the main technical changes:\n - Mention key files, components, classes, or functions changed or added\n - Use inline code formatting for file names and class/function names (e.g., `someFile.js`, `SomeClass`)\n - Explain each item concisely and clearly\n\nExample output:\n\n<type>: <short, clear summary of the change>\n- Added SomeUtility to handle core logic for X\n- Updated SomeComponent to support new behavior Y\n- Refactored someFile.js for improved performance\n\nOnly return the non formatted message — no extra explanation or commentary. If you are not confident about a message or what something does **strictly** do not add it to the commit message\n\nGit diff:\n\n%s",
string(diffOutput))
reqBody := OllamaRequest{
Model: "deepseek-r1:1.5b",
Messages: []OllamaMessage{
{
Role: "user",
Content: prompt,
},
},
Stream: false,
}
bodyBytes, err := json.Marshal(reqBody)
if err != nil {
return errMsg{err: errors.New("Failed to encode request body")}
}
ollamaURL := getOllamaURL()
req, err := http.NewRequest("POST", ollamaURL+"/api/chat", bytes.NewReader(bodyBytes))
if err != nil {
return errMsg{err: err}
}
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
return errMsg{err: errors.New(fmt.Sprintf("Failed to connect to Ollama at %s. Make sure Ollama is running.", ollamaURL))}
}
body, err := io.ReadAll(res.Body)
if err != nil {
return errMsg{err: err}
}
defer res.Body.Close()
if res.StatusCode != 200 {
var errorResp Error
err = json.Unmarshal(body, &errorResp)
if err != nil {
return errMsg{err: errors.New(fmt.Sprintf("Ollama error (status %d): %s", res.StatusCode, string(body)))}
}
return errMsg{err: errors.New(fmt.Sprintf("Ollama error: %s", errorResp.Error))}
}
var ollamaResponse OllamaResponse
err = json.Unmarshal(body, &ollamaResponse)
if err != nil {
return errMsg{err: err}
}
if ollamaResponse.Message.Content == "" {
return errMsg{err: errors.New("No commit generated")}
}
commit := strings.ReplaceAll(ollamaResponse.Message.Content, "```", "")
commit = strings.TrimSpace(commit)
return commitMsg{
commit: commit,
}
}
}
func commitCode(commit string) tea.Cmd {
return func() tea.Msg {
tmpFile, err := os.CreateTemp("", "commit-msg-*.txt")
if err != nil {
return commitDoneMsg{err}
}
defer os.Remove(tmpFile.Name())
_, err = tmpFile.WriteString(commit)
if err != nil {
return commitDoneMsg{err}
}
tmpFile.Close()
c := exec.Command("git", "commit", "-F", tmpFile.Name())
err = c.Run()
return commitDoneMsg{err}
}
}