3

I need to check if some packages are installed but I need to do that using code, not go list tool in shell. I found a solution but it's very slow (2-3 seconds). This is my current code:

out, err := exec.Command("sh", "-c", "go list all").Output()
if err != nil {
    output := strings.Split(string(out), "\n")
    for _, value := range output {
        if value == "github.com/some/package" {
            // package is installed
        }
    }
}
Alen
  • 1,750
  • 7
  • 31
  • 62

1 Answers1

8

So basically you answered your own question. You want a faster solution? Try "tuning" the go list command.

To check the existence of a single package, you may pass that single package to go list, and if it exists, it will output it, else the output will be an error message.

For example, executing

go list github.com/some/package

If github.com/some/package exists, output will be:

github.com/some/package

You can also pass multiple packages to go list:

go list github.com/some/package github.com/other/package

And output will be:

github.com/some/package
github.com/other/package

If the passed package doesn't exist, output will be something like:

can't load package: package github.com/some/package: cannot find package "github.com/some/package" in any of:
    /usr/local/go/src/github.com/some/package (from $GOROOT)
    <GOPATH-here>/src/github.com/some/package (from $GOPATH)

Also note that if the package you pass does not contain *.go files, you get a different message:

can't load package: package github.com/some/package: no buildable Go source files in <GOPATH-here>/src/github.com/some/package

If you expect some package inside it, append the ...:

go list github.com/some/package/...

For more options and possibilities, run go help list, and see related question: How to list installed go packages

Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827