Skip to content

Commit

Permalink
Fix bug with multiple GOPATH full package name resolving
Browse files Browse the repository at this point in the history
This commit fixes the bug where GOPATH values that are longer than the input package name cause 'slice bounds out of range'  errors.
  • Loading branch information
dvic committed Jun 27, 2018
1 parent e7657b9 commit a76eb35
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
4 changes: 4 additions & 0 deletions codegen/codegen.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
31 changes: 31 additions & 0 deletions codegen/codegen_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}

0 comments on commit a76eb35

Please sign in to comment.