This repository has been archived by the owner on Oct 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 243
/
watcher.go
79 lines (72 loc) · 1.5 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
package watcher
import (
"context"
"log/slog"
"os"
"path/filepath"
"strings"
"time"
"github.com/fsnotify/fsnotify"
"github.com/sst/ion/internal/util"
"github.com/sst/ion/pkg/server/bus"
)
type FileChangedEvent struct {
Path string
}
func Start(ctx context.Context, root string) (util.CleanupFunc, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
err = watcher.AddWith(root)
if err != nil {
return nil, err
}
ignoreSubstrings := []string{"node_modules"}
err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
if strings.HasPrefix(info.Name(), ".") {
return filepath.SkipDir
}
for _, substring := range ignoreSubstrings {
if strings.Contains(path, substring) {
return filepath.SkipDir
}
}
slog.Info("watching", "path", path)
err = watcher.Add(path)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, err
}
go func() {
limiter := map[string]time.Time{}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
slog.Info("file event", "path", event.Name, "op", event.Op)
if time.Since(limiter[event.Name]) > 500*time.Millisecond {
limiter[event.Name] = time.Now()
bus.Publish(&FileChangedEvent{Path: event.Name})
}
case <-ctx.Done():
return
}
}
}()
return func() error {
slog.Info("cleaning up file watcher")
return watcher.Close()
}, nil
}