-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
84 lines (78 loc) · 1.62 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package watch
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/fsnotify/fsnotify"
)
type Watch struct {
watch *fsnotify.Watcher
timeChan chan uint
}
func InitWatch(path string, timeChan chan uint) {
ww, _ := fsnotify.NewWatcher()
w := Watch{
watch: ww,
timeChan: timeChan,
}
w.watchDir(path)
}
//监控目录
func (w *Watch) addTimeChan() {
w.timeChan <- uint(time.Now().UnixNano() % 1000000000000 / 1000)
}
func (w *Watch) watchDir(dir string) {
_ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
path, err := filepath.Abs(path)
if err != nil {
return err
}
err = w.watch.Add(path)
if err != nil {
return err
}
}
return nil
})
go func() {
for {
select {
case ev := <-w.watch.Events:
{
if ev.Op&fsnotify.Create == fsnotify.Create {
w.addTimeChan()
fmt.Println("创建 : ", ev.Name)
fi, err := os.Stat(ev.Name)
if err == nil && fi.IsDir() {
_ = w.watch.Add(ev.Name)
}
}
if ev.Op&fsnotify.Write == fsnotify.Write {
w.addTimeChan()
fmt.Println("写入 : ", ev.Name)
}
if ev.Op&fsnotify.Remove == fsnotify.Remove {
w.addTimeChan()
fmt.Println("删除 : ", ev.Name)
fi, err := os.Stat(ev.Name)
if err == nil && fi.IsDir() {
_ = w.watch.Remove(ev.Name)
}
}
if ev.Op&fsnotify.Rename == fsnotify.Rename {
w.addTimeChan()
fmt.Println("重命名 : ", ev.Name)
_ = w.watch.Remove(ev.Name)
}
}
case err := <-w.watch.Errors:
{
fmt.Println("error : ", err)
return
}
}
}
}()
}