Debian Codegraph @

gopls/internal/test/integration/fake/sandbox.go

raw symbols SCIP
1 // Copyright 2020 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 fake
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "os"
12 "path/filepath"
13 "strings"
14
15 "golang.org/x/tools/internal/gocommand"
16 "golang.org/x/tools/internal/robustio"
17 "golang.org/x/tools/txtar"
18 )
19
20 // Sandbox holds a collection of temporary resources to use for working with Go
21 // code in tests.
22 type Sandbox struct {
23 gopath string
24 rootdir string
25 goproxy string
26 Workdir *Workdir
27 goCommandRunner gocommand.Runner
28 }
29
30 // SandboxConfig controls the behavior of a test sandbox. The zero value
31 // defines a reasonable default.
32 type SandboxConfig struct {
33 // RootDir sets the base directory to use when creating temporary
34 // directories. If not specified, defaults to a new temporary directory.
35 RootDir string
36 // Files holds a txtar-encoded archive of files to populate the initial state
37 // of the working directory.
38 //
39 // For convenience, the special substring "$SANDBOX_WORKDIR" is replaced with
40 // the sandbox's resolved working directory before writing files.
41 Files map[string][]byte
42 // InGoPath specifies that the working directory should be within the
43 // temporary GOPATH.
44 InGoPath bool
45 // Workdir configures the working directory of the Sandbox. It behaves as
46 // follows:
47 // - if set to an absolute path, use that path as the working directory.
48 // - if set to a relative path, create and use that path relative to the
49 // sandbox.
50 // - if unset, default to a the 'work' subdirectory of the sandbox.
51 //
52 // This option is incompatible with InGoPath or Files.
53 Workdir string
54 // ProxyFiles holds a txtar-encoded archive of files to populate a file-based
55 // Go proxy.
56 ProxyFiles map[string][]byte
57 // GOPROXY is the explicit GOPROXY value that should be used for the sandbox.
58 //
59 // This option is incompatible with ProxyFiles.
60 GOPROXY string
61 }
62
63 // NewSandbox creates a collection of named temporary resources, with a
64 // working directory populated by the txtar-encoded content in srctxt, and a
65 // file-based module proxy populated with the txtar-encoded content in
66 // proxytxt.
67 //
68 // If rootDir is non-empty, it will be used as the root of temporary
69 // directories created for the sandbox. Otherwise, a new temporary directory
70 // will be used as root.
71 //
72 // TODO(rfindley): the sandbox abstraction doesn't seem to carry its weight.
73 // Sandboxes should be composed out of their building-blocks, rather than via a
74 // monolithic configuration.
75 func NewSandbox(config *SandboxConfig) (_ *Sandbox, err error) {
76 if config == nil {
77 config = new(SandboxConfig)
78 }
79 if err := validateConfig(*config); err != nil {
80 return nil, fmt.Errorf("invalid SandboxConfig: %v", err)
81 }
82
83 sb := &Sandbox{}
84 defer func() {
85 // Clean up if we fail at any point in this constructor.
86 if err != nil {
87 sb.Close() // ignore error
88 }
89 }()
90
91 rootDir := config.RootDir
92 if rootDir == "" {
93 rootDir, err = os.MkdirTemp(config.RootDir, "gopls-sandbox-")
94 if err != nil {
95 return nil, fmt.Errorf("creating temporary workdir: %v", err)
96 }
97 }
98 sb.rootdir = rootDir
99 sb.gopath = filepath.Join(sb.rootdir, "gopath")
100 if err := os.Mkdir(sb.gopath, 0755); err != nil {
101 return nil, err
102 }
103 if config.GOPROXY != "" {
104 sb.goproxy = config.GOPROXY
105 } else {
106 proxydir := filepath.Join(sb.rootdir, "proxy")
107 if err := os.Mkdir(proxydir, 0755); err != nil {
108 return nil, err
109 }
110 sb.goproxy, err = WriteProxy(proxydir, config.ProxyFiles)
111 if err != nil {
112 return nil, err
113 }
114 }
115 // Short-circuit writing the workdir if we're given an absolute path, since
116 // this is used for running in an existing directory.
117 // TODO(findleyr): refactor this to be less of a workaround.
118 if filepath.IsAbs(config.Workdir) {
119 sb.Workdir, err = NewWorkdir(config.Workdir, nil)
120 if err != nil {
121 return nil, err
122 }
123 return sb, nil
124 }
125 var workdir string
126 if config.Workdir == "" {
127 if config.InGoPath {
128 // Set the working directory as $GOPATH/src.
129 workdir = filepath.Join(sb.gopath, "src")
130 } else if workdir == "" {
131 workdir = filepath.Join(sb.rootdir, "work")
132 }
133 } else {
134 // relative path
135 workdir = filepath.Join(sb.rootdir, config.Workdir)
136 }
137 if err := os.MkdirAll(workdir, 0755); err != nil {
138 return nil, err
139 }
140 sb.Workdir, err = NewWorkdir(workdir, config.Files)
141 if err != nil {
142 return nil, err
143 }
144 return sb, nil
145 }
146
147 func UnpackTxt(txt string) map[string][]byte {
148 dataMap := make(map[string][]byte)
149 archive := txtar.Parse([]byte(txt))
150 for _, f := range archive.Files {
151 if _, ok := dataMap[f.Name]; ok {
152 panic(fmt.Sprintf("found file %q twice", f.Name))
153 }
154 dataMap[f.Name] = f.Data
155 }
156 return dataMap
157 }
158
159 func validateConfig(config SandboxConfig) error {
160 if filepath.IsAbs(config.Workdir) && (len(config.Files) > 0 || config.InGoPath) {
161 return errors.New("absolute Workdir cannot be set in conjunction with Files or InGoPath")
162 }
163 if config.Workdir != "" && config.InGoPath {
164 return errors.New("Workdir cannot be set in conjunction with InGoPath")
165 }
166 if config.GOPROXY != "" && config.ProxyFiles != nil {
167 return errors.New("GOPROXY cannot be set in conjunction with ProxyFiles")
168 }
169 return nil
170 }
171
172 // splitModuleVersionPath extracts module information from files stored in the
173 // directory structure modulePath@version/suffix.
174 // For example:
175 //
176 // splitModuleVersionPath("[email protected]/package") = ("mod.com", "v1.2.3", "package")
177 func splitModuleVersionPath(path string) (modulePath, version, suffix string) {
178 parts := strings.Split(path, "/")
179 var modulePathParts []string
180 for i, p := range parts {
181 if strings.Contains(p, "@") {
182 mv := strings.SplitN(p, "@", 2)
183 modulePathParts = append(modulePathParts, mv[0])
184 return strings.Join(modulePathParts, "/"), mv[1], strings.Join(parts[i+1:], "/")
185 }
186 modulePathParts = append(modulePathParts, p)
187 }
188 // Default behavior: this is just a module path.
189 return path, "", ""
190 }
191
192 func (sb *Sandbox) RootDir() string {
193 return sb.rootdir
194 }
195
196 // GOPATH returns the value of the Sandbox GOPATH.
197 func (sb *Sandbox) GOPATH() string {
198 return sb.gopath
199 }
200
201 // GoEnv returns the default environment variables that can be used for
202 // invoking Go commands in the sandbox.
203 func (sb *Sandbox) GoEnv() map[string]string {
204 return map[string]string{
205 "GOPATH": sb.GOPATH(),
206 "GOPROXY": sb.goproxy,
207 "GO111MODULE": "",
208 "GOSUMDB": "off",
209 "GOPACKAGESDRIVER": "off",
210 "GOTOOLCHAIN": "local", // tests should not download toolchains
211 // TODO(golang/go#74595): Why don't we respect GOMODCACHE in the
212 // settings.env? See comment at env.CleanModCache.
213 "GOMODCACHE": "",
214 }
215 }
216
217 // goCommandInvocation returns a new gocommand.Invocation initialized with the
218 // sandbox environment variables and working directory.
219 func (sb *Sandbox) goCommandInvocation() gocommand.Invocation {
220 var vars []string
221 for k, v := range sb.GoEnv() {
222 vars = append(vars, fmt.Sprintf("%s=%s", k, v))
223 }
224 inv := gocommand.Invocation{
225 Env: vars,
226 }
227 // sb.Workdir may be nil if we exited the constructor with errors (we call
228 // Close to clean up any partial state from the constructor, which calls
229 // RunGoCommand).
230 if sb.Workdir != nil {
231 inv.WorkingDir = string(sb.Workdir.RelativeTo)
232 }
233 return inv
234 }
235
236 // RunGoCommand executes a go command in the sandbox and returns its standard
237 // output. If checkForFileChanges is true, the sandbox scans the working
238 // directory and emits file change events for any file changes it finds.
239 func (sb *Sandbox) RunGoCommand(ctx context.Context, dir, verb string, args, env []string, checkForFileChanges bool) ([]byte, error) {
240 inv := sb.goCommandInvocation()
241 inv.Verb = verb
242 inv.Args = args
243 inv.Env = append(inv.Env, env...)
244 if dir != "" {
245 inv.WorkingDir = sb.Workdir.AbsPath(dir)
246 }
247 stdout, stderr, _, err := sb.goCommandRunner.RunRaw(ctx, inv)
248 if err != nil {
249 return nil, fmt.Errorf("go command failed (stdout: %s) (stderr: %s): %v", stdout.String(), stderr.String(), err)
250 }
251 // Since running a go command may result in changes to workspace files,
252 // check if we need to send any "watched" file events.
253 //
254 // TODO(rFindley): this side-effect can impact the usability of the sandbox
255 // for benchmarks. Consider refactoring.
256 if sb.Workdir != nil && checkForFileChanges {
257 if err := sb.Workdir.CheckForFileChanges(ctx); err != nil {
258 return nil, fmt.Errorf("checking for file changes: %w", err)
259 }
260 }
261 return stdout.Bytes(), nil
262 }
263
264 // GoVersion checks the version of the go command.
265 // It returns the X in Go 1.X.
266 func (sb *Sandbox) GoVersion(ctx context.Context) (int, error) {
267 inv := sb.goCommandInvocation()
268 return gocommand.GoVersion(ctx, inv, &sb.goCommandRunner)
269 }
270
271 // Close removes all state associated with the sandbox.
272 func (sb *Sandbox) Close() error {
273 var goCleanErr error
274 // Careful: sb may not be fully initialized.
275 if sb.gopath != "" && sb.Workdir != nil {
276 // Important: run this command in RootDir so that it doesn't interact with
277 // any toolchain downloads that may occur
278 _, goCleanErr = sb.RunGoCommand(context.Background(), sb.RootDir(), "clean", []string{"-modcache"}, nil, false)
279 }
280 err := robustio.RemoveAll(sb.rootdir)
281 if err != nil || goCleanErr != nil {
282 return fmt.Errorf("error(s) cleaning sandbox: cleaning modcache: %v; removing files: %v", goCleanErr, err)
283 }
284 return nil
285 }