-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.go
69 lines (58 loc) · 1.03 KB
/
watch.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
package gfx
import (
"sync"
"github.com/fsnotify/fsnotify"
)
var (
_ = Watch
once sync.Once
notify *fsnotify.Watcher
)
func Watch(path string, watcher Watcher) (err error) {
if nil == notify {
notify, err = fsnotify.NewWatcher()
}
if nil != err {
return
}
// 只能被调用一次
once.Do(func() {
go watch(watcher)
})
err = notify.Add(path)
return
}
func watch(watcher Watcher) {
for {
select {
case event, ok := <-notify.Events:
onEvent(watcher, event, ok)
case err, ok := <-notify.Errors:
onError(watcher, err, ok)
}
}
}
func onEvent(watcher Watcher, event fsnotify.Event, ok bool) {
if !ok {
return
}
path := event.Name
switch event.Op {
case fsnotify.Write:
watcher.OnChanged(path)
case fsnotify.Remove:
watcher.OnDeleted(path)
case fsnotify.Rename:
watcher.OnRenamed(path)
case fsnotify.Create:
watcher.OnCreated(path)
case fsnotify.Chmod:
watcher.OnPermissionChanged(path)
}
}
func onError(watcher Watcher, err error, ok bool) {
if !ok {
return
}
watcher.OnError(err)
}