|
9 | 9 | "strings"
|
10 | 10 |
|
11 | 11 | hcversion "github.com/hashicorp/go-version"
|
| 12 | + "github.com/ldez/grignotin/goenv" |
12 | 13 | "github.com/ldez/grignotin/gomod"
|
13 | 14 | "golang.org/x/mod/modfile"
|
14 | 15 | )
|
@@ -80,43 +81,57 @@ func IsGoGreaterThanOrEqual(current, limit string) bool {
|
80 | 81 | }
|
81 | 82 |
|
82 | 83 | func detectGoVersion() string {
|
83 |
| - goVersion := detectGoVersionFromGoMod() |
84 |
| - if goVersion != "" { |
85 |
| - return goVersion |
86 |
| - } |
87 |
| - |
88 |
| - return cmp.Or(os.Getenv("GOVERSION"), "1.17") |
| 84 | + return cmp.Or(detectGoVersionFromGoMod(), "1.17") |
89 | 85 | }
|
90 | 86 |
|
91 | 87 | // detectGoVersionFromGoMod tries to get Go version from go.mod.
|
92 | 88 | // It returns `toolchain` version if present,
|
93 | 89 | // else it returns `go` version if present,
|
| 90 | +// else it returns `GOVERSION` version if present, |
94 | 91 | // else it returns empty.
|
95 | 92 | func detectGoVersionFromGoMod() string {
|
96 |
| - modPath, err := gomod.GetGoModPath() |
| 93 | + values, err := goenv.Get(goenv.GOMOD, goenv.GOVERSION) |
97 | 94 | if err != nil {
|
98 |
| - modPath = detectGoModFallback() |
99 |
| - if modPath == "" { |
100 |
| - return "" |
| 95 | + values = map[string]string{ |
| 96 | + goenv.GOMOD: detectGoModFallback(), |
101 | 97 | }
|
102 | 98 | }
|
103 | 99 |
|
104 |
| - file, err := parseGoMod(modPath) |
| 100 | + if values[goenv.GOMOD] == "" { |
| 101 | + return parseGoVersion(values[goenv.GOVERSION]) |
| 102 | + } |
| 103 | + |
| 104 | + file, err := parseGoMod(values[goenv.GOMOD]) |
105 | 105 | if err != nil {
|
106 |
| - return "" |
| 106 | + return parseGoVersion(values[goenv.GOVERSION]) |
107 | 107 | }
|
108 | 108 |
|
109 | 109 | // The toolchain exists only if 'toolchain' version > 'go' version.
|
110 | 110 | // If 'toolchain' version <= 'go' version, `go mod tidy` will remove 'toolchain' version from go.mod.
|
111 | 111 | if file.Toolchain != nil && file.Toolchain.Name != "" {
|
112 |
| - return strings.TrimPrefix(file.Toolchain.Name, "go") |
| 112 | + return parseGoVersion(file.Toolchain.Name) |
113 | 113 | }
|
114 | 114 |
|
115 | 115 | if file.Go != nil && file.Go.Version != "" {
|
116 | 116 | return file.Go.Version
|
117 | 117 | }
|
118 | 118 |
|
119 |
| - return "" |
| 119 | + return parseGoVersion(values[goenv.GOVERSION]) |
| 120 | +} |
| 121 | + |
| 122 | +func parseGoVersion(v string) string { |
| 123 | + raw := strings.TrimPrefix(v, "go") |
| 124 | + |
| 125 | + // prerelease version (ex: go1.24rc1) |
| 126 | + idx := strings.IndexFunc(raw, func(r rune) bool { |
| 127 | + return (r < '0' || r > '9') && r != '.' |
| 128 | + }) |
| 129 | + |
| 130 | + if idx != -1 { |
| 131 | + raw = raw[:idx] |
| 132 | + } |
| 133 | + |
| 134 | + return raw |
120 | 135 | }
|
121 | 136 |
|
122 | 137 | func parseGoMod(goMod string) (*modfile.File, error) {
|
|
0 commit comments