diff options
Diffstat (limited to 'internal')
| -rw-r--r-- | internal/watcher/debounce.go | 62 | ||||
| -rw-r--r-- | internal/watcher/fsnotify.go | 4 | ||||
| -rw-r--r-- | internal/watcher/watcher.go | 11 |
3 files changed, 76 insertions, 1 deletions
diff --git a/internal/watcher/debounce.go b/internal/watcher/debounce.go new file mode 100644 index 0000000..b2961bd --- /dev/null +++ b/internal/watcher/debounce.go @@ -0,0 +1,62 @@ +package watcher + +import ( + "context" + "time" +) + +// notify schedules a debounced notification. +// +// Multiple filesystem events collapse into a single callback. +func (w *Watcher) notify() { + if w.config.OnChange == nil { + return + } + + select { + case w.debounce <- struct{}{}: + default: + } +} + +func (w *Watcher) debounceLoop(ctx context.Context) { + if w.config.OnChange == nil { + return + } + + timer := time.NewTimer(time.Hour) + + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } + + var pending bool + + for { + select { + case <-ctx.Done(): + return + + case <-w.debounce: + pending = true + + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } + + timer.Reset(w.config.Debounce) + + case <-timer.C: + if pending { + pending = false + w.config.OnChange() + } + } + } +} diff --git a/internal/watcher/fsnotify.go b/internal/watcher/fsnotify.go index 7251907..b759c50 100644 --- a/internal/watcher/fsnotify.go +++ b/internal/watcher/fsnotify.go @@ -22,6 +22,8 @@ func (w *Watcher) Run(ctx context.Context) error { _ = fswatcher.Close() }() + go w.debounceLoop(ctx) + for _, root := range w.config.Roots { if err := watchTree(fswatcher, root); err != nil { return err @@ -40,6 +42,8 @@ func (w *Watcher) Run(ctx context.Context) error { log.Printf("watcher: %v %s", event.Op, event.Name) + w.notify() + if !event.Has(fsnotify.Create) { continue } diff --git a/internal/watcher/watcher.go b/internal/watcher/watcher.go index 1ca8e37..ee16b7b 100644 --- a/internal/watcher/watcher.go +++ b/internal/watcher/watcher.go @@ -1,11 +1,20 @@ package watcher +import "time" + type Watcher struct { config Config + + debounce chan struct{} } func New(config Config) *Watcher { + if config.Debounce <= 0 { + config.Debounce = 500 * time.Millisecond + } + return &Watcher{ - config: config, + config: config, + debounce: make(chan struct{}), } } |