aboutsummaryrefslogtreecommitdiff
path: root/worker/lib/watchers/linux/linux.go
blob: 473bb05e35a1e0c9a6c10332fa6babca025c1f0e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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)
}