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
5package fake
6
7import (
8	"bytes"
9	"context"
10	"crypto/sha256"
11	"fmt"
12	"io/ioutil"
13	"os"
14	"path/filepath"
15	"strings"
16	"sync"
17
18	"golang.org/x/tools/internal/lsp/protocol"
19	"golang.org/x/tools/internal/span"
20	errors "golang.org/x/xerrors"
21)
22
23// FileEvent wraps the protocol.FileEvent so that it can be associated with a
24// workdir-relative path.
25type FileEvent struct {
26	Path, Content string
27	ProtocolEvent protocol.FileEvent
28}
29
30// RelativeTo is a helper for operations relative to a given directory.
31type RelativeTo string
32
33// AbsPath returns an absolute filesystem path for the workdir-relative path.
34func (r RelativeTo) AbsPath(path string) string {
35	fp := filepath.FromSlash(path)
36	if filepath.IsAbs(fp) {
37		return fp
38	}
39	return filepath.Join(string(r), filepath.FromSlash(path))
40}
41
42// RelPath returns a '/'-encoded path relative to the working directory (or an
43// absolute path if the file is outside of workdir)
44func (r RelativeTo) RelPath(fp string) string {
45	root := string(r)
46	if rel, err := filepath.Rel(root, fp); err == nil && !strings.HasPrefix(rel, "..") {
47		return filepath.ToSlash(rel)
48	}
49	return filepath.ToSlash(fp)
50}
51
52func 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)
57		}
58	}
59	return nil
60}
61
62// WriteFileData writes content to the relative path, replacing the special
63// token $SANDBOX_WORKDIR with the relative root given by rel.
64func 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)
69	}
70	if err := ioutil.WriteFile(fp, []byte(content), 0644); err != nil {
71		return errors.Errorf("writing %q: %w", path, err)
72	}
73	return nil
74}
75
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.
79type Workdir struct {
80	RelativeTo
81
82	watcherMu sync.Mutex
83	watchers  []func(context.Context, []FileEvent)
84
85	fileMu sync.Mutex
86	files  map[string]string
87}
88
89// NewWorkdir writes the txtar-encoded file data in txt to dir, and returns a
90// Workir for operating on these files using
91func NewWorkdir(dir string) *Workdir {
92	return &Workdir{RelativeTo: RelativeTo(dir)}
93}
94
95func hashFile(data []byte) string {
96	return fmt.Sprintf("%x", sha256.Sum256(data))
97}
98
99func (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)
106		}
107	}
108	return nil
109}
110
111// RootURI returns the root URI for this working directory of this scratch
112// environment.
113func (w *Workdir) RootURI() protocol.DocumentURI {
114	return toURI(string(w.RelativeTo))
115}
116
117// AddWatcher registers the given func to be called on any file change.
118func (w *Workdir) AddWatcher(watcher func(context.Context, []FileEvent)) {
119	w.watcherMu.Lock()
120	w.watchers = append(w.watchers, watcher)
121	w.watcherMu.Unlock()
122}
123
124// URI returns the URI to a the workdir-relative path.
125func (w *Workdir) URI(path string) protocol.DocumentURI {
126	return toURI(w.AbsPath(path))
127}
128
129// URIToPath converts a uri to a workdir-relative path (or an absolute path,
130// if the uri is outside of the workdir).
131func (w *Workdir) URIToPath(uri protocol.DocumentURI) string {
132	fp := uri.SpanURI().Filename()
133	return w.RelPath(fp)
134}
135
136func toURI(fp string) protocol.DocumentURI {
137	return protocol.DocumentURI(span.URIFromPath(fp))
138}
139
140// ReadFile reads a text file specified by a workdir-relative path.
141func (w *Workdir) ReadFile(path string) (string, error) {
142	b, err := ioutil.ReadFile(w.AbsPath(path))
143	if err != nil {
144		return "", err
145	}
146	return string(b), nil
147}
148
149func (w *Workdir) RegexpRange(path, re string) (Pos, Pos, error) {
150	content, err := w.ReadFile(path)
151	if err != nil {
152		return Pos{}, Pos{}, err
153	}
154	return regexpRange(content, re)
155}
156
157// RegexpSearch searches the file corresponding to path for the first position
158// matching re.
159func (w *Workdir) RegexpSearch(path string, re string) (Pos, error) {
160	content, err := w.ReadFile(path)
161	if err != nil {
162		return Pos{}, err
163	}
164	start, _, err := regexpRange(content, re)
165	return start, err
166}
167
168// ChangeFilesOnDisk executes the given on-disk file changes in a batch,
169// simulating the action of changing branches outside of an editor.
170func (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)
177			}
178		case protocol.Changed, protocol.Created:
179			if _, err := w.writeFile(ctx, e.Path, e.Content); err != nil {
180				return err
181			}
182		}
183	}
184	w.sendEvents(ctx, events)
185	return nil
186}
187
188// RemoveFile removes a workdir-relative file path.
189func (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)
193	}
194	evts := []FileEvent{{
195		Path: path,
196		ProtocolEvent: protocol.FileEvent{
197			URI:  w.URI(path),
198			Type: protocol.Deleted,
199		},
200	}}
201	w.sendEvents(ctx, evts)
202	return nil
203}
204
205func (w *Workdir) sendEvents(ctx context.Context, evts []FileEvent) {
206	if len(evts) == 0 {
207		return
208	}
209	w.watcherMu.Lock()
210	watchers := make([]func(context.Context, []FileEvent), len(w.watchers))
211	copy(watchers, w.watchers)
212	w.watcherMu.Unlock()
213	for _, w := range watchers {
214		go w(ctx, evts)
215	}
216}
217
218// WriteFiles writes the text file content to workdir-relative paths.
219// It batches notifications rather than sending them consecutively.
220func (w *Workdir) WriteFiles(ctx context.Context, files map[string]string) error {
221	var evts []FileEvent
222	for filename, content := range files {
223		evt, err := w.writeFile(ctx, filename, content)
224		if err != nil {
225			return err
226		}
227		evts = append(evts, evt)
228	}
229	w.sendEvents(ctx, evts)
230	return nil
231}
232
233// WriteFile writes text file content to a workdir-relative path.
234func (w *Workdir) WriteFile(ctx context.Context, path, content string) error {
235	evt, err := w.writeFile(ctx, path, content)
236	if err != nil {
237		return err
238	}
239	w.sendEvents(ctx, []FileEvent{evt})
240	return nil
241}
242
243func (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)
248	}
249	var changeType protocol.FileChangeType
250	if os.IsNotExist(err) {
251		changeType = protocol.Created
252	} else {
253		changeType = protocol.Changed
254	}
255	if err := WriteFileData(path, []byte(content), w.RelativeTo); err != nil {
256		return FileEvent{}, err
257	}
258	return FileEvent{
259		Path: path,
260		ProtocolEvent: protocol.FileEvent{
261			URI:  w.URI(path),
262			Type: changeType,
263		},
264	}, nil
265}
266
267// listFiles lists files in the given directory, returning a map of relative
268// path to modification time.
269func (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 {
273		if err != nil {
274			return err
275		}
276		if info.IsDir() {
277			return nil
278		}
279		path := w.RelPath(fp)
280		data, err := ioutil.ReadFile(fp)
281		if err != nil {
282			return err
283		}
284		files[path] = hashFile(data)
285		return nil
286	}); err != nil {
287		return nil, err
288	}
289	return files, nil
290}
291
292// CheckForFileChanges walks the working directory and checks for any files
293// that have changed since the last poll.
294func (w *Workdir) CheckForFileChanges(ctx context.Context) error {
295	evts, err := w.pollFiles()
296	if err != nil {
297		return err
298	}
299	w.sendEvents(ctx, evts)
300	return nil
301}
302
303// pollFiles updates w.files and calculates FileEvents corresponding to file
304// state changes since the last poll. It does not call sendEvents.
305func (w *Workdir) pollFiles() ([]FileEvent, error) {
306	w.fileMu.Lock()
307	defer w.fileMu.Unlock()
308
309	files, err := w.listFiles(".")
310	if err != nil {
311		return nil, err
312	}
313	var evts []FileEvent
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
319		switch {
320		case !ok:
321			typ = protocol.Created
322		case oldhash != hash:
323			typ = protocol.Changed
324		default:
325			continue
326		}
327		evts = append(evts, FileEvent{
328			Path: path,
329			ProtocolEvent: protocol.FileEvent{
330				URI:  w.URI(path),
331				Type: typ,
332			},
333		})
334	}
335	// Any remaining files must have been deleted.
336	for path := range w.files {
337		evts = append(evts, FileEvent{
338			Path: path,
339			ProtocolEvent: protocol.FileEvent{
340				URI:  w.URI(path),
341				Type: protocol.Deleted,
342			},
343		})
344	}
345	w.files = files
346	return evts, nil
347}
348