github.com/annwntech/go-micro/v2@v2.9.5/config/source/file/watcher_linux.go (about)

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