-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileWatcherStart.go
More file actions
76 lines (65 loc) · 1.73 KB
/
FileWatcherStart.go
File metadata and controls
76 lines (65 loc) · 1.73 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
package devwatch
import (
"sync"
"github.com/fsnotify/fsnotify"
)
func (h *DevWatch) FileWatcherStart(wg *sync.WaitGroup) {
if h.shouldWatch != nil && !h.shouldWatch() {
//h.Logger("Skipping file watcher - not a valid Go project")
<-h.ExitChan
wg.Done()
return
}
w := h.Watcher()
if w == nil {
if watcher, err := fsnotify.NewWatcher(); err != nil {
h.Logger("Error New Watcher: ", err)
return
} else {
h.SetWatcher(watcher)
w = watcher
}
}
// Register existing directories BEFORE starting the event loop.
// Events queued by the OS during scanning are discarded below to prevent
// spurious recompile/reload cycles at startup.
h.watcherMu.RLock()
var dirs []string
if len(h.directories) > 0 {
dirs = make([]string, len(h.directories))
copy(dirs, h.directories)
}
h.watcherMu.RUnlock()
for _, dir := range dirs {
if err := h.scanAndRegisterDirectory(dir); err != nil {
h.Logger("Error scanning directory:", dir, err)
}
}
// Drain events buffered during the scan phase so startup artifacts
// (e.g. inotify CREATE events from a prior go build) never reach handlers.
h.drainStartupEvents()
h.Logger("Listening for File Changes ...")
// Start the event processing loop only AFTER the initial scan is complete.
go h.watchEvents()
// Wait for exit signal after watching is active
<-h.ExitChan
w.Close()
wg.Done()
}
// drainStartupEvents discards any OS events that accumulated in the watcher
// channel during the initial directory scan. This prevents those events from
// triggering spurious compilations or reloads on startup.
func (h *DevWatch) drainStartupEvents() {
w := h.Watcher()
if w == nil {
return
}
for {
select {
case <-w.Events:
case <-w.Errors:
default:
return
}
}
}