-
Notifications
You must be signed in to change notification settings - Fork 1
/
inotify.go
111 lines (96 loc) · 2.04 KB
/
inotify.go
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//go:build linux
// +build linux
package rnotify
import (
"os"
"path/filepath"
"strings"
"github.com/fsnotify/fsnotify"
)
// Watcher watches files and directories, delivering events to a channel.
type Watcher struct {
Events chan fsnotify.Event
Errors chan error
fswatcher *fsnotify.Watcher
ignore map[string]struct{}
}
// NewWatcher builds a new watcher.
func NewWatcher() (*Watcher, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
w := &Watcher{
fswatcher: watcher,
Events: make(chan fsnotify.Event),
Errors: make(chan error),
ignore: map[string]struct{}{},
}
go w.readEvents()
return w, nil
}
// Add starts watching the directory (recursively).
func (w *Watcher) Add(name string) error {
err := filepath.Walk(name, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
for ignorePath := range w.ignore {
if strings.Contains(path, ignorePath) {
return nil
}
}
if err = w.fswatcher.Add(path); err != nil {
return err
}
}
return nil
})
return err
}
// Close stops watching.
func (w *Watcher) Close() error {
return w.fswatcher.Close()
}
// Ignore specifies directories to ignore.
func (w *Watcher) Ignore(paths []string) {
for _, path := range paths {
w.ignore[path] = struct{}{}
}
}
func (w *Watcher) readEvents() {
defer close(w.Errors)
defer close(w.Events)
for {
select {
case event, ok := <-w.fswatcher.Events:
if ok {
if event.Op&fsnotify.Create == fsnotify.Create {
info, err := os.Stat(event.Name)
if err != nil {
w.Errors <- err
} else if info.IsDir() {
skip := false
for ignorePath := range w.ignore {
if strings.Contains(event.Name, ignorePath) {
skip = true
break
}
}
if !skip {
if err = w.fswatcher.Add(event.Name); err != nil {
w.Errors <- err
}
}
}
}
w.Events <- event
}
case err, ok := <-w.fswatcher.Errors:
if ok {
w.Errors <- err
}
}
}
}