2019-08-19 10:28:24 +03:00
|
|
|
//+build linux
|
|
|
|
|
|
|
|
package file
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
2020-08-06 20:21:09 +03:00
|
|
|
"reflect"
|
2019-08-19 10:28:24 +03:00
|
|
|
|
|
|
|
"github.com/fsnotify/fsnotify"
|
2020-08-19 17:47:17 +03:00
|
|
|
"github.com/unistack-org/micro/v3/config/source"
|
2019-08-19 10:28:24 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type watcher struct {
|
|
|
|
f *file
|
|
|
|
|
|
|
|
fw *fsnotify.Watcher
|
|
|
|
exit chan bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func newWatcher(f *file) (source.Watcher, error) {
|
|
|
|
fw, err := fsnotify.NewWatcher()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
fw.Add(f.path)
|
|
|
|
|
|
|
|
return &watcher{
|
|
|
|
f: f,
|
|
|
|
fw: fw,
|
|
|
|
exit: make(chan bool),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *watcher) Next() (*source.ChangeSet, error) {
|
|
|
|
// is it closed?
|
|
|
|
select {
|
|
|
|
case <-w.exit:
|
2019-08-21 00:32:47 +03:00
|
|
|
return nil, source.ErrWatcherStopped
|
2019-08-19 10:28:24 +03:00
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:21:09 +03:00
|
|
|
for {
|
|
|
|
// try get the event
|
|
|
|
select {
|
|
|
|
case event, _ := <-w.fw.Events:
|
|
|
|
if event.Op == fsnotify.Rename {
|
|
|
|
// check existence of file, and add watch again
|
|
|
|
_, err := os.Stat(event.Name)
|
|
|
|
if err == nil || os.IsExist(err) {
|
|
|
|
w.fw.Add(event.Name)
|
|
|
|
}
|
2019-08-19 10:28:24 +03:00
|
|
|
}
|
|
|
|
|
2020-08-06 20:21:09 +03:00
|
|
|
c, err := w.f.Read()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-08-19 10:28:24 +03:00
|
|
|
|
2020-08-06 20:21:09 +03:00
|
|
|
// ARCH: Linux centos-7.shared 3.10.0-693.5.2.el7.x86_64
|
|
|
|
// Sometimes, ioutil.WriteFile triggers multiple fsnotify.Write events, which may be a bug.
|
2019-08-19 10:28:24 +03:00
|
|
|
|
2020-08-06 20:21:09 +03:00
|
|
|
// Detect if the file has changed
|
|
|
|
if reflect.DeepEqual(c.Data, w.f.data) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
w.f.data = c.Data
|
|
|
|
|
|
|
|
return c, nil
|
|
|
|
case err := <-w.fw.Errors:
|
|
|
|
return nil, err
|
|
|
|
case <-w.exit:
|
|
|
|
return nil, source.ErrWatcherStopped
|
|
|
|
}
|
2019-08-19 10:28:24 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *watcher) Stop() error {
|
|
|
|
return w.fw.Close()
|
|
|
|
}
|