From 52f1f8ac2819784d319e78f383423d6b7493a1e4 Mon Sep 17 00:00:00 2001 From: Torsten Bronger Date: Sun, 23 May 2021 20:16:20 +0200 Subject: [PATCH] Re-structure according to fsnotify recommendations For some very obscure reason (or let's call it "badly explained"), the reading from the event and error channel should take place in a separate goroutine. See https://github.com/howeyc/fsnotify/issues/7 for a discussion about it. Apparently, something may block if done otherwise. Although all material about this topic fails to give a code example that exhibits this problem, I obey and put the events reader into its own goroutine. --- watchdog.go | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/watchdog.go b/watchdog.go index 6818b5d..0724cdb 100644 --- a/watchdog.go +++ b/watchdog.go @@ -71,10 +71,8 @@ func longestPrefix(paths []string) string { return result } -func getWatcher() *fsnotify.Watcher { - watcher, err := fsnotify.NewWatcher() - check(err) - err = filepath.WalkDir(os.Args[2], +func addWatches(watcher *fsnotify.Watcher) { + err := filepath.WalkDir(os.Args[2], func(path string, d fs.DirEntry, err error) error { if err != nil { return err @@ -86,7 +84,6 @@ func getWatcher() *fsnotify.Watcher { return nil }) check(err) - return watcher } func eventsWatcher(watcher *fsnotify.Watcher, workItems chan<- workItem) { @@ -186,11 +183,15 @@ func worker(workPackages <-chan []workItem) { } func main() { - watcher := getWatcher() workItems := make(chan workItem) workPackages := make(chan []workItem) go workMarshaller(workItems, workPackages) go worker(workPackages) + watcher, err := fsnotify.NewWatcher() + check(err) + done := make(chan bool) + go eventsWatcher(watcher, workItems) logger.Println("Watching …") - eventsWatcher(watcher, workItems) + addWatches(watcher) + <-done }