-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreloader.go
100 lines (90 loc) · 2.12 KB
/
reloader.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
package main
import (
"context"
"log"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/mightyguava/monty/livereload"
"github.com/mightyguava/monty/subproc"
"github.com/rjeczalik/notify"
"golang.org/x/time/rate"
)
// Reloader handles restarting the command and reloading chrome
type Reloader struct {
r *subproc.Runner
chrome *livereload.Chrome
w chan notify.EventInfo
}
// NewReloader initializes and returns a new Reloader instance
func NewReloader(r *subproc.Runner, chrome *livereload.Chrome, w chan notify.EventInfo) *Reloader {
return &Reloader{
r: r,
chrome: chrome,
w: w,
}
}
// WatchAndRun watches for file changes and restarts the command. If it gets a SIGINT or SIGTERM, it
// will tell the child command to exit and then exit itself.
func (r *Reloader) WatchAndRun() error {
var err error
limitWindow := 1 * time.Second
mu := &sync.Mutex{}
reloadPending := false
lm := rate.NewLimiter(rate.Every(limitWindow), 1)
sigChan := make(chan os.Signal)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
errChan := make(chan error)
for {
select {
case <-r.w:
mu.Lock()
if !reloadPending {
reloadPending = true
go func() {
lm.Wait(context.Background())
if err = r.Reload(); err != nil {
errChan <- err
}
reloadPending = false
}()
}
mu.Unlock()
case <-sigChan:
log.Println("signal received, exiting")
r.Shutdown()
return nil
}
}
}
// Reload starts the command or reloads the chrome window
func (r *Reloader) Reload() error {
if r.r != nil {
log.Println("change detected, restarting command")
if err := r.r.Restart(); err != nil {
return err
}
}
if r.chrome != nil {
log.Println("change detected, reloading chrome")
if err := r.chrome.Reload(); err != nil {
return err
}
}
return nil
}
// Shutdown stops any running command and closes the chrome window
func (r *Reloader) Shutdown() {
if r.r != nil {
if err := r.r.Stop(); err != nil {
log.Println("error stopping process:", err)
}
}
if r.chrome != nil {
if err := r.chrome.Close(); err != nil {
log.Println("error closing Chrome:", err)
}
}
}