From 2012ac320441c7ccf086a87aa0e898922c63da13 Mon Sep 17 00:00:00 2001 From: kim Date: Mon, 10 Aug 2020 15:25:39 +0800 Subject: [PATCH] correct parent packet for gomod --- tools/goctl/api/gogen/util.go | 38 +++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/tools/goctl/api/gogen/util.go b/tools/goctl/api/gogen/util.go index 392b583e..5b3b8274 100644 --- a/tools/goctl/api/gogen/util.go +++ b/tools/goctl/api/gogen/util.go @@ -12,20 +12,46 @@ import ( "github.com/tal-tech/go-zero/core/collection" "github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/util" + goctlutil "github.com/tal-tech/go-zero/tools/goctl/util" ) +const goModeIdentifier = "go.mod" + func getParentPackage(dir string) (string, error) { absDir, err := filepath.Abs(dir) if err != nil { return "", err } - gopath := os.Getenv("GOPATH") - parent := path.Join(gopath, "src") - pos := strings.Index(absDir, parent) - if pos < 0 { - return "", fmt.Errorf("%s not in GOPATH %s directory", absDir, gopath) + + var rootPath string + var tempPath = absDir + var hasGoMod = false + for { + tempPath = filepath.Dir(tempPath) + if goctlutil.FileExists(filepath.Join(tempPath, goModeIdentifier)) { + tempPath = filepath.Dir(tempPath) + rootPath = absDir[len(tempPath)+1:] + hasGoMod = true + break + } + if tempPath == string(filepath.Separator) { + break + } + } + if !hasGoMod { + gopath := os.Getenv("GOPATH") + parent := path.Join(gopath, "src") + pos := strings.Index(absDir, parent) + if pos < 0 { + message := fmt.Sprintf("%s not in gomod project path, or not in GOPATH of %s directory", absDir, gopath) + println(message) + tempPath = filepath.Dir(absDir) + rootPath = absDir[len(tempPath)+1:] + } else { + rootPath = absDir[len(parent)+1:] + } } - return absDir[len(parent)+1:], nil + return rootPath, nil } func writeIndent(writer io.Writer, indent int) {