0

As mentioned here one can get all the standard Go packages using https://godoc.org/golang.org/x/tools/go/packages 's Load() function in which one can give "pattern" as input.

pkgs, err := packages.Load(nil, pattern)

For example, if pattern = "std" then it returns all the standard packages.

But, if I want to get a list of custom/user-defined packages having custom patterns such as only the vendor folders of the form github.com/X/Y/vendor/... then how exactly I can specify the pattern?

I have tried using /vendor/, github.com/X/Y/vendor/ and some other combinations as pattern in the Load() function. None of them have worked.

Satyajit Das
  • 2,740
  • 5
  • 16
  • 30

1 Answers1

1

You can use the ... syntax in pattern field of the Load() function.

Example

My Go module requires github.com/hashicorp/go-multierror package :

module mymodule

require github.com/hashicorp/go-multierror v1.0.0

So, the following code :

package main

import (
    "fmt"
    "golang.org/x/tools/go/packages"
)

func main() {
    pkgs, err := packages.Load(nil, "github.com/hashicorp...")
    if err == nil {
        for _, pkg := range pkgs {
            fmt.Println(pkg.ID)
        }
    }
}

returns all the required packages starting with github.com/hashicorp (even transitive ones) :

github.com/hashicorp/errwrap
github.com/hashicorp/go-multierror

Note that you can also use ... anywhere in your pattern (...hashicorp..., ...ha...corp..., github.com/...).

norbjd
  • 10,166
  • 4
  • 45
  • 80
  • Thanks @norbjd! It turned out I had tried all combinations except the `...` ones which I mentioned in the question itself. :| BTW when I use `...vendor...` I don't get expected results. But I do get expected results for all other combinations like `...X...`. Is it the case for you as well? What's so special about `vendor`? – Satyajit Das Oct 21 '19 at 11:11
  • 1
    If you are talking about `vendor` directory (generated by `go mod vendor`), it is not a package itself, it is just a directory with a local copy of all your external dependencies. – norbjd Oct 22 '19 at 10:32