gitee.com/sasukebo/go-micro/v4@v4.7.1/config/source/file/watcher_linux.go (about)

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