Can I list all standard Go packages?
Asked Answered
S

3

203

Is there a way in Go to list all the standard/built-in packages (i.e., the packages which come installed with a Go installation)?

I have a list of packages and I want to figure out which packages are standard.

Supernumerary answered 23/4, 2019 at 8:41 Comment(6)
Default Go packages golang.org/pkgToshikotoss
Is there a function like isStandardPackage(importPath string) bool which i can use?Supernumerary
can this be used? golang.org/pkg/cmd/go/internal/list ?Supernumerary
I think list to show you all install packages.Toshikotoss
what are you trying to achieve here? An import statement without a . is either an internal package of your own or a part of the standard library.Stokehole
We were trying to organize code in kubernetes. We need a easy way to figure out in one of the scripts if this a standard package and can be ignored for analysis.Supernumerary
O
57

You can use the new golang.org/x/tools/go/packages for this. This provides a programmatic interface for most of go list:

package main

import (
    "fmt"

    "golang.org/x/tools/go/packages"
)

func main() {
    pkgs, err := packages.Load(nil, "std")
    if err != nil {
        panic(err)
    }

    fmt.Println(pkgs)
    // Output: [archive/tar archive/zip bufio bytes compress/bzip2 ... ]
}

To get a isStandardPackage() you can store it in a map, like so:

package main

import (
    "fmt"

    "golang.org/x/tools/go/packages"
)

var standardPackages = make(map[string]struct{})

func init() {
    pkgs, err := packages.Load(nil, "std")
    if err != nil {
        panic(err)
    }

    for _, p := range pkgs {
        standardPackages[p.PkgPath] = struct{}{}
    }
}

func isStandardPackage(pkg string) bool {
    _, ok := standardPackages[pkg]
    return ok
}

func main() {
    fmt.Println(isStandardPackage("fmt"))  // true
    fmt.Println(isStandardPackage("nope")) // false
}
Olmos answered 18/5, 2019 at 13:5 Comment(2)
Immediately searched where does ok come from and found this nice article. reddit.com/r/golang/comments/35d0b2/about_the_comma_ok_idiomAkerboom
The packages.Load(nil, "std") call executes the go list command and parses the output. I note this for others who might also make the incorrect assumption that the package provides the command implementation.Perky
C
40

Use the go list std command to list the standard packages. The special import path std expands to all packages in the standard Go library (doc).

Exec that command to get the list in a Go program:

cmd := exec.Command("go", "list", "std")
p, err := cmd.Output()
if err != nil {
    // handle error
}
stdPkgs = strings.Fields(string(p))
Cresa answered 23/4, 2019 at 18:46 Comment(0)
B
3

If you want a simple solution, you could check if a package is present in $GOROOT/pkg. All standard packages are installed here.

Buie answered 23/4, 2019 at 13:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.