// Package dirwatch watches a directory, and calls a function once the // directory has gone a short time without a change after one. The rule // files and the lookup database are read again this way. package dirwatch import ( "context" "time" "github.com/fsnotify/fsnotify" ) // quietTime is how long the directory must go without a change before the // function is called, so that a file still being written, such as one // saved in place, appended to or copied in with scp, is read only once // whole. const quietTime = 2 * time.Second // Watcher watches one directory. The directory is watched, rather than a // file in it, so that a file replaced by a rename is seen. type Watcher struct { watcher *fsnotify.Watcher } // New starts watching dir, or returns why it cannot. func New(dir string) (*Watcher, error) { watcher, err := fsnotify.NewWatcher() if err != nil { return nil, err } err = watcher.Add(dir) if err != nil { _ = watcher.Close() return nil, err } return &Watcher{watcher: watcher}, nil } // Close stops watching the directory. func (w *Watcher) Close() error { return w.watcher.Close() } // CallWhenQuiet calls changed each time the directory has gone quietTime // without a change, after a change to a path for which counts is true, until // ctx is done. It also calls failed with each error the watch reports. The // wait starts at once, as if for a change, so that a change made before the // watch began is taken in too. func (w *Watcher) CallWhenQuiet( ctx context.Context, counts func(path string) bool, changed func(), failed func(error), ) { callWhenQuiet( ctx, w.watcher.Events, w.watcher.Errors, counts, changed, failed, ) } // callWhenQuiet is CallWhenQuiet, for the changes from events and the // errors from errs. func callWhenQuiet( ctx context.Context, events <-chan fsnotify.Event, errs <-chan error, counts func(path string) bool, changed func(), failed func(error), ) { quiet := time.NewTimer(quietTime) defer quiet.Stop() for { select { case <-ctx.Done(): return case event := <-events: if counts(event.Name) { quiet.Reset(quietTime) } case <-quiet.C: changed() case err := <-errs: failed(err) } } }