-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
172 lines (142 loc) · 3.49 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
package main
import (
"bufio"
"flag"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/fatih/color"
"github.com/fsnotify/fsnotify"
)
// Delay - milliseconds to wait before restart after a file change
const Delay = 100
var (
flagDirectory = flag.String("dir", "./", "Directory to watch for changes")
flagOutput = flag.String("out", "./cmd/app", "Output directory for binary after build")
flagBuild = flag.String("build", "go build", "Command to rebuild after changes")
outDir = ""
)
func printSuccess(format string) {
log.Println(color.GreenString(format))
}
func printFail(format string, err ...interface{}) {
log.Println(color.RedString(format, err))
}
func main() {
flag.Parse()
if *flagDirectory == "" {
printFail("Directory flag is required")
os.Exit(1)
}
setupWatcher()
}
func setupWatcher() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
printFail("Failed to setup watcher: ", err.Error())
os.Exit(1)
}
defer watcher.Close()
outDir, err = filepath.Abs(*flagOutput)
if outDir == "" {
printFail("Invalid output directory: ", err.Error())
os.Exit(1)
}
watchFiles(watcher)
var currentProcess *os.Process
if build() {
currentProcess = runBinary().Process
printSuccess("Waiting for changes...")
}
for {
select {
case err := <-watcher.Errors:
printFail("Failed to reload: ", err.Error())
case event := <-watcher.Events:
if event.Op&fsnotify.Remove == fsnotify.Remove || event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create {
time.Sleep(Delay * time.Millisecond)
if currentProcess != nil {
killProcess(currentProcess)
}
printSuccess("Restarting...")
if build() {
currentProcess = runBinary().Process
printSuccess("Started")
}
}
}
}
}
func watchFiles(watcher *fsnotify.Watcher) {
err := filepath.Walk(*flagDirectory, func(path string, info os.FileInfo, err error) error {
if err == nil && info.IsDir() {
return watcher.Add(path)
}
return err
})
if err != nil {
printFail("Failed to add inner folders for watching: ", err.Error())
os.Exit(1)
}
err = watcher.Add(*flagDirectory)
if err != nil {
printFail("Failed to add folder for watching: ", err.Error())
os.Exit(1)
}
}
func build() bool {
args := strings.Split(*flagBuild, " ")
if len(args) == 0 {
return true
}
args = append(args, "-o", outDir)
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = *flagDirectory
if output, err := cmd.CombinedOutput(); err != nil {
printFail("Failed while building:\n%s", output)
return false
}
return true
}
func runBinary() *exec.Cmd {
var stdout, stderr io.ReadCloser
var err error
cmd := exec.Command(outDir)
if stdout, err = cmd.StdoutPipe(); err != nil {
printFail("Failed get stdout pipe: ", err.Error())
return nil
}
if stderr, err = cmd.StderrPipe(); err != nil {
printFail("Failed get stderr pipe: ", err.Error())
return nil
}
go logger(stdout)
go logger(stderr)
if err = cmd.Start(); err != nil {
printFail("Failed while running: ", err.Error())
return nil
}
return cmd
}
func logger(pipe io.ReadCloser) {
reader := bufio.NewReader(pipe)
for {
line, err := reader.ReadString('\n')
if err != nil {
break
}
log.Printf("%+v", line)
}
}
func killProcess(process *os.Process) {
if err := process.Kill(); err != nil {
printFail("Can not kill current process: ", err.Error())
}
if _, err := process.Wait(); err != nil {
printFail("Can not wait for exiting of current process: ", err.Error())
}
}