-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
101 lines (85 loc) · 2.02 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
package main
import (
"crypto/md5"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"path"
)
var (
binFile, lastHash string
bs *buildStatus
watchChan chan string
buildFlags string
)
func init() {
binFile = path.Join(tmpPath(), `server`)
bs = &buildStatus{errFile: path.Join(tmpPath(), `error`)}
watchChan = make(chan string, 1000)
}
func main() {
flag.StringVar(&buildFlags, `build-flags`, ``, `Set build flags for go build`)
flag.Parse()
go watch()
handleSig()
start()
}
func start() {
var build, server *exec.Cmd
debounce := newDebouncer(watchChan, 5)
for {
// Execute through bash command to pass all arbitrary build flags like `-ldflags "-X sampleValue=3"`
build = exec.Command(`bash`, `-c`, fmt.Sprintf("go build -o %s %s", binFile, buildFlags))
build.Stdout = os.Stdout
build.Stderr = os.Stderr
if err := build.Run(); err != nil {
bs.error()
log.Printf(`failed to build source => %v`, err)
} else {
bs.success()
if should, err := shouldRestart(); err != nil {
log.Printf("failed to check server binary => %v", err)
} else if should {
if server != nil && server.Process != nil {
log.Println(`[go-watch] restarting...`)
if err := server.Process.Kill(); err != nil {
log.Fatalf(`failed to terminate server process => %v`, err)
}
} else {
log.Println(`[go-watch] start`)
}
server = exec.Command(binFile, flag.Args()...)
server.Stdout = os.Stdout
server.Stderr = os.Stderr
if err := server.Start(); err != nil {
log.Fatalf(`failed to start server process => %v`, err)
}
}
}
debounce()
}
}
func shouldRestart() (bool, error) {
if h, err := binHash(); err != nil {
return false, err
} else if h != lastHash {
lastHash = h
return true, nil
}
return false, nil
}
func binHash() (string, error) {
f, err := os.Open(binFile)
if err != nil {
return ``, err
}
defer fileClose(f)
h := md5.New()
if _, err := io.Copy(h, f); err != nil {
return ``, err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}