From 7560b4f1da8dc0d244e76ef9dc0a8d010b568f6f Mon Sep 17 00:00:00 2001 From: Ludovic Fernandez Date: Thu, 7 Nov 2024 19:35:58 +0100 Subject: [PATCH] fix: improve Go detection (#5112) --- pkg/config/config.go | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/pkg/config/config.go b/pkg/config/config.go index 93b331bec457..b863b329f931 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -75,10 +75,9 @@ func IsGoGreaterThanOrEqual(current, limit string) bool { } func detectGoVersion() string { - file, _ := gomoddirectives.GetModuleFile() - - if file != nil && file.Go != nil && file.Go.Version != "" { - return file.Go.Version + goVersion := detectGoVersionFromGoMod() + if goVersion != "" { + return goVersion } v := os.Getenv("GOVERSION") @@ -88,3 +87,26 @@ func detectGoVersion() string { return "1.17" } + +// detectGoVersionFromGoMod tries to get Go version from go.mod. +// It returns `toolchain` version if present, +// else it returns `go` version if present, +// else it returns empty. +func detectGoVersionFromGoMod() string { + file, _ := gomoddirectives.GetModuleFile() + if file == nil { + return "" + } + + // The toolchain exists only if 'toolchain' version > 'go' version. + // If 'toolchain' version <= 'go' version, `go mod tidy` will remove 'toolchain' version from go.mod. + if file.Toolchain != nil && file.Toolchain.Name != "" { + return strings.TrimPrefix(file.Toolchain.Name, "go") + } + + if file.Go != nil && file.Go.Version != "" { + return file.Go.Version + } + + return "" +}