Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
executable file
·307 lines (276 loc) · 7.32 KB
/
Copy pathmain.go
File metadata and controls
executable file
·307 lines (276 loc) · 7.32 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
package main
import (
"bufio"
"context"
_ "embed"
"errors"
"fmt"
"io"
"os"
"os/signal"
"strings"
"syscall"
"unicode/utf8"
"gitmeh/internal/aiapi"
"gitmeh/internal/config"
"gitmeh/internal/git"
"gitmeh/internal/version"
"golang.org/x/term"
)
// helpText is filled at compile time from help.txt. The next line is a Go
// compiler directive (not ordinary documentation): it tells the toolchain to
// copy that file into the binary. import _ "embed" is required so the compiler
// enables //go:embed even though we do not reference embed.FS in code.
//
//go:embed help.txt
var helpText string
const commitMsgPrompt = "Commit message: "
func main() {
for _, arg := range os.Args[1:] {
switch arg {
case "-h", "--help":
fmt.Print(helpText)
return
case "-v", "--version":
fmt.Printf("gitmeh %s\n", version.Version)
return
}
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := git.AddAll(); err != nil {
fatalErr(err)
}
cfg := config.Load()
diff, err := git.StagedDiffTruncated(cfg.Chat.MaxDiffBytes)
if err != nil {
fatalErr(err)
}
if strings.TrimSpace(diff) == "" {
fatalMsg("nothing staged to commit")
}
insecureHost := config.HostedHostname()
if config.IsDev() {
insecureHost = "*"
}
httpClient := aiapi.HTTPClientForChatBase(cfg.Chat.BaseURL, insecureHost)
msg, err := aiapi.CommitMessageOpenAIChat(ctx, httpClient, aiapi.OpenAIChatParams{
BaseURL: cfg.Chat.BaseURL,
APIKey: cfg.Chat.APIKey,
Model: cfg.Chat.Model,
SystemPrompt: cfg.Chat.Prompt,
FallbackModels: cfg.Chat.FallbackModels,
}, diff)
if err != nil {
if errors.Is(err, context.Canceled) {
fatalMsg("cancelled")
}
fatalErr(err)
}
if strings.TrimSpace(msg) == "" {
fatalMsg("empty commit message from API")
}
final, proceed, err := reviewCommitMessage(msg, os.Stdin, os.Stdout)
if err != nil {
fatalErr(err)
}
if !proceed {
os.Exit(1)
}
if err := git.CommitAndPush(final); err != nil {
fatalErr(err)
}
fmt.Println("Git commands executed successfully!")
}
// reviewCommitMessage loops until the user accepts (Y), aborts (n), or edits (e).
// After edit, pressing Enter on the edited line submits that message (ok true).
// ok is false when the user aborts without error.
// stdin and stdout are injected for tests (e.g. strings.NewReader, io.Discard).
// If stdout is nil, os.Stdout is used.
//nolint:errcheck // UI output writes — safe to ignore
func reviewCommitMessage(suggested string, stdin io.Reader, stdout io.Writer) (final string, ok bool, err error) {
if stdout == nil {
stdout = os.Stdout
}
current := strings.TrimSpace(suggested)
rd := bufio.NewReader(stdin)
for {
fmt.Fprintln(stdout, "\nSuggested commit message:")
fmt.Fprintf(stdout, "\033[32m%s\033[0m\n", current)
fmt.Fprint(stdout, "\nCommit and push? [Y/n/e]: ")
line, err := rd.ReadString('\n')
if err != nil {
if err == io.EOF {
return "", false, fmt.Errorf("no input (EOF)")
}
return "", false, err
}
ans := strings.ToLower(strings.TrimSpace(line))
switch ans {
case "", "y", "yes":
return current, true, nil
case "n", "no":
fmt.Fprintln(stdout, "Aborted.")
return "", false, nil
case "e", "edit":
fmt.Fprintln(stdout)
edited, err := readCommitMessageInline(current, stdin, rd, stdout)
if err != nil {
return "", false, err
}
edited = strings.TrimSpace(edited)
if edited == "" {
fmt.Fprintln(stdout, "Commit message is empty; keeping previous text.")
continue
}
return edited, true, nil
default:
fmt.Fprintln(stdout, "Please enter y, n, or e (or press Enter for yes).")
}
}
}
// stdinTerminalFD returns the FD to put in raw mode when stdin is an
// [os.File] connected to a terminal; otherwise ok is false.
func stdinTerminalFD(stdin io.Reader) (fd int, ok bool) {
f, isFile := stdin.(*os.File)
if !isFile {
return 0, false
}
fd = int(f.Fd())
if !term.IsTerminal(fd) {
return 0, false
}
return fd, true
}
// readCommitMessageInline shows an editable single-line field prefilled with
// initial; Enter submits the current line. Ctrl+C aborts with an error.
// stdin must be the same reader rd wraps (e.g. bufio.NewReader(stdin)).
// stdout is used for prompts (inject io.Discard in tests). If nil, os.Stdout.
//nolint:errcheck // UI output writes — safe to ignore
func readCommitMessageInline(initial string, stdin io.Reader, rd *bufio.Reader, stdout io.Writer) (string, error) {
if stdout == nil {
stdout = os.Stdout
}
fd, useTTY := stdinTerminalFD(stdin)
if !useTTY {
fmt.Fprintf(stdout, "%s\033[32m%s\033[0m\n", commitMsgPrompt, initial)
fmt.Fprint(stdout, "(not a terminal — press Enter to keep, or type a new message)\n> ")
line, err := rd.ReadString('\n')
if err != nil {
return "", err
}
t := strings.TrimSpace(line)
if t == "" {
return initial, nil
}
return t, nil
}
old, err := term.MakeRaw(fd)
if err != nil {
return "", err
}
defer func() { _ = term.Restore(fd, old) }()
width, _, err := term.GetSize(fd)
if err != nil {
width = 80
}
line := []rune(initial)
pos := len(line)
prevCursorRow := 0
// redraw clears the display area and repaints the prompt + message with
// the cursor positioned at the insertion point between left and right.
redraw := func() {
if prevCursorRow > 0 {
fmt.Fprintf(stdout, "\033[%dA", prevCursorRow)
}
fmt.Fprint(stdout, "\r\033[J")
left := ""
if pos > 0 {
left = string(line[:pos])
}
right := ""
if pos < len(line) {
right = string(line[pos:])
}
fmt.Fprintf(stdout, "%s\033[32m%s%s\033[0m", commitMsgPrompt, left, right)
totalChars := len(commitMsgPrompt) + len(line)
totalLines := (totalChars + width - 1) / width
if totalLines < 1 {
totalLines = 1
}
charsBefore := len(commitMsgPrompt) + pos
cursorRow := charsBefore / width
cursorCol := charsBefore % width
lastRow := totalLines - 1
fmt.Fprint(stdout, "\r")
if lastRow > cursorRow {
fmt.Fprintf(stdout, "\033[%dA", lastRow-cursorRow)
}
if cursorCol > 0 {
fmt.Fprintf(stdout, "\033[%dC", cursorCol)
}
prevCursorRow = cursorRow
}
redraw()
for {
r, size, err := rd.ReadRune()
if err != nil {
if err == io.EOF {
fmt.Fprint(stdout, "\r\n")
return "", io.EOF
}
return "", err
}
if r == utf8.RuneError && size == 1 {
continue
}
switch r {
case '\r', '\n':
// Enter — submit the current line.
fmt.Fprint(stdout, "\r\n")
return string(line), nil
case 3:
// Ctrl+C — abort editing.
fmt.Fprint(stdout, "\r\n")
return "", fmt.Errorf("interrupted")
case 127, '\b':
// Backspace — delete the character before the cursor.
if pos > 0 {
line = append(line[:pos-1], line[pos:]...)
pos--
redraw()
}
case 27:
// ESC sequence starter — decode arrow keys.
br, _, err := rd.ReadRune()
if err != nil || br != '[' {
continue
}
dir, _, err := rd.ReadRune()
if err != nil {
continue
}
switch dir {
case 'D':
// Left arrow — move cursor one position left.
if pos > 0 {
pos--
redraw()
}
case 'C':
// Right arrow — move cursor one position right.
if pos < len(line) {
pos++
redraw()
}
}
default:
// Printable characters (ASCII 32–126) — insert at cursor.
if r >= 32 {
line = append(line[:pos], append([]rune{r}, line[pos:]...)...)
pos++
redraw()
}
}
}
}