-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
66 lines (61 loc) · 1.23 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
package main
import (
"fmt"
fp "path/filepath"
"slices"
"sync"
"github.com/fsnotify/fsnotify"
log "github.com/sirupsen/logrus"
)
func watch(dir string, names []string, f func(fsnotify.Event)) (err error) {
if f == nil {
return fmt.Errorf("nil callback error")
}
initErr := make(chan error)
go func() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
initErr <- err
return
}
err = watcher.Add(dir)
if err != nil {
initErr <- err
return
}
initErr <- nil
defer func(watcher *fsnotify.Watcher) {
if err := watcher.Close(); err != nil {
log.Error("failed to close watcher: ", err)
}
}(watcher)
eventWG := sync.WaitGroup{}
eventWG.Add(1)
go func() {
defer eventWG.Done()
for {
select {
case event, ok := <-watcher.Events:
log.Trace("File: ", event.Name, ", Op: ", event.Op, ", Ok: ", ok)
if !ok {
return
}
_, thisName := fp.Split(event.Name)
if slices.Contains(names, thisName) ||
len(names) == 0 { //监听整个文件夹的情况
f(event)
}
case err, ok := <-watcher.Errors:
log.Error(err, ", Ok: ", ok)
return
}
}
}()
eventWG.Wait()
}()
err = <-initErr
if err != nil {
return err
}
return nil
}