-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgowatch.go
186 lines (161 loc) · 3.69 KB
/
gowatch.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
package main
import (
"flag"
"go/parser"
"go/token"
"io"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"gopkg.in/fsnotify.v1"
)
var (
watchedRun []string
watchedFmt, _ = os.Getwd()
noRun = flag.Bool("n", false, "only run gofmt on watched Go files")
inFile = flag.String("i", "", "input file")
delay = flag.Int("d", 1, "delay time before detecting file change")
isPipe = false
exitCode = 0
lastReport = make(map[string]time.Time)
)
func isGoFile(f os.FileInfo) bool {
name := f.Name()
return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
}
func isMainPackage(sourceName string) bool {
fset := token.NewFileSet()
f, _ := parser.ParseFile(fset, sourceName, nil, parser.PackageClauseOnly)
return f.Name.Name == "main"
}
func format(path string) error {
log.Println("fmt", path)
command := exec.Command("gofmt", "-w", path)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
command.Run()
return nil
}
func goFiles(path string) (goFiles, mainFiles []string) {
filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if isGoFile(info) {
goFiles = append(goFiles, path)
if isMainPackage(path) {
mainFiles = append(mainFiles, path)
}
}
return nil
})
return
}
var (
goRunCmd *exec.Cmd
firstTime = true
)
func runGoRun(sourceNames []string) {
killGoRun()
var args []string
args = append(args, "run")
args = append(args, sourceNames...)
goRunCmd = exec.Command("go", args...)
func(goRunCmd *exec.Cmd) {
if len(*inFile) > 0 {
f, err := os.Open(*inFile)
if err != nil {
goRunCmd.Stdin = os.Stdin
} else {
goRunCmd.Stdin = f
defer f.Close()
}
}
goRunCmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
goRunCmd.Stdout = os.Stdout
goRunCmd.Stderr = os.Stderr
goRunCmd.Start()
if firstTime {
log.Println("run main package")
firstTime = false
} else {
log.Println("restart main package")
}
goRunCmd.Wait()
}(goRunCmd)
}
func killGoRun() {
if goRunCmd != nil && goRunCmd.Process != nil && goRunCmd.ProcessState == nil {
// to properly kill go run and its children
// we need to set goRunCmd.SysProcAttr.Setid to true
// and send kill signal to the process group
// with negative PID
syscall.Kill(-goRunCmd.Process.Pid, syscall.SIGKILL)
goRunCmd.Process.Wait()
}
}
func main() {
gowatchMain()
os.Exit(exitCode)
}
func gowatchMain() {
flag.Parse()
path, err := filepath.Abs(watchedFmt)
if err != nil {
panic(err)
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
err = watcher.Add(path)
if err != nil {
panic(err)
}
defer watcher.Close()
goFiles, mainFiles := goFiles(path)
// pre run gofmt on found Go files
for _, f := range goFiles {
format(f)
}
watchedRun = append(watchedRun, mainFiles...)
if len(watchedRun) > 0 && !*noRun {
go runGoRun(watchedRun)
defer killGoRun()
}
log.Println("watching", path)
fi, _ := os.Stdout.Stat()
isPipe = fi.Mode()&os.ModeNamedPipe != 0
sig := make(chan os.Signal)
signal.Notify(sig, os.Interrupt, os.Kill)
for {
select {
case <-sig:
return
case event, more := <-watcher.Events:
if more {
if event.Op == fsnotify.Create || event.Op == fsnotify.Write {
if time.Since(lastReport[event.Name]) < time.Duration(*delay)*time.Second {
continue
}
lastReport[event.Name] = time.Now()
relPath, _ := filepath.Rel(path, event.Name)
if isPipe {
io.WriteString(os.Stdout, relPath+"\n")
} else {
if f, _ := os.Stat(event.Name); isGoFile(f) {
format(event.Name)
if !*noRun {
go runGoRun(watchedRun)
}
}
}
}
} else {
return
}
}
}
}