forked from codegangsta/gin
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.go
312 lines (275 loc) · 6.25 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
package main
import (
"bufio"
"context"
"errors"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/mattn/go-shellwords"
"github.com/urfave/cli/v2"
"github.com/acoshift/goreload/internal"
)
var (
logger = log.New(os.Stdout, "[goreload] ", 0)
colorGreen = string([]byte{27, 91, 57, 55, 59, 51, 50, 59, 49, 109})
colorYellow = string([]byte{27, 91, 57, 55, 59, 51, 51, 59, 49, 109})
colorRed = string([]byte{27, 91, 57, 55, 59, 51, 49, 59, 49, 109})
colorReset = string([]byte{27, 91, 48, 109})
)
func main() {
app := cli.NewApp()
app.Name = "goreload"
app.Usage = "A live reload utility for Go web applications."
app.Action = mainAction
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: "bin",
Aliases: []string{"b"},
Value: ".goreload",
Usage: "name of generated binary file",
},
&cli.StringFlag{
Name: "path",
Aliases: []string{"t"},
Value: ".",
Usage: "Path to watch files from",
},
&cli.StringFlag{
Name: "build",
Aliases: []string{"d"},
Value: "",
Usage: "Path to build files from (defaults to same value as --path)",
},
&cli.StringSliceFlag{
Name: "excludeDir",
Aliases: []string{"x"},
Value: &cli.StringSlice{},
Usage: "Relative directories to exclude",
},
&cli.BoolFlag{
Name: "all",
Usage: "reloads whenever any file changes, as opposed to reloading only on .go file change",
},
&cli.StringFlag{
Name: "buildArgs",
Usage: "Additional go build arguments",
},
&cli.StringFlag{
Name: "logPrefix",
Usage: "Log prefix",
Value: "goreload",
},
}
app.Commands = []*cli.Command{
{
Name: "run",
Aliases: []string{"r"},
Usage: "Run the goreload",
Action: mainAction,
},
}
if err := app.Run(os.Args); err != nil {
logger.Fatal(err)
}
}
func mainAction(c *cli.Context) error {
logger.SetPrefix(fmt.Sprintf("[%s] ", c.String("logPrefix")))
all := c.Bool("all")
wd, err := os.Getwd()
if err != nil {
logger.Fatal(err)
return err
}
buildArgs, err := shellwords.Parse(c.String("buildArgs"))
if err != nil {
return err
}
buildPath := c.String("build")
if buildPath == "" {
buildPath = c.String("path")
}
builder := internal.NewBuilder(buildPath, c.String("bin"), wd, buildArgs)
runner := internal.NewRunner(filepath.Join(wd, builder.Binary()), c.Args().Slice()...)
runner.SetWriter(os.Stdout)
shutdown(runner)
ctx, cancel := context.WithCancel(context.Background())
buildAndRun(ctx, builder, runner)
scanChanges(c.String("path"), c.StringSlice("excludeDir"), all, func() {
cancel()
runner.Kill()
ctx, cancel = context.WithCancel(context.Background())
go buildAndRun(ctx, builder, runner)
})
return nil
}
var lockBuildAndRun sync.Mutex
func buildAndRun(ctx context.Context, builder *internal.Builder, runner *internal.Runner) {
// allow only single buildAndRun at anytime
lockBuildAndRun.Lock()
defer lockBuildAndRun.Unlock()
logger.Println("Building...")
err := builder.Build(ctx)
if err == context.Canceled {
logger.Printf("%sBuild canceled%s\n", colorYellow, colorReset)
return
}
if err != nil {
logger.Printf("%sBuild failed%s\n", colorRed, colorReset)
fmt.Println(err)
return
}
logger.Printf("%sBuild finished%s\n", colorGreen, colorReset)
runner.Run()
}
func scanChanges(watchPath string, excludeDirs []string, allFiles bool, cb func()) {
scanChangesFswatch(watchPath, excludeDirs, allFiles, cb)
scanChangesWalk(watchPath, excludeDirs, allFiles, cb)
}
func scanChangesFswatch(watchPath string, excludeDirs []string, allFiles bool, cb func()) {
if runtime.GOOS != "darwin" {
return
}
exit := false
curDir, err := os.Getwd()
if err != nil {
return
}
curDir += "/"
debouncedCallback := newDebounce(cb, 100*time.Millisecond)
// always retry when fswatch exit
for {
func() {
cmd := exec.Command("fswatch",
"-r",
"--event=Created",
"--event=Updated",
"--event=Removed",
watchPath,
)
p, err := cmd.StdoutPipe()
if err != nil {
return
}
err = cmd.Start()
if err != nil {
// fswatch not found, or can not start
exit = true
return
}
defer func() {
if cmd.Process != nil {
cmd.Process.Kill()
}
}()
r := bufio.NewReader(p)
for {
pathBytes, _, err := r.ReadLine()
if err != nil {
break
}
path := string(pathBytes)
path = strings.TrimPrefix(path, curDir)
if strings.HasPrefix(path, ".git/") {
continue
}
{
skip := false
for _, x := range excludeDirs {
if strings.HasPrefix(path, x) {
skip = true
break
}
}
if skip {
continue
}
}
if filepath.Base(path)[0] == '.' {
continue
}
if !(allFiles || filepath.Ext(path) == ".go") {
continue
}
debouncedCallback.Call()
}
}()
if exit {
return
}
time.Sleep(500 * time.Millisecond)
}
}
func scanChangesWalk(watchPath string, excludeDirs []string, allFiles bool, cb func()) {
excludeDir := make(map[string]bool)
for _, x := range excludeDirs {
excludeDir[x] = true
}
startTime := time.Now()
var errDone = errors.New("done")
for {
filepath.Walk(watchPath, func(path string, info os.FileInfo, err error) error {
if path == ".git" && info.IsDir() {
return filepath.SkipDir
}
if excludeDir[path] {
return filepath.SkipDir
}
// ignore hidden files
if filepath.Base(path)[0] == '.' {
return nil
}
if (allFiles || filepath.Ext(path) == ".go") && info.ModTime().After(startTime) {
cb()
startTime = time.Now()
return errDone
}
return nil
})
time.Sleep(500 * time.Millisecond)
}
}
func shutdown(runner *internal.Runner) {
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
s := <-c
log.Println("Got signal: ", s)
err := runner.Kill()
if err != nil {
log.Print("Error killing: ", err)
}
os.Exit(1)
}()
}
type debounce struct {
mu sync.Mutex
t *time.Timer
f func()
d time.Duration
}
func newDebounce(f func(), d time.Duration) *debounce {
return &debounce{
f: f,
d: d,
}
}
func (d *debounce) Call() {
d.mu.Lock()
defer d.mu.Unlock()
if d.t == nil {
d.f()
d.t = time.AfterFunc(0, func() {})
return
}
d.t.Stop()
d.t = time.AfterFunc(d.d, d.f)
}