github.com/nycdavid/zeus@v0.0.0-20201208104106-9ba439429e03/go/filemonitor/filemonitor_fsnotify.go (about)

     1  // +build !darwin
     2  
     3  package filemonitor
     4  
     5  import (
     6  	"time"
     7  
     8  	"github.com/fsnotify/fsnotify"
     9  )
    10  
    11  type fsnotifyMonitor struct {
    12  	gatheringMonitor
    13  	watcher *fsnotify.Watcher
    14  }
    15  
    16  const flagsWorthReloadingFor = fsnotify.Write | fsnotify.Remove | fsnotify.Rename
    17  
    18  func NewFileMonitor(fileChangeDelay time.Duration) (FileMonitor, error) {
    19  	watcher, err := fsnotify.NewWatcher()
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  
    24  	f := fsnotifyMonitor{
    25  		watcher: watcher,
    26  	}
    27  	f.fileChangeDelay = fileChangeDelay
    28  	f.changes = make(chan string)
    29  
    30  	go f.serveListeners()
    31  	go f.watch()
    32  
    33  	return &f, nil
    34  }
    35  
    36  func (f *fsnotifyMonitor) Add(file string) error {
    37  	if err := f.watcher.Add(file); err != nil {
    38  		return err
    39  	}
    40  
    41  	return nil
    42  }
    43  
    44  func (f *fsnotifyMonitor) Close() error {
    45  	return f.watcher.Close()
    46  }
    47  
    48  func (f *fsnotifyMonitor) watch() {
    49  	// Detect zero value and return
    50  	// otherwise debounce
    51  
    52  	for event := range f.watcher.Events {
    53  		if (event.Op & flagsWorthReloadingFor) == 0 {
    54  			continue
    55  		}
    56  
    57  		f.changes <- event.Name
    58  	}
    59  
    60  	close(f.changes)
    61  }