/
manage.go
76 lines (61 loc) · 1.29 KB
/
manage.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
package main
import (
"github.com/howeyc/fsnotify"
"os/exec"
"path"
"path/filepath"
)
type CmdPayload struct {
Cmd *exec.Cmd
LogOutput bool
}
func Manage(events chan *fsnotify.FileEvent, rules []*Rule) (queue chan CmdPayload) {
queue = make(chan CmdPayload)
go func() {
for ev := range events {
dir, file := path.Split(ev.Name)
dir = stripTrailingSlash(dir)
matches := matchingRules(rules, dir, file)
if len(matches) > 0 {
for _, rule := range matches {
cmd := exec.Command(rule.Run, getEventType(ev), ev.Name)
if rule.ChangePwd {
cmd.Dir = dir
}
payload := CmdPayload{cmd, rule.LogOutput}
queue <- payload
}
}
}
}()
return queue
}
func matchingRules(rules []*Rule, dir, filename string) (matches []*Rule) {
matches = make([]*Rule, 0)
for _, r := range rules {
if r.Path == dir {
if r.Pattern == "*" {
matches = append(matches, r)
continue
}
match, err := filepath.Match(r.Pattern, filename)
if match && err == nil {
matches = append(matches, r)
}
}
}
return matches
}
func getEventType(ev *fsnotify.FileEvent) string {
switch {
case ev.IsCreate():
return "CREATE"
case ev.IsModify():
return "MODIFY"
case ev.IsDelete():
return "DELETE"
case ev.IsRename():
return "RENAME"
}
return ""
}