1// Copyright 2018 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 implements the caching layer for gopls.
6package cache
7
8import (
9	"context"
10	"encoding/json"
11	"fmt"
12	"io"
13	"io/ioutil"
14	"os"
15	"path"
16	"path/filepath"
17	"reflect"
18	"regexp"
19	"sort"
20	"strings"
21	"sync"
22
23	"golang.org/x/mod/modfile"
24	"golang.org/x/mod/semver"
25	exec "golang.org/x/sys/execabs"
26	"golang.org/x/tools/go/packages"
27	"golang.org/x/tools/internal/event"
28	"golang.org/x/tools/internal/gocommand"
29	"golang.org/x/tools/internal/imports"
30	"golang.org/x/tools/internal/lsp/protocol"
31	"golang.org/x/tools/internal/lsp/source"
32	"golang.org/x/tools/internal/memoize"
33	"golang.org/x/tools/internal/span"
34	"golang.org/x/tools/internal/xcontext"
35	errors "golang.org/x/xerrors"
36)
37
38type View struct {
39	session *Session
40	id      string
41
42	optionsMu sync.Mutex
43	options   *source.Options
44
45	// mu protects most mutable state of the view.
46	mu sync.Mutex
47
48	// baseCtx is the context handed to NewView. This is the parent of all
49	// background contexts created for this view.
50	baseCtx context.Context
51
52	// cancel is called when all action being performed by the current view
53	// should be stopped.
54	cancel context.CancelFunc
55
56	// name is the user visible name of this view.
57	name string
58
59	// folder is the folder with which this view was constructed.
60	folder span.URI
61
62	importsState *importsState
63
64	// moduleUpgrades tracks known upgrades for module paths.
65	moduleUpgrades map[string]string
66
67	// keep track of files by uri and by basename, a single file may be mapped
68	// to multiple uris, and the same basename may map to multiple files
69	filesByURI  map[span.URI]*fileBase
70	filesByBase map[string][]*fileBase
71
72	// initCancelFirstAttempt can be used to terminate the view's first
73	// attempt at initialization.
74	initCancelFirstAttempt context.CancelFunc
75
76	snapshotMu sync.Mutex
77	snapshot   *snapshot
78
79	// initialWorkspaceLoad is closed when the first workspace initialization has
80	// completed. If we failed to load, we only retry if the go.mod file changes,
81	// to avoid too many go/packages calls.
82	initialWorkspaceLoad chan struct{}
83
84	// initializationSema is used limit concurrent initialization of snapshots in
85	// the view. We use a channel instead of a mutex to avoid blocking when a
86	// context is canceled.
87	initializationSema chan struct{}
88
89	// rootURI is the rootURI directory of this view. If we are in GOPATH mode, this
90	// is just the folder. If we are in module mode, this is the module rootURI.
91	rootURI span.URI
92
93	// workspaceInformation tracks various details about this view's
94	// environment variables, go version, and use of modules.
95	workspaceInformation
96
97	// tempWorkspace is a temporary directory dedicated to holding the latest
98	// version of the workspace go.mod file. (TODO: also go.sum file)
99	tempWorkspace span.URI
100}
101
102type workspaceInformation struct {
103	// The Go version in use: X in Go 1.X.
104	goversion int
105
106	// hasGopackagesDriver is true if the user has a value set for the
107	// GOPACKAGESDRIVER environment variable or a gopackagesdriver binary on
108	// their machine.
109	hasGopackagesDriver bool
110
111	// `go env` variables that need to be tracked by gopls.
112	environmentVariables
113
114	// userGo111Module is the user's value of GO111MODULE.
115	userGo111Module go111module
116
117	// The value of GO111MODULE we want to run with.
118	effectiveGo111Module string
119
120	// goEnv is the `go env` output collected when a view is created.
121	// It includes the values of the environment variables above.
122	goEnv map[string]string
123}
124
125type go111module int
126
127const (
128	off = go111module(iota)
129	auto
130	on
131)
132
133type environmentVariables struct {
134	gocache, gopath, goroot, goprivate, gomodcache, go111module string
135}
136
137type workspaceMode int
138
139const (
140	moduleMode workspaceMode = 1 << iota
141
142	// tempModfile indicates whether or not the -modfile flag should be used.
143	tempModfile
144
145	// usesWorkspaceModule indicates support for the experimental workspace module
146	// feature.
147	usesWorkspaceModule
148)
149
150type builtinPackageHandle struct {
151	handle *memoize.Handle
152}
153
154// fileBase holds the common functionality for all files.
155// It is intended to be embedded in the file implementations
156type fileBase struct {
157	uris  []span.URI
158	fname string
159
160	view *View
161}
162
163func (f *fileBase) URI() span.URI {
164	return f.uris[0]
165}
166
167func (f *fileBase) filename() string {
168	return f.fname
169}
170
171func (f *fileBase) addURI(uri span.URI) int {
172	f.uris = append(f.uris, uri)
173	return len(f.uris)
174}
175
176func (v *View) ID() string { return v.id }
177
178// tempModFile creates a temporary go.mod file based on the contents of the
179// given go.mod file. It is the caller's responsibility to clean up the files
180// when they are done using them.
181func tempModFile(modFh source.FileHandle, gosum []byte) (tmpURI span.URI, cleanup func(), err error) {
182	filenameHash := hashContents([]byte(modFh.URI().Filename()))
183	tmpMod, err := ioutil.TempFile("", fmt.Sprintf("go.%s.*.mod", filenameHash))
184	if err != nil {
185		return "", nil, err
186	}
187	defer tmpMod.Close()
188
189	tmpURI = span.URIFromPath(tmpMod.Name())
190	tmpSumName := sumFilename(tmpURI)
191
192	content, err := modFh.Read()
193	if err != nil {
194		return "", nil, err
195	}
196
197	if _, err := tmpMod.Write(content); err != nil {
198		return "", nil, err
199	}
200
201	cleanup = func() {
202		_ = os.Remove(tmpSumName)
203		_ = os.Remove(tmpURI.Filename())
204	}
205
206	// Be careful to clean up if we return an error from this function.
207	defer func() {
208		if err != nil {
209			cleanup()
210			cleanup = nil
211		}
212	}()
213
214	// Create an analogous go.sum, if one exists.
215	if gosum != nil {
216		if err := ioutil.WriteFile(tmpSumName, gosum, 0655); err != nil {
217			return "", cleanup, err
218		}
219	}
220
221	return tmpURI, cleanup, nil
222}
223
224// Name returns the user visible name of this view.
225func (v *View) Name() string {
226	return v.name
227}
228
229// Folder returns the folder at the base of this view.
230func (v *View) Folder() span.URI {
231	return v.folder
232}
233
234func (v *View) TempWorkspace() span.URI {
235	return v.tempWorkspace
236}
237
238func (v *View) Options() *source.Options {
239	v.optionsMu.Lock()
240	defer v.optionsMu.Unlock()
241	return v.options
242}
243
244func minorOptionsChange(a, b *source.Options) bool {
245	// Check if any of the settings that modify our understanding of files have been changed
246	if !reflect.DeepEqual(a.Env, b.Env) {
247		return false
248	}
249	if !reflect.DeepEqual(a.DirectoryFilters, b.DirectoryFilters) {
250		return false
251	}
252	if a.MemoryMode != b.MemoryMode {
253		return false
254	}
255	aBuildFlags := make([]string, len(a.BuildFlags))
256	bBuildFlags := make([]string, len(b.BuildFlags))
257	copy(aBuildFlags, a.BuildFlags)
258	copy(bBuildFlags, b.BuildFlags)
259	sort.Strings(aBuildFlags)
260	sort.Strings(bBuildFlags)
261	// the rest of the options are benign
262	return reflect.DeepEqual(aBuildFlags, bBuildFlags)
263}
264
265func (v *View) SetOptions(ctx context.Context, options *source.Options) (source.View, error) {
266	// no need to rebuild the view if the options were not materially changed
267	v.optionsMu.Lock()
268	if minorOptionsChange(v.options, options) {
269		v.options = options
270		v.optionsMu.Unlock()
271		return v, nil
272	}
273	v.optionsMu.Unlock()
274	newView, err := v.session.updateView(ctx, v, options)
275	return newView, err
276}
277
278func (v *View) Rebuild(ctx context.Context) (source.Snapshot, func(), error) {
279	newView, err := v.session.updateView(ctx, v, v.Options())
280	if err != nil {
281		return nil, func() {}, err
282	}
283	snapshot, release := newView.Snapshot(ctx)
284	return snapshot, release, nil
285}
286
287func (s *snapshot) WriteEnv(ctx context.Context, w io.Writer) error {
288	s.view.optionsMu.Lock()
289	env := s.view.options.EnvSlice()
290	buildFlags := append([]string{}, s.view.options.BuildFlags...)
291	s.view.optionsMu.Unlock()
292
293	fullEnv := make(map[string]string)
294	for k, v := range s.view.goEnv {
295		fullEnv[k] = v
296	}
297	for _, v := range env {
298		s := strings.SplitN(v, "=", 2)
299		if len(s) != 2 {
300			continue
301		}
302		if _, ok := fullEnv[s[0]]; ok {
303			fullEnv[s[0]] = s[1]
304		}
305	}
306	goVersion, err := s.view.session.gocmdRunner.Run(ctx, gocommand.Invocation{
307		Verb:       "version",
308		Env:        env,
309		WorkingDir: s.view.rootURI.Filename(),
310	})
311	if err != nil {
312		return err
313	}
314	fmt.Fprintf(w, `go env for %v
315(root %s)
316(go version %s)
317(valid build configuration = %v)
318(build flags: %v)
319`,
320		s.view.folder.Filename(),
321		s.view.rootURI.Filename(),
322		strings.TrimRight(goVersion.String(), "\n"),
323		s.ValidBuildConfiguration(),
324		buildFlags)
325	for k, v := range fullEnv {
326		fmt.Fprintf(w, "%s=%s\n", k, v)
327	}
328	return nil
329}
330
331func (s *snapshot) RunProcessEnvFunc(ctx context.Context, fn func(*imports.Options) error) error {
332	return s.view.importsState.runProcessEnvFunc(ctx, s, fn)
333}
334
335func (s *snapshot) locateTemplateFiles(ctx context.Context) {
336	if !s.view.Options().ExperimentalTemplateSupport {
337		return
338	}
339	dir := s.workspace.root.Filename()
340	searched := 0
341	// Change to WalkDir when we move up to 1.16
342	err := filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
343		if err != nil {
344			return err
345		}
346		if strings.HasSuffix(filepath.Ext(path), "tmpl") && !pathExcludedByFilter(path, s.view.options) &&
347			!fi.IsDir() {
348			k := span.URIFromPath(path)
349			fh, err := s.GetVersionedFile(ctx, k)
350			if err != nil {
351				return nil
352			}
353			s.files[k] = fh
354		}
355		searched++
356		if fileLimit > 0 && searched > fileLimit {
357			return errExhausted
358		}
359		return nil
360	})
361	if err != nil {
362		event.Error(ctx, "searching for template files failed", err)
363	}
364}
365
366func (v *View) contains(uri span.URI) bool {
367	inRoot := source.InDir(v.rootURI.Filename(), uri.Filename())
368	inFolder := source.InDir(v.folder.Filename(), uri.Filename())
369	if !inRoot && !inFolder {
370		return false
371	}
372	// Filters are applied relative to the workspace folder.
373	if inFolder {
374		return !pathExcludedByFilter(strings.TrimPrefix(uri.Filename(), v.folder.Filename()), v.Options())
375	}
376	return true
377}
378
379func (v *View) mapFile(uri span.URI, f *fileBase) {
380	v.filesByURI[uri] = f
381	if f.addURI(uri) == 1 {
382		basename := basename(f.filename())
383		v.filesByBase[basename] = append(v.filesByBase[basename], f)
384	}
385}
386
387func basename(filename string) string {
388	return strings.ToLower(filepath.Base(filename))
389}
390
391func (v *View) relevantChange(c source.FileModification) bool {
392	// If the file is known to the view, the change is relevant.
393	if v.knownFile(c.URI) {
394		return true
395	}
396	// The gopls.mod may not be "known" because we first access it through the
397	// session. As a result, treat changes to the view's gopls.mod file as
398	// always relevant, even if they are only on-disk changes.
399	// TODO(rstambler): Make sure the gopls.mod is always known to the view.
400	if c.URI == goplsModURI(v.rootURI) {
401		return true
402	}
403	// If the file is not known to the view, and the change is only on-disk,
404	// we should not invalidate the snapshot. This is necessary because Emacs
405	// sends didChangeWatchedFiles events for temp files.
406	if c.OnDisk && (c.Action == source.Change || c.Action == source.Delete) {
407		return false
408	}
409	return v.contains(c.URI)
410}
411
412func (v *View) knownFile(uri span.URI) bool {
413	v.mu.Lock()
414	defer v.mu.Unlock()
415
416	f, err := v.findFile(uri)
417	return f != nil && err == nil
418}
419
420// getFile returns a file for the given URI.
421func (v *View) getFile(uri span.URI) *fileBase {
422	v.mu.Lock()
423	defer v.mu.Unlock()
424
425	f, _ := v.findFile(uri)
426	if f != nil {
427		return f
428	}
429	f = &fileBase{
430		view:  v,
431		fname: uri.Filename(),
432	}
433	v.mapFile(uri, f)
434	return f
435}
436
437// findFile checks the cache for any file matching the given uri.
438//
439// An error is only returned for an irreparable failure, for example, if the
440// filename in question does not exist.
441func (v *View) findFile(uri span.URI) (*fileBase, error) {
442	if f := v.filesByURI[uri]; f != nil {
443		// a perfect match
444		return f, nil
445	}
446	// no exact match stored, time to do some real work
447	// check for any files with the same basename
448	fname := uri.Filename()
449	basename := basename(fname)
450	if candidates := v.filesByBase[basename]; candidates != nil {
451		pathStat, err := os.Stat(fname)
452		if os.IsNotExist(err) {
453			return nil, err
454		}
455		if err != nil {
456			return nil, nil // the file may exist, return without an error
457		}
458		for _, c := range candidates {
459			if cStat, err := os.Stat(c.filename()); err == nil {
460				if os.SameFile(pathStat, cStat) {
461					// same file, map it
462					v.mapFile(uri, c)
463					return c, nil
464				}
465			}
466		}
467	}
468	// no file with a matching name was found, it wasn't in our cache
469	return nil, nil
470}
471
472func (v *View) Shutdown(ctx context.Context) {
473	v.session.removeView(ctx, v)
474}
475
476// TODO(rFindley): probably some of this should also be one in View.Shutdown
477// above?
478func (v *View) shutdown(ctx context.Context) {
479	// Cancel the initial workspace load if it is still running.
480	v.initCancelFirstAttempt()
481
482	v.mu.Lock()
483	if v.cancel != nil {
484		v.cancel()
485		v.cancel = nil
486	}
487	v.mu.Unlock()
488	v.snapshotMu.Lock()
489	go v.snapshot.generation.Destroy()
490	v.snapshotMu.Unlock()
491	v.importsState.destroy()
492}
493
494func (v *View) Session() *Session {
495	return v.session
496}
497
498func (s *snapshot) IgnoredFile(uri span.URI) bool {
499	filename := uri.Filename()
500	var prefixes []string
501	if len(s.workspace.getActiveModFiles()) == 0 {
502		for _, entry := range filepath.SplitList(s.view.gopath) {
503			prefixes = append(prefixes, filepath.Join(entry, "src"))
504		}
505	} else {
506		prefixes = append(prefixes, s.view.gomodcache)
507		for m := range s.workspace.getActiveModFiles() {
508			prefixes = append(prefixes, dirURI(m).Filename())
509		}
510	}
511	for _, prefix := range prefixes {
512		if strings.HasPrefix(filename, prefix) {
513			return checkIgnored(filename[len(prefix):])
514		}
515	}
516	return false
517}
518
519// checkIgnored implements go list's exclusion rules. go help list:
520// 		Directory and file names that begin with "." or "_" are ignored
521// 		by the go tool, as are directories named "testdata".
522func checkIgnored(suffix string) bool {
523	for _, component := range strings.Split(suffix, string(filepath.Separator)) {
524		if len(component) == 0 {
525			continue
526		}
527		if component[0] == '.' || component[0] == '_' || component == "testdata" {
528			return true
529		}
530	}
531	return false
532}
533
534func (v *View) Snapshot(ctx context.Context) (source.Snapshot, func()) {
535	return v.getSnapshot(ctx)
536}
537
538func (v *View) getSnapshot(ctx context.Context) (*snapshot, func()) {
539	v.snapshotMu.Lock()
540	defer v.snapshotMu.Unlock()
541	return v.snapshot, v.snapshot.generation.Acquire(ctx)
542}
543
544func (s *snapshot) initialize(ctx context.Context, firstAttempt bool) {
545	select {
546	case <-ctx.Done():
547		return
548	case s.view.initializationSema <- struct{}{}:
549	}
550
551	defer func() {
552		<-s.view.initializationSema
553	}()
554
555	if s.initializeOnce == nil {
556		return
557	}
558	s.initializeOnce.Do(func() {
559		s.loadWorkspace(ctx, firstAttempt)
560	})
561}
562
563func (s *snapshot) loadWorkspace(ctx context.Context, firstAttempt bool) {
564	defer func() {
565		s.initializeOnce = nil
566		if firstAttempt {
567			close(s.view.initialWorkspaceLoad)
568		}
569	}()
570
571	// If we have multiple modules, we need to load them by paths.
572	var scopes []interface{}
573	var modDiagnostics []*source.Diagnostic
574	addError := func(uri span.URI, err error) {
575		modDiagnostics = append(modDiagnostics, &source.Diagnostic{
576			URI:      uri,
577			Severity: protocol.SeverityError,
578			Source:   source.ListError,
579			Message:  err.Error(),
580		})
581	}
582	s.locateTemplateFiles(ctx)
583	if len(s.workspace.getActiveModFiles()) > 0 {
584		for modURI := range s.workspace.getActiveModFiles() {
585			fh, err := s.GetFile(ctx, modURI)
586			if err != nil {
587				addError(modURI, err)
588				continue
589			}
590			parsed, err := s.ParseMod(ctx, fh)
591			if err != nil {
592				addError(modURI, err)
593				continue
594			}
595			if parsed.File == nil || parsed.File.Module == nil {
596				addError(modURI, fmt.Errorf("no module path for %s", modURI))
597				continue
598			}
599			path := parsed.File.Module.Mod.Path
600			scopes = append(scopes, moduleLoadScope(path))
601		}
602	} else {
603		scopes = append(scopes, viewLoadScope("LOAD_VIEW"))
604	}
605	var err error
606	if len(scopes) > 0 {
607		err = s.load(ctx, firstAttempt, append(scopes, packagePath("builtin"))...)
608	}
609	if ctx.Err() != nil {
610		return
611	}
612
613	var criticalErr *source.CriticalError
614	if err != nil {
615		event.Error(ctx, "initial workspace load failed", err)
616		extractedDiags, _ := s.extractGoCommandErrors(ctx, err.Error())
617		criticalErr = &source.CriticalError{
618			MainError: err,
619			DiagList:  append(modDiagnostics, extractedDiags...),
620		}
621	} else if len(modDiagnostics) == 1 {
622		criticalErr = &source.CriticalError{
623			MainError: fmt.Errorf(modDiagnostics[0].Message),
624			DiagList:  modDiagnostics,
625		}
626	} else if len(modDiagnostics) > 1 {
627		criticalErr = &source.CriticalError{
628			MainError: fmt.Errorf("error loading module names"),
629			DiagList:  modDiagnostics,
630		}
631	}
632
633	// Lock the snapshot when setting the initialized error.
634	s.mu.Lock()
635	defer s.mu.Unlock()
636	s.initializedErr = criticalErr
637}
638
639// invalidateContent invalidates the content of a Go file,
640// including any position and type information that depends on it.
641func (v *View) invalidateContent(ctx context.Context, changes map[span.URI]*fileChange, forceReloadMetadata bool) (*snapshot, func()) {
642	// Detach the context so that content invalidation cannot be canceled.
643	ctx = xcontext.Detach(ctx)
644
645	// Cancel all still-running previous requests, since they would be
646	// operating on stale data.
647	v.snapshot.cancel()
648
649	// Do not clone a snapshot until its view has finished initializing.
650	v.snapshot.AwaitInitialized(ctx)
651
652	// This should be the only time we hold the view's snapshot lock for any period of time.
653	v.snapshotMu.Lock()
654	defer v.snapshotMu.Unlock()
655
656	oldSnapshot := v.snapshot
657
658	var workspaceChanged bool
659	v.snapshot, workspaceChanged = oldSnapshot.clone(ctx, v.baseCtx, changes, forceReloadMetadata)
660	if workspaceChanged && v.tempWorkspace != "" {
661		snap := v.snapshot
662		release := snap.generation.Acquire(ctx)
663		go func() {
664			defer release()
665			wsdir, err := snap.getWorkspaceDir(ctx)
666			if err != nil {
667				event.Error(ctx, "getting workspace dir", err)
668			}
669			if err := copyWorkspace(v.tempWorkspace, wsdir); err != nil {
670				event.Error(ctx, "copying workspace dir", err)
671			}
672		}()
673	}
674	go oldSnapshot.generation.Destroy()
675
676	return v.snapshot, v.snapshot.generation.Acquire(ctx)
677}
678
679func copyWorkspace(dst span.URI, src span.URI) error {
680	for _, name := range []string{"go.mod", "go.sum"} {
681		srcname := filepath.Join(src.Filename(), name)
682		srcf, err := os.Open(srcname)
683		if err != nil {
684			return errors.Errorf("opening snapshot %s: %w", name, err)
685		}
686		defer srcf.Close()
687		dstname := filepath.Join(dst.Filename(), name)
688		dstf, err := os.Create(dstname)
689		if err != nil {
690			return errors.Errorf("truncating view %s: %w", name, err)
691		}
692		defer dstf.Close()
693		if _, err := io.Copy(dstf, srcf); err != nil {
694			return errors.Errorf("copying %s: %w", name, err)
695		}
696	}
697	return nil
698}
699
700func (s *Session) getWorkspaceInformation(ctx context.Context, folder span.URI, options *source.Options) (*workspaceInformation, error) {
701	if err := checkPathCase(folder.Filename()); err != nil {
702		return nil, errors.Errorf("invalid workspace configuration: %w", err)
703	}
704	var err error
705	inv := gocommand.Invocation{
706		WorkingDir: folder.Filename(),
707		Env:        options.EnvSlice(),
708	}
709	goversion, err := gocommand.GoVersion(ctx, inv, s.gocmdRunner)
710	if err != nil {
711		return nil, err
712	}
713
714	go111module := os.Getenv("GO111MODULE")
715	if v, ok := options.Env["GO111MODULE"]; ok {
716		go111module = v
717	}
718	// Make sure to get the `go env` before continuing with initialization.
719	envVars, env, err := s.getGoEnv(ctx, folder.Filename(), goversion, go111module, options.EnvSlice())
720	if err != nil {
721		return nil, err
722	}
723	// If using 1.16, change the default back to auto. The primary effect of
724	// GO111MODULE=on is to break GOPATH, which we aren't too interested in.
725	if goversion >= 16 && go111module == "" {
726		go111module = "auto"
727	}
728	// The value of GOPACKAGESDRIVER is not returned through the go command.
729	gopackagesdriver := os.Getenv("GOPACKAGESDRIVER")
730	for _, s := range env {
731		split := strings.SplitN(s, "=", 2)
732		if split[0] == "GOPACKAGESDRIVER" {
733			gopackagesdriver = split[1]
734		}
735	}
736
737	// A user may also have a gopackagesdriver binary on their machine, which
738	// works the same way as setting GOPACKAGESDRIVER.
739	tool, _ := exec.LookPath("gopackagesdriver")
740	hasGopackagesDriver := gopackagesdriver != "off" && (gopackagesdriver != "" || tool != "")
741
742	return &workspaceInformation{
743		hasGopackagesDriver:  hasGopackagesDriver,
744		effectiveGo111Module: go111module,
745		userGo111Module:      go111moduleForVersion(go111module, goversion),
746		goversion:            goversion,
747		environmentVariables: envVars,
748		goEnv:                env,
749	}, nil
750}
751
752func go111moduleForVersion(go111module string, goversion int) go111module {
753	// Off by default until Go 1.12.
754	if go111module == "off" || (goversion < 12 && go111module == "") {
755		return off
756	}
757	// On by default as of Go 1.16.
758	if go111module == "on" || (goversion >= 16 && go111module == "") {
759		return on
760	}
761	return auto
762}
763
764// findWorkspaceRoot searches for the best workspace root according to the
765// following heuristics:
766//   - First, look for a parent directory containing a gopls.mod file
767//     (experimental only).
768//   - Then, a parent directory containing a go.mod file.
769//   - Then, a child directory containing a go.mod file, if there is exactly
770//     one (non-experimental only).
771// Otherwise, it returns folder.
772// TODO (rFindley): move this to workspace.go
773// TODO (rFindley): simplify this once workspace modules are enabled by default.
774func findWorkspaceRoot(ctx context.Context, folder span.URI, fs source.FileSource, excludePath func(string) bool, experimental bool) (span.URI, error) {
775	patterns := []string{"go.mod"}
776	if experimental {
777		patterns = []string{"gopls.mod", "go.mod"}
778	}
779	for _, basename := range patterns {
780		dir, err := findRootPattern(ctx, folder, basename, fs)
781		if err != nil {
782			return "", errors.Errorf("finding %s: %w", basename, err)
783		}
784		if dir != "" {
785			return dir, nil
786		}
787	}
788
789	// The experimental workspace can handle nested modules at this point...
790	if experimental {
791		return folder, nil
792	}
793
794	// ...else we should check if there's exactly one nested module.
795	all, err := findModules(folder, excludePath, 2)
796	if err == errExhausted {
797		// Fall-back behavior: if we don't find any modules after searching 10000
798		// files, assume there are none.
799		event.Log(ctx, fmt.Sprintf("stopped searching for modules after %d files", fileLimit))
800		return folder, nil
801	}
802	if err != nil {
803		return "", err
804	}
805	if len(all) == 1 {
806		// range to access first element.
807		for uri := range all {
808			return dirURI(uri), nil
809		}
810	}
811	return folder, nil
812}
813
814func findRootPattern(ctx context.Context, folder span.URI, basename string, fs source.FileSource) (span.URI, error) {
815	dir := folder.Filename()
816	for dir != "" {
817		target := filepath.Join(dir, basename)
818		exists, err := fileExists(ctx, span.URIFromPath(target), fs)
819		if err != nil {
820			return "", err
821		}
822		if exists {
823			return span.URIFromPath(dir), nil
824		}
825		next, _ := filepath.Split(dir)
826		if next == dir {
827			break
828		}
829		dir = next
830	}
831	return "", nil
832}
833
834// OS-specific path case check, for case-insensitive filesystems.
835var checkPathCase = defaultCheckPathCase
836
837func defaultCheckPathCase(path string) error {
838	return nil
839}
840
841func validBuildConfiguration(folder span.URI, ws *workspaceInformation, modFiles map[span.URI]struct{}) bool {
842	// Since we only really understand the `go` command, if the user has a
843	// different GOPACKAGESDRIVER, assume that their configuration is valid.
844	if ws.hasGopackagesDriver {
845		return true
846	}
847	// Check if the user is working within a module or if we have found
848	// multiple modules in the workspace.
849	if len(modFiles) > 0 {
850		return true
851	}
852	// The user may have a multiple directories in their GOPATH.
853	// Check if the workspace is within any of them.
854	for _, gp := range filepath.SplitList(ws.gopath) {
855		if source.InDir(filepath.Join(gp, "src"), folder.Filename()) {
856			return true
857		}
858	}
859	return false
860}
861
862// getGoEnv gets the view's various GO* values.
863func (s *Session) getGoEnv(ctx context.Context, folder string, goversion int, go111module string, configEnv []string) (environmentVariables, map[string]string, error) {
864	envVars := environmentVariables{}
865	vars := map[string]*string{
866		"GOCACHE":     &envVars.gocache,
867		"GOPATH":      &envVars.gopath,
868		"GOROOT":      &envVars.goroot,
869		"GOPRIVATE":   &envVars.goprivate,
870		"GOMODCACHE":  &envVars.gomodcache,
871		"GO111MODULE": &envVars.go111module,
872	}
873
874	// We can save ~200 ms by requesting only the variables we care about.
875	args := append([]string{"-json"}, imports.RequiredGoEnvVars...)
876	for k := range vars {
877		args = append(args, k)
878	}
879
880	inv := gocommand.Invocation{
881		Verb:       "env",
882		Args:       args,
883		Env:        configEnv,
884		WorkingDir: folder,
885	}
886	// Don't go through runGoCommand, as we don't need a temporary -modfile to
887	// run `go env`.
888	stdout, err := s.gocmdRunner.Run(ctx, inv)
889	if err != nil {
890		return environmentVariables{}, nil, err
891	}
892	env := make(map[string]string)
893	if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
894		return environmentVariables{}, nil, err
895	}
896
897	for key, ptr := range vars {
898		*ptr = env[key]
899	}
900
901	// Old versions of Go don't have GOMODCACHE, so emulate it.
902	if envVars.gomodcache == "" && envVars.gopath != "" {
903		envVars.gomodcache = filepath.Join(filepath.SplitList(envVars.gopath)[0], "pkg/mod")
904	}
905	// GO111MODULE does not appear in `go env` output until Go 1.13.
906	if goversion < 13 {
907		envVars.go111module = go111module
908	}
909	return envVars, env, err
910}
911
912func (v *View) IsGoPrivatePath(target string) bool {
913	return globsMatchPath(v.goprivate, target)
914}
915
916func (v *View) ModuleUpgrades() map[string]string {
917	v.mu.Lock()
918	defer v.mu.Unlock()
919
920	upgrades := map[string]string{}
921	for mod, ver := range v.moduleUpgrades {
922		upgrades[mod] = ver
923	}
924	return upgrades
925}
926
927func (v *View) RegisterModuleUpgrades(upgrades map[string]string) {
928	v.mu.Lock()
929	defer v.mu.Unlock()
930
931	for mod, ver := range upgrades {
932		v.moduleUpgrades[mod] = ver
933	}
934}
935
936// Copied from
937// https://cs.opensource.google/go/go/+/master:src/cmd/go/internal/str/path.go;l=58;drc=2910c5b4a01a573ebc97744890a07c1a3122c67a
938func globsMatchPath(globs, target string) bool {
939	for globs != "" {
940		// Extract next non-empty glob in comma-separated list.
941		var glob string
942		if i := strings.Index(globs, ","); i >= 0 {
943			glob, globs = globs[:i], globs[i+1:]
944		} else {
945			glob, globs = globs, ""
946		}
947		if glob == "" {
948			continue
949		}
950
951		// A glob with N+1 path elements (N slashes) needs to be matched
952		// against the first N+1 path elements of target,
953		// which end just before the N+1'th slash.
954		n := strings.Count(glob, "/")
955		prefix := target
956		// Walk target, counting slashes, truncating at the N+1'th slash.
957		for i := 0; i < len(target); i++ {
958			if target[i] == '/' {
959				if n == 0 {
960					prefix = target[:i]
961					break
962				}
963				n--
964			}
965		}
966		if n > 0 {
967			// Not enough prefix elements.
968			continue
969		}
970		matched, _ := path.Match(glob, prefix)
971		if matched {
972			return true
973		}
974	}
975	return false
976}
977
978var modFlagRegexp = regexp.MustCompile(`-mod[ =](\w+)`)
979
980// TODO(rstambler): Consolidate modURI and modContent back into a FileHandle
981// after we have a version of the workspace go.mod file on disk. Getting a
982// FileHandle from the cache for temporary files is problematic, since we
983// cannot delete it.
984func (s *snapshot) vendorEnabled(ctx context.Context, modURI span.URI, modContent []byte) (bool, error) {
985	if s.workspaceMode()&moduleMode == 0 {
986		return false, nil
987	}
988	matches := modFlagRegexp.FindStringSubmatch(s.view.goEnv["GOFLAGS"])
989	var modFlag string
990	if len(matches) != 0 {
991		modFlag = matches[1]
992	}
993	if modFlag != "" {
994		// Don't override an explicit '-mod=vendor' argument.
995		// We do want to override '-mod=readonly': it would break various module code lenses,
996		// and on 1.16 we know -modfile is available, so we won't mess with go.mod anyway.
997		return modFlag == "vendor", nil
998	}
999
1000	modFile, err := modfile.Parse(modURI.Filename(), modContent, nil)
1001	if err != nil {
1002		return false, err
1003	}
1004	if fi, err := os.Stat(filepath.Join(s.view.rootURI.Filename(), "vendor")); err != nil || !fi.IsDir() {
1005		return false, nil
1006	}
1007	vendorEnabled := modFile.Go != nil && modFile.Go.Version != "" && semver.Compare("v"+modFile.Go.Version, "v1.14") >= 0
1008	return vendorEnabled, nil
1009}
1010
1011func (v *View) allFilesExcluded(pkg *packages.Package) bool {
1012	opts := v.Options()
1013	folder := filepath.ToSlash(v.folder.Filename())
1014	for _, f := range pkg.GoFiles {
1015		f = filepath.ToSlash(f)
1016		if !strings.HasPrefix(f, folder) {
1017			return false
1018		}
1019		if !pathExcludedByFilter(strings.TrimPrefix(f, folder), opts) {
1020			return false
1021		}
1022	}
1023	return true
1024}
1025
1026func pathExcludedByFilterFunc(opts *source.Options) func(string) bool {
1027	return func(path string) bool {
1028		return pathExcludedByFilter(path, opts)
1029	}
1030}
1031
1032func pathExcludedByFilter(path string, opts *source.Options) bool {
1033	path = strings.TrimPrefix(filepath.ToSlash(path), "/")
1034
1035	excluded := false
1036	for _, filter := range opts.DirectoryFilters {
1037		op, prefix := filter[0], filter[1:]
1038		// Non-empty prefixes have to be precise directory matches.
1039		if prefix != "" {
1040			prefix = prefix + "/"
1041			path = path + "/"
1042		}
1043		if !strings.HasPrefix(path, prefix) {
1044			continue
1045		}
1046		excluded = op == '-'
1047	}
1048	return excluded
1049}
1050