Debian Codegraph @

internal/goenv/goenv.go

raw symbols SCIP
1 // goenv is used by various testscript-related package to avoid
2 // invoking `go env` multiple times independently
3 // when a single execution is sufficient.
4 package goenv
5
6 import (
7 "bytes"
8 "encoding/json"
9 "fmt"
10 "os/exec"
11 "sync"
12 )
13
14 // Unmarshal JSON-unmarshals the result of `go env -json` into the value pointed
15 // to by dst.
16 func Unmarshal(dst any) error {
17 data, err := goEnv()
18 if err != nil {
19 return err
20 }
21 if err := json.Unmarshal(data, dst); err != nil {
22 return fmt.Errorf("failed to unmarshal environment from go command out: %v\n%s", err, data)
23 }
24 return nil
25 }
26
27 var goEnv = sync.OnceValues(func() ([]byte, error) {
28 var stdout, stderr bytes.Buffer
29 // Note: we explicitly mention all the variables that
30 // any of the callers of goenv might need to avoid
31 // fetching any of the variables that are costly to calculate.
32 cmd := exec.Command("go", "env", "-json",
33 "GOCACHE",
34 "GOMODCACHE",
35 "GONOPROXY",
36 "GOPROXY",
37 "GOROOT",
38 )
39 cmd.Stdout = &stdout
40 cmd.Stderr = &stderr
41 if err := cmd.Run(); err != nil {
42 return nil, fmt.Errorf("failed to determine environment from go command: %v\n%v", err, &stderr)
43 }
44 return stdout.Bytes(), nil
45 })