Skip to content
This repository has been archived by the owner on Jun 27, 2023. It is now read-only.

Commit

Permalink
support multi-path gopath (#435)
Browse files Browse the repository at this point in the history
Support multi-path gopaths.
  • Loading branch information
wencan committed Jun 12, 2020
1 parent 92f53b0 commit b76a85f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 6 deletions.
15 changes: 9 additions & 6 deletions mockgen/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
43 changes: 43 additions & 0 deletions mockgen/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
)

Expand Down Expand Up @@ -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)
}
}

0 comments on commit b76a85f

Please sign in to comment.