forked from romanoff/fsmonitor
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfsmonitor.go
More file actions
100 lines (91 loc) · 2.12 KB
/
fsmonitor.go
File metadata and controls
100 lines (91 loc) · 2.12 KB
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
97
98
99
100
package fsmonitor
import (
"github.com/go-fsnotify/fsnotify"
"os"
"path/filepath"
)
func NewWatcher() (*Watcher, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
monitorWatcher := initWatcher(watcher, []string{})
return monitorWatcher, nil
}
func NewWatcherWithSkipFolders(skipFolders []string) (*Watcher, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
monitorWatcher := initWatcher(watcher, skipFolders)
return monitorWatcher, nil
}
func initWatcher(watcher *fsnotify.Watcher, skipFolders []string) *Watcher {
event := make(chan *fsnotify.Event)
watcherError := make(chan error)
monitorWatcher := &Watcher{Events: event, Error: watcherError, watcher: watcher, SkipFolders: skipFolders}
go func() {
for {
select {
case ev := <-watcher.Events:
if ev.Op&fsnotify.Create == fsnotify.Create {
go func() {
if f, err := os.Stat(ev.Name); err == nil {
if f.IsDir() {
monitorWatcher.watchAllFolders(ev.Name)
}
}
}()
}
if ev.Op&fsnotify.Remove == fsnotify.Remove {
go func() {
watcher.Remove(ev.Name)
}()
}
monitorWatcher.Events <- &ev
case e := <-watcher.Errors:
watcherError <- e
}
}
}()
return monitorWatcher
}
type Watcher struct {
Events chan *fsnotify.Event
Error chan error
SkipFolders []string
watcher *fsnotify.Watcher
}
func (self *Watcher) Watch(path string) error {
err := self.watchAllFolders(path)
if err != nil {
return err
}
return nil
}
func (self *Watcher) watchAllFolders(path string) (err error) {
err = filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
if f != nil && f.IsDir() {
filename := f.Name()
for _, skipFolder := range self.SkipFolders {
match, err := filepath.Match(skipFolder, filename)
if err != nil {
return err
}
if match {
return filepath.SkipDir
}
}
err := self.addWatcher(path)
if err != nil {
return err
}
}
return nil
})
return
}
func (self *Watcher) addWatcher(path string) (err error) {
err = self.watcher.Add(path)
return
}