-
Notifications
You must be signed in to change notification settings - Fork 0
/
folder-watcher.go
55 lines (48 loc) · 971 Bytes
/
folder-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
package main
import (
"fmt"
"log"
"os"
"os/exec"
"strings"
"github.com/fsnotify/fsnotify"
)
func main() {
if len(os.Args) < 3 {
fmt.Println("Usage: folder-watcher <folder-to-watch> <command> <...args> $filepath")
os.Exit(0)
}
folderToWatch := os.Args[1]
commands := os.Args[2:]
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
rest := append(commands[1:], event.Name)
log.Printf("executing %s %s", commands[0], strings.Join(rest, " "))
out, _ := exec.Command(commands[0], rest...).CombinedOutput()
log.Printf("\n%s", out)
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
// Add a path.
err = watcher.Add(folderToWatch)
if err != nil {
log.Fatal(err)
}
// Block main goroutine forever.
<-make(chan struct{})
}