-
Notifications
You must be signed in to change notification settings - Fork 8
/
plugin.go
97 lines (82 loc) · 2.27 KB
/
plugin.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
package cmd
import (
"fmt"
"os"
"path/filepath"
"github.com/krakendio/krakend-cobra/v2/plugin"
"github.com/spf13/cobra"
"golang.org/x/mod/modfile"
)
// indirectRequires returns the indirect dependencies of the go.sum file.
func indirectRequires(goSum string) (map[string]struct{}, error) {
dir := filepath.Dir(goSum)
filename := filepath.Join(dir, "go.mod")
data, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("reading go.mod: %w", err)
}
f, err := modfile.Parse(filename, data, nil)
if err != nil {
return nil, fmt.Errorf("parsing go.mod: %w", err)
}
indirects := map[string]struct{}{}
for _, r := range f.Require {
if r.Indirect {
indirects[r.Mod.Path] = struct{}{}
}
}
return indirects, nil
}
// getBuildInfo returns the dependencies of the binary calling it.
// It is a var to allow the replacement of the function in the tests
// as the debug.ReadBuildInfo function is not available in the tests
// https://github.com/golang/go/issues/68045
var localDescriber = plugin.Local
func pluginFunc(cmd *cobra.Command, args []string) {
if err := pluginFuncErr(cmd, args); err != nil {
cmd.Println(err)
os.Exit(1)
}
}
func pluginFuncErr(cmd *cobra.Command, _ []string) error {
f, err := os.Open(goSum)
if err != nil {
return err
}
defer func() { _ = f.Close() }() // Workaround false positive for GO-S2307.
desc, err := plugin.Describe(f, goVersion, libcVersion)
if err != nil {
return err
}
diffs := localDescriber().Compare(desc)
if len(diffs) == 0 {
cmd.Println("No incompatibilities found!")
return nil
}
if gogetEnabled {
indirects, err := indirectRequires(goSum)
if err != nil {
return err
}
for _, diff := range diffs {
if diff.Name != "go" && diff.Name != "libc" {
if _, ok := indirects[diff.Name]; ok {
cmd.Printf("go mod edit --replace %s=%s@%s\n", diff.Name, diff.Name, diff.Expected)
} else {
cmd.Printf("go get %s@%s\n", diff.Name, diff.Expected)
}
continue
}
cmd.Println(diff.Name)
cmd.Println("\thave:", diff.Have)
cmd.Println("\twant:", diff.Expected)
}
} else {
for _, diff := range diffs {
cmd.Println(diff.Name)
cmd.Println("\thave:", diff.Have)
cmd.Println("\twant:", diff.Expected)
}
}
return fmt.Errorf("%d incompatibilities found", len(diffs))
}