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

Commit b76a85f

Browse files
authored
support multi-path gopath (#435)
Support multi-path gopaths.
1 parent 92f53b0 commit b76a85f

File tree

2 files changed

+52
-6
lines changed

2 files changed

+52
-6
lines changed

mockgen/parse.go

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -641,13 +641,16 @@ func parsePackageImport(srcDir string) (string, error) {
641641
}
642642
}
643643
// fall back to GOPATH mode
644-
goPath := os.Getenv("GOPATH")
645-
if goPath == "" {
644+
goPaths := os.Getenv("GOPATH")
645+
if goPaths == "" {
646646
return "", fmt.Errorf("GOPATH is not set")
647647
}
648-
sourceRoot := filepath.Join(goPath, "src") + string(os.PathSeparator)
649-
if !strings.HasPrefix(srcDir, sourceRoot) {
650-
return "", errOutsideGoPath
648+
goPathList := strings.Split(goPaths, string(os.PathListSeparator))
649+
for _, goPath := range goPathList {
650+
sourceRoot := filepath.Join(goPath, "src") + string(os.PathSeparator)
651+
if strings.HasPrefix(srcDir, sourceRoot) {
652+
return filepath.ToSlash(strings.TrimPrefix(srcDir, sourceRoot)), nil
653+
}
651654
}
652-
return filepath.ToSlash(strings.TrimPrefix(srcDir, sourceRoot)), nil
655+
return "", errOutsideGoPath
653656
}

mockgen/parse_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"io/ioutil"
88
"os"
99
"path/filepath"
10+
"strings"
1011
"testing"
1112
)
1213

@@ -202,3 +203,45 @@ func TestParsePackageImport_FallbackGoPath(t *testing.T) {
202203
t.Errorf("expect %s, got %s", expected, pkgPath)
203204
}
204205
}
206+
207+
func TestParsePackageImport_FallbackMultiGoPath(t *testing.T) {
208+
var goPathList []string
209+
210+
// first gopath
211+
goPath, err := ioutil.TempDir("", "gopath1")
212+
if err != nil {
213+
t.Error(err)
214+
}
215+
goPathList = append(goPathList, goPath)
216+
defer func() {
217+
if err = os.RemoveAll(goPath); err != nil {
218+
t.Error(err)
219+
}
220+
}()
221+
srcDir := filepath.Join(goPath, "src/example.com/foo")
222+
err = os.MkdirAll(srcDir, 0755)
223+
if err != nil {
224+
t.Error(err)
225+
}
226+
227+
// second gopath
228+
goPath, err = ioutil.TempDir("", "gopath2")
229+
if err != nil {
230+
t.Error(err)
231+
}
232+
goPathList = append(goPathList, goPath)
233+
defer func() {
234+
if err = os.RemoveAll(goPath); err != nil {
235+
t.Error(err)
236+
}
237+
}()
238+
239+
goPaths := strings.Join(goPathList, string(os.PathListSeparator))
240+
os.Setenv("GOPATH", goPaths)
241+
os.Setenv("GO111MODULE", "on")
242+
pkgPath, err := parsePackageImport(srcDir)
243+
expected := "example.com/foo"
244+
if pkgPath != expected {
245+
t.Errorf("expect %s, got %s", expected, pkgPath)
246+
}
247+
}

0 commit comments

Comments
 (0)