diff --git a/internal/code/imports.go b/internal/code/imports.go index ad62f7c56b1..3660079633a 100644 --- a/internal/code/imports.go +++ b/internal/code/imports.go @@ -51,21 +51,21 @@ func NameForDir(dir string) string { return SanitizePackageName(filepath.Base(dir)) } -// ImportPathForDir takes a path and returns a golang import path for the package -func ImportPathForDir(dir string) (res string) { +// goModuleRoot returns the root of the current go module if there is a go.mod file in the directory tree +// If not, it returns false +func goModuleRoot(dir string) (string, bool) { dir, err := filepath.Abs(dir) if err != nil { panic(err) } dir = filepath.ToSlash(dir) - modDir := dir assumedPart := "" for { f, err := ioutil.ReadFile(filepath.Join(modDir, "go.mod")) if err == nil { // found it, stop searching - return string(modregex.FindSubmatch(f)[1]) + assumedPart + return string(modregex.FindSubmatch(f)[1]) + assumedPart, true } assumedPart = "/" + filepath.Base(modDir) + assumedPart @@ -80,6 +80,21 @@ func ImportPathForDir(dir string) (res string) { } modDir = parentDir } + return "", false +} + +// ImportPathForDir takes a path and returns a golang import path for the package +func ImportPathForDir(dir string) (res string) { + dir, err := filepath.Abs(dir) + if err != nil { + panic(err) + } + dir = filepath.ToSlash(dir) + + modDir, ok := goModuleRoot(dir) + if ok { + return modDir + } for _, gopath := range gopaths { if len(gopath) < len(dir) && strings.EqualFold(gopath, dir[0:len(gopath)]) { diff --git a/internal/code/util.go b/internal/code/util.go index 2be83a23cea..cbe40858e24 100644 --- a/internal/code/util.go +++ b/internal/code/util.go @@ -41,6 +41,11 @@ func NormalizeVendor(pkg string) string { func QualifyPackagePath(importPath string) string { wd, _ := os.Getwd() + // in go module mode, the import path doesn't need fixing + if _, ok := goModuleRoot(wd); ok { + return importPath + } + pkg, err := build.Import(importPath, wd, 0) if err != nil { return importPath