Debian Codegraph @

gopls/internal/test/integration/fake/workdir.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 "bytes"
9 "context"
10 "crypto/sha256"
11 "fmt"
12 "io/fs"
13 "os"
14 "path/filepath"
15 "runtime"
16 "slices"
17 "sort"
18 "strings"
19 "sync"
20 "time"
21
22 "golang.org/x/tools/gopls/internal/protocol"
23 "golang.org/x/tools/internal/robustio"
24 )
25
26 // RelativeTo is a helper for operations relative to a given directory.
27 type RelativeTo string
28
29 // AbsPath returns an absolute filesystem path for the workdir-relative path.
30 func (r RelativeTo) AbsPath(path string) string {
31 fp := filepath.FromSlash(path)
32 if filepath.IsAbs(fp) {
33 return fp
34 }
35 return filepath.Join(string(r), filepath.FromSlash(path))
36 }
37
38 // RelPath returns a '/'-encoded path relative to the working directory (or an
39 // absolute path if the file is outside of workdir)
40 func (r RelativeTo) RelPath(fp string) string {
41 root := string(r)
42 if rel, err := filepath.Rel(root, fp); err == nil && !strings.HasPrefix(rel, "..") {
43 return filepath.ToSlash(rel)
44 }
45 return filepath.ToSlash(fp)
46 }
47
48 // writeFileData writes content to the relative path, replacing the special
49 // token $SANDBOX_WORKDIR with the relative root given by rel. It does not
50 // trigger any file events.
51 func writeFileData(path string, content []byte, rel RelativeTo) error {
52 content = bytes.ReplaceAll(content, []byte("$SANDBOX_WORKDIR"), []byte(rel))
53 fp := rel.AbsPath(path)
54 if err := os.MkdirAll(filepath.Dir(fp), 0755); err != nil {
55 return fmt.Errorf("creating nested directory: %w", err)
56 }
57 backoff := 1 * time.Millisecond
58 for {
59 err := os.WriteFile(fp, content, 0644)
60 if err != nil {
61 // This lock file violation is not handled by the robustio package, as it
62 // indicates a real race condition that could be avoided.
63 if isWindowsErrLockViolation(err) {
64 time.Sleep(backoff)
65 backoff *= 2
66 continue
67 }
68 return fmt.Errorf("writing %q: %w", path, err)
69 }
70 return nil
71 }
72 }
73
74 // isWindowsErrLockViolation reports whether err is ERROR_LOCK_VIOLATION
75 // on Windows.
76 var isWindowsErrLockViolation = func(error) bool { return false }
77
78 // Workdir is a temporary working directory for tests. It exposes file
79 // operations in terms of relative paths, and fakes file watching by triggering
80 // events on file operations.
81 type Workdir struct {
82 RelativeTo
83
84 watcherMu sync.Mutex
85 watchers []func(context.Context, []protocol.FileEvent)
86
87 fileMu sync.Mutex
88 // File identities we know about, for the purpose of detecting changes.
89 //
90 // Since files is only used for detecting _changes_, we are tolerant of
91 // fileIDs that may have hash and mtime coming from different states of the
92 // file: if either are out of sync, then the next poll should detect a
93 // discrepancy. It is OK if we detect too many changes, but not OK if we miss
94 // changes.
95 //
96 // For that matter, this mechanism for detecting changes can still be flaky
97 // on platforms where mtime is very coarse (such as older versions of WSL).
98 // It would be much better to use a proper fs event library, but we can't
99 // currently import those into x/tools.
100 //
101 // TODO(golang/go#52284): replace this polling mechanism with a
102 // cross-platform library for filesystem notifications.
103 files map[string]fileID
104 }
105
106 // NewWorkdir writes the txtar-encoded file data in txt to dir, and returns a
107 // Workdir for operating on these files using relative paths.
108 func NewWorkdir(dir string, files map[string][]byte) (*Workdir, error) {
109 w := &Workdir{RelativeTo: RelativeTo(dir)}
110 for name, data := range files {
111 if err := writeFileData(name, data, w.RelativeTo); err != nil {
112 return nil, fmt.Errorf("writing to workdir: %w", err)
113 }
114 }
115 _, err := w.pollFiles() // poll files to populate the files map.
116 return w, err
117 }
118
119 // fileID identifies a file version on disk.
120 type fileID struct {
121 mtime time.Time
122 hash string // empty if mtime is old enough to be reliable; otherwise a file digest
123 }
124
125 func hashFile(data []byte) string {
126 return fmt.Sprintf("%x", sha256.Sum256(data))
127 }
128
129 // RootURI returns the root URI for this working directory of this scratch
130 // environment.
131 func (w *Workdir) RootURI() protocol.DocumentURI {
132 return protocol.URIFromPath(string(w.RelativeTo))
133 }
134
135 // AddWatcher registers the given func to be called on any file change.
136 func (w *Workdir) AddWatcher(watcher func(context.Context, []protocol.FileEvent)) {
137 w.watcherMu.Lock()
138 w.watchers = append(w.watchers, watcher)
139 w.watcherMu.Unlock()
140 }
141
142 // URI returns the URI to a the workdir-relative path.
143 func (w *Workdir) URI(path string) protocol.DocumentURI {
144 return protocol.URIFromPath(w.AbsPath(path))
145 }
146
147 // URIToPath converts a uri to a workdir-relative path (or an absolute path,
148 // if the uri is outside of the workdir).
149 func (w *Workdir) URIToPath(uri protocol.DocumentURI) string {
150 return w.RelPath(uri.Path())
151 }
152
153 // EntireFile returns the entire extent of the file named by the workdir-relative path.
154 func (w *Workdir) EntireFile(path string) protocol.Location {
155 return protocol.Location{URI: w.URI(path)}
156 }
157
158 // ReadFile reads a text file specified by a workdir-relative path.
159 func (w *Workdir) ReadFile(path string) ([]byte, error) {
160 backoff := 1 * time.Millisecond
161 for {
162 b, err := os.ReadFile(w.AbsPath(path))
163 if err != nil {
164 if runtime.GOOS == "plan9" && strings.HasSuffix(err.Error(), " exclusive use file already open") {
165 // Plan 9 enforces exclusive access to locked files.
166 // Give the owner time to unlock it and retry.
167 time.Sleep(backoff)
168 backoff *= 2
169 continue
170 }
171 return nil, err
172 }
173 return b, nil
174 }
175 }
176
177 // RegexpSearch searches the file corresponding to path for the first position
178 // matching re.
179 func (w *Workdir) RegexpSearch(path string, re string) (protocol.Location, error) {
180 content, err := w.ReadFile(path)
181 if err != nil {
182 return protocol.Location{}, err
183 }
184 mapper := protocol.NewMapper(w.URI(path), content)
185 return regexpLocation(mapper, re)
186 }
187
188 // RemoveFile removes a workdir-relative file path and notifies watchers of the
189 // change.
190 func (w *Workdir) RemoveFile(ctx context.Context, path string) error {
191 fp := w.AbsPath(path)
192 if err := robustio.RemoveAll(fp); err != nil {
193 return fmt.Errorf("removing %q: %w", path, err)
194 }
195
196 return w.CheckForFileChanges(ctx)
197 }
198
199 // WriteFiles writes the text file content to workdir-relative paths and
200 // notifies watchers of the changes.
201 func (w *Workdir) WriteFiles(ctx context.Context, files map[string]string) error {
202 for path, content := range files {
203 fp := w.AbsPath(path)
204 _, err := os.Stat(fp)
205 if err != nil && !os.IsNotExist(err) {
206 return fmt.Errorf("checking if %q exists: %w", path, err)
207 }
208 if err := writeFileData(path, []byte(content), w.RelativeTo); err != nil {
209 return err
210 }
211 }
212 return w.CheckForFileChanges(ctx)
213 }
214
215 // WriteFile writes text file content to a workdir-relative path and notifies
216 // watchers of the change.
217 func (w *Workdir) WriteFile(ctx context.Context, path, content string) error {
218 return w.WriteFiles(ctx, map[string]string{path: content})
219 }
220
221 // RenameFile performs an on disk-renaming of the workdir-relative oldPath to
222 // workdir-relative newPath, and notifies watchers of the changes.
223 //
224 // oldPath must either be a regular file or in the same directory as newPath.
225 func (w *Workdir) RenameFile(ctx context.Context, oldPath, newPath string) error {
226 oldAbs := w.AbsPath(oldPath)
227 newAbs := w.AbsPath(newPath)
228
229 // For os.Rename, “OS-specific restrictions may apply when oldpath and newpath
230 // are in different directories.” If that applies here, we may fall back to
231 // ReadFile, WriteFile, and RemoveFile to perform the rename non-atomically.
232 //
233 // However, the fallback path only works for regular files: renaming a
234 // directory would be much more complex and isn't needed for our tests.
235 fallbackOk := false
236 if filepath.Dir(oldAbs) != filepath.Dir(newAbs) {
237 fi, err := os.Stat(oldAbs)
238 if err == nil && !fi.Mode().IsRegular() {
239 return &os.PathError{
240 Op: "RenameFile",
241 Path: oldPath,
242 Err: fmt.Errorf("%w: file is not regular and not in the same directory as %s", os.ErrInvalid, newPath),
243 }
244 }
245 fallbackOk = true
246 }
247
248 var renameErr error
249 const debugFallback = false
250 if fallbackOk && debugFallback {
251 renameErr = fmt.Errorf("%w: debugging fallback path", os.ErrInvalid)
252 } else {
253 renameErr = robustio.Rename(oldAbs, newAbs)
254 }
255 if renameErr != nil {
256 if !fallbackOk {
257 return renameErr // The OS-specific Rename restrictions do not apply.
258 }
259
260 content, err := w.ReadFile(oldPath)
261 if err != nil {
262 // If we can't even read the file, the error from Rename may be accurate.
263 return renameErr
264 }
265 fi, err := os.Stat(newAbs)
266 if err == nil {
267 if fi.IsDir() {
268 // “If newpath already exists and is not a directory, Rename replaces it.”
269 // But if it is a directory, maybe not?
270 return renameErr
271 }
272 // On most platforms, Rename replaces the named file with a new file,
273 // rather than overwriting the existing file it in place. Mimic that
274 // behavior here.
275 if err := robustio.RemoveAll(newAbs); err != nil {
276 // Maybe we don't have permission to replace newPath?
277 return renameErr
278 }
279 } else if !os.IsNotExist(err) {
280 // If the destination path already exists or there is some problem with it,
281 // the error from Rename may be accurate.
282 return renameErr
283 }
284 if writeErr := writeFileData(newPath, content, w.RelativeTo); writeErr != nil {
285 // At this point we have tried to actually write the file.
286 // If it still doesn't exist, assume that the error from Rename was accurate:
287 // for example, maybe we don't have permission to create the new path.
288 // Otherwise, return the error from the write, which may indicate some
289 // other problem (such as a full disk).
290 if _, statErr := os.Stat(newAbs); !os.IsNotExist(statErr) {
291 return writeErr
292 }
293 return renameErr
294 }
295 if err := robustio.RemoveAll(oldAbs); err != nil {
296 // If we failed to remove the old file, that may explain the Rename error too.
297 // Make a best effort to back out the write to the new path.
298 robustio.RemoveAll(newAbs) // ignore error
299 return renameErr
300 }
301 }
302
303 return w.CheckForFileChanges(ctx)
304 }
305
306 // ListFiles returns a new sorted list of the relative paths of files in dir,
307 // recursively.
308 func (w *Workdir) ListFiles(dir string) ([]string, error) {
309 absDir := w.AbsPath(dir)
310 var paths []string
311 if err := filepath.Walk(absDir, func(fp string, info os.FileInfo, err error) error {
312 if err != nil {
313 return err
314 }
315 if info.Mode()&(fs.ModeDir|fs.ModeSymlink) == 0 {
316 paths = append(paths, w.RelPath(fp))
317 }
318 return nil
319 }); err != nil {
320 return nil, err
321 }
322 sort.Strings(paths)
323 return paths, nil
324 }
325
326 // CheckForFileChanges walks the working directory and checks for any files
327 // that have changed since the last poll.
328 func (w *Workdir) CheckForFileChanges(ctx context.Context) error {
329 evts, err := w.pollFiles()
330 if err != nil {
331 return err
332 }
333 if len(evts) == 0 {
334 return nil
335 }
336 w.watcherMu.Lock()
337 watchers := slices.Clone(w.watchers)
338 w.watcherMu.Unlock()
339 for _, w := range watchers {
340 w(ctx, evts)
341 }
342 return nil
343 }
344
345 // pollFiles updates w.files and calculates FileEvents corresponding to file
346 // state changes since the last poll. It does not call sendEvents.
347 func (w *Workdir) pollFiles() ([]protocol.FileEvent, error) {
348 w.fileMu.Lock()
349 defer w.fileMu.Unlock()
350
351 newFiles := make(map[string]fileID)
352 var evts []protocol.FileEvent
353 if err := filepath.Walk(string(w.RelativeTo), func(fp string, info os.FileInfo, err error) error {
354 if err != nil {
355 return err
356 }
357 // Skip directories and symbolic links (which may be links to directories).
358 //
359 // The latter matters for repos like Kubernetes, which use symlinks.
360 if info.Mode()&(fs.ModeDir|fs.ModeSymlink) != 0 {
361 return nil
362 }
363
364 // Opt: avoid reading the file if mtime is sufficiently old to be reliable.
365 //
366 // If mtime is recent, it may not sufficiently identify the file contents:
367 // a subsequent write could result in the same mtime. For these cases, we
368 // must read the file contents.
369 id := fileID{mtime: info.ModTime()}
370 if time.Since(info.ModTime()) < 2*time.Second {
371 data, err := os.ReadFile(fp)
372 if err != nil {
373 return err
374 }
375 id.hash = hashFile(data)
376 }
377 path := w.RelPath(fp)
378 newFiles[path] = id
379
380 if w.files != nil {
381 oldID, ok := w.files[path]
382 delete(w.files, path)
383 switch {
384 case !ok:
385 evts = append(evts, protocol.FileEvent{
386 URI: w.URI(path),
387 Type: protocol.Created,
388 })
389 case oldID != id:
390 changed := true
391
392 // Check whether oldID and id do not match because oldID was polled at
393 // a recent enough to time such as to require hashing.
394 //
395 // In this case, read the content to check whether the file actually
396 // changed.
397 if oldID.mtime.Equal(id.mtime) && oldID.hash != "" && id.hash == "" {
398 data, err := os.ReadFile(fp)
399 if err != nil {
400 return err
401 }
402 if hashFile(data) == oldID.hash {
403 changed = false
404 }
405 }
406 if changed {
407 evts = append(evts, protocol.FileEvent{
408 URI: w.URI(path),
409 Type: protocol.Changed,
410 })
411 }
412 }
413 }
414
415 return nil
416 }); err != nil {
417 return nil, err
418 }
419
420 // Any remaining files must have been deleted.
421 for path := range w.files {
422 evts = append(evts, protocol.FileEvent{
423 URI: w.URI(path),
424 Type: protocol.Deleted,
425 })
426 }
427 w.files = newFiles
428 return evts, nil
429 }