Fix: file-watcher bugs (#1897)

* Fix: file-watcher bugs

* Update watcher_linux.go

Co-authored-by: 杨铭哲 <yangmz@weipaitang.com>
Co-authored-by: Asim Aslam <asim@aslam.me>
This commit is contained in:
Z 2020-08-07 01:21:09 +08:00 committed by GitHub
parent 991cdba91d
commit dcf785677f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 56 additions and 36 deletions

View File

@ -10,6 +10,7 @@ import (
type file struct { type file struct {
path string path string
data []byte
opts source.Options opts source.Options
} }

View File

@ -39,6 +39,7 @@ func (w *watcher) Next() (*source.ChangeSet, error) {
default: default:
} }
for {
// try get the event // try get the event
select { select {
case event, _ := <-w.fw.Events: case event, _ := <-w.fw.Events:
@ -50,6 +51,14 @@ func (w *watcher) Next() (*source.ChangeSet, error) {
} }
} }
// ARCH: Darwin Kernel Version 18.7.0
// ioutil.WriteFile truncates it before writing, but the problem is that
// you will receive two events(fsnotify.Chmod and fsnotify.Write).
// We can solve this problem by ignoring fsnotify.Chmod event.
if event.Op&fsnotify.Write != fsnotify.Write {
continue
}
c, err := w.f.Read() c, err := w.f.Read()
if err != nil { if err != nil {
return nil, err return nil, err
@ -61,6 +70,7 @@ func (w *watcher) Next() (*source.ChangeSet, error) {
return nil, source.ErrWatcherStopped return nil, source.ErrWatcherStopped
} }
} }
}
func (w *watcher) Stop() error { func (w *watcher) Stop() error {
return w.fw.Close() return w.fw.Close()

View File

@ -4,6 +4,7 @@ package file
import ( import (
"os" "os"
"reflect"
"github.com/fsnotify/fsnotify" "github.com/fsnotify/fsnotify"
"github.com/micro/go-micro/v3/config/source" "github.com/micro/go-micro/v3/config/source"
@ -39,6 +40,7 @@ func (w *watcher) Next() (*source.ChangeSet, error) {
default: default:
} }
for {
// try get the event // try get the event
select { select {
case event, _ := <-w.fw.Events: case event, _ := <-w.fw.Events:
@ -55,8 +57,14 @@ func (w *watcher) Next() (*source.ChangeSet, error) {
return nil, err return nil, err
} }
// add path again for the event bug of fsnotify // ARCH: Linux centos-7.shared 3.10.0-693.5.2.el7.x86_64
w.fw.Add(w.f.path) // Sometimes, ioutil.WriteFile triggers multiple fsnotify.Write events, which may be a bug.
// Detect if the file has changed
if reflect.DeepEqual(c.Data, w.f.data) {
continue
}
w.f.data = c.Data
return c, nil return c, nil
case err := <-w.fw.Errors: case err := <-w.fw.Errors:
@ -65,6 +73,7 @@ func (w *watcher) Next() (*source.ChangeSet, error) {
return nil, source.ErrWatcherStopped return nil, source.ErrWatcherStopped
} }
} }
}
func (w *watcher) Stop() error { func (w *watcher) Stop() error {
return w.fw.Close() return w.fw.Close()