-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.go
117 lines (104 loc) · 2.3 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"errors"
"log"
"os"
"os/exec"
"path/filepath"
"github.com/fsnotify/fsnotify"
)
type CliInput struct {
directory string
pattern string
eventType string
commandArgs []string
nonBlocking bool
}
func eventTypeConverter(event string) (fsnotify.Op, error) {
var eventType fsnotify.Op
switch event {
case "create":
eventType = fsnotify.Create
case "write":
eventType = fsnotify.Write
case "remove":
eventType = fsnotify.Remove
case "rename":
eventType = fsnotify.Rename
case "chmod":
eventType = fsnotify.Chmod
default:
return fsnotify.Create, errors.New("failed to convert event string")
}
return eventType, nil
}
func filterDirsGlob(path, pattern string) (bool, error) {
file := filepath.Base(path)
return filepath.Match(pattern, file)
}
func executeCommand(cliInput CliInput, fileName string) error {
// concat the file name to the end of the commandArgs
commandArgs := cliInput.commandArgs
commandArgs = append(commandArgs, fileName)
// parse the commandArgs into golang Command function
executable := commandArgs[0]
commandArgs = commandArgs[1:]
cmd := exec.Command(executable, commandArgs...)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
if cliInput.nonBlocking {
if err := cmd.Start(); err != nil {
return err
}
return nil
}
if err := cmd.Run(); err != nil {
return err
}
return nil
}
// blatantly copied from fsnotify example
func goracle(cliInput CliInput) {
eventType, err := eventTypeConverter(cliInput.eventType)
if err != nil {
log.Fatal(err)
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
fileName := event.Name
checkFile, err := filterDirsGlob(fileName, cliInput.pattern)
if err != nil {
log.Fatal("Error occured: ", err)
}
if event.Op&eventType == eventType && checkFile {
// do something here
err = executeCommand(cliInput, fileName)
if err != nil {
log.Printf("Failed to start cmd: %v", err)
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
err = watcher.Add(cliInput.directory)
if err != nil {
log.Fatal(err)
}
<-done
}