我正在使用该go/types
包作为解析 Go 源代码的工具。我的代码如下所示:
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
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,即使我的代码构建良好,我也会从 conf.Check 收到错误。错误是:
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))))))))))))))))
Run Code Online (Sandbox Code Playgroud)
最终的错误是:could not import github.com/golang/protobuf/proto
如果我go list -f '{{ .Dir }}' github.com/golang/protobuf/proto
从同一个包运行,我会得到/Users/home/go/pkg/mod/github.com/golang/protobuf@v1.3.1/proto
,很明显该包是可用的。我在 Golang 存储库中发布了一个错误,但我想我也应该在这里发布,以防我做一些明显错误的事情。