From 9e9a988e33eab6224c61f4e4fd4867db9d9fdf47 Mon Sep 17 00:00:00 2001 From: valoq Date: Sat, 30 May 2026 11:20:06 +0200 Subject: [PATCH] fix: prevent deadlock when watching files (#2599) * fix deadlock * improve patch * re-trigger ci * improve patch --- watch.go | 46 ++++++++++++++++++++++++++++------------------ 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/watch.go b/watch.go index 2bb146d4..833e3872 100644 --- a/watch.go +++ b/watch.go @@ -2,24 +2,27 @@ package main import ( "log" + "maps" "os" "path/filepath" + "slices" + "sync" "time" "github.com/fsnotify/fsnotify" ) type watch struct { - watcher *fsnotify.Watcher - events <-chan fsnotify.Event - quit chan struct{} - pending map[watchUpdate]bool - timeout chan watchUpdate - dirChan chan<- *dir - fileChan chan<- *file - delChan chan<- string - addChan chan string - paths map[string]bool + watcher *fsnotify.Watcher + events <-chan fsnotify.Event + quit chan struct{} + pending map[watchUpdate]bool + timeout chan watchUpdate + dirChan chan<- *dir + fileChan chan<- *file + delChan chan<- string + paths map[string]bool + pathsLock sync.Mutex } func newWatch(dirChan chan<- *dir, fileChan chan<- *file, delChan chan<- string) *watch { @@ -30,7 +33,6 @@ func newWatch(dirChan chan<- *dir, fileChan chan<- *file, delChan chan<- string) dirChan: dirChan, fileChan: fileChan, delChan: delChan, - addChan: make(chan string, 1024), paths: make(map[string]bool), } @@ -76,17 +78,19 @@ func (watch *watch) add(path string) { return } - watch.addChan <- path + if err := watch.watcher.Add(path); err != nil { + log.Printf("watch path %s: %s", path, err) + return + } + + watch.pathsLock.Lock() + watch.paths[path] = true + watch.pathsLock.Unlock() } func (watch *watch) loop() { for { select { - case path := <-watch.addChan: - watch.paths[path] = true - if err := watch.watcher.Add(path); err != nil { - log.Printf("watch path %s: %s", path, err) - } case ev := <-watch.events: if ev.Has(fsnotify.Create) { for _, path := range watch.getSameDirs(filepath.Dir(ev.Name)) { @@ -127,7 +131,9 @@ func (watch *watch) loop() { delete(watch.pending, update) } case <-watch.quit: + watch.pathsLock.Lock() clear(watch.paths) + watch.pathsLock.Unlock() return } } @@ -175,7 +181,11 @@ func (watch *watch) getSameDirs(dir string) []string { return nil } - for path := range watch.paths { + watch.pathsLock.Lock() + all := slices.Collect(maps.Keys(watch.paths)) + watch.pathsLock.Unlock() + + for _, path := range all { if path == dir { paths = append(paths, path) continue