How to use "pattern" argument in golang.org/x/tools/go/packages package

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!

Which output did you expect for your test ?

Thanks for replying! I believe I may have found a solution to my problem. Regarding my expected output, further observation has now made me believe that the given output should be the expected behavior.

I was mainly concerned with finding a pattern such that I don’t have to walk the file tree via filepath.Walk(...). After scouring the docs I discovered all I was missing while using the wildcard was a slash at the end (e.g. /path/to/working/dir/… instead of /path/to/working/dir…). Using this I was able to get the following output:

2022/04/19 09:20:45 resolver
2022/04/19 09:20:45 main
2022/04/19 09:20:45 main
2022/04/19 09:20:45 testpkg
2022/04/19 09:20:45 mypkg

Essentially the same as my the output from above, where directories with no Go files seem to be not included.

Source of example I found using the pattern correctly: Go Modules Reference - The Go Programming Language

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.