-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (77 loc) · 2.26 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
package main
import (
"fmt"
"github.com/pmezard/go-difflib/difflib"
"log"
"os"
"os/exec"
"strings"
)
func main() {
prohibitIndirectDepUpdate := os.Getenv("PROHIBIT_INDIRECT_DEP_UPDATE") == "true"
// Read the original go.mod and go.sum files
originalGoMod, err := os.ReadFile("go.mod")
if err != nil {
log.Fatalf("Failed to read go.mod: %v", err)
}
originalGoSum, err := os.ReadFile("go.sum")
if err != nil {
log.Fatalf("Failed to read go.sum: %v", err)
}
if prohibitIndirectDepUpdate {
// Remove indirect lines
lines := strings.Split(string(originalGoMod), "\n")
var cleanedGoMod []string
for _, line := range lines {
if strings.HasSuffix(line, "// indirect") {
continue
}
cleanedGoMod = append(cleanedGoMod, line)
}
err = os.WriteFile("go.mod", []byte(strings.Join(cleanedGoMod, "\n")), 0644)
if err != nil {
log.Fatalf("Failed to write cleaned go.mod: %v", err)
}
}
// Run go mod tidy
cmd := exec.Command("go", "mod", "tidy")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
log.Fatalf("Failed to run go mod tidy: %v", err)
}
// Read
updatedGoMod, err := os.ReadFile("go.mod")
if err != nil {
log.Fatalf("Failed to read updated go.mod: %v", err)
}
updatedGoSum, err := os.ReadFile("go.sum")
if err != nil {
log.Fatalf("Failed to read updated go.sum: %v", err)
}
// Compare the original and updated files
if string(originalGoMod) != string(updatedGoMod) || string(originalGoSum) != string(updatedGoSum) {
fmt.Println("go.mod or go.sum files have changed after running go mod tidy. Please commit the changes.")
printDiff("go.mod", string(originalGoMod), string(updatedGoMod))
printDiff("go.sum", string(originalGoSum), string(updatedGoSum))
os.Exit(1)
}
fmt.Println("Go mod check action completed successfully.")
}
func printDiff(filename, originalContent, updatedContent string) {
diff := difflib.UnifiedDiff{
A: difflib.SplitLines(originalContent),
B: difflib.SplitLines(updatedContent),
FromFile: "Original",
ToFile: "Updated",
Context: 3,
}
diffStr, err := difflib.GetUnifiedDiffString(diff)
if err != nil {
log.Fatalf("Failed to generate diff: %v", err)
}
if diffStr != "" {
fmt.Printf("\nChanges detected in %s:\n\n%s\n", filename, diffStr)
}
}