Add polling as a fallback to native filesystem events in server watch

Fixes #8720
Fixes #6849
Fixes #7930
This commit is contained in:
Bjørn Erik Pedersen
2021-07-02 09:54:03 +02:00
parent 0019d60f67
commit 24ce98b6d1
8 changed files with 731 additions and 13 deletions

View File

@@ -17,11 +17,12 @@ import (
"time"
"github.com/fsnotify/fsnotify"
"github.com/gohugoio/hugo/watcher/filenotify"
)
// Batcher batches file watch events in a given interval.
type Batcher struct {
*fsnotify.Watcher
filenotify.FileWatcher
interval time.Duration
done chan struct{}
@@ -29,12 +30,25 @@ type Batcher struct {
}
// New creates and starts a Batcher with the given time interval.
func New(interval time.Duration) (*Batcher, error) {
watcher, err := fsnotify.NewWatcher()
// It will fall back to a poll based watcher if native isn's supported.
// To always use polling, set poll to true.
func New(intervalBatcher, intervalPoll time.Duration, poll bool) (*Batcher, error) {
var err error
var watcher filenotify.FileWatcher
if poll {
watcher = filenotify.NewPollingWatcher(intervalPoll)
} else {
watcher, err = filenotify.New(intervalPoll)
}
if err != nil {
return nil, err
}
batcher := &Batcher{}
batcher.Watcher = watcher
batcher.interval = interval
batcher.FileWatcher = watcher
batcher.interval = intervalBatcher
batcher.done = make(chan struct{}, 1)
batcher.Events = make(chan []fsnotify.Event, 1)
@@ -42,7 +56,7 @@ func New(interval time.Duration) (*Batcher, error) {
go batcher.run()
}
return batcher, err
return batcher, nil
}
func (b *Batcher) run() {
@@ -51,7 +65,7 @@ func (b *Batcher) run() {
OuterLoop:
for {
select {
case ev := <-b.Watcher.Events:
case ev := <-b.FileWatcher.Events():
evs = append(evs, ev)
case <-tick:
if len(evs) == 0 {
@@ -69,5 +83,5 @@ OuterLoop:
// Close stops the watching of the files.
func (b *Batcher) Close() {
b.done <- struct{}{}
b.Watcher.Close()
b.FileWatcher.Close()
}