-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
96 lines (78 loc) · 1.55 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
96
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"github.com/fsnotify/fsnotify"
)
type WatchCallback func(e fsnotify.Event)
type FileWatcher struct {
w *fsnotify.Watcher
}
func (f *FileWatcher) Init() {
var err error
f.w, err = fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
}
func (f *FileWatcher) Add(path string) {
f.w.Add(path)
}
func (f *FileWatcher) AddRecursive(path string) {
addDir := func(path string, fi os.FileInfo, err error) error {
if fi.Mode().IsDir() {
f.w.Add(path)
}
return nil
}
// starting at the root of the project, walk each file/directory searching for
// directories
if err := filepath.Walk(path, addDir); err != nil {
fmt.Println("ERROR", err)
}
}
func (f *FileWatcher) isIgnored(e fsnotify.Event) bool {
// TODO: Make ignore regex extensible
match, err := regexp.MatchString(`(\.swp)|(\.swx)|(~$)|(/.git/)`, e.Name)
if err != nil {
log.Fatal(err)
}
if match {
return true
}
// TODO: Make Event type filter configurable
if e.Op != fsnotify.Write {
return true
}
return false
}
func (f *FileWatcher) handleEvent(e fsnotify.Event, callback WatchCallback) {
if !f.isIgnored(e) {
callback(e)
}
}
func (f *FileWatcher) Start(callback WatchCallback) {
defer f.w.Close()
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-f.w.Events:
if !ok {
return
}
f.handleEvent(event, callback)
case err, ok := <-f.w.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
// Wait until done listening
<-done
}