简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM