| 1 | // Copyright 2022 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package goroot is a copy of package internal/goroot |
| 6 | // in the main GO repot. It provides a utility to produce |
| 7 | // an import path to package file map mapping |
| 8 | // standard library packages to the locations of their export |
| 9 | // data files. |
| 10 | package goroot |
| 11 | |
| 12 | import ( |
| 13 | "fmt" |
| 14 | "os/exec" |
| 15 | "strings" |
| 16 | "sync" |
| 17 | ) |
| 18 | |
| 19 | // PkgfileMap returns a map of package paths to the location on disk |
| 20 | // of the .a file for the package. |
| 21 | // The caller must not modify the map. |
| 22 | func PkgfileMap() (map[string]string, error) { |
| 23 | return pkgFileMapOnce() |
| 24 | } |
| 25 | |
| 26 | var pkgFileMapOnce = sync.OnceValues(func() (map[string]string, error) { |
| 27 | m := make(map[string]string) |
| 28 | output, err := exec.Command("go", "list", "-export", "-e", "-f", "{{.ImportPath}} {{.Export}}", "std", "cmd").Output() |
| 29 | if err != nil { |
| 30 | return m, err |
| 31 | } |
| 32 | for line := range strings.SplitSeq(string(output), "\n") { |
| 33 | if line == "" { |
| 34 | continue |
| 35 | } |
| 36 | sp := strings.SplitN(line, " ", 2) |
| 37 | if len(sp) != 2 { |
| 38 | return m, fmt.Errorf("determining pkgfile map: invalid line in go list output: %q", line) |
| 39 | } |
| 40 | importPath, export := sp[0], sp[1] |
| 41 | if export != "" { |
| 42 | m[importPath] = export |
| 43 | } |
| 44 | } |
| 45 | return m, nil |
| 46 | }) |