Serge Bazanski | 8bd2ab1 | 2021-12-17 17:32:16 +0100 | [diff] [blame^] | 1 | // This tool generates //build/analysis/lib:stdlib_packages.go, which contains a |
| 2 | // set of all Go stdlib packges. This is generated ahead of time in the build |
| 3 | // system as it can be an expensive operation that also depends on the presence |
| 4 | // of a working `go` tool environment, so we want to do this as rarely as |
| 5 | // possible. |
| 6 | package main |
| 7 | |
| 8 | import ( |
| 9 | "fmt" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "sort" |
| 13 | "strings" |
| 14 | |
| 15 | "golang.org/x/tools/go/packages" |
| 16 | |
| 17 | "source.monogon.dev/build/toolbase/gotoolchain" |
| 18 | ) |
| 19 | |
| 20 | func main() { |
| 21 | os.Setenv("PATH", filepath.Dir(gotoolchain.Go)) |
| 22 | |
| 23 | gocache, err := os.MkdirTemp("/tmp", "gocache") |
| 24 | if err != nil { |
| 25 | panic(err) |
| 26 | } |
| 27 | defer os.RemoveAll(gocache) |
| 28 | |
| 29 | gopath, err := os.MkdirTemp("/tmp", "gopath") |
| 30 | if err != nil { |
| 31 | panic(err) |
| 32 | } |
| 33 | defer os.RemoveAll(gopath) |
| 34 | |
| 35 | os.Setenv("GOCACHE", gocache) |
| 36 | os.Setenv("GOPATH", gopath) |
| 37 | |
| 38 | pkgs, err := packages.Load(nil, "std") |
| 39 | if err != nil { |
| 40 | panic(err) |
| 41 | } |
| 42 | sort.Slice(pkgs, func(i, j int) bool { return pkgs[i].PkgPath < pkgs[j].PkgPath }) |
| 43 | |
| 44 | if len(os.Args) != 2 { |
| 45 | panic("must be called with output file name") |
| 46 | } |
| 47 | |
| 48 | out, err := os.Create(os.Args[1]) |
| 49 | if err != nil { |
| 50 | panic(err) |
| 51 | } |
| 52 | defer out.Close() |
| 53 | |
| 54 | fmt.Fprintf(out, "// Code generated by //build/analysis/lib/genstd. DO NOT EDIT.\n") |
| 55 | fmt.Fprintf(out, "package lib\n\n") |
| 56 | fmt.Fprintf(out, "// StdlibPackages is a set of all package paths that are part of the Go standard\n") |
| 57 | fmt.Fprintf(out, "// library.\n") |
| 58 | fmt.Fprintf(out, "var StdlibPackages = map[string]bool{\n") |
| 59 | for _, pkg := range pkgs { |
| 60 | path := pkg.PkgPath |
| 61 | if strings.Contains(path, "/internal/") { |
| 62 | continue |
| 63 | } |
| 64 | if strings.HasPrefix(path, "vendor/") { |
| 65 | continue |
| 66 | } |
| 67 | fmt.Fprintf(out, "\t%q: true,\n", pkg.PkgPath) |
| 68 | } |
| 69 | fmt.Fprintf(out, "}\n") |
| 70 | } |