@@ -5,6 +5,7 @@ import (
55 "fmt"
66 "log/slog"
77 "os"
8+ "path/filepath"
89 "sync"
910 "sync/atomic"
1011 "time"
@@ -13,22 +14,23 @@ import (
1314 "github.com/charmbracelet/crush/internal/csync"
1415 "github.com/charmbracelet/crush/internal/fsext"
1516 "github.com/charmbracelet/crush/internal/lsp/protocol"
16− "github.com/fsnotify/fsnotify"
17+ "github.com/rjeczalik/notify"
1718)
1819
19−// global manages a single fsnotify.Watcher instance shared across all LSP clients.
20+// global manages file watching shared across all LSP clients.
2021//
21−// IMPORTANT: This implementation only watches directories, not individual files.
22−// The fsnotify library automatically provides events for all files within watched
23−// directories, making this approach much more efficient than watching individual files.
22+// IMPORTANT: This implementation uses github.com/rjeczalik/notify which provides
23+// recursive watching on all platforms. On macOS it uses FSEvents, on Linux it
24+// uses inotify (with recursion handled by the library), and on Windows it uses
25+// ReadDirectoryChangesW.
2426//
25−// Key benefits of directory-only watching:
26−// - Significantly fewer file descriptors used
27−// - Automatic coverage of new files created in watched directories
28−// - Better performance with large codebases
29−// - fsnotify handles deduplication internally (no need to track watched dirs)
27+// Key benefits:
28+// - Single watch point for entire directory tree
29+// - Automatic recursive watching without manually adding subdirectories
30+// - No file descriptor exhaustion issues
3031type global struct {
31− watcher *fsnotify.Watcher
32+ // Channel for receiving file system events
33+ events chan notify.EventInfo
3234
3335 // Map of workspace watchers by client name
3436 watchers *csync.Map[string, *Client]
@@ -54,6 +56,7 @@ type global struct {
5456var instance = sync.OnceValue(func() *global {
5557 ctx, cancel := context.WithCancel(context.Background())
5658 gw := &global{
59+ events: make(chan notify.EventInfo, 4096), // Large buffer to prevent dropping events
5760 watchers: csync.NewMap[string, *Client](),
5861 debounceTime: 300 * time.Millisecond,
5962 debounceMap: csync.NewMap[string, *time.Timer](),
@@ -61,15 +64,6 @@ var instance = sync.OnceValue(func() *global {
6164 cancel: cancel,
6265 }
6366
64− // Initialize the fsnotify watcher
65− watcher, err := fsnotify.NewWatcher()
66− if err != nil {
67− slog.Error("lsp watcher: Failed to create global file watcher", "error", err)
68− return gw
69− }
70−
71− gw.watcher = watcher
72−
7367 return gw
7468})
7569
@@ -85,11 +79,11 @@ func (gw *global) unregister(name string) {
8579 slog.Debug("lsp watcher: Unregistered workspace watcher", "name", name)
8680}
8781
88−// Start walks the given path and sets up the watcher on it.
82+// Start sets up recursive watching on the workspace root.
8983//
90−// Note: We only watch directories, not individual files. fsnotify automatically provides
91−// events for all files within watched directories. Multiple calls with the same workspace
92−// are safe since fsnotify handles directory deduplication internally.
84+// Note: We use github.com/rjeczalik/notify which provides recursive watching
85+// with a single watch point. The "..." suffix means watch recursively.
86+// This is much more efficient than manually walking and watching each directory.
9387func Start() error {
9488 gw := instance()
9589
@@ -107,59 +101,33 @@ func Start() error {
107101 gw.root = root
108102 gw.started.Store(true)
109103
110− // Start the event processing goroutine now that we're initialized
104+ // Start the event processing goroutine
111105 gw.wg.Add(1)
112106 go gw.processEvents()
113107
114− // Walk the workspace and add only directories to the watcher
115− // fsnotify will automatically provide events for all files within these directories
116− // Multiple calls with the same directories are safe (fsnotify deduplicates)
117− err := fsext.WalkDirectories(root, func(path string, d os.DirEntry, err error) error {
118− if err != nil {
119− return err
120− }
121−
122− // Add directory to watcher (fsnotify handles deduplication automatically)
123− if err := gw.addDirectoryToWatcher(path); err != nil {
124− slog.Error("lsp watcher: Error watching directory", "path", path, "error", err)
125− }
126−
127− return nil
128− })
129− if err != nil {
130− return fmt.Errorf("lsp watcher: error walking workspace %s: %w", root, err)
131− }
132−
133− return nil
134−}
108+ // Set up recursive watching on the root directory
109+ // The "..." suffix tells notify to watch recursively
110+ watchPath := filepath.Join(root, "...")
135111
136−// addDirectoryToWatcher adds a directory to the fsnotify watcher.
137−// fsnotify handles deduplication internally, so we don't need to track watched directories.
138−func (gw *global) addDirectoryToWatcher(dirPath string) error {
139− if gw.watcher == nil {
140− return fmt.Errorf("lsp watcher: global watcher not initialized")
141− }
112+ // Watch for all event types we care about
113+ events := notify.Create | notify.Write | notify.Remove | notify.Rename
142114
143− // Add directory to fsnotify watcher - fsnotify handles deduplication
144− // "A path can only be watched once; watching it more than once is a no-op"
145− err := gw.watcher.Add(dirPath)
146− if err != nil {
147− return fmt.Errorf("lsp watcher: failed to watch directory %s: %w", dirPath, err)
115+ if err := notify.Watch(watchPath, gw.events, events); err != nil {
116+ return fmt.Errorf("lsp watcher: error setting up recursive watch on %s: %w", root, err)
148117 }
149118
150− slog.Debug("lsp watcher: watching directory", "path", dirPath)
119+ slog.Info("lsp watcher: Started recursive watching", "root", root)
151120 return nil
152121}
153122
154−// processEvents processes file system events and handles them centrally.
155−// Since we only watch directories, we automatically get events for all files
156−// within those directories. When new directories are created, we add them
157−// to the watcher to ensure complete coverage.
123+// processEvents processes file system events from the notify library.
124+// Since notify handles recursive watching for us, we don't need to manually
125+// add new directories - they're automatically included.
158126func (gw *global) processEvents() {
159127 defer gw.wg.Done()
160128 cfg := config.Get()
161129
162− if gw.watcher == nil || !gw.started.Load() {
130+ if !gw.started.Load() {
163131 slog.Error("lsp watcher: Global watcher not initialized")
164132 return
165133 }
@@ -169,68 +137,89 @@ func (gw *global) processEvents() {
169137 case <-gw.ctx.Done():
170138 return
171139
172− case event, ok := <-gw.watcher.Events:
140+ case event, ok := <-gw.events:
173141 if !ok {
174142 return
175143 }
176144
177− // Handle directory creation globally (only once)
178− // When new directories are created, we need to add them to the watcher
179− // to ensure we get events for files created within them
180− if event.Op&fsnotify.Create != 0 {
181− if info, err := os.Stat(event.Name); err == nil && info.IsDir() {
182− if !fsext.ShouldExcludeFile(gw.root, event.Name) {
183− if err := gw.addDirectoryToWatcher(event.Name); err != nil {
184− slog.Error("lsp watcher: Error adding new directory to watcher", "path", event.Name, "error", err)
185− }
186− } else if cfg != nil && cfg.Options.DebugLSP {
187− slog.Debug("lsp watcher: Skipping ignored new directory", "path", event.Name)
188− }
189− }
145+ path := event.Path()
146+
147+ // Skip ignored files
148+ if fsext.ShouldExcludeFile(gw.root, path) {
149+ continue
190150 }
191151
192152 if cfg != nil && cfg.Options.DebugLSP {
193− slog.Debug("lsp watcher: Global watcher received event", "path", event.Name, "op", event.Op.String())
153+ slog.Debug("lsp watcher: Global watcher received event", "path", path, "event", event.Event().String())
194154 }
195155
196− // Process the event centrally
156+ // Convert notify event to our internal format and handle it
197157 gw.handleFileEvent(event)
198−
199− case err, ok := <-gw.watcher.Errors:
200− if !ok {
201− return
202− }
203− slog.Error("lsp watcher: Global watcher error", "error", err)
204158 }
205159 }
206160}
207161
208162// handleFileEvent processes a file system event and distributes notifications to relevant clients
209−func (gw *global) handleFileEvent(event fsnotify.Event) {
163+func (gw *global) handleFileEvent(event notify.EventInfo) {
210164 cfg := config.Get()
211− uri := string(protocol.URIFromPath(event.Name))
212−
213− // Handle file creation for all relevant clients (only once)
214− if event.Op&fsnotify.Create != 0 {
215− if info, err := os.Stat(event.Name); err == nil && !info.IsDir() {
216− if !fsext.ShouldExcludeFile(gw.root, event.Name) {
217− gw.openMatchingFileForClients(event.Name)
165+ path := event.Path()
166+ uri := string(protocol.URIFromPath(path))
167+
168+ // Map notify events to our change types
169+ var changeType protocol.FileChangeType
170+ var watchKindNeeded protocol.WatchKind
171+
172+ switch event.Event() {
173+ case notify.Create:
174+ changeType = protocol.FileChangeType(protocol.Created)
175+ watchKindNeeded = protocol.WatchCreate
176+ // Handle file creation for all relevant clients
177+ if !isDir(path) && !fsext.ShouldExcludeFile(gw.root, path) {
178+ gw.openMatchingFileForClients(path)
179+ }
180+ case notify.Write:
181+ changeType = protocol.FileChangeType(protocol.Changed)
182+ watchKindNeeded = protocol.WatchChange
183+ case notify.Remove:
184+ changeType = protocol.FileChangeType(protocol.Deleted)
185+ watchKindNeeded = protocol.WatchDelete
186+ case notify.Rename:
187+ // Treat rename as delete + create
188+ // First handle as delete
189+ for _, watcher := range gw.watchers.Seq2() {
190+ if !watcher.client.HandlesFile(path) {
191+ continue
218192 }
193+ if watched, watchKind := watcher.isPathWatched(path); watched {
194+ if watchKind&protocol.WatchDelete != 0 {
195+ gw.handleFileEventForClient(watcher, uri, protocol.FileChangeType(protocol.Deleted))
196+ }
197+ }
198+ }
199+ // Then check if renamed file exists and treat as create
200+ if !isDir(path) {
201+ changeType = protocol.FileChangeType(protocol.Created)
202+ watchKindNeeded = protocol.WatchCreate
203+ } else {
204+ return // Already handled delete, nothing more to do for directories
219205 }
206+ default:
207+ // Unknown event type, skip
208+ return
220209 }
221210
222211 // Process the event for each relevant client
223212 for client, watcher := range gw.watchers.Seq2() {
224− if !watcher.client.HandlesFile(event.Name) {
213+ if !watcher.client.HandlesFile(path) {
225214 continue // client doesn't handle this filetype
226215 }
227216
228217 // Debug logging per client
229218 if cfg.Options.DebugLSP {
230− matched, kind := watcher.isPathWatched(event.Name)
219+ matched, kind := watcher.isPathWatched(path)
231220 slog.Debug("lsp watcher: File event for client",
232− "path", event.Name,
233− "operation", event.Op.String(),
221+ "path", path,
222+ "event", event.Event().String(),
234223 "watched", matched,
235224 "kind", kind,
236225 "client", client,
@@ -238,46 +227,31 @@ func (gw *global) handleFileEvent(event fsnotify.Event) {
238227 }
239228
240229 // Check if this path should be watched according to server registrations
241− if watched, watchKind := watcher.isPathWatched(event.Name); watched {
242− switch {
243− case event.Op&fsnotify.Write != 0:
244− if watchKind&protocol.WatchChange != 0 {
245− gw.debounceHandleFileEventForClient(watcher, uri, protocol.FileChangeType(protocol.Changed))
246− }
247− case event.Op&fsnotify.Create != 0:
248− // File creation was already handled globally above
249− // Just send the notification if needed
250− info, err := os.Stat(event.Name)
251− if err != nil {
252− if !os.IsNotExist(err) {
253− slog.Debug("lsp watcher: Error getting file info", "path", event.Name, "error", err)
254− }
230+ if watched, watchKind := watcher.isPathWatched(path); watched {
231+ if watchKind&watchKindNeeded != 0 {
232+ // Skip directory events for non-delete operations
233+ if changeType != protocol.FileChangeType(protocol.Deleted) && isDir(path) {
255234 continue
256235 }
257− if !info.IsDir() && watchKind&protocol.WatchCreate != 0 {
258− gw.debounceHandleFileEventForClient(watcher, uri, protocol.FileChangeType(protocol.Created))
259− }
260− case event.Op&fsnotify.Remove != 0:
261− if watchKind&protocol.WatchDelete != 0 {
262− gw.handleFileEventForClient(watcher, uri, protocol.FileChangeType(protocol.Deleted))
263− }
264− case event.Op&fsnotify.Rename != 0:
265− // For renames, first delete
266− if watchKind&protocol.WatchDelete != 0 {
267− gw.handleFileEventForClient(watcher, uri, protocol.FileChangeType(protocol.Deleted))
268− }
269236
270− // Then check if the new file exists and create an event
271− if info, err := os.Stat(event.Name); err == nil && !info.IsDir() {
272− if watchKind&protocol.WatchCreate != 0 {
273− gw.debounceHandleFileEventForClient(watcher, uri, protocol.FileChangeType(protocol.Created))
274− }
237+ if changeType == protocol.FileChangeType(protocol.Deleted) {
238+ // Don't debounce deletes
239+ gw.handleFileEventForClient(watcher, uri, changeType)
240+ } else {
241+ // Debounce creates and changes
242+ gw.debounceHandleFileEventForClient(watcher, uri, changeType)
275243 }
276244 }
277245 }
278246 }
279247}
280248
249+// isDir checks if a path is a directory
250+func isDir(path string) bool {
251+ info, err := os.Stat(path)
252+ return err == nil && info.IsDir()
253+}
254+
281255// openMatchingFileForClients opens a newly created file for all clients that handle it (only once per file)
282256func (gw *global) openMatchingFileForClients(path string) {
283257 // Skip directories
@@ -349,10 +323,9 @@ func (gw *global) shutdown() {
349323 gw.cancel()
350324 }
351325
352− if gw.watcher != nil {
353− gw.watcher.Close()
354− gw.watcher = nil
355− }
326+ // Stop watching and close the event channel
327+ notify.Stop(gw.events)
328+ close(gw.events)
356329
357330 gw.wg.Wait()
358331 slog.Debug("lsp watcher: Global watcher shutdown complete")