-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathwatcher.go
172 lines (153 loc) · 3.91 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// watches the current directory for changes and runs the specificed program on change
package main
import (
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/howeyc/fsnotify"
)
var (
verbose = flag.Bool("v", false, "verbose")
depth = flag.Int("depth", 1, "recursion depth")
dir = flag.String("dir", ".", "directory root to use for watching")
quiet = flag.Duration("quiet", 800*time.Millisecond, "quiet period after command execution")
wait = flag.Duration("wait", 10*time.Millisecond, "time to wait between change detection and exec")
ignore = flag.String("ignore", "", "path ignore pattern")
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: %s [flags] [command to execute and args]\n", os.Args[0])
flag.PrintDefaults()
}
func main() {
flag.Usage = usage
flag.Parse()
watcher, err := newWatcher()
if err != nil {
log.Fatal(err)
}
if len(flag.Args()) == 0 {
flag.Usage()
os.Exit(1)
}
cmd, args := flag.Args()[0], flag.Args()[1:]
fileEvents := make(chan interface{}, 100)
// pipe all events to fileEvents (for buffering and draining)
go watcher.pipeEvents(fileEvents)
// if we have an ignore pattern, set up predicate and replace fileEvents
if *ignore != "" {
fileEvents = filter(fileEvents, func(e interface{}) bool {
fe := e.(*fsnotify.FileEvent)
wd, _ := os.Getwd()
relPath, _ := filepath.Rel(wd, fe.Name)
ignored, err := filepath.Match(*ignore, relPath)
if err != nil {
fmt.Fprintln(os.Stderr, "error performing match:", err)
}
return !ignored
})
}
go watchAndExecute(fileEvents, cmd, args)
defer watcher.Close()
dir, err := filepath.Abs(*dir)
if err != nil {
log.Fatal(err)
}
err = watcher.watchDirAndChildren(dir, *depth)
if err != nil {
log.Fatal(err)
}
select {}
}
type watcher struct {
*fsnotify.Watcher
}
func newWatcher() (watcher, error) {
fsnw, err := fsnotify.NewWatcher()
return watcher{fsnw}, err
}
// Execute cmd with args when a file event occurs
func watchAndExecute(fileEvents chan interface{}, cmd string, args []string) {
for {
time.Sleep(*wait)
// execute command
c := exec.Command(cmd, args...)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Stdin = os.Stdin
fmt.Fprintln(os.Stderr, "running", cmd, args)
if err := c.Run(); err != nil {
fmt.Fprintln(os.Stderr, "error running:", err)
}
if *verbose {
fmt.Fprintln(os.Stderr, "done.")
}
// drain until quiet period is over
drainFor(*quiet, fileEvents)
ev := <-fileEvents
if *verbose {
fmt.Fprintln(os.Stderr, "File changed:", ev)
}
}
}
// Add dir and children (recursively) to watcher
func (w watcher) watchDirAndChildren(path string, depth int) error {
if err := w.Watch(path); err != nil {
return err
}
baseNumSeps := strings.Count(path, string(os.PathSeparator))
return filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
pathDepth := strings.Count(path, string(os.PathSeparator)) - baseNumSeps
if pathDepth > depth {
return filepath.SkipDir
}
if *verbose {
fmt.Fprintln(os.Stderr, "Watching", path)
}
if err := w.Watch(path); err != nil {
return err
}
}
return nil
})
}
// pipeEvents sends valid events to `events` and errors to stderr
func (w watcher) pipeEvents(events chan interface{}) {
for {
select {
case ev := <-w.Event:
events <- ev
// @todo handle created/renamed/deleted dirs
case err := <-w.Error:
log.Println("fsnotify error:", err)
}
}
}
func filter(items chan interface{}, predicate func(interface{}) bool) chan interface{} {
results := make(chan interface{})
go func() {
for {
item := <-items
if predicate(item) {
results <- item
}
}
}()
return results
}
// drainFor drains events from channel with a until a period in ms has elapsed timeout
func drainFor(drainUntil time.Duration, c chan interface{}) {
timeout := time.After(drainUntil)
for {
select {
case <-c:
case <-timeout:
return
}
}
}