apply review comments

use masks for checking the events.

Signed-off-by: Xavier Coulon <xcoulon@redhat.com>
This commit is contained in:
Xavier Coulon 2018-07-13 10:30:23 +02:00
parent 242f4890f5
commit c1250e5dd7
2 changed files with 6 additions and 3 deletions

View file

@ -260,6 +260,7 @@ func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) {
}
func WatchConfig() { v.WatchConfig() }
func (v *Viper) WatchConfig() {
initWG := sync.WaitGroup{}
initWG.Add(1)
@ -294,8 +295,9 @@ func (v *Viper) WatchConfig() {
// we only care about the config file with the following cases:
// 1 - if the config file was modified or created
// 2 - if the real path to the config file changed (eg: k8s ConfigMap replacement)
const writeOrCreateMask = fsnotify.Write | fsnotify.Create
if (filepath.Clean(event.Name) == configFile &&
(event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create)) ||
event.Op&writeOrCreateMask != 0) ||
(currentConfigFile != "" && currentConfigFile != realConfigFile) {
realConfigFile = currentConfigFile
err := v.ReadInConfig()
@ -306,7 +308,7 @@ func (v *Viper) WatchConfig() {
v.onConfigChange(event)
}
} else if filepath.Clean(event.Name) == configFile &&
event.Op&fsnotify.Remove == fsnotify.Remove {
event.Op&fsnotify.Remove&fsnotify.Remove != 0 {
eventsWG.Done()
return
}
@ -324,6 +326,7 @@ func (v *Viper) WatchConfig() {
initWG.Done() // done initalizing the watch in this go routine, so the parent routine can move on...
eventsWG.Wait() // now, wait for event loop to end in this go-routine...
}()
fmt.Println(" init WG done")
initWG.Wait() // make sure that the go routine above fully ended before returning
}

View file

@ -1426,12 +1426,12 @@ func TestWatchFile(t *testing.T) {
fmt.Printf("test config file: %s\n", configFile)
defer cleanup()
wg := sync.WaitGroup{}
wg.Add(1)
v.WatchConfig()
v.OnConfigChange(func(in fsnotify.Event) {
t.Logf("config file changed")
wg.Done()
})
wg.Add(1)
// when overwriting the file and waiting for the custom change notification handler to be triggered
err := ioutil.WriteFile(configFile, []byte("foo: baz\n"), 0640)
wg.Wait()