-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
132 lines (119 loc) · 1.92 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
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path"
"runtime"
"syscall"
"time"
"github.com/fsnotify/fsnotify"
)
var (
isWin = runtime.GOOS == "windows"
ch = make(chan struct{})
c *exec.Cmd
)
func run() {
prog := "sola-dev"
if isWin {
prog += ".exe"
}
cx := exec.Command(
"go",
"build",
"-o",
prog,
".",
) // TODO
cx.Stdin = os.Stdin
cx.Stdout = os.Stdout
cx.Stderr = os.Stderr
if e := cx.Run(); e != nil {
log.Println(e)
}
c = exec.Command("./sola-dev") // TODO
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
if e := c.Run(); e != nil {
log.Println(e)
}
}
func restart() {
// fmt.Println("up", c.Process.Signal(syscall.SIGHUP))
if isWin {
fmt.Println("kill", c.Process.Kill())
} else {
fmt.Println("int", c.Process.Signal(syscall.SIGINT))
fmt.Println("term", c.Process.Signal(syscall.SIGTERM))
}
go run()
}
func throttle() {
var after <-chan time.Time
after = time.After(1 * time.Second)
select {
case <-ch:
return
case <-after:
fmt.Println("restart")
restart()
go readch()
return
}
}
func readch() {
select {
case <-ch:
// fmt.Println("first ch")
return
}
}
func main() {
l := len(os.Args)
watcher, err := fsnotify.NewWatcher()
if l <= 1 {
watcher.Add(".")
} else {
for _, p := range os.Args {
watcher.Add(p)
}
}
if err != nil {
log.Fatalln(err)
}
defer watcher.Close()
go run()
go readch()
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
eventDispatcher(event)
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}
func eventDispatcher(event fsnotify.Event) {
ext := path.Ext(event.Name)
switch event.Op {
case
fsnotify.Write,
fsnotify.Rename:
if ext == ".go" || ext == ".yml" {
// log.Println("EVENT", event.Op.String(), event.Name)
ch <- struct{}{}
go throttle()
}
case fsnotify.Remove:
case fsnotify.Create:
}
}