-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
79 lines (72 loc) · 1.56 KB
/
main.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
package main
import (
"errors"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
"gopkg.in/fsnotify.v1"
"os"
"path/filepath"
)
func main() {
app := cli.NewApp()
app.Name = "watch"
app.Usage = "a glorified file watcher"
app.Action = func(c *cli.Context) {
run(c.Args().First())
}
app.Before = func(c *cli.Context) error {
if c.Args().First() == "" {
return errors.New("must pass in one directory to watch argument")
}
return nil
}
app.RunAndExitOnError()
}
func run(dir string) {
log.WithField("path", dir).Info("Scanning path")
// create watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
defer watcher.Close()
// set up 'watching'
go func() {
for {
select {
case event := <-watcher.Events:
log.WithFields(log.Fields{
"path": event.Name,
"operation": event.Op,
}).Info("change detected")
case err := <-watcher.Errors:
log.WithField("error", err).Error("error on watch")
}
}
}()
// recursively add watcher to everything
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.WithFields(log.Fields{
"path": path,
"error": err,
}).Warn("unable to watch path")
return nil
}
if err = watcher.Add(path); err != nil {
log.WithFields(log.Fields{
"path": path,
"error": err,
}).Warn("unable to watch path")
}
return nil
})
if err != nil {
log.WithFields(log.Fields{
"path": dir,
"error": err,
}).Fatal("unable to fully walk path, exiting")
}
done := make(chan struct{})
<-done
}