diff --git a/go.mod b/go.mod index f6e4fe6..77d890e 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.26 require ( github.com/BurntSushi/toml v1.6.0 + github.com/fsnotify/fsnotify v1.10.1 github.com/jotfs/fastcdc-go v0.2.0 github.com/spf13/cobra v1.10.2 github.com/zeebo/blake3 v0.2.4 @@ -13,4 +14,5 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/klauspost/cpuid/v2 v2.0.12 // indirect github.com/spf13/pflag v1.0.9 // indirect + golang.org/x/sys v0.13.0 // indirect ) diff --git a/go.sum b/go.sum index 875407e..bbb77a9 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,8 @@ github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= +github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jotfs/fastcdc-go v0.2.0 h1:WHYIGk3k9NumGWfp4YMsemEcx/s4JKpGAa6tpCpHJOo= @@ -19,4 +21,6 @@ github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCR github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/watch/watch.go b/internal/watch/watch.go new file mode 100644 index 0000000..7fddc4e --- /dev/null +++ b/internal/watch/watch.go @@ -0,0 +1,100 @@ +// Package watch reports debounced "something changed" signals for a directory +// tree, using fsnotify with recursive (re-)subscription as subdirectories appear. +package watch + +import ( + "io/fs" + "os" + "path/filepath" + "time" + + "github.com/fsnotify/fsnotify" +) + +// Watcher emits a coalesced signal on Events() after the tree has been quiet for +// the debounce interval following one or more filesystem changes. +type Watcher struct { + fsw *fsnotify.Watcher + events chan struct{} + done chan struct{} + debounce time.Duration +} + +// New starts watching root (recursively) with the given debounce interval. +func New(root string, debounce time.Duration) (*Watcher, error) { + fsw, err := fsnotify.NewWatcher() + if err != nil { + return nil, err + } + w := &Watcher{ + fsw: fsw, + events: make(chan struct{}, 1), + done: make(chan struct{}), + debounce: debounce, + } + if err := w.addTree(root); err != nil { + fsw.Close() + return nil, err + } + go w.loop() + return w, nil +} + +// Events delivers a signal each time a debounced batch of changes settles. +func (w *Watcher) Events() <-chan struct{} { return w.events } + +// Close stops the watcher. +func (w *Watcher) Close() error { + close(w.done) + return w.fsw.Close() +} + +// addTree adds a watch on root and every directory beneath it. fsnotify watches +// a single directory level, so we subscribe each dir (and re-add new ones live). +func (w *Watcher) addTree(root string) error { + return filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return nil // ponytail: skip unreadable dirs rather than abort the whole add + } + if d.IsDir() { + _ = w.fsw.Add(p) + } + return nil + }) +} + +func (w *Watcher) loop() { + var timer *time.Timer + var timerC <-chan time.Time + for { + select { + case <-w.done: + return + case ev, ok := <-w.fsw.Events: + if !ok { + return + } + if ev.Op&fsnotify.Create != 0 { + if info, err := os.Stat(ev.Name); err == nil && info.IsDir() { + _ = w.addTree(ev.Name) // watch newly-created subdirs + } + } + if timer == nil { + timer = time.NewTimer(w.debounce) + } else { + timer.Reset(w.debounce) + } + timerC = timer.C + case <-timerC: + timerC = nil + select { + case w.events <- struct{}{}: + default: // a pending signal is already queued; coalesce + } + case _, ok := <-w.fsw.Errors: + if !ok { + return + } + } + } +} diff --git a/internal/watch/watch_test.go b/internal/watch/watch_test.go new file mode 100644 index 0000000..34f9b8d --- /dev/null +++ b/internal/watch/watch_test.go @@ -0,0 +1,86 @@ +package watch + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +func waitSignal(t *testing.T, w *Watcher, within time.Duration) bool { + t.Helper() + select { + case <-w.Events(): + return true + case <-time.After(within): + return false + } +} + +func TestWatchDetectsChange(t *testing.T) { + root := t.TempDir() + w, err := New(root, 50*time.Millisecond) + if err != nil { + t.Fatal(err) + } + defer w.Close() + + if err := os.WriteFile(filepath.Join(root, "a.txt"), []byte("hi"), 0o644); err != nil { + t.Fatal(err) + } + if !waitSignal(t, w, 2*time.Second) { + t.Fatal("no signal after file create") + } +} + +func TestWatchPicksUpNewSubdir(t *testing.T) { + root := t.TempDir() + w, err := New(root, 50*time.Millisecond) + if err != nil { + t.Fatal(err) + } + defer w.Close() + + sub := filepath.Join(root, "sub") + if err := os.Mkdir(sub, 0o755); err != nil { + t.Fatal(err) + } + waitSignal(t, w, 2*time.Second) // drain the mkdir signal + + if err := os.WriteFile(filepath.Join(sub, "b.txt"), []byte("yo"), 0o644); err != nil { + t.Fatal(err) + } + if !waitSignal(t, w, 2*time.Second) { + t.Fatal("no signal after writing into newly-created subdir") + } +} + +func TestWatchCoalesces(t *testing.T) { + root := t.TempDir() + w, err := New(root, 80*time.Millisecond) + if err != nil { + t.Fatal(err) + } + defer w.Close() + + for i := 0; i < 10; i++ { + _ = os.WriteFile(filepath.Join(root, "f.txt"), []byte{byte(i)}, 0o644) + time.Sleep(5 * time.Millisecond) + } + if !waitSignal(t, w, 2*time.Second) { + t.Fatal("expected at least one coalesced signal") + } + // After settling, the burst should not have produced a flood of signals. + extra := 0 + for { + select { + case <-w.Events(): + extra++ + if extra > 3 { + t.Fatal("too many signals; debounce not coalescing") + } + case <-time.After(300 * time.Millisecond): + return + } + } +}