watcher.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. err = fw.Add(f.path)
  20. if err != nil {
  21. return nil, err
  22. }
  23. return &watcher{
  24. f: f,
  25. fw: fw,
  26. exit: make(chan bool),
  27. }, nil
  28. }
  29. func (w *watcher) Next() (*source.ChangeSet, error) {
  30. // is it closed?
  31. select {
  32. case <-w.exit:
  33. return nil, source.ErrWatcherStopped
  34. default:
  35. }
  36. // try get the event
  37. select {
  38. case event, _ := <-w.fw.Events:
  39. if event.Op == fsnotify.Rename {
  40. // check existence of file, and add watch again
  41. _, err := os.Stat(event.Name)
  42. if err == nil || os.IsExist(err) {
  43. err := w.fw.Add(event.Name)
  44. if err != nil {
  45. return nil, err
  46. }
  47. }
  48. }
  49. c, err := w.f.Read()
  50. if err != nil {
  51. return nil, err
  52. }
  53. return c, nil
  54. case err := <-w.fw.Errors:
  55. return nil, err
  56. case <-w.exit:
  57. return nil, source.ErrWatcherStopped
  58. }
  59. }
  60. func (w *watcher) Stop() error {
  61. return w.fw.Close()
  62. }