forked from githubnemo/CompileDaemon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
daemon.go
461 lines (368 loc) · 12.5 KB
/
daemon.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/*
CompileDaemon is a very simple compile daemon for Go.
CompileDaemon watches your .go files in a directory and invokes `go build`
if a file changes.
Examples
In its simplest form, the defaults will do. With the current working directory set
to the source directory you can simply…
$ CompileDaemon
… and it will recompile your code whenever you save a source file.
If you want it to also run your program each time it builds you might add…
$ CompileDaemon -command="./MyProgram -my-options"
… and it will also keep a copy of your program running. Killing the old one and
starting a new one each time you build. For advanced usage you can also supply
the changed file to the command by doing…
$ CompileDaemon -command="./MyProgram -my-options %[1]s"
…but note that this will not be set on the first start.
You may find that you need to exclude some directories and files from
monitoring, such as a .git repository or emacs temporary files…
$ CompileDaemon -exclude-dir=.git -exclude=".#*"
If you want to monitor files other than .go and .c files you might…
$ CompileDaemon -include=Makefile -include="*.less" -include="*.tmpl"
Options
There are command line options.
FILE SELECTION
-directory=XXX – Which directory to monitor for changes
-recursive=XXX – Look into subdirectories
-exclude-dir=XXX – Exclude directories matching glob pattern XXX
-exlude=XXX – Exclude files whose basename matches glob pattern XXX
-include=XXX – Include files whose basename matches glob pattern XXX
-pattern=XXX – Include files whose path matches regexp XXX
FILE WATCH
-polling - Use polling instead of FS notifications to detect changes. Default is false
-polling-interval - Milliseconds of interval between polling file changes when polling option is selected
MISC
-color - Enable colorized output
-log-prefix - Enable/disable stdout/stderr labelling for the child process
-graceful-kill - On supported platforms, send the child process a SIGTERM to
allow it to exit gracefully if possible.
-graceful-timeout - Duration (in seconds) to wait for graceful kill to complete
-verbose - Print information about watched directories.
ACTIONS
-build=CCC – Execute CCC to rebuild when a file changes
-command=CCC – Run command CCC after a successful build, stops previous command first
*/
package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/fatih/color"
)
// Milliseconds to wait for the next job to begin after a file change
const WorkDelay = 900
// Default pattern to match files which trigger a build
const FilePattern = `(.+\.go|.+\.c)$`
type globList []string
func (g *globList) String() string {
return fmt.Sprint(*g)
}
func (g *globList) Set(value string) error {
*g = append(*g, filepath.Clean(value))
return nil
}
func (g *globList) Matches(value string) bool {
for _, v := range *g {
if match, err := filepath.Match(v, value); err != nil {
log.Fatalf("Bad pattern \"%s\": %s", v, err.Error())
} else if match {
return true
}
}
return false
}
type buildCommandList struct {
commands []string
}
func (f *buildCommandList) String() string {
return ""
}
func (f *buildCommandList) Set(s string) error {
f.commands = append(f.commands, s)
return nil
}
var (
flagPattern = flag.String("pattern", FilePattern, "Pattern of watched files")
flagCommand = flag.String("command", "", "Command to run and restart after build")
flagCommandStop = flag.Bool("command-stop", false, "Stop command before building")
flagRecursive = flag.Bool("recursive", true, "Watch all dirs. recursively")
flagBuildDir = flag.String("build-dir", "", "Directory to run build command in. Defaults to directory")
flagRunDir = flag.String("run-dir", "", "Directory to run command in. Defaults to directory")
flagColor = flag.Bool("color", false, "Colorize output for CompileDaemon status messages")
flagLogPrefix = flag.Bool("log-prefix", true, "Print log timestamps and subprocess stderr/stdout output")
flagGracefulKill = flag.Bool("graceful-kill", false, "Gracefully attempt to kill the child process by sending a SIGTERM first")
flagGracefulTimeout = flag.Uint("graceful-timeout", 3, "Duration (in seconds) to wait for graceful kill to complete")
flagVerbose = flag.Bool("verbose", false, "Be verbose about which directories are watched.")
flagPolling = flag.Bool("polling", false, "Use polling method to watch file change instead of fsnotify")
flagPollingInterval = flag.Int("polling-interval", 100, "Milliseconds of interval between polling file changes when polling option is selected")
// initialized in main() due to custom type.
flagDirectories globList
flagExcludedDirs globList
flagExcludedFiles globList
flagIncludedFiles globList
flagBuildCommandList buildCommandList
)
func okColor(format string, args ...interface{}) string {
if *flagColor {
return color.GreenString(format, args...)
} else {
return fmt.Sprintf(format, args...)
}
}
func failColor(format string, args ...interface{}) string {
if *flagColor {
return color.RedString(format, args...)
} else {
return fmt.Sprintf(format, args...)
}
}
// Run `go build` and print the output if something's gone wrong.
func build() bool {
log.Println(okColor("Running build commands!"))
for _, c := range flagBuildCommandList.commands {
err := runBuildCommand(c)
if err != nil {
log.Println(failColor("Command failed: "), failColor(c))
return false
}
}
log.Println(okColor("Build ok."))
return true
}
func runBuildCommand(c string) error {
c = strings.TrimSpace(c)
args := strings.Split(c, " ")
if len(args) == 0 {
return nil
}
cmd := exec.Command(args[0], args[1:]...)
if *flagBuildDir != "" {
cmd.Dir = *flagBuildDir
} else if len(flagDirectories) > 0 {
cmd.Dir = flagDirectories[0]
}
output, err := cmd.CombinedOutput()
if err != nil {
log.Println(failColor("Error while building:\n"), failColor(string(output)))
return err
}
return nil
}
func matchesPattern(pattern *regexp.Regexp, file string) bool {
return pattern.MatchString(file)
}
// Accept build jobs and start building when there are no jobs rushing in.
// The inrush protection is WorkDelay milliseconds long, in this period
// every incoming job will reset the timer.
func builder(jobs <-chan string, buildStarted chan<- string, buildDone chan<- bool) {
createThreshold := func() <-chan time.Time {
return time.After(time.Duration(WorkDelay * time.Millisecond))
}
threshold := createThreshold()
eventPath := ""
for {
select {
case eventPath = <-jobs:
threshold = createThreshold()
case <-threshold:
buildStarted <- eventPath
buildDone <- build()
}
}
}
func logger(pipeChan <-chan io.ReadCloser) {
dumper := func(pipe io.ReadCloser, prefix string) {
reader := bufio.NewReader(pipe)
readloop:
for {
line, err := reader.ReadString('\n')
if err != nil {
break readloop
}
if *flagLogPrefix {
log.Print(prefix, " ", line)
} else {
log.Print(line)
}
}
}
for {
pipe := <-pipeChan
go dumper(pipe, "stdout:")
pipe = <-pipeChan
go dumper(pipe, "stderr:")
}
}
// Start the supplied command and return stdout and stderr pipes for logging.
func startCommand(command string) (cmd *exec.Cmd, stdout io.ReadCloser, stderr io.ReadCloser, err error) {
args := strings.Split(command, " ")
cmd = exec.Command(args[0], args[1:]...)
if *flagRunDir != "" {
cmd.Dir = *flagRunDir
}
if stdout, err = cmd.StdoutPipe(); err != nil {
err = fmt.Errorf("can't get stdout pipe for command: %s", err)
return
}
if stderr, err = cmd.StderrPipe(); err != nil {
err = fmt.Errorf("can't get stderr pipe for command: %s", err)
return
}
if err = cmd.Start(); err != nil {
err = fmt.Errorf("can't start command: %s", err)
return
}
return
}
// Run the command in the given string and restart it after
// a message was received on the buildDone channel.
func runner(commandTemplate string, buildStarted <-chan string, buildSuccess <-chan bool) {
var currentProcess *os.Process
pipeChan := make(chan io.ReadCloser)
go logger(pipeChan)
// Launch concurrent process watching for signals from outside that
// indicate termination to kill the running process alongside
// CompileDaemon to prevent orphan processes.
go func() {
processSignalChannel := make(chan os.Signal, 1)
signal.Notify(processSignalChannel, fatalSignals...)
<-processSignalChannel
log.Println(okColor("Received signal, terminating cleanly."))
if currentProcess != nil {
killProcess(currentProcess)
}
os.Exit(0)
}()
for {
eventPath := <-buildStarted
// prepend %0.s (which adds nothing) to prevent warning about missing
// format specifier if the user did not supply one.
command := fmt.Sprintf("%0.s"+commandTemplate, eventPath)
if !*flagCommandStop {
if !<-buildSuccess {
continue
}
}
if currentProcess != nil {
killProcess(currentProcess)
}
if *flagCommandStop {
log.Println(okColor("Command stopped. Waiting for build to complete."))
if !<-buildSuccess {
continue
}
}
log.Println(okColor("Restarting the given command."))
cmd, stdoutPipe, stderrPipe, err := startCommand(command)
if err != nil {
log.Fatal(failColor("Could not start command: %s", err))
}
pipeChan <- stdoutPipe
pipeChan <- stderrPipe
currentProcess = cmd.Process
}
}
func killProcess(process *os.Process) {
if *flagGracefulKill {
killProcessGracefully(process)
} else {
killProcessHard(process)
}
}
func killProcessHard(process *os.Process) {
log.Println(okColor("Hard stopping the current process.."))
if err := process.Kill(); err != nil {
log.Println(failColor("Warning: could not kill child process. It may have already exited."))
}
if _, err := process.Wait(); err != nil {
log.Fatal(failColor("Could not wait for child process. Aborting due to danger of infinite forks."))
}
}
func killProcessGracefully(process *os.Process) {
done := make(chan error, 1)
go func() {
log.Println(okColor("Gracefully stopping the current process.."))
if err := terminateGracefully(process); err != nil {
done <- err
return
}
_, err := process.Wait()
done <- err
}()
select {
case <-time.After(time.Duration(*flagGracefulTimeout) * time.Second):
log.Println(failColor("Could not gracefully stop the current process, proceeding to hard stop."))
killProcessHard(process)
<-done
case err := <-done:
if err != nil {
log.Fatal(failColor("Could not kill child process. Aborting due to danger of infinite forks."))
}
}
}
func flusher(buildStarted <-chan string, buildSuccess <-chan bool) {
for {
<-buildStarted
<-buildSuccess
}
}
func main() {
flag.Var(&flagDirectories, "directory", "Directory to watch for changes, can be set more than once")
flag.Var(&flagExcludedDirs, "exclude-dir", " Don't watch directories matching this name, can be set more than once")
flag.Var(&flagExcludedFiles, "exclude", " Don't watch files matching this name, can be set more than once")
flag.Var(&flagIncludedFiles, "include", " Watch files matching this name, can be set more than once")
flag.Var(&flagBuildCommandList, "build", "Command to rebuild after changes, can be set more than once. Defaults to 'go build'.")
flag.Parse()
if !*flagLogPrefix {
log.SetFlags(0)
}
if len(flagDirectories) == 0 {
flagDirectories = globList([]string{"."})
}
if *flagGracefulKill && !gracefulTerminationPossible() {
log.Fatal("Graceful termination is not supported on your platform.")
}
if len(flagBuildCommandList.commands) == 0 {
_ = flagBuildCommandList.Set("go build")
}
pattern := regexp.MustCompile(*flagPattern)
cfg := &WatcherConfig{
flagVerbose: *flagVerbose,
flagRecursive: *flagRecursive,
flagPolling: *flagPolling,
flagPollingInterval: *flagPollingInterval,
flagDirectories: flagDirectories,
flagExcludedDirs: flagExcludedDirs,
flagExcludedFiles: flagExcludedFiles,
flagIncludedFiles: flagIncludedFiles,
pattern: pattern,
}
watcher, err := NewWatcher(cfg)
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
err = watcher.AddFiles()
if err != nil {
log.Fatal("watcher.Addfiles():", err)
}
jobs := make(chan string)
buildSuccess := make(chan bool)
buildStarted := make(chan string)
go builder(jobs, buildStarted, buildSuccess)
if *flagCommand != "" {
go runner(*flagCommand, buildStarted, buildSuccess)
} else {
go flusher(buildStarted, buildSuccess)
}
watcher.Watch(jobs) // start watching files
}