From a76eb35fc1a0a2ebef8e1e5034e2249b7b91f520 Mon Sep 17 00:00:00 2001 From: Damir Vandic Date: Wed, 27 Jun 2018 11:05:52 +0200 Subject: [PATCH] Fix bug with multiple GOPATH full package name resolving This commit fixes the bug where GOPATH values that are longer than the input package name cause 'slice bounds out of range' errors. --- codegen/codegen.go | 4 ++++ codegen/codegen_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 codegen/codegen_test.go diff --git a/codegen/codegen.go b/codegen/codegen.go index e36f3226cec..1a8e4f87d0a 100644 --- a/codegen/codegen.go +++ b/codegen/codegen.go @@ -156,8 +156,12 @@ func fullPackageName(dir string, pkgName string) string { for _, gopath := range filepath.SplitList(build.Default.GOPATH) { gopath = filepath.Join(gopath, "src") + string(os.PathSeparator) + if len(gopath) > len(fullPkgName) { + continue + } if strings.EqualFold(gopath, fullPkgName[0:len(gopath)]) { fullPkgName = fullPkgName[len(gopath):] + break } } return filepath.ToSlash(fullPkgName) diff --git a/codegen/codegen_test.go b/codegen/codegen_test.go new file mode 100644 index 00000000000..6af82cf2a7b --- /dev/null +++ b/codegen/codegen_test.go @@ -0,0 +1,31 @@ +package codegen + +import ( + "go/build" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_fullPackageName(t *testing.T) { + origBuildContext := build.Default + defer func() { build.Default = origBuildContext }() + + t.Run("gopath longer than package name", func(t *testing.T) { + build.Default.GOPATH = "/a/src/xxxxxxxxxxxxxxxxxxxxxxxx:/b/src/y" + var got string + ok := assert.NotPanics(t, func() { got = fullPackageName("/b/src/y/foo/bar", "bar") }) + if ok { + assert.Equal(t, "/b/src/y/foo/bar", got) + } + }) + t.Run("stop searching on first hit", func(t *testing.T) { + build.Default.GOPATH = "/a/src/x:/b/src/y" + + var got string + ok := assert.NotPanics(t, func() { got = fullPackageName("/a/src/x/foo/bar", "bar") }) + if ok { + assert.Equal(t, "/a/src/x/foo/bar", got) + } + }) +}