2025-03-22 20:06:16 -03:00
|
|
|
package fsnotifyext
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/fsnotify/fsnotify"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Deduper struct {
|
|
|
|
w *fsnotify.Watcher
|
|
|
|
waitTime time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewDeduper(w *fsnotify.Watcher, waitTime time.Duration) *Deduper {
|
|
|
|
return &Deduper{
|
|
|
|
w: w,
|
|
|
|
waitTime: waitTime,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-04-22 11:39:02 +02:00
|
|
|
// GetChan returns a chan of deduplicated [fsnotify.Event].
|
|
|
|
//
|
|
|
|
// [fsnotify.Chmod] operations will be skipped.
|
2025-04-22 11:29:58 +02:00
|
|
|
func (d *Deduper) GetChan() <-chan fsnotify.Event {
|
2025-03-22 20:06:16 -03:00
|
|
|
channel := make(chan fsnotify.Event)
|
|
|
|
|
|
|
|
go func() {
|
2025-04-22 11:29:31 +02:00
|
|
|
timers := make(map[string]*time.Timer)
|
2025-03-22 20:06:16 -03:00
|
|
|
for {
|
|
|
|
event, ok := <-d.w.Events
|
|
|
|
switch {
|
|
|
|
case !ok:
|
|
|
|
return
|
2025-04-22 11:40:56 +02:00
|
|
|
case event.Has(fsnotify.Chmod):
|
2025-03-22 20:06:16 -03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
timer, ok := timers[event.String()]
|
|
|
|
if !ok {
|
|
|
|
timer = time.AfterFunc(math.MaxInt64, func() { channel <- event })
|
|
|
|
timer.Stop()
|
|
|
|
timers[event.String()] = timer
|
|
|
|
}
|
|
|
|
|
|
|
|
timer.Reset(d.waitTime)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return channel
|
|
|
|
}
|