goocsp/pkg/filewatcher/filewatcher.go

36 lines
825 B
Go
Raw Permalink Normal View History

package filewatcher
import (
"context"
"path"
"github.com/fsnotify/fsnotify"
"github.com/sirupsen/logrus"
)
// Watch creates file system monitoring for the given file and runs the callback on changes.
func Watch(ctx context.Context, filepath string, callback func(watcher *fsnotify.Watcher)) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
logrus.Fatalf("could not create file watcher: %v", err)
}
defer func(watcher *fsnotify.Watcher) {
_ = watcher.Close()
logrus.Infof("stopped watching for %s changes", filepath)
}(watcher)
go callback(watcher)
err = watcher.Add(path.Dir(filepath))
if err != nil {
logrus.Fatalf("could not watch %s: %v", filepath, err)
}
logrus.Infof("watching for changes on %s", filepath)
<-ctx.Done()
logrus.Infof("ending background tasks for %s", filepath)
}