I am looking for a way to retrieve the package(s) installed locally which contain the declaration for a given type and the default package name.
ie:
// FindPackagesForType returns the list of possible packages for a given type
func FindPackagesForType(typeName string) []string {
return []string {} // TODO: implement
}
func TestFindPackagesForType(t *testing.T) {
assert.Contains(t, FindPackagesForType("io.Reader"), "io")
assert.Contains(
t,
FindPackagesForType("types.Timestamp"),
"github.com/gogo/protobuf/types",
)
assert.Contains(
t,
FindPackagesForType("types.ContainerCreateConfig"),
"github.com/docker/docker/api/types",
)
}
I could try to retrieve all packages installed, and go through the AST in each looking for the declaration but if there is a solution which could do this more efficiently while also providing support for go modules I would like to use that.
The reason for this is to improve a code generation tool. The idea is to let the user provide the name of a type and let the tool identify the most likely candidate the same way goimports adds missing imports.
You can use
reflect.TypeOf(any).PkgPath()to get the package path of certain type. However we need to pass an object with desired type (not string like you wanted).