file.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package watcher
  2. import (
  3. "github.com/fsnotify/fsnotify"
  4. )
  5. // File is a file watcher that notifies when a file has been changed
  6. type File struct {
  7. watcher *fsnotify.Watcher
  8. shutdown chan struct{}
  9. }
  10. // NewFile is a standard constructor
  11. func NewFile() (*File, error) {
  12. watcher, err := fsnotify.NewWatcher()
  13. if err != nil {
  14. return nil, err
  15. }
  16. f := &File{
  17. watcher: watcher,
  18. shutdown: make(chan struct{}),
  19. }
  20. return f, nil
  21. }
  22. // Add adds a file to start watching
  23. func (f *File) Add(filepath string) error {
  24. return f.watcher.Add(filepath)
  25. }
  26. // Shutdown stop the file watching run loop
  27. func (f *File) Shutdown() {
  28. // don't block if Start quit early
  29. select {
  30. case f.shutdown <- struct{}{}:
  31. default:
  32. }
  33. }
  34. // Start is a runloop to watch for files changes from the file paths added from Add()
  35. func (f *File) Start(notifier Notification) {
  36. for {
  37. select {
  38. case event, ok := <-f.watcher.Events:
  39. if !ok {
  40. return
  41. }
  42. if event.Op&fsnotify.Write == fsnotify.Write {
  43. notifier.WatcherItemDidChange(event.Name)
  44. }
  45. case err, ok := <-f.watcher.Errors:
  46. if !ok {
  47. return
  48. }
  49. notifier.WatcherDidError(err)
  50. case <-f.shutdown:
  51. f.watcher.Close()
  52. return
  53. }
  54. }
  55. }