/
gomon.go
234 lines (198 loc) · 4.77 KB
/
gomon.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
// Package gomon is a simple command line file watcher for Go.
// Usage: gomon run <file.go> [args]
package main
import (
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"gopkg.in/fsnotify.v1"
)
const (
threshold = 500 * time.Millisecond
)
type watch struct {
mu sync.Mutex
cmd *exec.Cmd
args []string
*fsnotify.Watcher
}
var (
done = make(chan bool)
sig = make(chan os.Signal)
)
// SubDirectories walks through the path(recursively)
// and returns a list of folders
func SubDirectories(p string) []string {
filelist := []string{}
err := filepath.Walk(p, func(file string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
dir := info.Name()
if ShouldIgnore(dir) && dir != "." && dir != ".." {
return filepath.SkipDir
}
filelist = append(filelist, file)
}
return nil
})
if err != nil {
log.Fatal(err)
}
return filelist
}
// NewWatcher adds all valid directories to watch list
// It assumes the current working directory to be the root of the project
func (w *watch) NewWatcher() {
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
list := SubDirectories(wd)
for _, dir := range list {
w.AddFolder(dir)
}
}
func (w *watch) AddFolder(p string) {
err := w.Add(p)
if err != nil {
log.Println("error Watching: ", p, err)
}
}
// Describe checks for the type of operation occured and
// logs the event info
func Describe(event fsnotify.Event) {
desc := ""
base := filepath.Base(event.Name)
if event.Op&fsnotify.Create == fsnotify.Create {
desc = "create"
} else if event.Op&fsnotify.Remove == fsnotify.Remove {
desc = "delete"
} else if event.Op&fsnotify.Write == fsnotify.Write {
desc = "modify"
} else if event.Op&fsnotify.Rename == fsnotify.Rename {
desc = "rename"
} else if event.Op&fsnotify.Chmod == fsnotify.Chmod {
desc = "chmod"
}
log.Println(desc, base)
}
func (w *watch) HandleEvent(event fsnotify.Event) {
if event.Op&fsnotify.Create == fsnotify.Create {
f, err := os.Stat(event.Name)
if err != nil {
log.Println("err watching ", filepath.Base(event.Name))
} else if f.IsDir() && !ShouldIgnore(f.Name()) {
w.AddFolder(event.Name)
}
}
}
// Run waits for watcher events sent by fsnotify
// and triggers the restart process if required
func (w *watch) Run() {
t := time.Now()
for {
select {
case event := <-w.Events:
if time.Since(t) < threshold || event.Name == "" {
break
}
t = time.Now()
f, err := os.Stat(event.Name)
if err != nil {
log.Println("error watching ", err)
break
}
if filepath.Ext(event.Name) == ".go" || filepath.Ext(event.Name) == ".tmpl" || f.IsDir() {
Describe(event)
w.HandleEvent(event)
log.Println("restarting...")
// Lock w to ensure that restart is an atomic operation
w.mu.Lock()
w.KillProcess()
go w.StartNewProcess()
}
case err := <-w.Errors:
if err != nil {
log.Println("error:", err)
}
}
}
}
// StartNewProcess starts the app as an separate process
// instead of being a child process of gomon
func (w *watch) StartNewProcess() {
// After the app has restarted successfully
// Unlock w to continue execution of other threads
defer w.mu.Unlock()
w.cmd = exec.Command("go", w.args...)
w.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
w.cmd.Stdout = os.Stdout
w.cmd.Stderr = os.Stderr
err := w.cmd.Start()
if err != nil {
log.Fatal("unable to start process", err)
}
}
// KillProcess kills the new process created by StartNewProcess
// It kills the whole process group to ensure
// all of its child processes are killed
func (w *watch) KillProcess() {
pgid, err := syscall.Getpgid(w.cmd.Process.Pid)
if err == nil {
syscall.Kill(-pgid, syscall.SIGTERM)
}
}
// HandleSignal waits for program termination signal
// to gracefully shutdown the process
func (w *watch) HandleSignal() {
<-sig
w.Stop()
}
// Stop terminates the watch process and kills the app(started by StartNewProcess())
// and then shuts down
func (w *watch) Stop() {
w.Watcher.Close()
w.KillProcess()
log.Println("shutting down...")
done <- true
}
func main() {
args := append([]string{"run"}, os.Args[1:]...)
signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
log.Println("starting gomon")
w := &watch{
Watcher: watcher,
args: args,
}
w.NewWatcher()
w.mu.Lock()
go w.StartNewProcess()
go w.HandleSignal()
defer func() {
if r := recover(); r != nil {
w.Stop()
}
}()
go w.Run()
<-done
}
// ShouldIgnore checks if the directory can be ignored
// so that no of watched files doesn't go beyond the ulimit
func ShouldIgnore(d string) bool {
if d == "node_modules" || d == "vendor" || strings.HasPrefix(d, ".") {
return true
}
return false
}