Debian Codegraph @

gotooltest/setup.go

raw symbols SCIP
1 // Copyright 2015 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 gotooltest implements functionality useful for testing
6 // tools that use the go command.
7 package gotooltest
8
9 import (
10 "bytes"
11 "fmt"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "regexp"
16 "runtime"
17 "strings"
18 "sync"
19
20 "github.com/rogpeppe/go-internal/internal/goenv"
21 "github.com/rogpeppe/go-internal/testscript"
22 )
23
24 var (
25 goVersionRegex = regexp.MustCompile(`^go([1-9][0-9]*)\.([1-9][0-9]*)$`)
26
27 goEnv struct {
28 GOROOT string
29 GOCACHE string
30 GOPROXY string
31 goversion string
32 releaseTags []string
33 once sync.Once
34 err error
35 }
36 )
37
38 // initGoEnv initialises goEnv. It should only be called using goEnv.once.Do,
39 // as in Setup.
40 //
41 // Run all of these probe commands in a temporary directory, so as not to make
42 // any assumptions about the caller's working directory.
43 func initGoEnv() (err error) {
44 td, err := os.MkdirTemp("", "gotooltest-initGoEnv")
45 if err != nil {
46 return fmt.Errorf("failed to create temporary directory for go command tests: %w", err)
47 }
48 defer func() {
49 if rerr := os.RemoveAll(td); rerr != nil && err == nil {
50 err = fmt.Errorf("failed to remove temporary directory for go command tests: %w", rerr)
51 }
52 }()
53
54 // Write a temporary go.mod file in td. This ensures that we create
55 // a porcelain environment in which to run these probe commands.
56 if err := os.WriteFile(filepath.Join(td, "go.mod"), []byte("module gotooltest"), 0600); err != nil {
57 return fmt.Errorf("failed to write temporary go.mod file: %w", err)
58 }
59
60 run := func(args ...string) (*bytes.Buffer, *bytes.Buffer, error) {
61 var stdout, stderr bytes.Buffer
62 cmd := exec.Command(args[0], args[1:]...)
63 cmd.Dir = td
64 cmd.Stdout = &stdout
65 cmd.Stderr = &stderr
66 return &stdout, &stderr, cmd.Run()
67 }
68
69 lout, stderr, err := run("go", "list", "-f={{context.ReleaseTags}}", "runtime")
70 if err != nil {
71 return fmt.Errorf("failed to determine release tags from go command: %v\n%v", err, stderr.String())
72 }
73 tagStr := strings.TrimSpace(lout.String())
74 tagStr = strings.Trim(tagStr, "[]")
75 goEnv.releaseTags = strings.Split(tagStr, " ")
76
77 if err := goenv.Unmarshal(&goEnv); err != nil {
78 return err
79 }
80 version := goEnv.releaseTags[len(goEnv.releaseTags)-1]
81 if !goVersionRegex.MatchString(version) {
82 return fmt.Errorf("invalid go version %q", version)
83 }
84 goEnv.goversion = version[2:]
85
86 return nil
87 }
88
89 // Setup sets up the given test environment for tests that use the go
90 // command. It adds support for go tags to p.Condition and adds the go
91 // command to p.Cmds. It also wraps p.Setup to set up the environment
92 // variables for running the go command appropriately.
93 //
94 // It checks go command can run, but not that it can build or run
95 // binaries.
96 func Setup(p *testscript.Params) error {
97 goEnv.once.Do(func() {
98 goEnv.err = initGoEnv()
99 })
100 if goEnv.err != nil {
101 return goEnv.err
102 }
103
104 origSetup := p.Setup
105 p.Setup = func(e *testscript.Env) error {
106 e.Vars = goEnviron(e.Vars)
107 if origSetup != nil {
108 return origSetup(e)
109 }
110 return nil
111 }
112 if p.Cmds == nil {
113 p.Cmds = make(map[string]func(ts *testscript.TestScript, neg bool, args []string))
114 }
115 p.Cmds["go"] = cmdGo
116 return nil
117 }
118
119 func goEnviron(env0 []string) []string {
120 env := environ(env0)
121 workdir := env.get("WORK")
122 return append(env, []string{
123 "GOPATH=" + filepath.Join(workdir, ".gopath"),
124 "CCACHE_DISABLE=1", // ccache breaks with non-existent HOME
125 "GOARCH=" + runtime.GOARCH,
126 "GOOS=" + runtime.GOOS,
127 "GOROOT=" + goEnv.GOROOT,
128 "GOCACHE=" + goEnv.GOCACHE,
129 "GOPROXY=" + goEnv.GOPROXY,
130 "goversion=" + goEnv.goversion,
131 }...)
132 }
133
134 func cmdGo(ts *testscript.TestScript, neg bool, args []string) {
135 if len(args) < 1 {
136 ts.Fatalf("usage: go subcommand ...")
137 }
138 err := ts.Exec("go", args...)
139 if err != nil {
140 ts.Logf("[%v]\n", err)
141 if !neg {
142 ts.Fatalf("unexpected go command failure")
143 }
144 } else {
145 if neg {
146 ts.Fatalf("unexpected go command success")
147 }
148 }
149 }
150
151 type environ []string
152
153 func (e0 *environ) get(name string) string {
154 e := *e0
155 for i := len(e) - 1; i >= 0; i-- {
156 v := e[i]
157 if len(v) <= len(name) {
158 continue
159 }
160 if strings.HasPrefix(v, name) && v[len(name)] == '=' {
161 return v[len(name)+1:]
162 }
163 }
164 return ""
165 }