-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
83 lines (67 loc) · 1.44 KB
/
watcher.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
package main
import (
"strings"
"github.com/fsnotify/fsnotify"
"github.com/tliron/commonlog"
)
type Watcher struct {
Watcher *fsnotify.Watcher
Handlers []*Handler
Log commonlog.Logger
}
type HandlerFunc func(path string)
type Handler struct {
op fsnotify.Op
handle HandlerFunc
}
func NewWatcher() (*Watcher, error) {
if watcher, err := fsnotify.NewWatcher(); err == nil {
return &Watcher{
Watcher: watcher,
Log: commonlog.GetLogger("watcher"),
}, nil
} else {
return nil, err
}
}
func (self *Watcher) Add(directoryPath string, op fsnotify.Op, handle HandlerFunc) error {
self.Handlers = append(self.Handlers, &Handler{
op: op,
handle: handle,
})
return self.Watcher.Add(directoryPath)
}
func (self *Watcher) Close() error {
return self.Watcher.Close()
}
func (self *Watcher) Run() {
defer self.Close()
for self.Process() {
}
}
func (self *Watcher) Process() bool {
select {
case event, ok := <-self.Watcher.Events:
if !ok {
self.Log.Warning("no more events")
return false
}
// Ignore temporary files
if strings.HasSuffix(event.Name, "~") {
break
}
self.Log.Debugf("event: %s", event)
for _, handler := range self.Handlers {
if event.Op&handler.op == handler.op {
handler.handle(event.Name)
}
}
case err, ok := <-self.Watcher.Errors:
if !ok {
self.Log.Warning("no more errors")
return false
}
self.Log.Errorf("error: %s", err.Error())
}
return true
}