From: Nicolas Peugnet Date: Sun, 16 Mar 2025 13:48:57 +0100 Subject: Fix loading packages with Go modules disabled Forwarded: https://github.com/kubernetes/gengo/pull/291 This allows the parser to load packages even when Go modules are disabled, and when GOPATH mode is used. This is especially useful in Debian as we build Go packages in GOPATH mode, and the tests are also run in this mode. --- v2/parser/parse.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/v2/parser/parse.go b/v2/parser/parse.go index 4c1efa0..01db6b4 100644 --- a/v2/parser/parse.go +++ b/v2/parser/parse.go @@ -20,6 +20,7 @@ import ( "errors" "fmt" "go/ast" + "go/build" "go/constant" "go/token" gotypes "go/types" @@ -129,7 +130,14 @@ func (p *Parser) findPackages(baseCfg *packages.Config, patterns ...string) ([]s } var allErrs []error for _, pkg := range pkgs { - results = append(results, pkg.PkgPath) + pkgPath := pkg.PkgPath + if pkgPath[0] == '_' && strings.HasPrefix(pkgPath[1:], build.Default.GOPATH) { + // If GOPATH mode is used, the PkgPath returned by packages.Load + // will be of the form "_/src/". We thus + // reslice the string to only get the part. + pkgPath = pkg.PkgPath[len(build.Default.GOPATH)+6:] + } + results = append(results, pkgPath) // pkg.Errors is not a slice of `error`, but concrete types. We have // to iteratively convert each one into `error`.