| 1 | // Copyright 2026 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 | "errors" |
| 9 | "io/fs" |
| 10 | "log/slog" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "time" |
| 16 | |
| 17 | "github.com/fsnotify/fsnotify" |
| 18 | "golang.org/x/tools/gopls/internal/protocol" |
| 19 | "golang.org/x/tools/gopls/internal/settings" |
| 20 | "golang.org/x/tools/internal/robustio" |
| 21 | ) |
| 22 | |
| 23 | // ErrClosed is used when trying to operate on a closed Watcher. |
| 24 | var ErrClosed = errors.New("file watcher: watcher already closed") |
| 25 | |
| 26 | func NewFSNotifyWatcher(log *slog.Logger, onEvents func([]protocol.FileEvent), onError func(error)) (Watcher, error) { |
| 27 | watcher, err := fsnotify.NewWatcher() |
| 28 | if err != nil { |
| 29 | return nil, err |
| 30 | } |
| 31 | if log != nil { |
| 32 | log = log.With("watcher", "fsnotify") |
| 33 | } |
| 34 | w := &fsnotifyWatcher{ |
| 35 | log: log, |
| 36 | watcher: watcher, |
| 37 | onEvents: onEvents, |
| 38 | onError: onError, |
| 39 | knownDirs: make(map[string]struct{}), |
| 40 | stop: make(chan struct{}), |
| 41 | ready: make(chan struct{}, 1), |
| 42 | } |
| 43 | w.wg.Go(w.run) |
| 44 | w.wg.Go(w.process) |
| 45 | return w, nil |
| 46 | } |
| 47 | |
| 48 | // fsnotifyInterval is the debounce duration used to batch raw file system |
| 49 | // events before flushing them to the language server. A 500ms window strikes |
| 50 | // a practical balance: it is long enough to absorb bursts of noisy, rapid-fire |
| 51 | // OS events (such as those generated by a 'git checkout' or 'Save All') |
| 52 | // without thrashing the CPU, but short enough to keep the editor's diagnostics |
| 53 | // feeling responsive to the user. |
| 54 | const fsnotifyInterval = 500 * time.Millisecond |
| 55 | |
| 56 | // fsnotifyWatcher collects events from a [fsnotify.Watcher] and converts them |
| 57 | // into batched LSP [protocol.FileEvent]s. |
| 58 | type fsnotifyWatcher struct { |
| 59 | log *slog.Logger |
| 60 | onEvents func([]protocol.FileEvent) |
| 61 | onError func(error) |
| 62 | |
| 63 | stop chan struct{} // closed by Close to terminate run and process loop |
| 64 | wg sync.WaitGroup // counts the number of active run and process goroutines (max 2) |
| 65 | |
| 66 | ready chan struct{} // signals work to process |
| 67 | |
| 68 | watcher *fsnotify.Watcher |
| 69 | |
| 70 | mu sync.Mutex // guards all fields below |
| 71 | |
| 72 | // in is the queue of fsnotify events waiting to be processed. |
| 73 | in []fsnotify.Event |
| 74 | |
| 75 | // out is the current batch of unsent file events, which will be sent when |
| 76 | // the timer expires. |
| 77 | out []protocol.FileEvent |
| 78 | |
| 79 | // knownDirs tracks all known directories to help distinguish between file |
| 80 | // and directory deletion events. |
| 81 | knownDirs map[string]struct{} |
| 82 | } |
| 83 | |
| 84 | // run is the receiver and sender loop. |
| 85 | // |
| 86 | // As receiver, its primary responsibility is to drain events and errors from |
| 87 | // the fsnotify watcher as quickly as possible and enqueue events for processing |
| 88 | // by the process goroutine. This is critical to work around a potential |
| 89 | // fsnotify deadlock (see fsnotify/fsnotify#502). |
| 90 | // |
| 91 | // As sender, it manages a timer and flush events to the handler if there is |
| 92 | // no events captured for a period of time. |
| 93 | func (w *fsnotifyWatcher) run() { |
| 94 | timer := time.NewTimer(fsnotifyInterval) |
| 95 | defer timer.Stop() |
| 96 | |
| 97 | for { |
| 98 | select { |
| 99 | case <-w.stop: |
| 100 | return |
| 101 | |
| 102 | case <-timer.C: |
| 103 | // TODO(hxjiang): flush is triggered when there is no events captured |
| 104 | // in a certain period of time, it may be better to flush it when the |
| 105 | // w.in is completely empty. |
| 106 | // |
| 107 | // Currently, partial events may be emitted if a directory watch gets |
| 108 | // stuck. While this does not affect correctness, it means events |
| 109 | // might be sent to the client in multiple portions rather than a |
| 110 | // single batch. |
| 111 | w.mu.Lock() |
| 112 | events := w.out |
| 113 | w.out = nil |
| 114 | w.mu.Unlock() |
| 115 | |
| 116 | if len(events) > 0 { |
| 117 | w.onEvents(events) |
| 118 | } |
| 119 | |
| 120 | timer.Reset(fsnotifyInterval) |
| 121 | |
| 122 | case event, ok := <-w.watcher.Events: |
| 123 | // The watcher closed. Continue the loop and let the <-w.stop case |
| 124 | // handle the actual shutdown. |
| 125 | if !ok { |
| 126 | continue |
| 127 | } |
| 128 | |
| 129 | // TODO(hxjiang): perform some filtering before we reset the timer |
| 130 | // to avoid consistenly resetting the timer in a noisy file syestem, |
| 131 | // or simply convert the event here. |
| 132 | timer.Reset(fsnotifyInterval) |
| 133 | |
| 134 | w.mu.Lock() |
| 135 | w.in = append(w.in, event) |
| 136 | w.mu.Unlock() |
| 137 | |
| 138 | w.signal() |
| 139 | |
| 140 | case err, ok := <-w.watcher.Errors: |
| 141 | // The watcher closed. Continue the loop and let the <-w.stop case |
| 142 | // handle the actual shutdown. |
| 143 | if !ok { |
| 144 | continue |
| 145 | } |
| 146 | |
| 147 | w.onError(err) |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | // process is a worker goroutine that converts raw fsnotify events from queue |
| 153 | // and handles the potentially blocking work of watching new directories. It is |
| 154 | // the counterpart to the run goroutine. |
| 155 | func (w *fsnotifyWatcher) process() { |
| 156 | for { |
| 157 | select { |
| 158 | case <-w.stop: |
| 159 | return |
| 160 | |
| 161 | case <-w.ready: |
| 162 | w.mu.Lock() |
| 163 | events := w.in |
| 164 | w.in = nil |
| 165 | w.mu.Unlock() |
| 166 | |
| 167 | for _, event := range events { |
| 168 | // File watcher is closing, drop any remaining work. |
| 169 | select { |
| 170 | case <-w.stop: |
| 171 | return |
| 172 | default: |
| 173 | } |
| 174 | |
| 175 | // fsnotify does not guarantee clean filepaths. |
| 176 | event.Name = filepath.Clean(event.Name) |
| 177 | |
| 178 | // fsnotify.Event should not be handled concurrently, to preserve their |
| 179 | // original order. For example, if a file is deleted and recreated, |
| 180 | // concurrent handling could process the events in reverse order. |
| 181 | e, isDir := w.convertEvent(event) |
| 182 | if e == (protocol.FileEvent{}) { |
| 183 | continue |
| 184 | } |
| 185 | |
| 186 | var synthesized []protocol.FileEvent // synthesized create events |
| 187 | |
| 188 | if isDir { |
| 189 | switch e.Type { |
| 190 | case protocol.Created: |
| 191 | // Walks the entire directory tree, synthesizes create |
| 192 | // events for its contents, and establishes watches for |
| 193 | // subdirectories. This recursive, pre-order traversal |
| 194 | // guarantees a logical event sequence: parent directory |
| 195 | // creation events always precede those of their children. |
| 196 | // |
| 197 | // For example, consider a creation event for directory |
| 198 | // a, and suppose a has contents [a/b, a/b/c, a/c, a/c/d]. |
| 199 | // The effective events will be: |
| 200 | // |
| 201 | // CREATE a |
| 202 | // CREATE a/b |
| 203 | // CREATE a/b/c |
| 204 | // CREATE a/c |
| 205 | // CREATE a/c/d |
| 206 | w.walkDirWithRetry(event.Name, w.onError, func(path string, isDir bool) error { |
| 207 | if path != event.Name { |
| 208 | synthesized = append(synthesized, protocol.FileEvent{ |
| 209 | URI: protocol.URIFromPath(path), |
| 210 | Type: protocol.Created, |
| 211 | }) |
| 212 | } |
| 213 | |
| 214 | if isDir { |
| 215 | return w.watchDir(path) |
| 216 | } else { |
| 217 | return nil |
| 218 | } |
| 219 | }) |
| 220 | |
| 221 | case protocol.Deleted: |
| 222 | // Upon removal, we only need to remove the entries from |
| 223 | // the map. The [fsnotify.Watcher] removes the watch for |
| 224 | // us. fsnotify/fsnotify#268 |
| 225 | w.mu.Lock() |
| 226 | delete(w.knownDirs, event.Name) |
| 227 | w.mu.Unlock() |
| 228 | default: |
| 229 | // convertEvent enforces that dirs are only Created or Deleted. |
| 230 | panic("impossible") |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // Discovered events must be appended to the 'out' slice atomically. |
| 235 | // This ensures that at any point, the slice contains a logically |
| 236 | // correct (maybe slightly outdated) batch of file events that is |
| 237 | // ready to be flushed. |
| 238 | w.mu.Lock() |
| 239 | // Some systems emit duplicate change events in close |
| 240 | // succession upon file modification. While the current |
| 241 | // deduplication is naive and only handles immediate duplicates, |
| 242 | // a more robust solution is needed. |
| 243 | // https://github.com/fsnotify/fsnotify?tab=readme-ov-file#why-do-i-get-many-chmod-events |
| 244 | // |
| 245 | // TODO(hxjiang): Enhance deduplication. The current batching of |
| 246 | // events means all duplicates, regardless of proximity, should |
| 247 | // be removed. Consider checking the entire buffered slice or |
| 248 | // using a map for this. |
| 249 | if len(w.out) == 0 || w.out[len(w.out)-1] != e { |
| 250 | w.out = append(w.out, e) |
| 251 | } |
| 252 | w.out = append(w.out, synthesized...) // synthesized events are guaranteed to be unique |
| 253 | w.mu.Unlock() |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | // signal notifies the process goroutine that events are added to the queue and |
| 260 | // ready for handling. |
| 261 | func (w *fsnotifyWatcher) signal() { |
| 262 | select { |
| 263 | case w.ready <- struct{}{}: |
| 264 | default: |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | // skipDir reports whether the input dir should be skipped. |
| 269 | // Directories that are unlikely to contain Go source files relevant for |
| 270 | // analysis, such as .git directories or testdata, should be skipped to |
| 271 | // avoid unnecessary file system notifications. This reduces noise and |
| 272 | // improves efficiency. Conversely, any directory that might contain Go |
| 273 | // source code should be watched to ensure that gopls can respond to |
| 274 | // file changes. |
| 275 | func skipDir(dirName string) bool { |
| 276 | // TODO(hxjiang): the file watcher should honor gopls directory |
| 277 | // filter or the new go.mod ignore directive, or actively listening |
| 278 | // to gopls register capability request with method |
| 279 | // "workspace/didChangeWatchedFiles" like a real LSP client. |
| 280 | return strings.HasPrefix(dirName, ".") || strings.HasPrefix(dirName, "_") || dirName == "testdata" |
| 281 | } |
| 282 | |
| 283 | // skipFile reports whether the file should be skipped. |
| 284 | func skipFile(fileName string) bool { |
| 285 | switch strings.TrimPrefix(filepath.Ext(fileName), ".") { |
| 286 | case "go", "mod", "sum", "work", "s": |
| 287 | return false |
| 288 | default: |
| 289 | return true |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | // WatchDir walks through the directory and all its subdirectories, adding |
| 294 | // them to the watcher. |
| 295 | func (w *fsnotifyWatcher) WatchDir(dir string) error { |
| 296 | if w.log != nil { |
| 297 | w.log.Info("Watching", "dir", dir) |
| 298 | } |
| 299 | |
| 300 | return filepath.WalkDir(filepath.Clean(dir), func(path string, dirent fs.DirEntry, err error) error { |
| 301 | if err != nil { |
| 302 | // Permission errors or disappearing files are ignored during walk. |
| 303 | return nil |
| 304 | } |
| 305 | if dirent.IsDir() { |
| 306 | if skipDir(dirent.Name()) { |
| 307 | return filepath.SkipDir |
| 308 | } |
| 309 | |
| 310 | return w.watchDir(path) |
| 311 | } |
| 312 | return nil |
| 313 | }) |
| 314 | } |
| 315 | |
| 316 | // convertEvent translates an [fsnotify.Event] into a [protocol.FileEvent]. |
| 317 | // It returns the translated event and a boolean indicating if the path was a |
| 318 | // directory. For directories, the event Type is either Created or Deleted. |
| 319 | // It returns empty event for events that should be ignored. |
| 320 | func (w *fsnotifyWatcher) convertEvent(event fsnotify.Event) (_ protocol.FileEvent, isDir bool) { |
| 321 | // Determine if the event is for a directory. |
| 322 | if info, err := os.Stat(event.Name); err == nil { |
| 323 | isDir = info.IsDir() |
| 324 | } else if os.IsNotExist(err) { |
| 325 | // Upon deletion, the file/dir has been removed. fsnotify does not |
| 326 | // provide information regarding the deleted item. |
| 327 | // Use the set of known directories to determine if the deleted item was a directory. |
| 328 | isDir = w.isWatchedDir(event.Name) |
| 329 | } else { |
| 330 | // If statting failed, something is wrong with the file system. |
| 331 | // Log and move on. |
| 332 | if w.log != nil { |
| 333 | w.log.Error("failed to stat path, skipping event as its type (file/dir) is unknown", "path", event.Name, "err", err) |
| 334 | } |
| 335 | return protocol.FileEvent{}, false |
| 336 | } |
| 337 | |
| 338 | // Filter out events for directories and files that are not of interest. |
| 339 | if isDir && skipDir(filepath.Base(event.Name)) { |
| 340 | return protocol.FileEvent{}, true |
| 341 | } |
| 342 | if !isDir && skipFile(filepath.Base(event.Name)) { |
| 343 | return protocol.FileEvent{}, false |
| 344 | } |
| 345 | |
| 346 | var t protocol.FileChangeType |
| 347 | switch { |
| 348 | case event.Op.Has(fsnotify.Rename): |
| 349 | // A rename is treated as a deletion of the old path because the |
| 350 | // fsnotify RENAME event doesn't include the new path. A separate |
| 351 | // CREATE event will be sent for the new path if the destination |
| 352 | // directory is watched. |
| 353 | fallthrough |
| 354 | case event.Op.Has(fsnotify.Remove): |
| 355 | // TODO(hxjiang): Directory removal events from some LSP clients may |
| 356 | // not include corresponding removal events for child files and |
| 357 | // subdirectories. Should we do some filtering when adding the dir |
| 358 | // deletion event to the events slice. |
| 359 | t = protocol.Deleted |
| 360 | case event.Op.Has(fsnotify.Create): |
| 361 | t = protocol.Created |
| 362 | case event.Op.Has(fsnotify.Write): |
| 363 | if isDir { |
| 364 | return protocol.FileEvent{}, isDir // ignore dir write events |
| 365 | } |
| 366 | t = protocol.Changed |
| 367 | default: |
| 368 | return protocol.FileEvent{}, isDir // ignore the rest of the events |
| 369 | } |
| 370 | |
| 371 | return protocol.FileEvent{ |
| 372 | URI: protocol.URIFromPath(event.Name), |
| 373 | Type: t, |
| 374 | }, isDir |
| 375 | } |
| 376 | |
| 377 | // watchDir registers a watch for a directory, retrying with backoff if it fails. |
| 378 | // |
| 379 | // Returns nil on success or watcher closing; otherwise, the last error after |
| 380 | // all retries. |
| 381 | func (w *fsnotifyWatcher) watchDir(path string) error { |
| 382 | w.mu.Lock() |
| 383 | w.knownDirs[path] = struct{}{} |
| 384 | w.mu.Unlock() |
| 385 | |
| 386 | // On darwin, watching a directory will fail if it contains broken symbolic |
| 387 | // links. This state can occur temporarily during operations like a git |
| 388 | // branch switch. To handle this, we retry multiple times with exponential |
| 389 | // backoff, allowing time for the symbolic link's target to be created. |
| 390 | var ( |
| 391 | delay = 500 * time.Millisecond |
| 392 | err error |
| 393 | ) |
| 394 | |
| 395 | for i := range 5 { |
| 396 | if i > 0 { |
| 397 | select { |
| 398 | case <-time.After(delay): |
| 399 | delay *= 2 |
| 400 | case <-w.stop: |
| 401 | return nil |
| 402 | } |
| 403 | } |
| 404 | // This function may block due to fsnotify/fsnotify#502. |
| 405 | err = w.watcher.Add(path) |
| 406 | if afterAddHook != nil { |
| 407 | afterAddHook(path, err) |
| 408 | } |
| 409 | if err == nil { |
| 410 | break |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | return err |
| 415 | } |
| 416 | |
| 417 | var afterAddHook func(path string, err error) |
| 418 | |
| 419 | // isWatchedDir reports whether the given path is a known directory that |
| 420 | // the watcher is managing. |
| 421 | func (w *fsnotifyWatcher) isWatchedDir(path string) bool { |
| 422 | w.mu.Lock() |
| 423 | defer w.mu.Unlock() |
| 424 | |
| 425 | _, isDir := w.knownDirs[path] |
| 426 | return isDir |
| 427 | } |
| 428 | |
| 429 | func (w *fsnotifyWatcher) Mode() settings.FileWatcherMode { |
| 430 | return settings.FileWatcherFSNotify |
| 431 | } |
| 432 | |
| 433 | // Poke is a no-op for fsnotify watcher, as it relies on OS events. |
| 434 | func (w *fsnotifyWatcher) Poke() {} |
| 435 | |
| 436 | // Close shuts down the watcher, waits for the internal goroutine to terminate, |
| 437 | // and returns any final error. |
| 438 | func (w *fsnotifyWatcher) Close() error { |
| 439 | // Wait for fsnotify' watcher to terminate. |
| 440 | err := w.watcher.Close() |
| 441 | |
| 442 | // Wait for run and process loop to terminate. It's important to stop the |
| 443 | // run and process loop the last place because we don't know whether |
| 444 | // fsnotify's watcher expect us to keep consuming events or errors from |
| 445 | // [fsnotify.Watcher.Events] and [fsnotify.Watcher.Errors] while it's being |
| 446 | // closed. |
| 447 | // To avoid any potential deadlock, have the channel receiver running until |
| 448 | // the last minute. |
| 449 | close(w.stop) |
| 450 | w.wg.Wait() |
| 451 | |
| 452 | return err |
| 453 | } |
| 454 | |
| 455 | // walkDir calls fn against current path and recursively descends path for each |
| 456 | // file or directory of our interest. |
| 457 | func (w *fsnotifyWatcher) walkDir(path string, isDir bool, errHandler func(error), fn func(path string, isDir bool) error) { |
| 458 | if err := fn(path, isDir); err != nil { |
| 459 | errHandler(err) |
| 460 | return |
| 461 | } |
| 462 | |
| 463 | if !isDir { |
| 464 | return |
| 465 | } |
| 466 | |
| 467 | entries, err := tryFSOperation(w.stop, func() ([]fs.DirEntry, error) { |
| 468 | // ReadDir may fail due because other processes may be actively |
| 469 | // modifying the watched dir see golang/go#74820. |
| 470 | // TODO(hxjiang): consider adding robustio.ReadDir. |
| 471 | return os.ReadDir(path) |
| 472 | }) |
| 473 | if err != nil { |
| 474 | if err != ErrClosed { |
| 475 | errHandler(err) |
| 476 | } |
| 477 | return |
| 478 | } |
| 479 | |
| 480 | for _, e := range entries { |
| 481 | if e.IsDir() && skipDir(e.Name()) { |
| 482 | continue |
| 483 | } |
| 484 | if !e.IsDir() && skipFile(e.Name()) { |
| 485 | continue |
| 486 | } |
| 487 | |
| 488 | w.walkDir(filepath.Join(path, e.Name()), e.IsDir(), errHandler, fn) |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | // walkDirWithRetry walks the file tree rooted at root, calling fn for each |
| 493 | // file or directory of our interest in the tree, including root. |
| 494 | // |
| 495 | // All errors that arise visiting directories or files will be reported to the |
| 496 | // provided error handler function. If an error is encountered visiting a |
| 497 | // directory, that entire subtree will be skipped. |
| 498 | // |
| 499 | // walkDirWithRetry does not follow symbolic links. |
| 500 | // |
| 501 | // It is used instead of [filepath.WalkDir] because it provides control over |
| 502 | // retry behavior when reading a directory fails. If [os.ReadDir] fails with an |
| 503 | // ephemeral error, it is retried multiple times with exponential backoff. |
| 504 | // |
| 505 | // TODO(hxjiang): call walkDirWithRetry in WalkDir. |
| 506 | func (w *fsnotifyWatcher) walkDirWithRetry(root string, errHandler func(error), fn func(path string, isDir bool) error) { |
| 507 | info, err := tryFSOperation(w.stop, func() (os.FileInfo, error) { |
| 508 | return os.Lstat(root) // [os.Lstat] does not follow symlink. |
| 509 | }) |
| 510 | if err != nil { |
| 511 | if err != ErrClosed { |
| 512 | errHandler(err) |
| 513 | } |
| 514 | return |
| 515 | } |
| 516 | |
| 517 | w.walkDir(root, info.IsDir(), errHandler, fn) |
| 518 | } |
| 519 | |
| 520 | // tryFSOperation executes a function `op` with retry logic, making it resilient |
| 521 | // to transient errors. It attempts the operation up to 5 times with exponential |
| 522 | // backoff. Retries occur only if the error is ephemeral. |
| 523 | // |
| 524 | // The operation can be interrupted by closing the `stop` channel, in which case |
| 525 | // it returns [ErrClosed]. |
| 526 | func tryFSOperation[Result any](stop <-chan struct{}, op func() (Result, error)) (Result, error) { |
| 527 | var ( |
| 528 | delay = 50 * time.Millisecond |
| 529 | err error |
| 530 | ) |
| 531 | |
| 532 | for i := range 5 { |
| 533 | if i > 0 { |
| 534 | select { |
| 535 | case <-time.After(delay): |
| 536 | delay *= 2 |
| 537 | case <-stop: |
| 538 | var zero Result |
| 539 | return zero, ErrClosed |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | var res Result |
| 544 | res, err = op() |
| 545 | |
| 546 | if robustio.IsEphemeralError(err) { |
| 547 | continue |
| 548 | } else { |
| 549 | return res, err |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | var zero Result |
| 554 | return zero, err // return last error encountered |
| 555 | } |