-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwatcher.go
103 lines (97 loc) · 2.39 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
package main
import (
"fmt"
"os"
"time"
"github.com/fsnotify/fsnotify"
)
// fmt.Println("👀 Watcher v0.1.0")
// fmt.Printf("📂 Path: %s\n", opt.path)
// fmt.Printf("🔍 Events: %v\n", opt.registredEvents)
// fmt.Printf("🔄 Recursive: %v\n", opt.recursive)
func watchEvents(watcher *fsnotify.Watcher, cf CommandsFile) {
if watcher == nil {
panic("watcher is nil!")
}
eventTime := time.Now()
var lastEvent fsnotify.Op
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if !(time.Since(eventTime) > (time.Millisecond*400) || lastEvent != event.Op) {
continue
}
switch event.Op.String() {
case fsnotify.Write.String():
for _, v := range cf.Write {
if cmd := wrapCmd(parseCommand(v)); cmd != nil {
err := cmd.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "error running command %q: %s\n", v, err)
continue
}
}
}
case fsnotify.Create.String():
for _, v := range cf.Create {
if cmd := wrapCmd(parseCommand(v)); cmd != nil {
err := cmd.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "error running command %q: %s\n", v, err)
continue
}
}
}
case fsnotify.Remove.String():
for _, v := range cf.Remove {
if cmd := wrapCmd(parseCommand(v)); cmd != nil {
err := cmd.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "error running command %q: %s\n", v, err)
continue
}
}
}
case fsnotify.Rename.String():
for _, v := range cf.Rename {
if cmd := wrapCmd(parseCommand(v)); cmd != nil {
err := cmd.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "error running command %q: %s\n", v, err)
continue
}
}
}
case fsnotify.Chmod.String():
for _, v := range cf.Chmod {
if cmd := wrapCmd(parseCommand(v)); cmd != nil {
err := cmd.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "error running command %q: %s\n", v, err)
continue
}
}
}
}
for _, v := range cf.Common {
if cmd := wrapCmd(parseCommand(v)); cmd != nil {
err := cmd.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "error running command %q: %s\n", v, err)
continue
}
}
}
eventTime = time.Now()
lastEvent = event.Op
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Fprintf(os.Stderr, "error: %s\n", err.Error())
}
}
}