diff --git a/mockgen/parse.go b/mockgen/parse.go index 8ceed121..2bc503b4 100644 --- a/mockgen/parse.go +++ b/mockgen/parse.go @@ -641,13 +641,16 @@ func parsePackageImport(srcDir string) (string, error) { } } // fall back to GOPATH mode - goPath := os.Getenv("GOPATH") - if goPath == "" { + goPaths := os.Getenv("GOPATH") + if goPaths == "" { return "", fmt.Errorf("GOPATH is not set") } - sourceRoot := filepath.Join(goPath, "src") + string(os.PathSeparator) - if !strings.HasPrefix(srcDir, sourceRoot) { - return "", errOutsideGoPath + goPathList := strings.Split(goPaths, string(os.PathListSeparator)) + for _, goPath := range goPathList { + sourceRoot := filepath.Join(goPath, "src") + string(os.PathSeparator) + if strings.HasPrefix(srcDir, sourceRoot) { + return filepath.ToSlash(strings.TrimPrefix(srcDir, sourceRoot)), nil + } } - return filepath.ToSlash(strings.TrimPrefix(srcDir, sourceRoot)), nil + return "", errOutsideGoPath } diff --git a/mockgen/parse_test.go b/mockgen/parse_test.go index a274d8e0..28fb5d57 100644 --- a/mockgen/parse_test.go +++ b/mockgen/parse_test.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "os" "path/filepath" + "strings" "testing" ) @@ -202,3 +203,45 @@ func TestParsePackageImport_FallbackGoPath(t *testing.T) { t.Errorf("expect %s, got %s", expected, pkgPath) } } + +func TestParsePackageImport_FallbackMultiGoPath(t *testing.T) { + var goPathList []string + + // first gopath + goPath, err := ioutil.TempDir("", "gopath1") + if err != nil { + t.Error(err) + } + goPathList = append(goPathList, goPath) + defer func() { + if err = os.RemoveAll(goPath); err != nil { + t.Error(err) + } + }() + srcDir := filepath.Join(goPath, "src/example.com/foo") + err = os.MkdirAll(srcDir, 0755) + if err != nil { + t.Error(err) + } + + // second gopath + goPath, err = ioutil.TempDir("", "gopath2") + if err != nil { + t.Error(err) + } + goPathList = append(goPathList, goPath) + defer func() { + if err = os.RemoveAll(goPath); err != nil { + t.Error(err) + } + }() + + goPaths := strings.Join(goPathList, string(os.PathListSeparator)) + os.Setenv("GOPATH", goPaths) + os.Setenv("GO111MODULE", "on") + pkgPath, err := parsePackageImport(srcDir) + expected := "example.com/foo" + if pkgPath != expected { + t.Errorf("expect %s, got %s", expected, pkgPath) + } +}