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.
18 "golang.org/x/tools/internal/lsp/protocol"
19 "golang.org/x/tools/internal/span"
20 errors "golang.org/x/xerrors"
23 // FileEvent wraps the protocol.FileEvent so that it can be associated with a
24 // workdir-relative path.
25 type FileEvent struct {
27 ProtocolEvent protocol.FileEvent
30 // RelativeTo is a helper for operations relative to a given directory.
31 type RelativeTo string
33 // AbsPath returns an absolute filesystem path for the workdir-relative path.
34 func (r RelativeTo) AbsPath(path string) string {
35 fp := filepath.FromSlash(path)
36 if filepath.IsAbs(fp) {
39 return filepath.Join(string(r), filepath.FromSlash(path))
42 // RelPath returns a '/'-encoded path relative to the working directory (or an
43 // absolute path if the file is outside of workdir)
44 func (r RelativeTo) RelPath(fp string) string {
46 if rel, err := filepath.Rel(root, fp); err == nil && !strings.HasPrefix(rel, "..") {
47 return filepath.ToSlash(rel)
49 return filepath.ToSlash(fp)
52 func writeTxtar(txt string, rel RelativeTo) error {
53 files := unpackTxt(txt)
54 for name, data := range files {
55 if err := WriteFileData(name, data, rel); err != nil {
56 return errors.Errorf("writing to workdir: %w", err)
62 // WriteFileData writes content to the relative path, replacing the special
63 // token $SANDBOX_WORKDIR with the relative root given by rel.
64 func WriteFileData(path string, content []byte, rel RelativeTo) error {
65 content = bytes.ReplaceAll(content, []byte("$SANDBOX_WORKDIR"), []byte(rel))
66 fp := rel.AbsPath(path)
67 if err := os.MkdirAll(filepath.Dir(fp), 0755); err != nil {
68 return errors.Errorf("creating nested directory: %w", err)
70 if err := ioutil.WriteFile(fp, []byte(content), 0644); err != nil {
71 return errors.Errorf("writing %q: %w", path, err)
76 // Workdir is a temporary working directory for tests. It exposes file
77 // operations in terms of relative paths, and fakes file watching by triggering
78 // events on file operations.
83 watchers []func(context.Context, []FileEvent)
86 files map[string]string
89 // NewWorkdir writes the txtar-encoded file data in txt to dir, and returns a
90 // Workir for operating on these files using
91 func NewWorkdir(dir string) *Workdir {
92 return &Workdir{RelativeTo: RelativeTo(dir)}
95 func hashFile(data []byte) string {
96 return fmt.Sprintf("%x", sha256.Sum256(data))
99 func (w *Workdir) writeInitialFiles(txt string) error {
100 files := unpackTxt(txt)
101 w.files = map[string]string{}
102 for name, data := range files {
103 w.files[name] = hashFile(data)
104 if err := WriteFileData(name, data, w.RelativeTo); err != nil {
105 return errors.Errorf("writing to workdir: %w", err)
111 // RootURI returns the root URI for this working directory of this scratch
113 func (w *Workdir) RootURI() protocol.DocumentURI {
114 return toURI(string(w.RelativeTo))
117 // AddWatcher registers the given func to be called on any file change.
118 func (w *Workdir) AddWatcher(watcher func(context.Context, []FileEvent)) {
120 w.watchers = append(w.watchers, watcher)
124 // URI returns the URI to a the workdir-relative path.
125 func (w *Workdir) URI(path string) protocol.DocumentURI {
126 return toURI(w.AbsPath(path))
129 // URIToPath converts a uri to a workdir-relative path (or an absolute path,
130 // if the uri is outside of the workdir).
131 func (w *Workdir) URIToPath(uri protocol.DocumentURI) string {
132 fp := uri.SpanURI().Filename()
136 func toURI(fp string) protocol.DocumentURI {
137 return protocol.DocumentURI(span.URIFromPath(fp))
140 // ReadFile reads a text file specified by a workdir-relative path.
141 func (w *Workdir) ReadFile(path string) (string, error) {
142 b, err := ioutil.ReadFile(w.AbsPath(path))
146 return string(b), nil
149 func (w *Workdir) RegexpRange(path, re string) (Pos, Pos, error) {
150 content, err := w.ReadFile(path)
152 return Pos{}, Pos{}, err
154 return regexpRange(content, re)
157 // RegexpSearch searches the file corresponding to path for the first position
159 func (w *Workdir) RegexpSearch(path string, re string) (Pos, error) {
160 content, err := w.ReadFile(path)
164 start, _, err := regexpRange(content, re)
168 // ChangeFilesOnDisk executes the given on-disk file changes in a batch,
169 // simulating the action of changing branches outside of an editor.
170 func (w *Workdir) ChangeFilesOnDisk(ctx context.Context, events []FileEvent) error {
171 for _, e := range events {
172 switch e.ProtocolEvent.Type {
173 case protocol.Deleted:
174 fp := w.AbsPath(e.Path)
175 if err := os.Remove(fp); err != nil {
176 return errors.Errorf("removing %q: %w", e.Path, err)
178 case protocol.Changed, protocol.Created:
179 if _, err := w.writeFile(ctx, e.Path, e.Content); err != nil {
184 w.sendEvents(ctx, events)
188 // RemoveFile removes a workdir-relative file path.
189 func (w *Workdir) RemoveFile(ctx context.Context, path string) error {
190 fp := w.AbsPath(path)
191 if err := os.RemoveAll(fp); err != nil {
192 return errors.Errorf("removing %q: %w", path, err)
194 evts := []FileEvent{{
196 ProtocolEvent: protocol.FileEvent{
198 Type: protocol.Deleted,
201 w.sendEvents(ctx, evts)
205 func (w *Workdir) sendEvents(ctx context.Context, evts []FileEvent) {
210 watchers := make([]func(context.Context, []FileEvent), len(w.watchers))
211 copy(watchers, w.watchers)
213 for _, w := range watchers {
218 // WriteFiles writes the text file content to workdir-relative paths.
219 // It batches notifications rather than sending them consecutively.
220 func (w *Workdir) WriteFiles(ctx context.Context, files map[string]string) error {
222 for filename, content := range files {
223 evt, err := w.writeFile(ctx, filename, content)
227 evts = append(evts, evt)
229 w.sendEvents(ctx, evts)
233 // WriteFile writes text file content to a workdir-relative path.
234 func (w *Workdir) WriteFile(ctx context.Context, path, content string) error {
235 evt, err := w.writeFile(ctx, path, content)
239 w.sendEvents(ctx, []FileEvent{evt})
243 func (w *Workdir) writeFile(ctx context.Context, path, content string) (FileEvent, error) {
244 fp := w.AbsPath(path)
245 _, err := os.Stat(fp)
246 if err != nil && !os.IsNotExist(err) {
247 return FileEvent{}, errors.Errorf("checking if %q exists: %w", path, err)
249 var changeType protocol.FileChangeType
250 if os.IsNotExist(err) {
251 changeType = protocol.Created
253 changeType = protocol.Changed
255 if err := WriteFileData(path, []byte(content), w.RelativeTo); err != nil {
256 return FileEvent{}, err
260 ProtocolEvent: protocol.FileEvent{
267 // listFiles lists files in the given directory, returning a map of relative
268 // path to modification time.
269 func (w *Workdir) listFiles(dir string) (map[string]string, error) {
270 files := make(map[string]string)
271 absDir := w.AbsPath(dir)
272 if err := filepath.Walk(absDir, func(fp string, info os.FileInfo, err error) error {
279 path := w.RelPath(fp)
280 data, err := ioutil.ReadFile(fp)
284 files[path] = hashFile(data)
292 // CheckForFileChanges walks the working directory and checks for any files
293 // that have changed since the last poll.
294 func (w *Workdir) CheckForFileChanges(ctx context.Context) error {
295 evts, err := w.pollFiles()
299 w.sendEvents(ctx, evts)
303 // pollFiles updates w.files and calculates FileEvents corresponding to file
304 // state changes since the last poll. It does not call sendEvents.
305 func (w *Workdir) pollFiles() ([]FileEvent, error) {
307 defer w.fileMu.Unlock()
309 files, err := w.listFiles(".")
314 // Check which files have been added or modified.
315 for path, hash := range files {
316 oldhash, ok := w.files[path]
317 delete(w.files, path)
318 var typ protocol.FileChangeType
321 typ = protocol.Created
322 case oldhash != hash:
323 typ = protocol.Changed
327 evts = append(evts, FileEvent{
329 ProtocolEvent: protocol.FileEvent{
335 // Any remaining files must have been deleted.
336 for path := range w.files {
337 evts = append(evts, FileEvent{
339 ProtocolEvent: protocol.FileEvent{
341 Type: protocol.Deleted,