Skip to content

Commit 1b30c52

Browse files
committed
fix: improve Go version detection inside workspace
1 parent d40b6da commit 1b30c52

File tree

1 file changed

+42
-3
lines changed

1 file changed

+42
-3
lines changed

pkg/config/config.go

+42-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
package config
22

33
import (
4+
"cmp"
5+
"fmt"
46
"os"
7+
"path/filepath"
8+
"slices"
59
"strings"
610

711
hcversion "github.com/hashicorp/go-version"
8-
"github.com/ldez/gomoddirectives"
12+
"github.com/ldez/grignotin/gomod"
13+
"golang.org/x/mod/modfile"
914
)
1015

1116
// Config encapsulates the config data specified in the golangci-lint YAML config file.
@@ -93,8 +98,33 @@ func detectGoVersion() string {
9398
// else it returns `go` version if present,
9499
// else it returns empty.
95100
func detectGoVersionFromGoMod() string {
96-
file, _ := gomoddirectives.GetModuleFile()
97-
if file == nil {
101+
info, err := gomod.GetModuleInfo()
102+
if err != nil {
103+
return ""
104+
}
105+
106+
wd, err := os.Getwd()
107+
if err != nil {
108+
return ""
109+
}
110+
111+
slices.SortFunc(info, func(a, b gomod.ModInfo) int {
112+
return cmp.Compare(len(b.Path), len(a.Path))
113+
})
114+
115+
goMod := info[0]
116+
for _, m := range info {
117+
if !strings.HasPrefix(wd, m.Dir) {
118+
continue
119+
}
120+
121+
goMod = m
122+
123+
break
124+
}
125+
126+
file, err := parseGoMod(goMod.GoMod)
127+
if err != nil {
98128
return ""
99129
}
100130

@@ -110,3 +140,12 @@ func detectGoVersionFromGoMod() string {
110140

111141
return ""
112142
}
143+
144+
func parseGoMod(goMod string) (*modfile.File, error) {
145+
raw, err := os.ReadFile(filepath.Clean(goMod))
146+
if err != nil {
147+
return nil, fmt.Errorf("reading go.mod file: %w", err)
148+
}
149+
150+
return modfile.Parse("go.mod", raw, nil)
151+
}

0 commit comments

Comments
 (0)