-
Notifications
You must be signed in to change notification settings - Fork 0
/
dev.go
379 lines (306 loc) · 7.1 KB
/
dev.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
package cmd
import (
"context"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"
"github.com/fsnotify/fsnotify"
"github.com/spf13/cobra"
)
var c config
func init() {
devCmd.PersistentFlags().StringVarP(&c.root, "root", "r", ".",
"root path for watch, all files must be under root")
devCmd.PersistentFlags().StringVarP(&c.target, "target", "t", ".",
"target path for go build")
devCmd.PersistentFlags().StringSliceVarP(&c.extensions, "extensions", "e",
[]string{"go", "tmpl", "tpl", "html"}, "file extensions to watch")
devCmd.PersistentFlags().StringSliceVarP(&c.excludeDirs, "exclude_dirs", "D",
[]string{"assets", "tmp", "vendor", "node_modules"}, "ignore these directories")
devCmd.PersistentFlags().StringSliceVarP(&c.excludeFiles, "exclude_files", "F", nil, "ignore these files")
devCmd.PersistentFlags().DurationVarP(&c.delay, "delay", "d", time.Second,
"delay to trigger rerun")
}
// devCmd reruns the dawn project if watched files changed
var devCmd = &cobra.Command{
Use: "dev",
Short: "Rerun the dawn project if watched files changed",
RunE: devRunE,
}
func devRunE(_ *cobra.Command, _ []string) error {
return newEscort(c).run()
}
type config struct {
root string
target string
binPath string
extensions []string
excludeDirs []string
excludeFiles []string
delay time.Duration
}
type escort struct {
config
ctx context.Context
terminate context.CancelFunc
w *fsnotify.Watcher
watcherEvents chan fsnotify.Event
watcherErrors chan error
sig chan os.Signal
binPath string
bin *exec.Cmd
stdoutPipe io.ReadCloser
stderrPipe io.ReadCloser
hitCh chan struct{}
hitFunc func()
compiling atomic.Value
}
func newEscort(c config) *escort {
return &escort{
config: c,
hitCh: make(chan struct{}, 1),
sig: make(chan os.Signal, 1),
}
}
func (e *escort) run() (err error) {
if err = e.init(); err != nil {
return
}
log.Println("Welcome to dawn dev 👋")
defer func() {
_ = e.w.Close()
_ = os.Remove(e.binPath)
}()
go e.runBin()
go e.watchingBin()
go e.watchingFiles()
signal.Notify(e.sig, syscall.SIGTERM, syscall.SIGINT, os.Interrupt)
<-e.sig
e.terminate()
log.Println("See you next time 👋")
return nil
}
func (e *escort) init() (err error) {
if e.w, err = fsnotify.NewWatcher(); err != nil {
return
}
e.watcherEvents = e.w.Events
e.watcherErrors = e.w.Errors
e.ctx, e.terminate = context.WithCancel(context.Background())
// normalize root
if e.root, err = filepath.Abs(e.root); err != nil {
return
}
// create bin target
var f *os.File
if f, err = ioutil.TempFile("", ""); err != nil {
return
}
defer func() {
if e := f.Close(); e != nil {
err = e
}
}()
e.binPath = f.Name()
if runtime.GOOS == "windows" {
e.binPath += ".exe"
}
e.hitFunc = e.runBin
return
}
func (e *escort) watchingFiles() {
// walk root and add all dirs
e.walkForWatcher(e.root)
var (
info os.FileInfo
err error
)
for {
select {
case <-e.ctx.Done():
return
case event := <-e.watcherEvents:
p, op := event.Name, event.Op
// ignore chmod
if isChmoded(op) {
continue
}
if isRemoved(op) {
e.tryRemoveWatch(p)
continue
}
if info, err = os.Stat(p); err != nil {
log.Printf("Failed to get info of %s: %s\n", p, err)
continue
}
base := filepath.Base(p)
if info.IsDir() && isCreated(op) {
e.walkForWatcher(p)
e.hitCh <- struct{}{}
continue
}
if e.ignoredFiles(base) {
continue
}
if e.hitExtension(filepath.Ext(base)) {
e.hitCh <- struct{}{}
}
case err := <-e.watcherErrors:
log.Printf("Watcher error: %v\n", err)
}
}
}
func (e *escort) watchingBin() {
var timer *time.Timer
for range e.hitCh {
// reset timer
if timer != nil && !timer.Stop() {
select {
case <-timer.C:
default:
}
}
timer = time.AfterFunc(e.delay, e.hitFunc)
}
}
func (e *escort) runBin() {
if ok := e.compiling.Load(); ok != nil && ok.(bool) {
return
}
e.compiling.Store(true)
defer e.compiling.Store(false)
if e.bin != nil {
e.cleanOldBin()
log.Println("Recompiling...")
} else {
log.Println("Compiling...")
}
start := time.Now()
// build target
compile := execCommand("go", "build", "-o", e.binPath, e.target)
if out, err := compile.CombinedOutput(); err != nil {
log.Printf("Failed to compile %s: %s\n", e.target, out)
return
}
log.Printf("Compile done in %s!\n", formatLatency(time.Since(start)))
e.bin = execCommand(e.binPath)
e.bin.Env = os.Environ()
e.watchingPipes()
if err := e.bin.Start(); err != nil {
log.Printf("Failed to start bin: %s\n", err)
e.bin = nil
return
}
log.Println("New pid is", e.bin.Process.Pid)
}
func (e *escort) cleanOldBin() {
defer func() {
if e.stdoutPipe != nil {
_ = e.stdoutPipe.Close()
}
if e.stderrPipe != nil {
_ = e.stderrPipe.Close()
}
}()
pid := e.bin.Process.Pid
log.Println("Killing old pid", pid)
var err error
if runtime.GOOS == "windows" {
err = execCommand("TASKKILL", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
} else {
err = e.bin.Process.Kill()
_, _ = e.bin.Process.Wait()
}
if err != nil {
log.Printf("Failed to kill old pid %d: %s\n", pid, err)
}
e.bin = nil
}
func (e *escort) watchingPipes() {
var err error
if e.stdoutPipe, err = e.bin.StdoutPipe(); err != nil {
log.Printf("Failed to get stdout pipe: %s", err)
} else {
go func() { _, _ = io.Copy(os.Stdout, e.stdoutPipe) }()
}
if e.stderrPipe, err = e.bin.StderrPipe(); err != nil {
log.Printf("Failed to get stderr pipe: %s", err)
} else {
go func() { _, _ = io.Copy(os.Stderr, e.stderrPipe) }()
}
}
func (e *escort) walkForWatcher(root string) {
if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info != nil && !info.IsDir() {
return nil
}
base := filepath.Base(path)
if e.ignoredDirs(base) {
return filepath.SkipDir
}
log.Println("Add", path, "to watch")
return e.w.Add(path)
}); err != nil {
log.Printf("Failed to walk root %s: %s\n", e.root, err)
}
}
func (e *escort) tryRemoveWatch(p string) {
if err := e.w.Remove(p); err != nil && !strings.Contains(err.Error(), "non-existent") {
log.Printf("Failed to remove %s from watch: %s\n", p, err)
}
}
func (e *escort) hitExtension(ext string) bool {
if ext == "" {
return false
}
// remove '.'
ext = ext[1:]
for _, e := range e.extensions {
if ext == e {
return true
}
}
return false
}
func (e *escort) ignoredDirs(dir string) bool {
// exclude hidden directories like .git, .idea, etc.
if len(dir) > 1 && dir[0] == '.' {
return true
}
for _, d := range e.excludeDirs {
if dir == d {
return true
}
}
return false
}
func (e *escort) ignoredFiles(filename string) bool {
for _, f := range e.excludeFiles {
if filename == f {
return true
}
}
return false
}
func isRemoved(op fsnotify.Op) bool {
return op&fsnotify.Remove != 0
}
func isCreated(op fsnotify.Op) bool {
return op&fsnotify.Create != 0
}
func isChmoded(op fsnotify.Op) bool {
return op&fsnotify.Chmod != 0
}