I am using the go/types
package for a tool that parses Go source. My code looks like this:
packageName := "github.com/something/my-test-package"
imported, err := build.Default.Import(packageName, ".", build.FindOnly)
if err != nil {
return nil, errors.Wrapf(err, "Error importing package %s", packageName)
}
packages, err := parser.ParseDir(fileSet, imported.Dir, nil, 0)
if err != nil {
return nil, errors.Wrapf(err, "Error parsing package %s", packageName)
}
for _, astPkg := range packages {
var files []*ast.File
for _, file := range astPkg.Files {
files = append(files, file)
}
info := &types.Info{
Defs: make(map[*ast.Ident]types.Object),
}
conf := types.Config{
Importer: importer.ForCompiler(fileSet, "source", nil),
}
_, err := conf.Check(packageName, fileSet, files, info)
if err != nil {
panic(err) // Panics here
}
}
In the above example, I get an error from conf.Check even though my code builds fine. The error is:
panic: /Users/home/Dev/my-test-package/bindings/bindings.go:6:2: could not import github.com/something/my-test-package/prototype (type-checking package "github.com/something/my-test-package/prototype" failed (/Users/home/Dev/my-test-package/prototype/basic.go:3:8: could not import <omitted> could not import github.com/golang/protobuf/ptypes/wrappers (type-checking package "github.com/golang/protobuf/ptypes/wrappers" failed (/Users/home/go/pkg/mod/github.com/golang/protobuf@v1.2.0/ptypes/wrappers/wrappers.pb.go:6:14: could not import github.com/golang/protobuf/proto (cannot find package "github.com/golang/protobuf/proto" in any of:
/usr/local/go/src/github.com/golang/protobuf/proto (from $GOROOT)
/Users/home/go/src/github.com/golang/protobuf/proto (from $GOPATH))))))))))))))))
The ultimate error is: could not import github.com/golang/protobuf/proto
If I run go list -f '{{ .Dir }}' github.com/golang/protobuf/proto
from the same package, I get /Users/home/go/pkg/mod/github.com/golang/protobuf@v1.3.1/proto
, so clearly the package is available. I posted a bug in the Golang repo, but thought I'd also post here in case I'm doing something obviously wrong.