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