-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.go
123 lines (101 loc) · 2.32 KB
/
watcher.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
package main
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"time"
"github.com/fsnotify/fsnotify"
"go.imnhan.com/s4g/writablefs"
)
const debounceInterval = 500 * time.Millisecond
// Watches for relevant changes in FS, debounces by debounceInterval,
// then executes callback.
// Returns cleanup function.
func WatchLocalFS(fsys writablefs.FS, callback func()) (Close func() error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
fsysPath := fsys.Path()
fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
if !d.IsDir() || (shouldIgnore(path) && path != ".") {
return nil
}
fullPath := filepath.Join(fsysPath, path)
err = watcher.Add(fullPath)
if err != nil {
panic(err)
}
return nil
})
//printWatchList(watcher)
// Start listening for events.
events := make(chan struct{})
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if shouldIgnore(event.Name) {
break
}
relPath, err := filepath.Rel(fsysPath, event.Name)
if err != nil {
panic(err)
}
// Avoid infinite loop
if filepath.Ext(relPath) == ".html" ||
relPath == FeedPath ||
relPath == ManifestPath {
break
}
//fmt.Println("EVENT:", event.Op, relPath)
// Dynamically watch new/renamed folders
if event.Has(fsnotify.Create) || event.Has(fsnotify.Rename) {
stat, err := os.Stat(event.Name)
if err == nil && stat.IsDir() {
watcher.Add(event.Name)
}
}
events <- struct{}{}
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Println("error:", err)
}
}
}()
// Debounce
go func() {
timer := time.NewTimer(debounceInterval)
<-timer.C // drain once so callback isn't executed on startup
for {
select {
case <-events:
timer.Reset(debounceInterval)
case <-timer.C:
callback()
}
}
}()
return watcher.Close
}
func printWatchList(w *fsnotify.Watcher) {
fmt.Println("WatchList:")
for _, path := range w.WatchList() {
fmt.Println(" " + path)
}
}
// Ignore swap and dot files/dirs, which are typically editor
// temp files or supporting data like .git.
func shouldIgnore(path string) bool {
fname := filepath.Base(path)
return fname[0] == '.' ||
fname == ManifestPath ||
strings.HasSuffix(fname, ".swp")
}