-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfile_watcher.go
executable file
·96 lines (88 loc) · 2.33 KB
/
file_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
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"github.com/fsnotify/fsnotify"
"log"
"os"
"path/filepath"
)
type FileWatcher struct {
handler *fsnotify.Watcher
doneEvent chan struct{}
}
func (w *FileWatcher) Init() bool {
_, err := os.Stat(g_SyncCfg.LocalDir)
if err != nil {
log.Printf("os.Stat LocalDir %s error:v\n", g_SyncCfg.LocalDir, err)
return false
}
log.Printf("Start Watch: %s\n", g_SyncCfg.LocalDir)
filepath.Walk(g_SyncCfg.LocalDir, func(path string, info os.FileInfo, err error) error {
if info != nil && info.IsDir() {
path, err := filepath.Abs(path)
if err != nil {
log.Fatalf("Walk filepath:%s err1:%v\n", path, err)
}
if g_FileSyncer.IsIgnoreDir(path) {
// log.Printf("Ignore path: %s\n", path)
return nil
}
err = w.handler.Add(path)
if err != nil {
log.Fatalf("Walk filepath:%s err2:%v\n", path, err)
}
log.Printf("Watching path: %s\n", path)
}
return nil
})
log.Printf("Watch: %s Ok!\n", g_SyncCfg.LocalDir)
return true
}
func (w *FileWatcher) Run() {
defer g_WaitGroup.Done()
for {
select {
case event := <-w.handler.Events:
{
if (event.Op & fsnotify.Create) == fsnotify.Create {
log.Printf("----create event (name:%s) (op:%v)\n", event.Name, event.Op)
file, err := os.Stat(event.Name)
if err != nil {
log.Printf("----create no exist path:%s (op:%v)\n", event.Name, event.Op)
break
}
if file.IsDir() {
w.handler.Add(event.Name)
}
g_FileSyncer.syncEvent <- event.Name
}
if (event.Op & fsnotify.Write) == fsnotify.Write {
log.Printf("----write event (name:%s) (op:%v)\n", event.Name, event.Op)
g_FileSyncer.syncEvent <- event.Name
}
if (event.Op & fsnotify.Remove) == fsnotify.Remove {
log.Printf("----remove event (name:%s) (op:%v)\n", event.Name, event.Op)
file, err := os.Stat(event.Name)
if err == nil && file.IsDir() {
w.handler.Remove(event.Name)
}
g_FileSyncer.removeEvent <- event.Name
}
}
case err := <-w.handler.Errors:
{
log.Printf("File Watch Error: %v\n", err)
}
case <-w.doneEvent:
{
return
}
}
}
}
func newFileWatcher() *FileWatcher {
fw, _ := fsnotify.NewWatcher()
return &FileWatcher{
handler: fw,
doneEvent: make(chan struct{}),
}
}