-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
670 lines (592 loc) · 17.3 KB
/
main.go
File metadata and controls
670 lines (592 loc) · 17.3 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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
package main
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"strings"
"github.com/FreePeak/commitgen/pkg/commitrules"
"github.com/FreePeak/commitgen/pkg/providers"
"github.com/urfave/cli/v2"
)
// Version information (set by GoReleaser).
var (
version = "v0.1.5"
commit = "none"
date = "unknown"
builtBy = "local"
)
// Error definitions.
var (
ErrNotGitRepo = errors.New("not in a git repository")
ErrNoChangesFound = errors.New("no changes found to analyze")
ErrNoStagedFiles = errors.New("no staged files found")
ErrNoUntrackedFiles = errors.New("no untracked files found")
ErrUnsupportedProvider = errors.New("unsupported provider")
ErrPermissionDenied = errors.New("permission denied. Try: sudo commitgen install")
ErrProviderName = errors.New("provider name required")
)
func main() {
app := createApp()
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func createApp() *cli.App {
return &cli.App{
Name: "commitgen",
Version: version,
Usage: "AI-powered git commit message generator",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "provider",
Usage: "AI provider to use (claude*, gemini, copilot, opencode)",
Value: "claude",
},
&cli.BoolFlag{
Name: "yes",
Aliases: []string{"y"},
Usage: "Auto-confirm the generated commit message",
},
},
Commands: []*cli.Command{
createCommitCommand(),
createProvidersCommand(),
{
Name: "install",
Usage: "Install commitgen to /usr/local/bin",
Action: installBinary,
},
createVersionCommand(),
},
Action: func(c *cli.Context) error {
return generateCommitMessage("staged")(c)
},
}
}
func createCommitCommand() *cli.Command {
return &cli.Command{
Name: "commit",
Aliases: []string{"c"},
Usage: "Generate commit message from changes",
Subcommands: []*cli.Command{
createStagedCommand(),
createAllCommand(),
createUntrackedCommand(),
},
}
}
func createProvidersCommand() *cli.Command {
return &cli.Command{
Name: "provider",
Aliases: []string{"providers"},
Usage: "Manage AI providers",
Subcommands: []*cli.Command{
{
Name: "list",
Aliases: []string{"ls"},
Usage: "List available providers",
Action: listProviders,
},
{
Name: "default",
Aliases: []string{"d"},
Usage: "Set default provider",
Action: setDefaultProvider,
},
{
Name: "add",
Usage: "Add a custom provider",
Action: addProvider,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "command",
Usage: "Command to run",
Required: true,
},
&cli.StringSliceFlag{
Name: "args",
Usage: "Arguments for the command",
},
},
},
{
Name: "remove",
Usage: "Remove a custom provider",
Action: removeProvider,
},
},
}
}
func createStagedCommand() *cli.Command {
return &cli.Command{
Name: "staged",
Aliases: []string{"s"},
Usage: "Generate from staged files",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "provider",
Usage: "AI provider to use (claude*, gemini, copilot, opencode)",
Value: "claude",
},
&cli.BoolFlag{
Name: "yes",
Aliases: []string{"y"},
Usage: "Auto-confirm the generated commit message",
},
},
Action: generateCommitMessage("staged"),
}
}
func createAllCommand() *cli.Command {
return &cli.Command{
Name: "all",
Aliases: []string{"a"},
Usage: "Generate from all changes",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "provider",
Usage: "AI provider to use (claude*, gemini, copilot, opencode)",
Value: "claude",
},
&cli.BoolFlag{
Name: "yes",
Aliases: []string{"y"},
Usage: "Auto-confirm the generated commit message",
},
},
Action: generateCommitMessage("all"),
}
}
func createUntrackedCommand() *cli.Command {
return &cli.Command{
Name: "untracked",
Aliases: []string{"u"},
Usage: "Generate from untracked files",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "provider",
Usage: "AI provider to use (claude*, gemini, copilot, opencode)",
Value: "claude",
},
&cli.BoolFlag{
Name: "yes",
Aliases: []string{"y"},
Usage: "Auto-confirm the generated commit message",
},
},
Action: generateCommitMessage("untracked"),
}
}
func createVersionCommand() *cli.Command {
return &cli.Command{
Name: "version",
Aliases: []string{"v"},
Usage: "Show version information",
Action: func(c *cli.Context) error {
fmt.Printf("Commitgen %s\n", version)
fmt.Printf("Commit: %s\n", commit)
fmt.Printf("Built: %s\n", date)
fmt.Printf("Built by: %s\n", builtBy)
return nil
},
}
}
func generateCommitMessage(mode string) cli.ActionFunc {
return func(cliContext *cli.Context) error {
if !isGitRepo() {
return ErrNotGitRepo
}
analysisInput, err := getAnalysisInput(mode)
if err != nil {
return err
}
provider := getProvider(cliContext)
commitMessage, err := callAIAPI(analysisInput, provider)
if err != nil {
return fmt.Errorf("failed to generate commit message: %w", err)
}
commitMessage = commitrules.CleanCommitMessage(commitMessage)
validateAndShowWarning(commitMessage)
autoConfirm := cliContext.Bool("yes")
if confirmCommit(commitMessage, autoConfirm) {
return executeCommit(mode, commitMessage)
}
fmt.Println("Commit cancelled.")
return nil
}
}
func getAnalysisInput(mode string) (string, error) {
switch mode {
case "staged":
return analyzeStagedChanges()
case "all":
return analyzeAllChanges()
case "untracked":
return analyzeUntrackedFiles()
default:
return "", fmt.Errorf("%w: unknown mode: %s", ErrNoChangesFound, mode)
}
}
func getProvider(cliContext *cli.Context) string {
provider := cliContext.String("provider")
if provider == "" {
provider = providers.GetDefaultProvider()
}
return provider
}
func validateAndShowWarning(commitMessage string) {
if err := commitrules.ValidateCommitMessage(commitMessage); err != nil {
fmt.Printf("Warning: %s\n", err)
}
}
func confirmCommit(commitMessage string, autoConfirm bool) bool {
if autoConfirm {
fmt.Printf("Generated commit message:\n\"%s\"\n\n", commitMessage)
fmt.Println("Auto-confirming commit message...")
return true
}
fmt.Printf("Generated commit message:\n\"%s\"\n\n", commitMessage)
fmt.Print("Do you want to use this commit message? [y/N] ")
var response string
_, err := fmt.Scanln(&response)
if err != nil {
response = ""
}
confirmed := strings.ToLower(response) == "y" || strings.ToLower(response) == "yes"
if confirmed {
fmt.Println("Committed successfully!")
}
return confirmed
}
func isGitRepo() bool {
_, err := exec.Command("git", "rev-parse", "--git-dir").CombinedOutput()
return err == nil
}
// validateFilePath validates that a file path is safe to use.
func validateFilePath(path string) bool {
// Check for path traversal attempts
if strings.Contains(path, "..") {
return false
}
// Check for dangerous characters
if strings.ContainsAny(path, "&|;<>()$`\"'") {
return false
}
// Check for empty path
if path == "" {
return false
}
return true
}
func analyzeStagedChanges() (string, error) {
// Get staged files
cmd := exec.Command("git", "diff", "--cached", "--name-only")
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to get staged files: %w", err)
}
stagedFiles := strings.TrimSpace(string(output))
if stagedFiles == "" {
return "", ErrNoStagedFiles
}
var analysisInput strings.Builder
analysisInput.WriteString("=== STAGED CHANGES ANALYSIS ===\n")
files := strings.Split(stagedFiles, "\n")
analysisInput.WriteString(fmt.Sprintf("Files changed: %d\n", len(files)))
analysisInput.WriteString(fmt.Sprintf("Files: %s\n\n", strings.Join(files, " ")))
// Get diff stats
cmd = exec.Command("git", "diff", "--cached", "--stat")
output, _ = cmd.Output()
analysisInput.WriteString("=== DIFF ===\n")
analysisInput.Write(output)
analysisInput.WriteString("\n=== DETAILED CHANGES ===\n")
// Get detailed diff for each file
for _, file := range files {
if !validateFilePath(file) {
continue
}
if _, err := os.Stat(file); err == nil {
analysisInput.WriteString(fmt.Sprintf("\n--- %s ---\n", file))
//nolint:gosec // G204: file path is validated by validateFilePath()
cmd = exec.Command("git", "diff", "--cached", "--unified=3", "--", file)
output, _ := cmd.Output()
if len(output) > 2000 {
output = output[:2000]
}
analysisInput.Write(output)
}
}
return analysisInput.String(), nil
}
func analyzeAllChanges() (string, error) {
modifiedFiles, untrackedFiles, err := getModifiedAndUntrackedFiles()
if err != nil {
return "", err
}
if modifiedFiles == "" && untrackedFiles == "" {
return "", ErrNoChangesFound
}
var analysisInput strings.Builder
analysisInput.WriteString("=== ALL CHANGES ANALYSIS ===\n")
if modifiedFiles != "" {
addModifiedFilesToAnalysis(&analysisInput, modifiedFiles)
}
if untrackedFiles != "" {
addUntrackedFilesToAnalysis(&analysisInput, untrackedFiles)
}
return analysisInput.String(), nil
}
func getModifiedAndUntrackedFiles() (string, string, error) {
cmd := exec.Command("git", "diff", "--name-only")
modifiedOutput, err := cmd.Output()
if err != nil {
return "", "", fmt.Errorf("failed to get modified files: %w", err)
}
cmd = exec.Command("git", "ls-files", "--others", "--exclude-standard")
untrackedOutput, err := cmd.Output()
if err != nil {
return "", "", fmt.Errorf("failed to get untracked files: %w", err)
}
return strings.TrimSpace(string(modifiedOutput)), strings.TrimSpace(string(untrackedOutput)), nil
}
func addModifiedFilesToAnalysis(analysisInput *strings.Builder, modifiedFiles string) {
files := strings.Split(modifiedFiles, "\n")
fmt.Fprintf(analysisInput, "Modified files: %d\n", len(files))
analysisInput.WriteString("=== MODIFIED FILES ===\n")
fmt.Fprintf(analysisInput, "%s\n\n", strings.Join(files, " "))
analysisInput.WriteString("=== MODIFICATIONS ===\n")
for _, file := range files {
if !validateFilePath(file) {
continue
}
if _, err := os.Stat(file); err == nil {
addFileDiffToAnalysis(analysisInput, file)
}
}
}
func addUntrackedFilesToAnalysis(analysisInput *strings.Builder, untrackedFiles string) {
files := strings.Split(untrackedFiles, "\n")
analysisInput.WriteString("\n=== UNTRACKED FILES ===\n")
fmt.Fprintf(analysisInput, "%s\n\n", strings.Join(files, " "))
analysisInput.WriteString("=== FILE CONTENTS ===\n")
for _, file := range files {
if !validateFilePath(file) {
continue
}
if _, err := os.Stat(file); err == nil {
addFileContentToAnalysis(analysisInput, file)
}
}
}
func addFileDiffToAnalysis(analysisInput *strings.Builder, file string) {
fmt.Fprintf(analysisInput, "\n--- %s ---\n", file)
cmd := exec.Command("git", "diff", "--unified=3", file)
output, _ := cmd.Output()
if len(output) > 2000 {
output = output[:2000]
}
analysisInput.Write(output)
}
func addFileContentToAnalysis(analysisInput *strings.Builder, file string) {
fmt.Fprintf(analysisInput, "\n--- %s (new) ---\n", file)
//nolint:gosec // G304: file path is validated by validateFilePath()
content, _ := os.ReadFile(file)
if len(content) > 2000 {
content = content[:2000]
}
analysisInput.Write(content)
}
func analyzeUntrackedFiles() (string, error) {
cmd := exec.Command("git", "ls-files", "--others", "--exclude-standard")
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to get untracked files: %w", err)
}
untrackedFiles := strings.TrimSpace(string(output))
if untrackedFiles == "" {
return "", ErrNoUntrackedFiles
}
var analysisInput strings.Builder
analysisInput.WriteString("=== UNTRACKED FILES ANALYSIS ===\n")
files := strings.Split(untrackedFiles, "\n")
analysisInput.WriteString(fmt.Sprintf("Files: %d\n", len(files)))
analysisInput.WriteString(fmt.Sprintf("%s\n\n", strings.Join(files, " ")))
analysisInput.WriteString("=== FILE CONTENTS ===\n")
for _, file := range files {
if !validateFilePath(file) {
continue
}
if _, err := os.Stat(file); err == nil {
analysisInput.WriteString(fmt.Sprintf("\n--- %s ---\n", file))
//nolint:gosec // G304: file path is validated by validateFilePath()
content, _ := os.ReadFile(file)
if len(content) > 2000 {
content = content[:2000]
}
analysisInput.Write(content)
}
}
return analysisInput.String(), nil
}
func callAIAPI(analysisInput, provider string) (string, error) {
prompt := commitrules.GetPrompt(analysisInput)
// Get provider command and arguments
cmdName, cmdArgs := getProviderCmd(provider)
//nolint:gosec // G204: cmdName is from trusted provider configuration
cmd := exec.Command(cmdName, cmdArgs...)
cmd.Stdin = strings.NewReader(prompt)
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to call %s API: %w\nStderr: %s", provider, err, stderr.String())
}
result := strings.TrimSpace(string(output))
if result == "" && stderr.Len() > 0 {
// If stdout is empty but we have stderr content, treat it as an error
// This handles cases where tools exit with code 0 but fail (like opencode)
return "", fmt.Errorf("provider returned empty output: %w: %s", ErrNoChangesFound, stderr.String())
}
return result, nil
}
func getProviderCmd(provider string) (string, []string) {
cmdName, cmdArgs, err := providers.GetProvider(provider)
if err != nil {
return provider, []string{}
}
return cmdName, cmdArgs
}
func executeCommit(mode, commitMessage string) error {
var cmd *exec.Cmd
switch mode {
case "staged":
cmd = exec.Command("git", "commit", "-m", commitMessage)
case "all", "untracked":
// First stage all changes
if err := exec.Command("git", "add", ".").Run(); err != nil {
return fmt.Errorf("failed to stage changes: %w", err)
}
cmd = exec.Command("git", "commit", "-m", commitMessage)
}
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to commit: %w", err)
}
return nil
}
func listProviders(c *cli.Context) error {
providerList, err := providers.ListProviders()
if err != nil {
return fmt.Errorf("failed to list providers: %w", err)
}
defaultProvider := providers.GetDefaultProvider()
fmt.Println("Available providers:")
for _, name := range providerList {
details, exists := providers.GetProviderDetails(name)
if !exists {
continue
}
marker := " "
if name == defaultProvider {
marker = "*"
}
argsStr := ""
if len(details.Args) > 0 {
argsStr = fmt.Sprintf(" %s", strings.Join(details.Args, " "))
}
fmt.Printf(" %s %s: %s%s\n", marker, name, details.Command, argsStr)
}
fmt.Printf("\n * = default provider\n")
fmt.Printf("\nConfig file: ~/.commitgen/config.json\n")
return nil
}
func setDefaultProvider(c *cli.Context) error {
if c.Args().Len() == 0 {
return ErrProviderName
}
name := c.Args().First()
if err := providers.SetDefaultProvider(name); err != nil {
return fmt.Errorf("failed to set default provider: %w", err)
}
fmt.Printf("Default provider set to: %s\n", name)
return nil
}
func addProvider(ctx *cli.Context) error {
if ctx.Args().Len() == 0 {
return ErrProviderName
}
name := ctx.Args().First()
command := ctx.String("command")
args := ctx.StringSlice("args")
provider := providers.Provider{
Command: command,
Args: args,
}
if err := providers.AddProvider(name, provider); err != nil {
return fmt.Errorf("failed to add provider: %w", err)
}
fmt.Printf("Provider '%s' added: %s %s\n", name, command, strings.Join(args, " "))
return nil
}
func removeProvider(ctx *cli.Context) error {
if ctx.Args().Len() == 0 {
return ErrProviderName
}
name := ctx.Args().First()
if err := providers.RemoveProvider(name); err != nil {
return fmt.Errorf("failed to remove provider: %w", err)
}
fmt.Printf("Provider '%s' removed\n", name)
return nil
}
func installBinary(c *cli.Context) error {
exePath, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to get executable path: %w", err)
}
installPath := "/usr/local/bin/commitgen"
// Check if we have permission to write to /usr/local/bin
if _, err := os.Stat("/usr/local/bin"); os.IsPermission(err) {
return ErrPermissionDenied
}
// Copy binary to install path
if !validateFilePath(exePath) {
return fmt.Errorf("%w: invalid executable path: %s", ErrPermissionDenied, exePath)
}
//nolint:gosec // G304: exePath is validated by validateFilePath()
source, err := os.Open(exePath)
if err != nil {
return fmt.Errorf("failed to open source file: %w", err)
}
defer func() {
if closeErr := source.Close(); closeErr != nil {
fmt.Printf("Warning: failed to close source file: %v\n", closeErr)
}
}()
destination, err := os.Create(installPath)
if err != nil {
return fmt.Errorf("failed to create destination file: %w", err)
}
defer func() {
if closeErr := destination.Close(); closeErr != nil {
fmt.Printf("Warning: failed to close destination file: %v\n", closeErr)
}
}()
_, err = io.Copy(destination, source)
if err != nil {
return fmt.Errorf("failed to copy file content: %w", err)
}
// Make it executable (0755 is appropriate for system binaries in /usr/local/bin)
// This allows read and execute by all users, but write only by owner
//nolint:gosec // G302: 0755 is appropriate for system binaries
err = os.Chmod(installPath, 0o755)
if err != nil {
return fmt.Errorf("failed to set file permissions: %w", err)
}
fmt.Printf("Commitgen installed successfully to %s\n", installPath)
fmt.Println("You can now use 'commitgen' from anywhere!")
return nil
}