-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
331 lines (273 loc) · 6.56 KB
/
main.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package main
import (
"errors"
"flag"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/fsnotify/fsnotify"
)
var (
watchPathArg string
watchExtsArg string
ignoreDirArg string
ignoreDirArr []string
watchDirArg string
mod string
cmdArgs string
cmdArgsArr []string
printHelp bool
extMap = make(map[string]bool, 0)
watchPath string
buildTime time.Time
cmd *exec.Cmd
lock sync.Mutex
)
const (
intervalTime = 3 * time.Second
appName = "binTmp"
)
func checkFile(file string) bool {
if len(extMap) == 0 {
return true
}
ext := filepath.Ext(file)
return extMap[ext]
}
func rename(oldpath, newpath string) error {
finfo, err := os.Stat(oldpath)
if !os.IsNotExist(err) {
if finfo.IsDir() {
_, err := os.Stat(newpath)
if os.IsNotExist(err) {
log.Println("[INFO] rename", oldpath, "to", newpath)
return os.Rename(oldpath, newpath)
}
return err
}
}
return nil
}
func listenSignal(fn func()) {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, os.Kill)
for {
sign := <-c
log.Println("get signal:", sign)
if fn != nil {
fn()
}
log.Fatal("trying to exit gracefully...")
}
}
func autobuild() {
lock.Lock()
defer lock.Unlock()
if time.Now().Sub(buildTime) > intervalTime {
var err error
buildTime = time.Now()
os.Chdir(watchPath)
cmdName := "go"
binName := appName
if runtime.GOOS == "windows" {
binName += ".exe"
}
args := []string{"build"}
if mod != "" {
args = append(args, "-mod", mod)
}
args = append(args, "-o", binName)
cmd := exec.Command(cmdName, args...)
cmd.Env = append(os.Environ(), "GOGC=off")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Println("[INFO] Start building...")
err = cmd.Run()
if err != nil {
log.Println("[ERROR]================Build failed=================")
return
}
log.Println("[SUCCESS] Build success")
restart(binName)
}
}
func restart(binName string) {
log.Println("[INFO] Kill running process")
kill()
go start(binName)
}
func kill() {
defer func() {
if err := recover(); err != nil {
fmt.Println("[ERROR] Kill failed recover -> ", err)
}
}()
log.Println("[INFO] Killing process")
if cmd != nil && cmd.Process != nil {
err := cmd.Process.Kill()
if err != nil {
fmt.Println("[ERROR] Kill process -> ", err)
}
log.Println("[SUCCESS] Kill process success")
}
log.Println("[info] this process is nil")
}
func start(binName string) {
log.Printf("[INFO] Restarting %s %s ...\n", binName, cmdArgs)
binName = "./" + binName
cmd = exec.Command(binName, cmdArgsArr...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = append(os.Environ(), "")
go cmd.Run()
log.Printf("[INFO] %s is running...\n", binName)
}
func getCurrentDirectory() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
return strings.Replace(dir, "\\", "/", -1)
}
func addWatch(root string, watcher *fsnotify.Watcher) {
filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
for _, v := range ignoreDirArr {
if v == path {
return errors.New("ignore " + path)
}
}
if err != nil {
log.Printf("[ERROR] %s", err)
}
if info.IsDir() {
log.Printf("[TRAC] Directory( %s )\n", path)
}
if err := watcher.Add(path); err != nil {
log.Fatalf("[ERROR] Failed to watch directory[ %s ]\n", err)
}
return err
})
}
func removeWatch(root string, watcher *fsnotify.Watcher) {
filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info != nil {
if info.IsDir() {
log.Printf("[TRAC] Directory( %s )\n", path)
}
}
if err := watcher.Remove(path); err != nil {
log.Fatalf("[ERROR] Failed to remove watch [ %s ]\n", err)
}
return err
})
}
func main() {
var err error
flag.StringVar(&watchPathArg, "d", "./", "工作目录,默认当前目录.eg:/project,处在工作目录的文件会被自动监控变化")
flag.StringVar(&watchExtsArg, "e", "", "监听的文件类型,默认监听所有文件类型.eg:'.go','.html','.php'")
flag.StringVar(&ignoreDirArg, "i", "", "忽略监听的目录")
flag.BoolVar(&printHelp, "help", false, "显示帮助信息")
flag.StringVar(&cmdArgs, "args", "", "自定义命令参数")
flag.StringVar(&mod, "mod", "", "指定mod使用的vendor")
flag.StringVar(&watchDirArg, "w", "", "监听的目录")
flag.Parse()
if printHelp {
fmt.Fprintf(flag.CommandLine.Output(), "version: %s\n", "0.5.0")
flag.Usage()
return
}
cmdArgsArr = strings.Split(cmdArgs, " ")
if ignoreDirArg != "" {
ignoreDirArr = strings.Split(ignoreDirArg, ",")
for k, v := range ignoreDirArr {
ignoreDirArr[k], err = filepath.Abs(filepath.Clean(v))
if err != nil {
log.Fatalf("[FATAL] %v", err)
}
log.Println("[INFO] ignore:", ignoreDirArr[k])
}
}
watchPath, err = filepath.Abs(filepath.Clean(watchPathArg))
if err != nil {
log.Fatalf("[FATAL] %v", err)
}
extArr := strings.Split(watchExtsArg, ",")
if len(extArr) > 0 {
for _, v := range extArr {
if strings.TrimSpace(v) != "" {
extMap[v] = true
}
}
}
go listenSignal(func() {
kill()
})
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatalf("[FATAL] watcher -> %s", err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event := <-watcher.Events:
if !checkFile(event.Name) || filepath.Base(event.Name) == appName {
continue
}
if event.Op == fsnotify.Write {
log.Println("[INFO] Write: ", event.Name)
go autobuild()
}
if event.Op == fsnotify.Create {
log.Println("[INFO] Create: ", event.Name)
addWatch(event.Name, watcher)
go autobuild()
}
if event.Op == fsnotify.Remove || event.Op == fsnotify.Rename {
log.Println("[INFO] Remove: ", event.Name)
removeWatch(event.Name, watcher)
go autobuild()
}
case err := <-watcher.Errors:
log.Println("[ERROR] watcher error:", err)
}
}
}()
var watchDir []string
watchDir = append(watchDir, watchPath)
if watchDirArg != "" {
elems := strings.Split(watchDirArg, ",")
for _, v := range elems {
if v == "" {
continue
}
wp, err := filepath.Abs(filepath.Clean(v))
if err != nil {
log.Fatalf("[FATAL] %v", err)
}
watchDir = append(watchDir, wp)
}
}
for _, v := range watchDir {
log.Println("[INFO] watch", v, ",file ext", extArr)
err = watcher.Add(v)
if err != nil {
log.Fatalf("[FATAL] watcher -> %v", err)
}
addWatch(v, watcher)
}
autobuild()
<-done
}