-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
77 lines (58 loc) · 1.49 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
// Package watcher provides functions to watch files in a particular directory
// and run given functions when the files change
package watcher
import (
"fmt"
"os"
"os/signal"
"strings"
"github.com/fsnotify/fsnotify"
"github.com/op/go-logging"
"github.com/sethigeet/watcher/watcher/cmd"
)
var (
eventsChan chan string
watchers []*fsnotify.Watcher
)
func init() {
eventsChan = make(chan string, 1000)
}
func Setup() error {
// set the file watchers limit
setupWatchLimit()
go handleEvents()
// setup the watchers
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
go sendEvents(watcher)
paths := getFilesToWatch()
for _, path := range paths {
err = watcher.Add(path)
if err != nil {
return err
}
}
if *cmd.Config.ListOnStart {
log.Infof("%sFiles being watched:%s %s\n", logging.ColorSeqBold(logging.ColorWhite), []byte("\033[0m"), strings.Join(paths, ", "))
}
// Close the watcher in the end
defer watcher.Close()
// Start by running the cmd
if *cmd.Config.RunCmdOnStart {
eventsChan <- *cmd.Config.Directory
}
// the quit channel
quitChan := make(chan os.Signal, 1)
// accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught
signal.Notify(quitChan, os.Interrupt)
// accept 'q' for quitting and 'r' for force refresh
go detectKeys(quitChan, eventsChan)
// Block until we receive our signal.
<-quitChan
fmt.Printf("\n")
log.Warning("Disposing of all the watchers...")
return nil
}