watcher_linux.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //go:build linux
  2. // +build linux
  3. package file
  4. import (
  5. "os"
  6. "github.com/fsnotify/fsnotify"
  7. "gogs.baozhida.cn/zoie/OAuth-core/config/source"
  8. )
  9. type watcher struct {
  10. f *file
  11. fw *fsnotify.Watcher
  12. exit chan bool
  13. }
  14. func newWatcher(f *file) (source.Watcher, error) {
  15. fw, err := fsnotify.NewWatcher()
  16. if err != nil {
  17. return nil, err
  18. }
  19. fw.Add(f.path)
  20. return &watcher{
  21. f: f,
  22. fw: fw,
  23. exit: make(chan bool),
  24. }, nil
  25. }
  26. func (w *watcher) Next() (*source.ChangeSet, error) {
  27. // is it closed?
  28. select {
  29. case <-w.exit:
  30. return nil, source.ErrWatcherStopped
  31. default:
  32. }
  33. // try get the event
  34. select {
  35. case event, _ := <-w.fw.Events:
  36. if event.Op == fsnotify.Rename {
  37. // check existence of file, and add watch again
  38. _, err := os.Stat(event.Name)
  39. if err == nil || os.IsExist(err) {
  40. w.fw.Add(event.Name)
  41. }
  42. }
  43. c, err := w.f.Read()
  44. if err != nil {
  45. return nil, err
  46. }
  47. // add path again for the event bug of fsnotify
  48. w.fw.Add(w.f.path)
  49. return c, nil
  50. case err := <-w.fw.Errors:
  51. return nil, err
  52. case <-w.exit:
  53. return nil, source.ErrWatcherStopped
  54. }
  55. }
  56. func (w *watcher) Stop() error {
  57. return w.fw.Close()
  58. }