From a0935a3de0cec483a605df5017307f50a186f5cb Mon Sep 17 00:00:00 2001 From: Tim Culverhouse Date: Thu, 2 Mar 2023 16:46:00 -0600 Subject: worker/lib: implement an fswatcher interface Implement an FSWatcher interface. The interface is used to abstract away file system watchers, which have implementation specific backends. The initial interface has one implementation: inotify for linux. Subsequent commits will add a macOS watcher. Signed-off-by: Tim Culverhouse Tested-by: Ben Lee-Cohen Acked-by: Robin Jarry --- worker/lib/watchers/linux/linux.go | 73 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 worker/lib/watchers/linux/linux.go (limited to 'worker/lib') diff --git a/worker/lib/watchers/linux/linux.go b/worker/lib/watchers/linux/linux.go new file mode 100644 index 00000000..473bb05e --- /dev/null +++ b/worker/lib/watchers/linux/linux.go @@ -0,0 +1,73 @@ +package linux + +import ( + "git.sr.ht/~rjarry/aerc/log" + "git.sr.ht/~rjarry/aerc/worker/handlers" + "git.sr.ht/~rjarry/aerc/worker/types" + "github.com/fsnotify/fsnotify" +) + +func init() { + handlers.RegisterWatcherFactory("linux", newInotifyWatcher) +} + +type inotifyWatcher struct { + w *fsnotify.Watcher + ch chan *types.FSEvent +} + +func newInotifyWatcher() (types.FSWatcher, error) { + watcher := &inotifyWatcher{ + ch: make(chan *types.FSEvent), + } + w, err := fsnotify.NewWatcher() + if err != nil { + return nil, err + } + watcher.w = w + + go watcher.watch() + return watcher, nil +} + +func (w *inotifyWatcher) watch() { + defer log.PanicHandler() + for ev := range w.w.Events { + // we only care about files being created, removed or renamed + switch ev.Op { + case fsnotify.Create: + w.ch <- &types.FSEvent{ + Operation: types.FSCreate, + Path: ev.Name, + } + case fsnotify.Remove: + w.ch <- &types.FSEvent{ + Operation: types.FSRemove, + Path: ev.Name, + } + case fsnotify.Rename: + w.ch <- &types.FSEvent{ + Operation: types.FSRename, + Path: ev.Name, + } + default: + continue + } + } +} + +func (w *inotifyWatcher) Configure(root string) error { + return w.w.Add(root) +} + +func (w *inotifyWatcher) Events() chan *types.FSEvent { + return w.ch +} + +func (w *inotifyWatcher) Add(p string) error { + return w.w.Add(p) +} + +func (w *inotifyWatcher) Remove(p string) error { + return w.w.Remove(p) +} -- cgit