-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
359 lines (314 loc) · 11 KB
/
Copy pathmain.go
File metadata and controls
359 lines (314 loc) · 11 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime/debug"
"strconv"
"strings"
"time"
)
// ANSI color codes
const (
colorCyan = "\033[36m"
colorYellow = "\033[33m"
colorGreen = "\033[32m"
colorRed = "\033[31m"
colorGray = "\033[90m"
colorReset = "\033[0m"
)
// version is set at build time via -ldflags "-X main.version=..."
// When installed via `go install`, it falls back to the module version.
var version = "dev"
// debugMode controls whether verbose debug output is printed.
var debugMode bool
// getVersion returns the build version, falling back to the module version.
func getVersion() string {
if version != "dev" {
return version
}
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "" && info.Main.Version != "(devel)" {
return info.Main.Version
}
return version
}
// userConfig represents the optional ~/.config/ai-commit/config.json file.
type userConfig struct {
AIProvider string `json:"ai_provider,omitempty"`
}
// configPath returns the path to the config file (~/.config/ai-commit/config.json).
func configPath() string {
home, err := os.UserHomeDir()
if err != nil {
home = "."
}
return filepath.Join(home, ".config", "ai-commit", "config.json")
}
// loadConfig reads ~/.config/ai-commit/config.json if it exists and returns the
// parsed config. Returns an empty config when the file is missing or invalid.
func loadConfig() userConfig {
data, err := os.ReadFile(configPath())
if err != nil {
return userConfig{}
}
var cfg userConfig
if err := json.Unmarshal(data, &cfg); err != nil {
return userConfig{}
}
return cfg
}
// resolveProvider determines which AI provider to use. Priority order:
// 1. Explicit --provider flag (if non-empty)
// 2. Config file ai_provider value
// 3. Auto-detect: first available binary in PATH (copilot, then claude)
func resolveProvider(flagValue string) string {
if flagValue != "" {
return flagValue
}
cfg := loadConfig()
if cfg.AIProvider != "" {
return cfg.AIProvider
}
// Auto-detect based on available binaries.
for _, p := range []string{"copilot", "claude"} {
if _, err := exec.LookPath(p); err == nil {
return p
}
}
return "copilot"
}
func main() {
allFlag := flag.Bool("all", false, "Stage all changes before diffing")
flag.BoolVar(allFlag, "A", false, "Stage all changes before diffing (shorthand)")
providerFlag := flag.String("provider", "", "AI provider to use: \"copilot\" or \"claude\" (default from config or \"copilot\")")
modelFlag := flag.String("model", "", "AI model to use (default depends on provider)")
maxTurnsFlag := flag.Int("max-turns", 3, "Maximum number of agentic turns the AI model can take")
debugFlag := flag.Bool("debug", false, "Enable verbose debug output")
versionFlag := flag.Bool("version", false, "Print version and exit")
flag.Parse()
if *versionFlag {
fmt.Println("ai-commit " + getVersion())
os.Exit(0)
}
debugMode = *debugFlag
provider := resolveProvider(*providerFlag)
if provider != "copilot" && provider != "claude" {
exitError("unsupported provider " + strconv.Quote(provider) + ". Supported: copilot, claude")
}
// Apply default model per provider when not explicitly set.
model := *modelFlag
if model == "" {
switch provider {
case "claude":
model = "haiku"
default:
model = "claude-haiku-4.5"
}
}
printDebug("ai-commit started")
printDebug("flags: all=%v, provider=%s, model=%s, max-turns=%d, debug=%v", *allFlag, provider, model, *maxTurnsFlag, debugMode)
// 1. Verify we're inside a git repository.
if err := exec.Command("git", "rev-parse", "--is-inside-work-tree").Run(); err != nil {
exitError("Not inside a git repository.")
}
printDebug("confirmed inside a git repository")
// 2. Optionally stage all changes.
if *allFlag {
printCyan("Staging all changes...")
printDebug("running: git add -A")
if err := runGit("add", "-A"); err != nil {
exitError("Failed to stage changes: " + err.Error())
}
}
// 3. Get the list of touched files and the stat summary.
printCyan("Collecting changed files...")
namesList, err := runGitOutput("diff", "--cached", "--name-status")
if err != nil {
exitError("Failed to list changed files: " + err.Error())
}
if strings.TrimSpace(namesList) == "" {
exitError("No staged changes found. Did you forget to stage your changes? Try running with -A or --all to stage everything.")
}
printDebug("name-status output (%d bytes):\n%s", len(namesList), namesList)
stat, err := runGitOutput("diff", "--cached", "--stat")
if err != nil {
exitError("Failed to get diff stat: " + err.Error())
}
printDebug("stat output (%d bytes):\n%s", len(stat), stat)
// 4. Generate a commit message via AI (read-only agent).
// We feed it only the file list + stat summary and let it fetch
// whatever additional context it needs using its built-in tools.
printCyan("Generating commit message with AI (" + provider + ")...")
prompt := `You are a commit-message generator. Your job is to produce a single,
concise git commit message for the staged changes described below.
CHANGED FILES (name-status):
` + namesList + `
DIFF STAT:
` + stat + `
INSTRUCTIONS:
1. You have read-only access to the repository. Use your tools to inspect
files if you need more context (e.g. read a file, run "git diff --cached",
run "git diff --cached -- <path>", or "git log").
2. Do NOT modify any files or run any write commands.
3. After gathering enough context, output your final commit message wrapped
between the markers <COMMIT_MSG> and </COMMIT_MSG>.
Do NOT include any explanation, reasoning, or commentary outside these
markers. Example output:
<COMMIT_MSG>
Fix null pointer in user login flow
</COMMIT_MSG>`
cmd := buildAICommand(provider, model, *maxTurnsFlag, prompt)
printDebug("%s args: %v", provider, cmd.Args[1:])
printDebug("prompt length: %d bytes", len(prompt))
var out []byte
start := time.Now()
if debugMode {
// In debug mode, capture stdout and stderr separately so we can
// show ALL copilot output (tool calls, reasoning, etc.) while
// still extracting the commit message from stdout.
var stdoutBuf, stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
printDebug("running %s command...", provider)
err = cmd.Run()
elapsed := time.Since(start)
if stderrBuf.Len() > 0 {
printDebug("%s stderr (%d bytes):\n%s", provider, stderrBuf.Len(), stderrBuf.String())
}
printDebug("%s stdout (%d bytes):\n%s", provider, stdoutBuf.Len(), stdoutBuf.String())
printDebug("%s exited in %s", provider, elapsed)
if err != nil {
exitError("Failed to generate commit message: " + err.Error() + "\nstderr: " + stderrBuf.String())
}
out = stdoutBuf.Bytes()
} else {
out, err = cmd.Output()
if err != nil {
stderr := ""
if exitErr, ok := err.(*exec.ExitError); ok {
stderr = string(exitErr.Stderr)
}
exitError("Failed to generate commit message: " + err.Error() + "\n" + stderr)
}
}
rawOutput := strings.TrimSpace(string(out))
stripped := stripANSI(rawOutput)
printDebug("raw output length: %d bytes, stripped length: %d bytes", len(rawOutput), len(stripped))
message := extractCommitMessage(stripped)
if message == "" {
exitError("AI returned an empty commit message.")
}
printDebug("extracted commit message: %q", message)
// 5. Display the proposed message and ask for confirmation.
fmt.Printf("\n%sProposed commit message:%s\n", colorCyan, colorReset)
fmt.Printf("%s%s%s\n\n", colorYellow, message, colorReset)
fmt.Printf("Confirm commit? (y/n): ")
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(strings.ToLower(input))
if input != "y" && input != "yes" {
fmt.Printf("%sCommit aborted.%s\n", colorRed, colorReset)
os.Exit(1)
}
// 6. Commit with the generated message.
if err := runGit("commit", "-m", message); err != nil {
exitError("Failed to commit: " + err.Error())
}
fmt.Printf("%sCommit successful!%s\n", colorGreen, colorReset)
}
// buildAICommand constructs the exec.Cmd for the chosen AI provider.
// For "copilot" it uses GitHub Copilot CLI with --allow-tool restrictions.
// For "claude" it uses Claude Code CLI with --allowedTools restrictions.
func buildAICommand(provider, model string, maxTurns int, prompt string) *exec.Cmd {
switch provider {
case "claude":
args := []string{
"-p", prompt,
"--model", model,
"--max-turns", strconv.Itoa(maxTurns),
"--allowedTools", "Bash(git diff:*)",
"--allowedTools", "Bash(git log:*)",
"--allowedTools", "Bash(git show:*)",
"--allowedTools", "Bash(git blame:*)",
"--allowedTools", "Bash(git status)",
"--allowedTools", "Read",
}
return exec.Command("claude", args...)
default: // "copilot"
args := []string{
"--model", model,
"-p", prompt,
"-s",
"--autopilot",
"--max-autopilot-continues", strconv.Itoa(maxTurns),
"--allow-tool", "shell(git diff:*)",
"--allow-tool", "shell(git log:*)",
"--allow-tool", "shell(git show:*)",
"--allow-tool", "shell(git blame:*)",
"--allow-tool", "shell(git status)",
}
return exec.Command("copilot", args...)
}
}
// extractCommitMessage extracts the commit message from the AI's output.
// It looks for content between <COMMIT_MSG> and </COMMIT_MSG> markers.
// If no markers are found, it returns the entire output as-is.
func extractCommitMessage(raw string) string {
const openTag = "<COMMIT_MSG>"
const closeTag = "</COMMIT_MSG>"
if start := strings.Index(raw, openTag); start != -1 {
after := raw[start+len(openTag):]
if end := strings.Index(after, closeTag); end != -1 {
return strings.TrimSpace(after[:end])
}
// Opening tag found but no closing tag — take everything after it.
return strings.TrimSpace(after)
}
return raw
}
// ansiPattern matches ANSI escape sequences (colors, cursor movement, etc.).
var ansiPattern = regexp.MustCompile(`\x1b\[[0-9;]*[a-zA-Z]`)
// stripANSI removes all ANSI escape codes from a string.
func stripANSI(s string) string {
return ansiPattern.ReplaceAllString(s, "")
}
// runGit executes a git command and discards its output.
// Returns an error if the command fails.
func runGit(args ...string) error {
cmd := exec.Command("git", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
// runGitOutput executes a git command and returns its stdout as a string.
func runGitOutput(args ...string) (string, error) {
cmd := exec.Command("git", args...)
out, err := cmd.Output()
if err != nil {
return "", err
}
return string(out), nil
}
// printCyan prints a status message in cyan.
func printCyan(msg string) {
fmt.Printf("%s%s%s\n", colorCyan, msg, colorReset)
}
// exitError prints an error message in red and exits with code 1.
func exitError(msg string) {
fmt.Fprintf(os.Stderr, "%sError: %s%s\n", colorRed, msg, colorReset)
os.Exit(1)
}
// printDebug prints a debug message in gray when debug mode is enabled.
func printDebug(format string, args ...any) {
if !debugMode {
return
}
msg := fmt.Sprintf(format, args...)
fmt.Fprintf(os.Stderr, "%s[debug] %s%s\n", colorGray, msg, colorReset)
}