-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathwatcher.go
More file actions
219 lines (204 loc) · 4.99 KB
/
watcher.go
File metadata and controls
219 lines (204 loc) · 4.99 KB
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
package main
import (
"context"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/admpub/fsnotify"
"github.com/admpub/log"
"github.com/admpub/rundelay"
)
const (
DefaultWatchedFiles = "go"
DefaultIngoredPaths = `(\/\.\w+)|(^\.)|(\.\w+$)`
)
type Watcher struct {
WatchedDir string
OnChanged func()
Watcher *fsnotify.Watcher
FilePattern string
IgnoredPathPattern string
OnlyWatchBin bool
FileNameSuffix string
Paused bool
compiling atomic.Bool
lastEventTime atomic.Int64
}
func NewWatcher(dir, filePattern, ignoredPathPattern string) (w Watcher) {
w.WatchedDir = dir
w.FilePattern = DefaultWatchedFiles
w.IgnoredPathPattern = DefaultIngoredPaths
if len(filePattern) != 0 {
w.FilePattern = filePattern
}
if len(ignoredPathPattern) != 0 {
w.IgnoredPathPattern = ignoredPathPattern
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
w.Watcher = watcher
return
}
func (w *Watcher) Watch(ctx context.Context) (err error) {
for _, dir := range w.dirsToWatch() {
err = w.Watcher.Add(dir)
if err != nil {
return
}
}
filePattern := `\.(` + w.FilePattern + `)$`
if w.OnlyWatchBin {
filePattern = regexp.QuoteMeta(BinPrefix) + `[\d]+(\.exe)?$`
}
delay := time.Second * 2
dr := rundelay.New(delay, func(_ string) error {
w.OnChanged()
w.compiling.Store(false)
return nil
})
defer dr.Close()
expectedFileReg := regexp.MustCompile(filePattern)
defer w.Watcher.Close()
for {
select {
case file := <-w.Watcher.Events:
if w.Paused {
log.Info(`== Pause monitoring file changes.`)
continue
}
// Skip TMP files for Sublime Text.
if checkTMPFile(file.Name) {
continue
}
if !expectedFileReg.MatchString(file.Name) {
if w.OnlyWatchBin {
log.Info("== [IGNORE]", file.Name)
}
continue
}
fileName := filepath.Base(file.Name)
if w.OnlyWatchBin {
if !strings.HasPrefix(fileName, BinPrefix) {
log.Info(`忽略非`, BinPrefix, `前缀文件更改`)
return
}
if len(w.FileNameSuffix) > 0 {
fileName = strings.TrimSuffix(fileName, w.FileNameSuffix)
}
newAppBin := fileName
fileName = strings.TrimPrefix(fileName, BinPrefix)
newFileTs, err := strconv.ParseInt(fileName, 10, 64)
if err != nil {
log.Error(err)
continue
}
fileName = strings.TrimPrefix(AppBin, BinPrefix)
oldFileTs, err := strconv.ParseInt(fileName, 10, 64)
if err != nil {
log.Error(err)
continue
}
if newFileTs <= oldFileTs {
log.Info(`新文件时间戳小于旧文件,忽略`)
continue
}
AppBin = newAppBin
} else {
if strings.HasPrefix(fileName, BinPrefix) {
log.Info(`忽略`, fileName, `更改`)
continue
}
}
mt, isDir := getFileModTime(file.Name)
if file.Op == fsnotify.Create && isDir {
w.Watcher.Add(file.Name)
}
if t := w.lastEventTime.Load(); mt.Unix() == t {
log.Debugf("== [SKIP] # %s #", file.String())
continue
}
log.Infof("== [EVEN] %s", file)
w.lastEventTime.Store(mt.Unix())
if !w.compiling.Load() {
log.Warn("== Change detected: ", file.Name)
w.compiling.Store(true)
dr.Run(file.Name)
}
case err := <-w.Watcher.Errors:
log.Warn(err) // No need to exit here
case <-ctx.Done():
return nil
}
}
}
func (w *Watcher) dirsToWatch() (dirs []string) {
ignoredPathReg := regexp.MustCompile(w.IgnoredPathPattern)
matchedDirs := make(map[string]bool)
dir, _ := filepath.Abs("./")
matchedDirs[dir] = true
for _, dir := range strings.Split(w.WatchedDir, `|`) {
if dir == "" {
continue
}
dir, _ := filepath.Abs(dir)
f, err := os.Open(dir)
if err != nil {
continue
}
fi, err := f.Stat()
f.Close()
if err != nil {
log.Errorf("Fail to get file information[ %s ]", err)
continue
}
if !fi.IsDir() {
continue
}
log.Debug("")
log.Debug("")
log.Debug("Watch directory: ", dir)
log.Debug("==================================================================")
filepath.Walk(dir, func(filePath string, info os.FileInfo, e error) (err error) {
if e != nil {
return e
}
filePath = strings.Replace(filePath, "\\", "/", -1)
if !info.IsDir() || ignoredPathReg.MatchString(filePath) || ignoredPathReg.MatchString(filePath+`/`) {
return
}
if matchedDirs[filePath] {
return
}
log.Debug(" ->", filePath)
matchedDirs[filePath] = true
return
})
log.Debug("")
log.Debug("")
}
for dir := range matchedDirs {
dirs = append(dirs, dir)
}
return
}
func (w *Watcher) Reset() {
}
// checkTMPFile returns true if the event was for TMP files.
func checkTMPFile(name string) bool {
return strings.HasSuffix(strings.ToLower(name), ".tmp")
}
// getFileModTime retuens unix timestamp of `os.File.ModTime` by given path.
func getFileModTime(path string) (time.Time, bool) {
fi, err := os.Stat(path)
if err != nil {
log.Errorf("Fail to get file information[ %s ]", err)
return time.Now(), false
}
return fi.ModTime(), fi.IsDir()
}