-
Notifications
You must be signed in to change notification settings - Fork 54
/
run.go
244 lines (214 loc) · 5.21 KB
/
run.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
package run
import (
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"sync"
"time"
tp "github.com/henrylee2cn/teleport"
"github.com/xiaoenai/tp-micro/micro/create"
"github.com/xiaoenai/tp-micro/micro/info"
"github.com/xiaoenai/tp-micro/micro/run/fsnotify"
)
// RunProject runs project.
func RunProject(newWatchExts []string, newNotWatch []string) {
if err := os.Chdir(info.AbsPath()); err != nil {
tp.Fatalf("[micro] Jump working directory failed: %v", err)
}
if len(newWatchExts) > 0 {
watchExts = append(newWatchExts, ".go")
}
if len(newNotWatch) > 0 {
notWatch = append(notWatch, newNotWatch...)
}
go rewatch()
tp.Printf("[micro] Initializing watcher...")
select {}
}
// getFileModTime retuens unix timestamp of `os.File.ModTime` by given path.
func getFileModTime(path string) int64 {
path = strings.Replace(path, "\\", "/", -1)
f, err := os.Open(path)
if err != nil {
tp.Errorf("[micro] Fail to open file[ %s ]", err)
return time.Now().Unix()
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
tp.Errorf("[micro] Fail to get file information[ %s ]", err)
return time.Now().Unix()
}
return fi.ModTime().Unix()
}
// checkTMPFile returns true if the event was for TMP files.
func checkTMPFile(name string) bool {
if strings.HasSuffix(strings.ToLower(name), ".tmp") {
return true
}
return false
}
func rewatch() {
rerun()
time.Sleep(time.Second * 2)
var eventTime = make(map[string]int64)
filepath.Walk("./", func(retpath string, f os.FileInfo, err error) error {
if err != nil || f.IsDir() || checkTMPFile(retpath) || !checkIfWatchExt(retpath) {
return nil
}
eventTime[retpath] = f.ModTime().Unix()
return nil
})
watcher, err := fsnotify.NewWatcher()
if err != nil {
tp.Errorf("[micro] Fail to create new watcher[ %v ]", err)
os.Exit(2)
}
for _, path := range readAppDirectories("./") {
tp.Printf("[micro] Watching directory[ %s ]", path)
err = watcher.Watch(path)
if err != nil {
tp.Errorf("[micro] Fail to watch curpathectory[ %s ]", err)
os.Exit(2)
}
}
for {
select {
case e := <-watcher.Event:
isbuild := true
// Skip TMP files for Sublime Text.
if checkTMPFile(e.Name) {
continue
}
if !checkIfWatchExt(e.Name) {
continue
}
mt := getFileModTime(e.Name)
if t := eventTime[e.Name]; mt == t {
isbuild = false
}
eventTime[e.Name] = mt
if isbuild {
tp.Printf("%s", e.String())
watcher.Close()
if strings.HasSuffix(e.Name, create.MicroTpl) {
create.CreateProject(false, false)
}
go rewatch()
return
}
case err := <-watcher.Error:
tp.Warnf("[micro] %s", err.Error()) // No need to exit here
}
}
}
var (
state sync.Mutex
cmd *exec.Cmd
isFirstStart = true
)
func rerun() {
state.Lock()
defer state.Unlock()
tp.Printf("[micro] Start build...")
buildCom := exec.Command("go", "build", "-o", info.FileName())
buildCom.Env = []string{"GOPATH=" + info.Gopath()}
for _, env := range os.Environ() {
if strings.HasPrefix(strings.TrimSpace(env), "GOPATH=") {
continue
}
buildCom.Env = append(buildCom.Env, env)
}
buildCom.Stdout = os.Stdout
buildCom.Stderr = os.Stderr
err := buildCom.Run()
if err != nil {
tp.Errorf("[micro] ============== Build failed ===================")
return
}
tp.Printf("[micro] Build was successful")
var start string
if isFirstStart {
isFirstStart = false
tp.Printf("[micro] Starting app: %s", info.ProjName())
start = "Start"
} else {
tp.Printf("[micro] Restarting app: %s", info.ProjName())
defer func() {
if e := recover(); e != nil {
tp.Printf("[micro] Kill.recover -> %v", e)
}
}()
if cmd != nil && cmd.Process != nil {
err := cmd.Process.Kill()
cmd.Process.Release()
if err != nil {
tp.Printf("[micro] Kill -> %v", err)
}
}
start = "Restart"
}
go func() {
cmd = exec.Command("./" + info.FileName())
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = os.Environ()
if err := cmd.Start(); err != nil {
tp.Errorf("[micro] Fail to start app[ %s ]", err)
return
}
tp.Printf("[micro] %s was successful", start)
cmd.Wait()
tp.Printf("[micro] Old process was stopped")
}()
}
func readAppDirectories(dir string) (paths []string) {
fileInfos, err := ioutil.ReadDir(dir)
if err != nil {
tp.Fatalf("[micro] read project directorys failed: %v", err)
return
}
useDirectory := false
for _, fileInfo := range fileInfos {
if checkIfNotWatch(fileInfo.Name()) {
continue
}
if fileInfo.IsDir() == true && fileInfo.Name()[0] != '.' {
paths = append(paths, readAppDirectories(path.Join(dir, fileInfo.Name()))...)
continue
}
if useDirectory == true {
continue
}
if checkIfWatchExt(fileInfo.Name()) {
paths = append(paths, dir)
useDirectory = true
}
}
return
}
var notWatch = []string{}
func checkIfNotWatch(name string) bool {
if name[0] == '_' {
return true
}
for _, s := range notWatch {
if name == s {
return true
}
}
return false
}
var watchExts = []string{".go", ".ini", ".yaml", ".toml", ".xml"}
// checkIfWatchExt returns true if the name HasSuffix <watch_ext>.
func checkIfWatchExt(name string) bool {
for _, s := range watchExts {
if strings.HasSuffix(strings.ToLower(name), s) {
return true
}
}
return false
}