-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
340 lines (299 loc) · 7.08 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
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
// helps in developing the application by having
// source code change detection, recompiliation,
// and rerunning.
package main
import (
"fmt"
"go/parser"
"go/token"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/codegangsta/cli"
"github.com/howeyc/fsnotify"
"github.com/kballard/go-shellquote"
)
var (
wpaths = make(map[string]string)
include []*regexp.Regexp
exclude []*regexp.Regexp
includeFiles []*regexp.Regexp
excludeFiles []*regexp.Regexp
)
// run the program
func run(c *cli.Context, cmderr chan error) (*exec.Cmd, error) {
if len(c.Args()) > 0 {
log.Printf("Running program...\n")
args := shellquote.Join(c.Args()...)
if len(args) > 2 {
if args[0] == '\'' || args[0] == '"' {
args = args[1:]
}
if args[len(args)-1] == '\'' || args[len(args)-1] == '"' {
args = args[:len(args)-1]
}
}
cmd := exec.Command(os.ExpandEnv(c.String("shell")), "-c", args)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Start()
if err != nil {
return nil, err
}
// Wait for the program and send the error value
// on the channel. We use this later to determine
// if a program has closed on its own and whether we
go func() {
cmderr <- cmd.Wait()
}()
return cmd, nil
} else {
log.Println("Detected code change")
}
return nil, nil
}
// shouldRerun returns true if we should rerun the program
// because `name` changed
func shouldRerun(name string) (ret bool) {
ret = false
// um... should be configurable?
ret = !strings.HasPrefix(filepath.Base(name), ".")
if !ret {
return
}
for _, r := range excludeFiles {
if r.MatchString(name) {
ret = false
return
}
}
for _, r := range includeFiles {
if r.MatchString(name) {
ret = true
return
}
}
return false
}
func watcher(c *cli.Context) {
log.Println("Running watcher")
var wg sync.WaitGroup
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
cmderr := make(chan error)
wg.Add(1)
go func() {
defer wg.Done()
cmd, err := run(c, cmderr)
if err != nil {
log.Println(err)
}
for {
select {
case ev := <-watcher.Event:
// basic throttling. we only do something when
// we receive no file system events after
// a certain time
LOOP:
for {
select {
case <-watcher.Event:
continue LOOP
case <-time.After(300 * time.Millisecond):
break LOOP
}
}
if ev.IsModify() || ev.IsCreate() {
if shouldRerun(ev.Name) {
if cmd != nil && cmd.Process != nil {
// We use select here to determine if the
// program has closed. If we have a value
// on the cmderr channel, then the program
// has already closed and we don't need to kil
// it.
select {
case e := <-cmderr:
if e != nil {
log.Println(e)
}
default:
log.Printf("Killing program...\n")
if cmd.Process.Signal(os.Interrupt) != nil {
if runtime.GOOS == "windows" {
exec.Command("TASKKILL", "/F", "/T", "/PID", fmt.Sprintf("%d", cmd.Process.Pid)).Run()
} else {
cmd.Process.Kill()
}
}
<-cmderr
}
}
cmd, err = run(c, cmderr)
if err != nil {
log.Println(err)
}
}
}
case <-watcher.Error:
//log.Println("error:", err)
}
}
}()
for _, value := range wpaths {
err = watcher.Watch(value)
if err != nil {
log.Fatal(err)
}
}
wg.Wait()
}
// find where on the filesystem a package is
func which(pkg string, location string) string {
for _, top := range strings.Split(os.Getenv("GOPATH"), ":") {
dir := top + "/" + location + "/" + pkg
_, err := os.Stat(dir)
if err == nil {
return dir
}
p := err.(*os.PathError)
if !os.IsNotExist(p.Err) {
log.Print(err)
}
}
return ""
}
// shouldWatch determines if we should watch the given
// path based on the include and exclude regexps.
func shouldWatch(path string) bool {
for _, r := range exclude {
if r.MatchString(path) {
log.Println("exclude:", path)
return false
}
}
for _, r := range include {
if r.MatchString(path) {
return true
}
}
return false
}
// getWatchDirs will add path to the watched dirs if it is a directory,
// or call getWatchDirsFromFile if it's a file.
func getWatchDirs(path string, info os.FileInfo, err error) error {
if err != nil {
log.Print(err)
}
if info.IsDir() {
// add all dirs we encounter
if shouldWatch(path) {
wpaths[path] = path
}
} else if !info.IsDir() && strings.HasSuffix(path, ".go") {
// parse the go file and add all imports
err = getWatchDirsFromFile(path)
if err != nil {
log.Print(err)
}
}
return nil
}
// getWatchDirsFromFile finds all the watch directories from the
// imports of the file
func getWatchDirsFromFile(path string) error {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return err
}
for _, s := range f.Imports {
path, err := strconv.Unquote(s.Path.Value)
if err != nil {
return err // can't happen
}
wpath := which(path, "src")
if wpath != "" {
if shouldWatch(wpath) {
wpaths[wpath] = wpath
}
}
}
return nil
}
// Called when you run "devrun watch"
func cmdWatchAction(c *cli.Context) {
var err error
// build regexps
for _, r := range c.StringSlice("include") {
include = append(include, regexp.MustCompile(r))
}
for _, r := range c.StringSlice("exclude") {
exclude = append(exclude, regexp.MustCompile(r))
}
for _, r := range c.StringSlice("include-files") {
includeFiles = append(includeFiles, regexp.MustCompile(r))
}
for _, r := range c.StringSlice("exclude-files") {
excludeFiles = append(excludeFiles, regexp.MustCompile(r))
}
for _, d := range c.StringSlice("dir") {
err = filepath.Walk(d, getWatchDirs)
if err != nil {
log.Fatal(err)
}
}
watcher(c)
}
func main() {
app := cli.NewApp()
app.Name = "devrun"
app.Usage = "rebuild/rerun on source change"
app.Commands = []cli.Command{
{
Name: "watch",
Usage: "watches a repository for code changes. runs a specified command",
Action: cmdWatchAction,
Flags: []cli.Flag{
cli.StringFlag{
Name: "shell",
Value: "${SHELL}",
Usage: "shell to use (defaults to the env variable SHELL)",
},
cli.StringSliceFlag{
Name: "dir",
Value: &cli.StringSlice{"./"},
Usage: "The directory(s) where to watch and scan for dependencies"},
cli.StringSliceFlag{
Name: "include",
Value: &cli.StringSlice{".*"},
Usage: "Regexp of dirs to include for watching.",
},
cli.StringSliceFlag{
Name: "exclude",
Value: &cli.StringSlice{`^\.*$`},
Usage: `Regexp of dirs to exclude from watching.`,
},
cli.StringSliceFlag{
Name: "include-files",
Value: &cli.StringSlice{`^(.*\.go)$`},
Usage: `Regexp of files that, if changed, will cause a rerun.`,
},
cli.StringSliceFlag{
Name: "exclude-files",
Value: &cli.StringSlice{`^\.*$`},
Usage: `Regexp of files that, if changed, will not cause a rerun.`,
},
},
},
}
app.Run(os.Args)
}