From c1250e5dd7e8b4e2911c6c6aa5b83be016bd2a3c Mon Sep 17 00:00:00 2001 From: Xavier Coulon Date: Fri, 13 Jul 2018 10:30:23 +0200 Subject: [PATCH] apply review comments use masks for checking the events. Signed-off-by: Xavier Coulon --- viper.go | 7 +++++-- viper_test.go | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/viper.go b/viper.go index 72230f5..8284149 100644 --- a/viper.go +++ b/viper.go @@ -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 } diff --git a/viper_test.go b/viper_test.go index 9961970..0985821 100644 --- a/viper_test.go +++ b/viper_test.go @@ -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()