For those who are familiar with the golang.org/x/tools/go/packages
package, is there a way to specify a pattern
in the Load
function in which we can capture all the packages within a given directory path (e.g. the root directory of a Go project)? After reading the docs of this package, I have not been able to find a means to specify a pattern in this way.
The docs do explain a wildcard string of “…” (I appended “…” to the current working directory), but appending this to a project root directory yielded in no packages being type-checked.
The following code is my current approach. One of its issues is that files that share the same package name but are not in the same directory (e.g. package main defined in different directories) are treated as their own package:
c := &packages.Config{
Mode: packages.NeedName | packages.NeedTypesInfo | packages.NeedSyntax,
Dir: rootDir,
}
err := filepath.Walk(rootDir, func(path string, info os.FileInfo, e error) error {
if info.IsDir() {
pkgs, err := packages.Load(c, path)
if err != nil {
log.Panicln(err)
}
if pkgs != nil {
for _, pkg := range pkgs {
log.Println(pkg.Name)
}
}
. . .
Yielded the following output:
2022/04/18 22:17:55
2022/04/18 22:17:55
2022/04/18 22:17:55 main
2022/04/18 22:17:55 main
2022/04/18 22:17:56 mypkg
2022/04/18 22:17:56 resolver
2022/04/18 22:17:56 testpkg
The blank package names represent the root directory (i.e. go-types) and an IDE-related directory (i.e. go-types/.idea).
Here is my directory structure just for reference:
go-types/
.idea/
[IDE-related files]
cmd/
change/
main.go
main.go
mpkg/
src.go
resolver/
exported.go
util.go
testpkg/
exported.go
Any help would be great! Let me know if there is any confusion!