How to list all non-standard/custom packages in Go?

602 Views Asked by At

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.

1

There are 1 best solutions below

2
On BEST ANSWER

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/...).