diff --git a/go.mod b/go.mod index aad95cd76b7f..61cd7155b1df 100644 --- a/go.mod +++ b/go.mod @@ -67,6 +67,7 @@ require ( github.com/kyoh86/exportloopref v0.1.11 github.com/lasiar/canonicalheader v1.1.2 github.com/ldez/gomoddirectives v0.4.2 + github.com/ldez/grignotin v0.6.0 github.com/ldez/tagliatelle v0.6.0 github.com/ldez/usetesting v0.2.0 github.com/leonklingele/grouper v1.1.2 @@ -128,6 +129,7 @@ require ( go-simpler.org/sloglint v0.7.2 go.uber.org/automaxprocs v1.6.0 golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 + golang.org/x/mod v0.22.0 golang.org/x/sys v0.27.0 golang.org/x/tools v0.27.0 gopkg.in/yaml.v3 v3.0.1 @@ -164,7 +166,6 @@ require ( github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/ldez/grignotin v0.6.0 // indirect github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-isatty v0.0.20 // indirect @@ -197,7 +198,6 @@ require ( go.uber.org/multierr v1.6.0 // indirect go.uber.org/zap v1.24.0 // indirect golang.org/x/exp/typeparams v0.0.0-20241108190413-2d47ceb2692f // indirect - golang.org/x/mod v0.22.0 // indirect golang.org/x/sync v0.9.0 // indirect golang.org/x/text v0.18.0 // indirect google.golang.org/protobuf v1.34.2 // indirect diff --git a/pkg/config/config.go b/pkg/config/config.go index b863b329f931..f69035278afd 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -1,11 +1,16 @@ package config import ( + "cmp" + "fmt" "os" + "path/filepath" + "slices" "strings" hcversion "github.com/hashicorp/go-version" - "github.com/ldez/gomoddirectives" + "github.com/ldez/grignotin/gomod" + "golang.org/x/mod/modfile" ) // Config encapsulates the config data specified in the golangci-lint YAML config file. @@ -93,8 +98,33 @@ func detectGoVersion() string { // else it returns `go` version if present, // else it returns empty. func detectGoVersionFromGoMod() string { - file, _ := gomoddirectives.GetModuleFile() - if file == nil { + info, err := gomod.GetModuleInfo() + if err != nil { + return "" + } + + wd, err := os.Getwd() + if err != nil { + return "" + } + + slices.SortFunc(info, func(a, b gomod.ModInfo) int { + return cmp.Compare(len(b.Path), len(a.Path)) + }) + + goMod := info[0] + for _, m := range info { + if !strings.HasPrefix(wd, m.Dir) { + continue + } + + goMod = m + + break + } + + file, err := parseGoMod(goMod.GoMod) + if err != nil { return "" } @@ -110,3 +140,12 @@ func detectGoVersionFromGoMod() string { return "" } + +func parseGoMod(goMod string) (*modfile.File, error) { + raw, err := os.ReadFile(filepath.Clean(goMod)) + if err != nil { + return nil, fmt.Errorf("reading go.mod file: %w", err) + } + + return modfile.Parse("go.mod", raw, nil) +}