forked from cloudfoundry-incubator/cflocal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
65 lines (57 loc) · 1.17 KB
/
watch.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
// +build !darwin
package fs
import (
"os"
"path/filepath"
"time"
"github.com/fsnotify/fsnotify"
)
// TODO: replace done chan with done func
func (f *FS) Watch(dir string, wait time.Duration) (change <-chan time.Time, done chan<- struct{}, err error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, nil, err
}
if err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err == nil && info.Mode().IsDir() {
watcher.Add(path) // TODO: log error
}
return nil
}); err != nil {
return nil, nil, err
}
out := make(chan time.Time)
stop := make(chan struct{})
go func() {
var (
t time.Time
send chan time.Time
after <-chan time.Time
)
for {
select {
case <-watcher.Errors: // TODO: log error
case event := <-watcher.Events:
if !hasOp(event.Op, fsnotify.Chmod) {
after = time.After(wait)
}
case t = <-after:
send = out
case send <- t:
send = nil
case <-stop:
watcher.Close()
return
}
}
}()
return out, stop, nil
}
func hasOp(op fsnotify.Op, ops ...fsnotify.Op) bool {
for _, o := range ops {
if op&o == o {
return true
}
}
return false
}