aboutsummaryrefslogtreecommitdiffstats
path: root/worker/lib/watchers/darwin/darwin.go
blob: e20761f30dc3e69cbedc0b194e3996207e04cf65 (plain) (blame)
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
74
75
76
77
78
79
80
81
82
83
84
//go:build darwin
// +build darwin

package darwin

import (
	"time"

	"git.sr.ht/~rjarry/aerc/log"
	"git.sr.ht/~rjarry/aerc/worker/handlers"
	"git.sr.ht/~rjarry/aerc/worker/types"
	"github.com/fsnotify/fsevents"
)

func init() {
	handlers.RegisterWatcherFactory("darwin", newDarwinWatcher)
}

type darwinWatcher struct {
	ch        chan *types.FSEvent
	w         *fsevents.EventStream
	watcherCh chan []fsevents.Event
}

func newDarwinWatcher() (types.FSWatcher, error) {
	watcher := &darwinWatcher{
		watcherCh: make(chan []fsevents.Event),
		ch:        make(chan *types.FSEvent),
		w: &fsevents.EventStream{
			Flags:   fsevents.FileEvents | fsevents.WatchRoot,
			Latency: 500 * time.Millisecond,
		},
	}
	return watcher, nil
}

func (w *darwinWatcher) watch() {
	defer log.PanicHandler()
	for events := range w.w.Events {
		for _, ev := range events {
			switch {
			case ev.Flags&fsevents.ItemCreated > 0:
				w.ch <- &types.FSEvent{
					Operation: types.FSCreate,
					Path:      ev.Path,
				}
			case ev.Flags&fsevents.ItemRenamed > 0:
				w.ch <- &types.FSEvent{
					Operation: types.FSRename,
					Path:      ev.Path,
				}
			case ev.Flags&fsevents.ItemRemoved > 0:
				w.ch <- &types.FSEvent{
					Operation: types.FSRemove,
					Path:      ev.Path,
				}
			}
		}
	}
}

func (w *darwinWatcher) Configure(root string) error {
	dev, err := fsevents.DeviceForPath(root)
	if err != nil {
		return err
	}
	w.w.Device = dev
	w.w.Paths = []string{root}
	w.w.Start()
	go w.watch()
	return nil
}

func (w *darwinWatcher) Events() chan *types.FSEvent {
	return w.ch
}

func (w *darwinWatcher) Add(p string) error {
	return nil
}

func (w *darwinWatcher) Remove(p string) error {
	return nil
}