volcano.sh/volcano@v1.9.0/pkg/filewatcher/filewatcher.go (about)

     1  /*
     2  Copyright 2020 The Volcano Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package filewatcher
    18  
    19  import "github.com/fsnotify/fsnotify"
    20  
    21  // FileWatcher is an interface watching the underlying OS file path.
    22  type FileWatcher interface {
    23  	Events() chan fsnotify.Event
    24  	Errors() chan error
    25  	Close()
    26  }
    27  
    28  type fileWatcher struct {
    29  	watcher *fsnotify.Watcher
    30  }
    31  
    32  // NewFileWatcher creates a FileWatcher.
    33  func NewFileWatcher(path string) (FileWatcher, error) {
    34  	watcher, err := fsnotify.NewWatcher()
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  
    39  	err = watcher.Add(path)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	return &fileWatcher{
    45  		watcher: watcher,
    46  	}, nil
    47  }
    48  
    49  // Events returns the event channel.
    50  func (w *fileWatcher) Events() chan fsnotify.Event {
    51  	if w == nil || w.watcher == nil {
    52  		return nil
    53  	}
    54  	return w.watcher.Events
    55  }
    56  
    57  // Errors returns the error channel.
    58  func (w *fileWatcher) Errors() chan error {
    59  	if w == nil || w.watcher == nil {
    60  		return nil
    61  	}
    62  	return w.watcher.Errors
    63  }
    64  
    65  // Close closed the file watcher.
    66  func (w *fileWatcher) Close() {
    67  	if w == nil || w.watcher == nil {
    68  		return
    69  	}
    70  	w.watcher.Close()
    71  }