-
Notifications
You must be signed in to change notification settings - Fork 729
/
file.go
62 lines (55 loc) · 1.17 KB
/
file.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
package watcher
import (
"github.com/fsnotify/fsnotify"
)
// File is a file watcher that notifies when a file has been changed
type File struct {
watcher *fsnotify.Watcher
shutdown chan struct{}
}
// NewFile is a standard constructor
func NewFile() (*File, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
f := &File{
watcher: watcher,
shutdown: make(chan struct{}),
}
return f, nil
}
// Add adds a file to start watching
func (f *File) Add(filepath string) error {
return f.watcher.Add(filepath)
}
// Shutdown stop the file watching run loop
func (f *File) Shutdown() {
// don't block if Start quit early
select {
case f.shutdown <- struct{}{}:
default:
}
}
// Start is a runloop to watch for files changes from the file paths added from Add()
func (f *File) Start(notifier Notification) {
for {
select {
case event, ok := <-f.watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
notifier.WatcherItemDidChange(event.Name)
}
case err, ok := <-f.watcher.Errors:
if !ok {
return
}
notifier.WatcherDidError(err)
case <-f.shutdown:
f.watcher.Close()
return
}
}
}