-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
95 lines (81 loc) · 1.87 KB
/
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
package cli
import (
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"github.com/fsnotify/fsnotify"
)
// Watcher allows you to observe directories and call an action if any of
// them change.
type Watcher struct {
watchDirs []string
ignoreDirs []string
done chan bool
fsWatcher *fsnotify.Watcher
}
// WatcherCallback is the function signature that is executed when a
// file is changed.
type WatcherCallback func(string) error
func (w Watcher) walk(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
if !fi.IsDir() {
return nil
}
for _, folder := range w.ignoreDirs {
if regexp.MustCompile(folder).MatchString(path) {
return nil
}
}
return w.fsWatcher.Add(path)
}
// Close stops the filesystem watcher.
func (w Watcher) Close() {
if w.fsWatcher != nil {
w.done <- true
if err := w.fsWatcher.Close(); err != nil {
log.Print(err)
}
}
}
// Watch starts the watcher. A callback function is provided that gets
// executed anytime a file change occurs.
func (w *Watcher) Watch(callback WatcherCallback) error {
for _, watchDir := range w.watchDirs {
if err := filepath.Walk(watchDir, w.walk); err != nil {
return err
}
}
go func() {
for {
select {
case event := <-w.fsWatcher.Events:
if err := callback(event.Name); err != nil {
fmt.Println(err)
}
case err := <-w.fsWatcher.Errors:
fmt.Printf("Error: unexpected error in watcher - %v", err)
case <-w.done:
return
}
}
}()
return nil
}
// NewWatcher initializes a new instance of a Watcher. It specifies a
// list of directories to watch and directories to ignore.
func NewWatcher(watchDirs, ignoreDirs []string) (*Watcher, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
return &Watcher{
watchDirs: watchDirs,
ignoreDirs: ignoreDirs,
done: make(chan bool),
fsWatcher: watcher,
}, nil
}