-
Notifications
You must be signed in to change notification settings - Fork 67
/
run.go
78 lines (63 loc) · 1.61 KB
/
run.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
// Package watcher is a command line tool inspired by fresh (https://github.com/pilu/fresh) and used
// for watching .go file changes, and restarting the app in case of an update/delete/add operation.
// After you installed it, you can run your apps with their default parameters as:
// watcher -c config -p 7000 -h localhost
package watcher
import (
"log"
"os/exec"
"github.com/fatih/color"
)
// Runner listens for the change events and depending on that kills
// the obsolete process, and runs a new one
type Runner struct {
start chan string
done chan struct{}
cmd *exec.Cmd
}
// NewRunner creates a new Runner instance and returns its pointer
func NewRunner() *Runner {
return &Runner{
start: make(chan string),
done: make(chan struct{}),
}
}
// Run initializes runner with given parameters.
func (r *Runner) Run(p *Params) {
for fileName := range r.start {
color.Green("Running %s...\n", p.Get("run"))
cmd, err := runCommand(fileName, p.Package...)
if err != nil {
log.Printf("Could not run the go binary: %s \n", err)
r.kill(cmd)
continue
}
r.cmd = cmd
removeFile(fileName)
go func(cmd *exec.Cmd) {
if err := cmd.Wait(); err != nil {
log.Printf("process interrupted: %s \n", err)
r.kill(cmd)
}
}(r.cmd)
}
}
// Restart kills the process, removes the old binary and
// restarts the new process
func (r *Runner) restart(fileName string) {
r.kill(r.cmd)
r.start <- fileName
}
func (r *Runner) kill(cmd *exec.Cmd) {
if cmd != nil {
cmd.Process.Kill()
}
}
func (r *Runner) Close() {
close(r.start)
r.kill(r.cmd)
close(r.done)
}
func (r *Runner) Wait() {
<-r.done
}