-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatcher.go
More file actions
94 lines (75 loc) · 1.63 KB
/
Copy pathwatcher.go
File metadata and controls
94 lines (75 loc) · 1.63 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
package main
import (
"io/fs"
"log"
"path/filepath"
"strings"
"time"
"github.com/fsnotify/fsnotify"
)
func watchFiles(root string, ps *pubsub) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
basepath, err := filepath.Abs(root)
if err != nil {
log.Fatal(err)
}
walkDirsRecursive(basepath, func(dir string) {
logger.Debug("Watching %s", dir)
watcher.Add(dir)
})
debounce := debouncer{
duration: 50 * time.Millisecond,
}
for {
select {
case event := <-watcher.Events:
if !event.Has(fsnotify.Write) {
continue
}
relpath, err := filepath.Rel(basepath, event.Name)
if err != nil {
log.Fatal(err)
}
debounce.then(func() {
logger.Debug("Change event: %s", relpath)
ps.publish(relpath)
})
case err := <-watcher.Errors:
logger.Error("Watcher error: %v", err)
}
}
}
func walkDirsRecursive(root string, dirfn func(string)) {
walk(root, root, dirfn)
}
func walk(root string, sym string, dirfn func(string)) error {
return filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
logger.Warn("Unable to enter %s: %v", path, err)
return filepath.SkipDir
}
rel, err := filepath.Rel(root, path)
if err != nil {
return err
}
path = filepath.Join(sym, rel)
if d.IsDir() {
if isHidden(path) {
return filepath.SkipDir
}
dirfn(path)
}
if d.Type()&fs.ModeSymlink == fs.ModeSymlink {
realpath, _ := filepath.EvalSymlinks(path)
return walk(realpath, path, dirfn)
}
return nil
})
}
func isHidden(path string) bool {
return strings.HasPrefix(filepath.Base(path), ".")
}