/
main.go
85 lines (76 loc) · 1.63 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
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
flags "github.com/jessevdk/go-flags"
"github.com/howeyc/fsnotify"
)
var opts struct {
Program string `short:"p" long:"program" description:"The program to run for hot code reload" required:"true"`
Args string `short:"a" long:"args" description:"Arguments to pass to the program" optional:"true"`
Dir string `short:"d" long:"dir" description:"Directory to run the program in" optional:"true"`
}
func main() {
_, err := flags.Parse(&opts)
if err != nil {
fmt.Printf(err.Error())
os.Exit(1)
}
exe, cargs, dir := opts.Program, opts.Args, opts.Dir
if dir != "" {
err := os.Chdir(dir)
if err != nil {
panic(err.Error())
}
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
done := make(chan bool)
// Process events
go func() {
for {
select {
case ev := <-watcher.Event:
if ev.IsModify() && filepath.Ext(ev.Name) == ".go" {
time.Sleep(time.Second)
for nev, cont := <-watcher.Event; cont; {
ev = nev
select {
case nev = <-watcher.Event:
continue
default:
cont = false
}
}
log.Println("event:", ev)
log.Printf("%s", exe)
cmd := exec.Command(exe, strings.Split(cargs, " ")...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
if err != nil {
log.Println("%s", err.Error())
}
}
case err := <-watcher.Error:
panic(err.Error())
return
}
}
}()
cwd, _ := os.Getwd()
err = watcher.Watch(cwd)
if err != nil {
panic(err.Error())
}
<-done
/* ... do stuff ... */
watcher.Close()
}