Debian Codegraph @

gopls/internal/cache/fs_overlay.go

raw symbols SCIP
1 // Copyright 2023 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 cache
6
7 import (
8 "context"
9 "sync"
10 "time"
11
12 "golang.org/x/tools/gopls/internal/file"
13 "golang.org/x/tools/gopls/internal/protocol"
14 )
15
16 // An overlayFS is a file.Source that keeps track of overlays on top of a
17 // delegate FileSource.
18 type overlayFS struct {
19 delegate file.Source
20
21 mu sync.Mutex
22 overlays map[protocol.DocumentURI]*overlay
23 }
24
25 func newOverlayFS(delegate file.Source) *overlayFS {
26 return &overlayFS{
27 delegate: delegate,
28 overlays: make(map[protocol.DocumentURI]*overlay),
29 }
30 }
31
32 // Overlays returns a new unordered array of overlays.
33 func (fs *overlayFS) Overlays() []*overlay {
34 fs.mu.Lock()
35 defer fs.mu.Unlock()
36 overlays := make([]*overlay, 0, len(fs.overlays))
37 for _, overlay := range fs.overlays {
38 overlays = append(overlays, overlay)
39 }
40 return overlays
41 }
42
43 func (fs *overlayFS) ReadFile(ctx context.Context, uri protocol.DocumentURI) (file.Handle, error) {
44 fs.mu.Lock()
45 overlay, ok := fs.overlays[uri]
46 fs.mu.Unlock()
47 if ok {
48 return overlay, nil
49 }
50 return fs.delegate.ReadFile(ctx, uri)
51 }
52
53 // An overlay is a file open in the editor. It may have unsaved edits.
54 // It implements the file.Handle interface, and the implicit contract
55 // of the debug.FileTmpl template.
56 type overlay struct {
57 uri protocol.DocumentURI
58 content []byte
59 modTime time.Time
60 hash file.Hash
61 version int32
62 kind file.Kind
63
64 // saved is true if a file matches the state on disk,
65 // and therefore does not need to be part of the overlay sent to go/packages.
66 saved bool
67 }
68
69 func (o *overlay) String() string { return o.uri.Path() }
70
71 func (o *overlay) URI() protocol.DocumentURI { return o.uri }
72
73 func (o *overlay) Identity() file.Identity {
74 return file.Identity{
75 URI: o.uri,
76 Hash: o.hash,
77 }
78 }
79
80 func (o *overlay) Content() ([]byte, error) { return o.content, nil }
81 func (o *overlay) ModTime() (time.Time, error) { return o.modTime, nil }
82 func (o *overlay) Version() int32 { return o.version }
83 func (o *overlay) SameContentsOnDisk() bool { return o.saved }
84 func (o *overlay) Kind() file.Kind { return o.kind }