1
0
mirror of https://github.com/golang/go synced 2024-11-19 00:54:42 -07:00
go/internal/lsp/cache/watcher.go
Rebecca Stambler faa69481e7 internal/lsp/cache: add finer-grained control of file changes
This change is the first step in centralizing control of modifications
to different files, either within the workspace or outside of it. We add
a source.FileAction type to pass into the internal/lsp/cache package and
handle the difference between opening and creating a file.

Now that we load all packages in a workspace by default, we no longer
need to re-load a file on open. This CL should enable CL 206883 to work
correctly.

Change-Id: I2ddb21ca2dd33720d668066e73283f5629d02867
Reviewed-on: https://go-review.googlesource.com/c/tools/+/206888
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
2019-11-14 16:11:15 +00:00

68 lines
1.5 KiB
Go

// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cache
import (
"sync"
"golang.org/x/tools/internal/lsp/source"
)
type watcher struct {
id uint64
callback func(action source.FileAction) bool
}
type WatchMap struct {
mu sync.Mutex
nextID uint64
watchers map[interface{}][]watcher
}
func NewWatchMap() *WatchMap {
return &WatchMap{watchers: make(map[interface{}][]watcher)}
}
func (w *WatchMap) Watch(key interface{}, callback func(source.FileAction) bool) func() {
w.mu.Lock()
defer w.mu.Unlock()
id := w.nextID
w.nextID++
w.watchers[key] = append(w.watchers[key], watcher{
id: id,
callback: callback,
})
return func() {
// unwatch if invoked
w.mu.Lock()
defer w.mu.Unlock()
// find and delete the watcher entry
entries := w.watchers[key]
for i, entry := range entries {
if entry.id == id {
// found it
entries[i] = entries[len(entries)-1]
entries = entries[:len(entries)-1]
}
}
}
}
func (w *WatchMap) Notify(key interface{}, action source.FileAction) bool {
// Make a copy of the watcher callbacks so we don't need to hold
// the mutex during the callbacks (to avoid deadlocks).
w.mu.Lock()
entries := w.watchers[key]
entriesCopy := make([]watcher, len(entries))
copy(entriesCopy, entries)
w.mu.Unlock()
var result bool
for _, entry := range entriesCopy {
result = entry.callback(action) || result
}
return result
}