-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
103 lines (90 loc) · 2.24 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
package main
import (
"fmt"
"os"
"os/exec"
"github.com/spf13/cobra"
"strings"
)
var rootCmd = &cobra.Command{
Use: "gotcr",
Short: "Run tests and commit if they pass, revert if they fail",
Run: func(cmd *cobra.Command, args []string) {
// Run tests
runTestsAndCommitOrRevert()
},
}
var message string
var changesCount int
func getChangesCount() (int, error) {
// Run 'git diff' to get the changes
cmd := exec.Command("git", "diff", "--cached", "--numstat")
output, err := cmd.Output()
if err != nil {
return 0, err
}
// Count the number of lines in the output (each line represents a change)
lines := strings.Split(string(output), "\n")
changesCount := len(lines) - 1 // Exclude the empty line at the end
return changesCount, nil
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func runTestsAndCommitOrRevert() {
// Run 'go test' command
cmd := exec.Command("go", "test")
err := cmd.Run()
// Check if the command was successful (exit code 0)
if err == nil {
// All tests passed, commit changes
commitChanges()
} else {
// Tests failed, revert changes
revertChanges()
fmt.Println("Tests failed. Changes reverted.")
os.Exit(1)
}
}
func commitChanges(message string) {
// Add all changes to the staging area
cmd := exec.Command("git", "add", ".")
err := cmd.Run()
if err != nil {
fmt.Println("Error adding changes to the staging area:", err)
return
}
// Build the commit message
changesCount,err := getChangesCount()
if err != nil {
fmt.Println("Error get changes count:", err)
return
}
if (changesCount == 0) {
fmt.Println("Error: no changes detected")
return
}
message = fmt.Sprintf("%d changes added",changesCount)
fmt.Println(message)
// Commit the changes
cmd = exec.Command("git", "commit", "-m", message)
err = cmd.Run()
if err != nil {
fmt.Println("Error committing changes:", err)
return
}
fmt.Println("Changes committed successfully.")
}
func revertChanges(message string) {
// Revert changes
cmd := exec.Command("git", "reset", "--hard", "HEAD")
err := cmd.Run()
if err != nil {
fmt.Println("Error reverting changes:", err)
return
}
fmt.Println("Changes reverted successfully.")
}