filenotify.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Package filenotify provides a mechanism for watching file(s) for changes.
  2. // Generally leans on fsnotify, but provides a poll-based notifier which fsnotify does not support.
  3. // These are wrapped up in a common interface so that either can be used interchangeably in your code.
  4. package filenotify
  5. import "github.com/fsnotify/fsnotify"
  6. // FileWatcher is an interface for implementing file notification watchers
  7. type FileWatcher interface {
  8. Events() <-chan fsnotify.Event
  9. Errors() <-chan error
  10. Add(name string) error
  11. Remove(name string) error
  12. Close() error
  13. }
  14. // New tries to use an fs-event watcher, and falls back to the poller if there is an error
  15. func New() (FileWatcher, error) {
  16. if watcher, err := NewEventWatcher(); err == nil {
  17. return watcher, nil
  18. }
  19. return NewPollingWatcher(), nil
  20. }
  21. // NewPollingWatcher returns a poll-based file watcher
  22. func NewPollingWatcher() FileWatcher {
  23. return &filePoller{
  24. events: make(chan fsnotify.Event),
  25. errors: make(chan error),
  26. }
  27. }
  28. // NewEventWatcher returns an fs-event based file watcher
  29. func NewEventWatcher() (FileWatcher, error) {
  30. watcher, err := fsnotify.NewWatcher()
  31. if err != nil {
  32. return nil, err
  33. }
  34. return &fsNotifyWatcher{watcher}, nil
  35. }