forked from friendsofgo/killgrave
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
59 lines (50 loc) · 1.38 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
package killgrave
import (
"fmt"
"log"
"time"
"github.com/radovskyb/watcher"
)
// InitializeWatcher initialize a watcher to check for modification on all files
// in the given path to watch
func InitializeWatcher(pathToWatch string) (*watcher.Watcher, error) {
w := watcher.New()
w.SetMaxEvents(1)
w.FilterOps(watcher.Rename, watcher.Move, watcher.Create, watcher.Write)
if err := w.AddRecursive(pathToWatch); err != nil {
return nil, fmt.Errorf("%w: error trying to watch change on %s directory", err, pathToWatch)
}
return w, nil
}
// AttachWatcher start the watcher, if any error was produced while the starting process the application would crash
// you need to pass a function, this function is the function that will be executed when the watcher
// receive any event the type of defined on the InitializeWatcher function
func AttachWatcher(w *watcher.Watcher, fn func()) {
go func() {
if err := w.Start(time.Millisecond * 100); err != nil {
log.Fatalln(err)
}
}()
readEventsFromWatcher(w, fn)
}
func CloseWatcher(w *watcher.Watcher) {
if w == nil {
return
}
w.Close()
}
func readEventsFromWatcher(w *watcher.Watcher, fn func()) {
go func() {
for {
select {
case evt := <-w.Event:
log.Println("Modified file:", evt.Name())
fn()
case err := <-w.Error:
log.Printf("Error checking file change: %+v", err)
case <-w.Closed:
return
}
}
}()
}