-
Notifications
You must be signed in to change notification settings - Fork 0
/
dir-watcher.go
89 lines (78 loc) · 1.53 KB
/
dir-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
package main
import (
"io/fs"
"log"
"path"
"path/filepath"
"strings"
"sync"
"github.com/fsnotify/fsnotify"
)
type DirWatcher struct {
mu sync.Mutex
listeners map[*func()]struct{}
}
func NewDirwatcher() *DirWatcher {
return &DirWatcher{
listeners: map[*func()]struct{}{},
}
}
func (dw *DirWatcher) Start() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
// Start listening for events.
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if !event.Has(fsnotify.Write) {
continue
}
ext := path.Ext(event.Name)
if ext == ".lua" /*|| ext == ".go"*/ || strings.HasPrefix(event.Name, "pages/") {
log.Println("event:", event, path.Ext(event.Name))
dw.notify()
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
filepath.Walk(".", func(filename string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() && filename != ".git" && !strings.HasPrefix(filename, ".git/") {
println("watching", filename)
err = watcher.Add(filename)
if err != nil {
log.Fatal(err)
}
}
return err
})
}
func (dw *DirWatcher) notify() {
listeners := dw.listeners
for fn := range listeners {
(*fn)()
}
}
func (dw *DirWatcher) AddLuaListener(fn *func()) {
dw.mu.Lock()
dw.listeners[fn] = struct{}{}
dw.mu.Unlock()
}
func (dw *DirWatcher) RemoveListener(fn *func()) {
dw.mu.Lock()
delete(dw.listeners, fn)
dw.mu.Unlock()
}