-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
arelo.go
487 lines (439 loc) · 10.3 KB
/
arelo.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
package main
import (
"bufio"
"context"
"fmt"
"io"
"io/fs"
"log"
"os"
"os/signal"
"path"
"path/filepath"
"runtime/debug"
"strings"
"sync"
"syscall"
"time"
"github.com/bmatcuk/doublestar/v4"
"github.com/fsnotify/fsnotify"
"github.com/spf13/pflag"
"golang.org/x/xerrors"
)
const (
waitForTerm = 5 * time.Second
)
var (
version string
usage = `Usage: arelo [OPTION]... -- COMMAND
Run the COMMAND and restart when a file matches the pattern has been modified.
Options:
`
targets = pflag.StringArrayP("target", "t", nil, "observation target `path` (default \"./\")")
patterns = pflag.StringArrayP("pattern", "p", nil, "trigger pathname `glob` pattern (default \"**\")")
ignores = pflag.StringArrayP("ignore", "i", nil, "ignore pathname `glob` pattern")
delay = pflag.DurationP("delay", "d", time.Second, "`duration` to delay the restart of the command")
restart = pflag.BoolP("restart", "r", false, "restart the command on exit")
sigopt = pflag.StringP("signal", "s", "", "`signal` used to stop the command (default \"SIGTERM\")")
verbose = pflag.BoolP("verbose", "v", false, "verbose output")
help = pflag.BoolP("help", "h", false, "display this message")
showver = pflag.BoolP("version", "V", false, "display version")
filters = pflag.StringArrayP("filter", "f", nil, "filter file system `event` (CREATE|WRITE|REMOVE|RENAME|CHMOD)")
)
func main() {
pflag.Parse()
if *showver {
fmt.Println("arelo version", versionstr())
return
}
cmd := pflag.Args()
if *targets == nil {
*targets = []string{"./"}
}
if *patterns == nil {
*patterns = []string{"**"}
}
sig, sigstr := parseSignalOption(*sigopt)
filtOp, err := parseFilters(*filters)
if err != nil {
log.Fatalf("[ARELO] %v", err)
}
logVerbose("command: %q", cmd)
logVerbose("targets: %q", *targets)
logVerbose("patterns: %q", *patterns)
logVerbose("ignores: %q", *ignores)
logVerbose("filter: %v", filtOp)
logVerbose("delay: %v", delay)
logVerbose("signal: %s", sigstr)
logVerbose("restart: %v", *restart)
if *help {
fmt.Println("arelo version", versionstr())
fmt.Fprintf(os.Stderr, usage)
pflag.PrintDefaults()
return
}
if len(cmd) == 0 {
fmt.Fprintf(os.Stderr, "%s: COMMAND required.\n", os.Args[0])
os.Exit(1)
}
if sig == nil {
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], sigstr)
os.Exit(1)
}
modC, errC, err := watcher(*targets, *patterns, *ignores, filtOp)
if err != nil {
log.Fatalf("[ARELO] wacher error: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
reload := runner(ctx, &wg, cmd, *delay, sig.(syscall.Signal), *restart)
go func() {
for {
select {
case <-ctx.Done():
return
case name, ok := <-modC:
if !ok {
cancel()
wg.Wait()
log.Fatalf("[ARELO] wacher closed")
return
}
reload <- name
case err := <-errC:
cancel()
wg.Wait()
log.Fatalf("[ARELO] wacher error: %v", err)
return
}
}
}()
s := make(chan os.Signal, 1)
signal.Notify(s, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
sig = <-s
log.Printf("[ARELO] signal: %v", sig)
cancel()
wg.Wait()
}
func logVerbose(fmt string, args ...interface{}) {
if *verbose {
log.Printf("[ARELO] "+fmt, args...)
}
}
func versionstr() string {
if version != "" {
return "v" + version
}
info, ok := debug.ReadBuildInfo()
if !ok {
return "(devel)"
}
return info.Main.Version
}
func parseFilters(filters []string) (fsnotify.Op, error) {
var op fsnotify.Op
for _, f := range filters {
switch strings.ToUpper(f) {
case "CREATE":
op |= fsnotify.Create
case "WRITE":
op |= fsnotify.Write
case "REMOVE":
op |= fsnotify.Remove
case "RENAME":
op |= fsnotify.Rename
case "CHMOD":
op |= fsnotify.Chmod
default:
return 0, xerrors.Errorf("invalid filter event: %s", f)
}
}
return op, nil
}
func watcher(targets, patterns, ignores []string, filtOp fsnotify.Op) (<-chan string, <-chan error, error) {
w, err := fsnotify.NewWatcher()
if err != nil {
return nil, nil, err
}
if err := addTargets(w, targets, patterns, ignores); err != nil {
return nil, nil, err
}
modC := make(chan string)
errC := make(chan error)
watchOp := ^filtOp
go func() {
defer close(modC)
for {
select {
case event, ok := <-w.Events:
if !ok {
errC <- xerrors.Errorf("watcher.Events closed")
return
}
name := filepath.ToSlash(event.Name)
logVerbose("event: %v %q", event.Op, name)
if ignore, err := matchPatterns(name, ignores); err != nil {
errC <- xerrors.Errorf("match ignores: %w", err)
return
} else if ignore {
continue
}
if event.Has(watchOp) {
if match, err := matchPatterns(name, patterns); err != nil {
errC <- xerrors.Errorf("match patterns: %w", err)
return
} else if match {
modC <- name
}
}
// add watcher if new directory.
if event.Has(fsnotify.Create) {
fi, err := os.Stat(name)
if err != nil {
// ignore stat errors (notfound, permission, etc.)
log.Printf("[ARELO] watcher: %v", err)
} else if fi.IsDir() {
err := addDirRecursive(w, fi, name, patterns, ignores, modC)
if err != nil {
errC <- err
return
}
}
}
case err, ok := <-w.Errors:
errC <- xerrors.Errorf("watcher.Errors (%v): %w", ok, err)
return
}
}
}()
return modC, errC, nil
}
func matchPatterns(t string, pats []string) (bool, error) {
for _, p := range pats {
m, err := doublestar.Match(p, t)
if err != nil {
return false, xerrors.Errorf("match(%v, %v): %w", p, t, err)
}
if m {
return true, nil
}
if strings.HasPrefix(t, "./") {
m, err = doublestar.Match(p, t[2:])
if err != nil {
return false, xerrors.Errorf("match(%v, %v): %w", p, t[2:], err)
}
if m {
return true, nil
}
}
}
return false, nil
}
func addTargets(w *fsnotify.Watcher, targets, patterns, ignores []string) error {
for _, t := range targets {
t = path.Clean(t)
fi, err := os.Stat(t)
if err != nil {
return xerrors.Errorf("stat: %w", err)
}
if fi.IsDir() {
if err := addDirRecursive(w, fi, t, patterns, ignores, nil); err != nil {
return err
}
}
logVerbose("watching target: %q", t)
if err := w.Add(t); err != nil {
return err
}
}
return nil
}
func addDirRecursive(w *fsnotify.Watcher, fi fs.FileInfo, t string, patterns, ignores []string, ch chan<- string) error {
logVerbose("watching target: %q", t)
err := w.Add(t)
if err != nil {
return xerrors.Errorf("wacher add: %w", err)
}
des, err := os.ReadDir(t)
if err != nil {
return xerrors.Errorf("read dir: %w", err)
}
for _, de := range des {
name := path.Join(t, de.Name())
if ignore, err := matchPatterns(name, ignores); err != nil {
return xerrors.Errorf("match ignores: %w", err)
} else if ignore {
continue
}
if ch != nil {
if match, err := matchPatterns(name, patterns); err != nil {
return xerrors.Errorf("match patterns: %w", err)
} else if match {
ch <- name
}
}
if de.IsDir() {
fi, err := de.Info()
if err != nil {
return err
}
err = addDirRecursive(w, fi, name, patterns, ignores, ch)
if err != nil {
return err
}
}
}
return nil
}
type bytesErr struct {
bytes []byte
err error
}
// stdinReader bypasses stdin to child processes
//
// cmd.Wait() blocks until stdin.Read() returns.
// so stdinReader.Read() returns EOF when the child process exited.
type stdinReader struct {
input <-chan bytesErr
chldDone <-chan struct{}
}
func (s *stdinReader) Read(b []byte) (int, error) {
select {
case be, ok := <-s.input:
if !ok {
return 0, io.EOF
}
return copy(b, be.bytes), be.err
case <-s.chldDone:
return 0, io.EOF
}
}
func clearChBuf[T any](c <-chan T) {
for {
select {
case <-c:
default:
return
}
}
}
func runner(ctx context.Context, wg *sync.WaitGroup, cmd []string, delay time.Duration, sig syscall.Signal, autorestart bool) chan<- string {
reload := make(chan string)
trigger := make(chan string)
go func() {
for name := range reload {
// ignore restart when the trigger is not waiting
select {
case trigger <- name:
default:
}
}
}()
var pcmd string // command string for display.
for _, s := range cmd {
if strings.ContainsAny(s, " \t\"'") {
s = fmt.Sprintf("%q", s)
}
pcmd += " " + s
}
pcmd = pcmd[1:]
stdinC := make(chan bytesErr, 1)
go func() {
b1 := make([]byte, 255)
b2 := make([]byte, 255)
for {
n, err := os.Stdin.Read(b1)
stdinC <- bytesErr{b1[:n], err}
b1, b2 = b2, b1
}
}()
chldDone := makeChildDoneChan()
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
default:
}
cmdctx, cancel := context.WithCancel(ctx)
restart := make(chan struct{})
done := make(chan struct{})
go func() {
log.Printf("[ARELO] start: %s", pcmd)
clearChBuf(chldDone)
stdin := &stdinReader{stdinC, chldDone}
err := runCmd(cmdctx, cmd, sig, stdin)
if err != nil {
log.Printf("[ARELO] command error: %v", err)
} else {
log.Printf("[ARELO] command exit status 0")
}
if autorestart {
close(restart)
}
close(done)
}()
select {
case <-ctx.Done():
cancel()
<-done
return
case name := <-trigger:
log.Printf("[ARELO] triggered: %q", name)
case <-restart:
logVerbose("auto restart")
}
logVerbose("wait %v", delay)
select {
case <-ctx.Done():
cancel()
<-done
return
case <-time.After(delay):
}
cancel()
<-done // wait process closed
}
}()
return reload
}
func runCmd(ctx context.Context, cmd []string, sig syscall.Signal, stdin *stdinReader) error {
c := prepareCommand(cmd)
c.Stdin = bufio.NewReader(stdin)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
if err := c.Start(); err != nil {
return err
}
var cerr error
done := make(chan struct{})
go func() {
cerr = waitCmd(c)
close(done)
}()
select {
case <-done:
if cerr != nil {
cerr = xerrors.Errorf("process exit: %w", cerr)
}
return cerr
case <-ctx.Done():
if err := killChilds(c, sig); err != nil {
return xerrors.Errorf("kill childs: %w", err)
}
}
select {
case <-done:
case <-time.After(waitForTerm):
if err := killChilds(c, syscall.SIGKILL); err != nil {
return xerrors.Errorf("kill childs (SIGKILL): %w", err)
}
<-done
}
if cerr != nil {
return xerrors.Errorf("process canceled: %w", cerr)
}
return nil
}