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.
5 // Package cache implements the caching layer for gopls.
24 "golang.org/x/mod/modfile"
25 "golang.org/x/mod/semver"
26 "golang.org/x/tools/internal/event"
27 "golang.org/x/tools/internal/gocommand"
28 "golang.org/x/tools/internal/imports"
29 "golang.org/x/tools/internal/lsp/source"
30 "golang.org/x/tools/internal/memoize"
31 "golang.org/x/tools/internal/span"
32 "golang.org/x/tools/internal/xcontext"
33 errors "golang.org/x/xerrors"
41 options *source.Options
43 // mu protects most mutable state of the view.
46 // baseCtx is the context handed to NewView. This is the parent of all
47 // background contexts created for this view.
48 baseCtx context.Context
50 // backgroundCtx is the current context used by background tasks initiated
52 backgroundCtx context.Context
54 // cancel is called when all action being performed by the current view
56 cancel context.CancelFunc
58 // name is the user visible name of this view.
61 // folder is the folder with which this view was constructed.
64 importsState *importsState
66 // keep track of files by uri and by basename, a single file may be mapped
67 // to multiple uris, and the same basename may map to multiple files
68 filesByURI map[span.URI]*fileBase
69 filesByBase map[string][]*fileBase
74 // initialized is closed when the view has been fully initialized. On
75 // initialization, the view's workspace packages are loaded. All of the
76 // fields below are set as part of initialization. If we failed to load, we
77 // only retry if the go.mod file changes, to avoid too many go/packages
80 // When the view is created, initializeOnce is non-nil, initialized is
81 // open, and initCancelFirstAttempt can be used to terminate
82 // initialization. Once initialization completes, initializedErr may be set
83 // and initializeOnce becomes nil. If initializedErr is non-nil,
84 // initialization may be retried (depending on how files are changed). To
85 // indicate that initialization should be retried, initializeOnce will be
86 // set. The next time a caller requests workspace packages, the
87 // initialization will retry.
88 initialized chan struct{}
89 initCancelFirstAttempt context.CancelFunc
91 // initializationSema is used as a mutex to guard initializeOnce and
92 // initializedErr, which will be updated after each attempt to initialize
93 // the view. We use a channel instead of a mutex to avoid blocking when a
94 // context is canceled.
95 initializationSema chan struct{}
96 initializeOnce *sync.Once
99 // workspaceInformation tracks various details about this view's
100 // environment variables, go version, and use of modules.
104 type workspaceInformation struct {
105 // The Go version in use: X in Go 1.X.
108 // hasGopackagesDriver is true if the user has a value set for the
109 // GOPACKAGESDRIVER environment variable or a gopackagesdriver binary on
111 hasGopackagesDriver bool
113 // `go env` variables that need to be tracked by gopls.
116 // The value of GO111MODULE we want to run with.
119 // goEnv is the `go env` output collected when a view is created.
120 // It includes the values of the environment variables above.
121 goEnv map[string]string
123 // rootURI is the rootURI directory of this view. If we are in GOPATH mode, this
124 // is just the folder. If we are in module mode, this is the module rootURI.
128 type environmentVariables struct {
129 gocache, gopath, goprivate, gomodcache, gomod string
132 type workspaceMode int
135 moduleMode workspaceMode = 1 << iota
137 // tempModfile indicates whether or not the -modfile flag should be used.
140 // usesWorkspaceModule indicates support for the experimental workspace module
145 type builtinPackageHandle struct {
146 handle *memoize.Handle
149 type builtinPackageData struct {
150 parsed *source.BuiltinPackage
154 type moduleRoot struct {
156 modURI, sumURI span.URI
159 // fileBase holds the common functionality for all files.
160 // It is intended to be embedded in the file implementations
161 type fileBase struct {
168 func (f *fileBase) URI() span.URI {
172 func (f *fileBase) filename() string {
176 func (f *fileBase) addURI(uri span.URI) int {
177 f.uris = append(f.uris, uri)
181 func (v *View) ID() string { return v.id }
183 // tempModFile creates a temporary go.mod file based on the contents of the
184 // given go.mod file. It is the caller's responsibility to clean up the files
185 // when they are done using them.
186 func tempModFile(modFh, sumFH source.FileHandle) (tmpURI span.URI, cleanup func(), err error) {
187 filenameHash := hashContents([]byte(modFh.URI().Filename()))
188 tmpMod, err := ioutil.TempFile("", fmt.Sprintf("go.%s.*.mod", filenameHash))
194 tmpURI = span.URIFromPath(tmpMod.Name())
195 tmpSumName := sumFilename(tmpURI)
197 content, err := modFh.Read()
202 if _, err := tmpMod.Write(content); err != nil {
207 _ = os.Remove(tmpSumName)
208 _ = os.Remove(tmpURI.Filename())
211 // Be careful to clean up if we return an error from this function.
219 // Create an analogous go.sum, if one exists.
221 sumContents, err := sumFH.Read()
223 return "", cleanup, err
225 if err := ioutil.WriteFile(tmpSumName, sumContents, 0655); err != nil {
226 return "", cleanup, err
230 return tmpURI, cleanup, nil
233 // Name returns the user visible name of this view.
234 func (v *View) Name() string {
238 // Folder returns the folder at the base of this view.
239 func (v *View) Folder() span.URI {
243 func (v *View) Options() *source.Options {
245 defer v.optionsMu.Unlock()
249 func minorOptionsChange(a, b *source.Options) bool {
250 // Check if any of the settings that modify our understanding of files have been changed
251 if !reflect.DeepEqual(a.Env, b.Env) {
254 aBuildFlags := make([]string, len(a.BuildFlags))
255 bBuildFlags := make([]string, len(b.BuildFlags))
256 copy(aBuildFlags, a.BuildFlags)
257 copy(bBuildFlags, b.BuildFlags)
258 sort.Strings(aBuildFlags)
259 sort.Strings(bBuildFlags)
260 // the rest of the options are benign
261 return reflect.DeepEqual(aBuildFlags, bBuildFlags)
264 func (v *View) SetOptions(ctx context.Context, options *source.Options) (source.View, error) {
265 // no need to rebuild the view if the options were not materially changed
267 if minorOptionsChange(v.options, options) {
273 newView, err := v.session.updateView(ctx, v, options)
277 func (v *View) Rebuild(ctx context.Context) (source.Snapshot, func(), error) {
278 newView, err := v.session.updateView(ctx, v, v.Options())
280 return nil, func() {}, err
282 snapshot, release := newView.Snapshot(ctx)
283 return snapshot, release, nil
286 func (s *snapshot) WriteEnv(ctx context.Context, w io.Writer) error {
287 s.view.optionsMu.Lock()
288 env, buildFlags := s.view.envLocked()
289 s.view.optionsMu.Unlock()
291 fullEnv := make(map[string]string)
292 for k, v := range s.view.goEnv {
295 for _, v := range env {
296 s := strings.SplitN(v, "=", 2)
300 if _, ok := fullEnv[s[0]]; ok {
304 goVersion, err := s.view.session.gocmdRunner.Run(ctx, gocommand.Invocation{
307 WorkingDir: s.view.rootURI.Filename(),
312 fmt.Fprintf(w, `go env for %v
315 (valid build configuration = %v)
318 s.view.folder.Filename(),
319 s.view.rootURI.Filename(),
320 strings.TrimRight(goVersion.String(), "\n"),
321 s.ValidBuildConfiguration(),
323 for k, v := range fullEnv {
324 fmt.Fprintf(w, "%s=%s\n", k, v)
329 func (s *snapshot) RunProcessEnvFunc(ctx context.Context, fn func(*imports.Options) error) error {
330 return s.view.importsState.runProcessEnvFunc(ctx, s, fn)
333 // envLocked returns the environment and build flags for the current view.
334 // It assumes that the caller is holding the view's optionsMu.
335 func (v *View) envLocked() ([]string, []string) {
336 env := append(os.Environ(), v.options.EnvSlice()...)
337 buildFlags := append([]string{}, v.options.BuildFlags...)
338 return env, buildFlags
341 func (v *View) contains(uri span.URI) bool {
342 return strings.HasPrefix(string(uri), string(v.rootURI))
345 func (v *View) mapFile(uri span.URI, f *fileBase) {
346 v.filesByURI[uri] = f
347 if f.addURI(uri) == 1 {
348 basename := basename(f.filename())
349 v.filesByBase[basename] = append(v.filesByBase[basename], f)
353 func basename(filename string) string {
354 return strings.ToLower(filepath.Base(filename))
357 func (v *View) relevantChange(c source.FileModification) bool {
358 // If the file is known to the view, the change is relevant.
359 known := v.knownFile(c.URI)
361 // If the file is not known to the view, and the change is only on-disk,
362 // we should not invalidate the snapshot. This is necessary because Emacs
363 // sends didChangeWatchedFiles events for temp files.
364 if !known && c.OnDisk && (c.Action == source.Change || c.Action == source.Delete) {
367 return v.contains(c.URI) || known
370 func (v *View) knownFile(uri span.URI) bool {
374 f, err := v.findFile(uri)
375 return f != nil && err == nil
378 // getFile returns a file for the given URI. It will always succeed because it
379 // adds the file to the managed set if needed.
380 func (v *View) getFile(uri span.URI) (*fileBase, error) {
384 f, err := v.findFile(uri)
392 fname: uri.Filename(),
398 // findFile checks the cache for any file matching the given uri.
400 // An error is only returned for an irreparable failure, for example, if the
401 // filename in question does not exist.
402 func (v *View) findFile(uri span.URI) (*fileBase, error) {
403 if f := v.filesByURI[uri]; f != nil {
407 // no exact match stored, time to do some real work
408 // check for any files with the same basename
409 fname := uri.Filename()
410 basename := basename(fname)
411 if candidates := v.filesByBase[basename]; candidates != nil {
412 pathStat, err := os.Stat(fname)
413 if os.IsNotExist(err) {
417 return nil, nil // the file may exist, return without an error
419 for _, c := range candidates {
420 if cStat, err := os.Stat(c.filename()); err == nil {
421 if os.SameFile(pathStat, cStat) {
429 // no file with a matching name was found, it wasn't in our cache
433 func (v *View) Shutdown(ctx context.Context) {
434 v.session.removeView(ctx, v)
437 func (v *View) shutdown(ctx context.Context) {
438 // Cancel the initial workspace load if it is still running.
439 v.initCancelFirstAttempt()
448 go v.snapshot.generation.Destroy()
449 v.snapshotMu.Unlock()
452 func (v *View) BackgroundContext() context.Context {
456 return v.backgroundCtx
459 func (s *snapshot) IgnoredFile(uri span.URI) bool {
460 filename := uri.Filename()
461 var prefixes []string
462 if len(s.modules) == 0 {
463 for _, entry := range filepath.SplitList(s.view.gopath) {
464 prefixes = append(prefixes, filepath.Join(entry, "src"))
467 prefixes = append(prefixes, s.view.gomodcache)
468 for _, m := range s.modules {
469 prefixes = append(prefixes, m.rootURI.Filename())
472 for _, prefix := range prefixes {
473 if strings.HasPrefix(filename, prefix) {
474 return checkIgnored(filename[len(prefix):])
480 // checkIgnored implements go list's exclusion rules. go help list:
481 // Directory and file names that begin with "." or "_" are ignored
482 // by the go tool, as are directories named "testdata".
483 func checkIgnored(suffix string) bool {
484 for _, component := range strings.Split(suffix, string(filepath.Separator)) {
485 if len(component) == 0 {
488 if component[0] == '.' || component[0] == '_' || component == "testdata" {
495 func (v *View) Snapshot(ctx context.Context) (source.Snapshot, func()) {
497 defer v.snapshotMu.Unlock()
498 return v.snapshot, v.snapshot.generation.Acquire(ctx)
501 func (s *snapshot) initialize(ctx context.Context, firstAttempt bool) {
505 case s.view.initializationSema <- struct{}{}:
509 <-s.view.initializationSema
512 if s.view.initializeOnce == nil {
515 s.view.initializeOnce.Do(func() {
517 s.view.initializeOnce = nil
519 close(s.view.initialized)
523 // If we have multiple modules, we need to load them by paths.
524 var scopes []interface{}
525 var modErrors *source.ErrorList
526 addError := func(uri span.URI, err error) {
527 if modErrors == nil {
528 modErrors = &source.ErrorList{}
530 *modErrors = append(*modErrors, &source.Error{
532 Category: "compiler",
533 Kind: source.ListError,
534 Message: err.Error(),
537 if len(s.modules) > 0 {
538 for _, mod := range s.modules {
539 fh, err := s.GetFile(ctx, mod.modURI)
541 addError(mod.modURI, err)
544 parsed, err := s.ParseMod(ctx, fh)
546 addError(mod.modURI, err)
549 if parsed.File == nil || parsed.File.Module == nil {
550 addError(mod.modURI, fmt.Errorf("no module path for %s", mod.modURI))
553 path := parsed.File.Module.Mod.Path
554 scopes = append(scopes, moduleLoadScope(path))
557 if len(scopes) == 0 {
558 scopes = append(scopes, viewLoadScope("LOAD_VIEW"))
560 err := s.load(ctx, append(scopes, packagePath("builtin"))...)
561 if ctx.Err() != nil {
565 event.Error(ctx, "initial workspace load failed", err)
566 if modErrors != nil {
567 s.view.initializedErr = errors.Errorf("errors loading modules: %v: %w", err, modErrors)
569 s.view.initializedErr = err
575 // invalidateContent invalidates the content of a Go file,
576 // including any position and type information that depends on it.
577 // It returns true if we were already tracking the given file, false otherwise.
578 func (v *View) invalidateContent(ctx context.Context, uris map[span.URI]source.VersionedFileHandle, forceReloadMetadata bool) (source.Snapshot, func()) {
579 // Detach the context so that content invalidation cannot be canceled.
580 ctx = xcontext.Detach(ctx)
582 // Cancel all still-running previous requests, since they would be
583 // operating on stale data.
586 // Do not clone a snapshot until its view has finished initializing.
587 v.snapshot.AwaitInitialized(ctx)
589 // This should be the only time we hold the view's snapshot lock for any period of time.
591 defer v.snapshotMu.Unlock()
593 oldSnapshot := v.snapshot
594 var reinitialize reinitializeView
595 v.snapshot, reinitialize = oldSnapshot.clone(ctx, uris, forceReloadMetadata)
596 go oldSnapshot.generation.Destroy()
598 if reinitialize == maybeReinit || reinitialize == definitelyReinit {
599 v.reinitialize(reinitialize == definitelyReinit)
602 return v.snapshot, v.snapshot.generation.Acquire(ctx)
605 func (v *View) cancelBackground() {
609 // this can happen during shutdown
613 v.backgroundCtx, v.cancel = context.WithCancel(v.baseCtx)
616 func (v *View) reinitialize(force bool) {
617 v.initializationSema <- struct{}{}
619 <-v.initializationSema
622 if !force && v.initializedErr == nil {
626 v.initializeOnce = &once
629 func (s *Session) getWorkspaceInformation(ctx context.Context, folder span.URI, options *source.Options) (*workspaceInformation, error) {
630 if err := checkPathCase(folder.Filename()); err != nil {
631 return nil, errors.Errorf("invalid workspace configuration: %w", err)
634 inv := gocommand.Invocation{
635 WorkingDir: folder.Filename(),
636 Env: options.EnvSlice(),
638 goversion, err := gocommand.GoVersion(ctx, inv, s.gocmdRunner)
643 go111module := os.Getenv("GO111MODULE")
644 if v, ok := options.Env["GO111MODULE"]; ok {
647 // If using 1.16, change the default back to auto. The primary effect of
648 // GO111MODULE=on is to break GOPATH, which we aren't too interested in.
649 if goversion >= 16 && go111module == "" {
653 // Make sure to get the `go env` before continuing with initialization.
654 envVars, env, err := s.getGoEnv(ctx, folder.Filename(), append(options.EnvSlice(), "GO111MODULE="+go111module))
658 // The value of GOPACKAGESDRIVER is not returned through the go command.
659 gopackagesdriver := os.Getenv("GOPACKAGESDRIVER")
660 for _, s := range env {
661 split := strings.SplitN(s, "=", 2)
662 if split[0] == "GOPACKAGESDRIVER" {
663 gopackagesdriver = split[1]
666 // A user may also have a gopackagesdriver binary on their machine, which
667 // works the same way as setting GOPACKAGESDRIVER.
668 tool, _ := exec.LookPath("gopackagesdriver")
669 hasGopackagesDriver := gopackagesdriver != "off" && (gopackagesdriver != "" || tool != "")
672 if envVars.gomod != os.DevNull && envVars.gomod != "" {
673 modURI = span.URIFromPath(envVars.gomod)
676 if options.ExpandWorkspaceToModule && modURI != "" {
677 root = span.URIFromPath(filepath.Dir(modURI.Filename()))
679 return &workspaceInformation{
680 hasGopackagesDriver: hasGopackagesDriver,
681 go111module: go111module,
682 goversion: goversion,
684 environmentVariables: envVars,
689 // OS-specific path case check, for case-insensitive filesystems.
690 var checkPathCase = defaultCheckPathCase
692 func defaultCheckPathCase(path string) error {
696 func validBuildConfiguration(folder span.URI, ws *workspaceInformation, modules map[span.URI]*moduleRoot) bool {
697 // Since we only really understand the `go` command, if the user has a
698 // different GOPACKAGESDRIVER, assume that their configuration is valid.
699 if ws.hasGopackagesDriver {
702 // Check if the user is working within a module or if we have found
703 // multiple modules in the workspace.
704 if len(modules) > 0 {
707 // The user may have a multiple directories in their GOPATH.
708 // Check if the workspace is within any of them.
709 for _, gp := range filepath.SplitList(ws.gopath) {
710 if isSubdirectory(filepath.Join(gp, "src"), folder.Filename()) {
717 func isSubdirectory(root, leaf string) bool {
718 rel, err := filepath.Rel(root, leaf)
719 return err == nil && !strings.HasPrefix(rel, "..")
722 // getGoEnv gets the view's various GO* values.
723 func (s *Session) getGoEnv(ctx context.Context, folder string, configEnv []string) (environmentVariables, map[string]string, error) {
724 envVars := environmentVariables{}
725 vars := map[string]*string{
726 "GOCACHE": &envVars.gocache,
727 "GOPATH": &envVars.gopath,
728 "GOPRIVATE": &envVars.goprivate,
729 "GOMODCACHE": &envVars.gomodcache,
730 "GOMOD": &envVars.gomod,
732 // We can save ~200 ms by requesting only the variables we care about.
733 args := append([]string{"-json"}, imports.RequiredGoEnvVars...)
734 for k := range vars {
735 args = append(args, k)
738 inv := gocommand.Invocation{
744 // Don't go through runGoCommand, as we don't need a temporary -modfile to
746 stdout, err := s.gocmdRunner.Run(ctx, inv)
748 return environmentVariables{}, nil, err
750 env := make(map[string]string)
751 if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
752 return environmentVariables{}, nil, err
755 for key, ptr := range vars {
759 // Old versions of Go don't have GOMODCACHE, so emulate it.
760 if envVars.gomodcache == "" && envVars.gopath != "" {
761 envVars.gomodcache = filepath.Join(filepath.SplitList(envVars.gopath)[0], "pkg/mod")
763 return envVars, env, err
766 func (v *View) IsGoPrivatePath(target string) bool {
767 return globsMatchPath(v.goprivate, target)
771 // https://cs.opensource.google/go/go/+/master:src/cmd/go/internal/str/path.go;l=58;drc=2910c5b4a01a573ebc97744890a07c1a3122c67a
772 func globsMatchPath(globs, target string) bool {
774 // Extract next non-empty glob in comma-separated list.
776 if i := strings.Index(globs, ","); i >= 0 {
777 glob, globs = globs[:i], globs[i+1:]
779 glob, globs = globs, ""
785 // A glob with N+1 path elements (N slashes) needs to be matched
786 // against the first N+1 path elements of target,
787 // which end just before the N+1'th slash.
788 n := strings.Count(glob, "/")
790 // Walk target, counting slashes, truncating at the N+1'th slash.
791 for i := 0; i < len(target); i++ {
792 if target[i] == '/' {
801 // Not enough prefix elements.
804 matched, _ := path.Match(glob, prefix)
812 var modFlagRegexp = regexp.MustCompile(`-mod[ =](\w+)`)
814 // TODO(rstambler): Consolidate modURI and modContent back into a FileHandle
815 // after we have a version of the workspace go.mod file on disk. Getting a
816 // FileHandle from the cache for temporary files is problematic, since we
818 func (s *snapshot) needsModEqualsMod(ctx context.Context, modURI span.URI, modContent []byte) (bool, error) {
819 if s.view.goversion < 16 || s.workspaceMode()&moduleMode == 0 {
823 matches := modFlagRegexp.FindStringSubmatch(s.view.goEnv["GOFLAGS"])
825 if len(matches) != 0 {
829 // Don't override an explicit '-mod=vendor' argument.
830 // We do want to override '-mod=readonly': it would break various module code lenses,
831 // and on 1.16 we know -modfile is available, so we won't mess with go.mod anyway.
832 return modFlag == "vendor", nil
835 modFile, err := modfile.Parse(modURI.Filename(), modContent, nil)
839 if fi, err := os.Stat(filepath.Join(s.view.rootURI.Filename(), "vendor")); err != nil || !fi.IsDir() {
842 vendorEnabled := modFile.Go != nil && modFile.Go.Version != "" && semver.Compare("v"+modFile.Go.Version, "v1.14") >= 0
843 return !vendorEnabled, nil