| 1 | // Copyright 2025 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 filewatcher |
| 6 | |
| 7 | import ( |
| 8 | "fmt" |
| 9 | "log/slog" |
| 10 | |
| 11 | "golang.org/x/tools/gopls/internal/protocol" |
| 12 | "golang.org/x/tools/gopls/internal/settings" |
| 13 | ) |
| 14 | |
| 15 | // Watcher monitors file system events. |
| 16 | type Watcher interface { |
| 17 | // WatchDir adds a directory to the set of watched directories. |
| 18 | WatchDir(path string) error |
| 19 | |
| 20 | // Close stops the watcher and releases any associated resources. |
| 21 | Close() error |
| 22 | |
| 23 | // Poke signals the watcher to prioritize a scan, if applicable. |
| 24 | // This is used to implement adaptive polling. |
| 25 | Poke() |
| 26 | |
| 27 | // Mode returns the current mode of the file watcher. |
| 28 | Mode() settings.FileWatcherMode |
| 29 | } |
| 30 | |
| 31 | // New creates a new file watcher and starts its event-handling loop. The |
| 32 | // [Watcher.Close] method must be called to clean up resources. |
| 33 | // |
| 34 | // The provided event handler is called sequentially with a batch of file events, |
| 35 | // but the error handler is called concurrently. The watcher blocks until the |
| 36 | // handler returns, so the handlers should be fast and non-blocking. |
| 37 | func New(mode settings.FileWatcherMode, logger *slog.Logger, onEvents func([]protocol.FileEvent), onError func(error)) (Watcher, error) { |
| 38 | switch mode { |
| 39 | case settings.FileWatcherPoll: |
| 40 | return NewPollWatcher(logger, onEvents, onError), nil |
| 41 | case settings.FileWatcherFSNotify: |
| 42 | return NewFSNotifyWatcher(logger, onEvents, onError) |
| 43 | } |
| 44 | // TODO(hxjiang): support "auto" mode. |
| 45 | return nil, fmt.Errorf("unknown FileWatcher mode: %q", mode) |
| 46 | } |