forked from codeskyblue/fswatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fswatch.go
178 lines (158 loc) · 3.81 KB
/
fswatch.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package main
import (
"fmt"
"os"
"os/exec"
"io/ioutil"
"path/filepath"
"time"
"strings"
"github.com/howeyc/fsnotify"
"github.com/jessevdk/go-flags"
"github.com/shxsun/klog"
"encoding/json"
)
var (
K = klog.NewLogger(nil, "")
notifyDelay time.Duration
LeftRight = strings.Repeat("-", 10)
// golang c/cpp php js
LangExts = []string{".go", ".cpp", ".c", ".h", ".php", ".js"}
)
// Add dir and children (recursively) to watcher
func watchDirAndChildren(w *fsnotify.Watcher, path string, depth int) error {
if err := w.Watch(path); err != nil {
return err
}
baseNumSeps := strings.Count(path, string(os.PathSeparator))
return filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
pathDepth := strings.Count(path, string(os.PathSeparator)) - baseNumSeps
if pathDepth > depth {
return filepath.SkipDir
}
if opts.Verbose {
fmt.Fprintln(os.Stderr, "Watching", path)
}
if err := w.Watch(path); err != nil {
return err
}
}
return nil
})
}
// generate new event
func NewEvent(paths []string, depth int) chan *fsnotify.FileEvent {
watcher, err := fsnotify.NewWatcher()
if err != nil {
K.Fatalf("fail to create new Watcher: %s", err)
}
K.Info("Initial watcher")
for _, path := range paths {
K.Debugf("watch directory: %s", path)
err = watchDirAndChildren(watcher, path, depth)
if err != nil {
K.Fatal("fail to watch directory: %s", err)
}
}
// ignore watcher error
go func() {
for {
err := <-watcher.Error // ignore watcher error
K.Warnf("watch error: %s", err) // No need to exit here
}
}()
return watcher.Event
}
func execute(e chan *fsnotify.FileEvent, origCmd *exec.Cmd) {
var cmd *exec.Cmd
filterEvent := filter(e)
// make first time, do command
go func() {
filterEvent <- &fsnotify.FileEvent{}
}()
for {
ev := <-filterEvent
K.Info("Sense first:", ev)
CHECK:
select {
case ev = <-filterEvent:
K.Info("Sense again: ", ev)
goto CHECK
case <-time.After(notifyDelay):
}
// stop cmd
if cmd != nil && cmd.Process != nil {
K.Info("stop process")
cmd.Process.Kill()
}
// create new cmd
newCmd := *origCmd
cmd = &newCmd
K.Info(fmt.Sprintf("%s %5s %s", LeftRight, "START", LeftRight))
err := cmd.Start()
if err != nil {
K.Error(err)
continue
} else {
go func(cmd *exec.Cmd) {
err := cmd.Wait()
if err != nil {
K.Error(fmt.Sprintf("%s %5s %s", LeftRight, "ERROR", LeftRight))
} else {
K.Info(fmt.Sprintf("%s %5s %s", LeftRight, "E N D", LeftRight))
}
}(cmd)
}
}
}
var opts struct {
Verbose bool `short:"v" long:"verbose" description:"Show verbose debug infomation"`
Delay string `long:"delay" description:"Trigger event buffer time" default:"0.5s"`
Depth int `short:"d" long:"depth" description:"depth of watch" default:"1"`
}
type watchConfig struct {
Cmd string
Path []string
}
func main() {
parser := flags.NewParser(&opts, flags.Default|flags.PassAfterNonOption)
args, err := parser.Parse()
if err != nil {
K.Fatal(err)
os.Exit(1)
}
if opts.Verbose {
K.SetLevel(klog.LDebug)
}
notifyDelay, err = time.ParseDuration(opts.Delay)
if err != nil {
K.Warn(err)
notifyDelay = time.Millisecond * 500
}
K.Debugf("delay time: %s", notifyDelay)
if len(args) == 0 {
fmt.Printf("Use %s --help for more details\n", os.Args[0])
return
}
// // check if cmd exists
// _, err = exec.LookPath(args[0])
// if err != nil {
// fmt.Println(1)
// }
dataByte,err := ioutil.ReadFile(args[0])
if err!=nil{
K.Fatal(err)
}
var config watchConfig
err = json.Unmarshal(dataByte, &config)
if err != nil {
K.Fatal(err)
}
cmdSlice :=strings.Split(config.Cmd," ")
cmd := exec.Command(cmdSlice[0],cmdSlice[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
event := NewEvent(config.Path, 10)
execute(event, cmd)
}