go / types:Config.Check找不到包

时间:2019-05-03 20:46:10

标签: go

我正在使用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
    }
}

在上面的示例中,即使我的代码构建良好,我也从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))))))))))))))))

最终错误是: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,因此很明显该软件包可用。我posted a bug in the Golang repo,但以为我也会在这里发帖,以防万一我做错了明显的事情。

1 个答案:

答案 0 :(得分:0)

这似乎是一个已知问题,或与一个已知问题有关:tools that use GOPATH need special updates to work with go modules

一些issues similar to yours与该问题有关。