-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatcher.go
More file actions
99 lines (83 loc) · 1.68 KB
/
watcher.go
File metadata and controls
99 lines (83 loc) · 1.68 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
package main
import (
"log"
"os"
"sync"
"time"
"github.com/fsnotify/fsnotify"
)
// Watcher watches a file for changes with debouncing
type Watcher struct {
watcher *fsnotify.Watcher
done chan struct{}
mu sync.Mutex
timer *time.Timer
}
func NewWatcher() *Watcher {
return &Watcher{
done: make(chan struct{}),
}
}
func (w *Watcher) Watch(filepath string, onChange func(), onDelete func()) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
w.watcher = watcher
if err := watcher.Add(filepath); err != nil {
watcher.Close()
return err
}
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
// Only react to write events
if event.Op&fsnotify.Write == fsnotify.Write {
w.debounce(onChange)
}
// Handle file removal
if event.Op&fsnotify.Remove == fsnotify.Remove {
// Wait briefly for editors that delete+recreate
time.Sleep(300 * time.Millisecond)
if _, err := os.Stat(filepath); os.IsNotExist(err) {
// File is truly gone
if onDelete != nil {
onDelete()
}
} else {
// File was recreated (editor behavior)
watcher.Add(filepath)
w.debounce(onChange)
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Printf("Watcher error: %v", err)
case <-w.done:
return
}
}
}()
return nil
}
func (w *Watcher) debounce(fn func()) {
w.mu.Lock()
defer w.mu.Unlock()
if w.timer != nil {
w.timer.Stop()
}
w.timer = time.AfterFunc(100*time.Millisecond, fn)
}
func (w *Watcher) Close() error {
close(w.done)
if w.watcher != nil {
return w.watcher.Close()
}
return nil
}