From a212099cbe6fbe8d07476bfda8d2d39b6ff8f325 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Mon, 11 Jan 2016 16:07:23 +0100 Subject: [PATCH] Watch the entire config dir for changes Then checking the file name in the event handler. This seems to be the only robust way of handling changes from a single file on multiple platforms and editors. See #142 --- viper.go | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/viper.go b/viper.go index 68ebf8c..00049ec 100644 --- a/viper.go +++ b/viper.go @@ -237,17 +237,24 @@ func (v *Viper) WatchConfig() { } defer watcher.Close() + // we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way + configFile := filepath.Clean(v.getConfigFile()) + configDir, _ := filepath.Split(configFile) + done := make(chan bool) go func() { for { select { case event := <-watcher.Events: - if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create { - err := v.ReadInConfig() - if err != nil { - log.Println("error:", err) + // we only care about the config file + if filepath.Clean(event.Name) == configFile { + if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create { + err := v.ReadInConfig() + if err != nil { + log.Println("error:", err) + } + v.onConfigChange(event) } - v.onConfigChange(event) } case err := <-watcher.Errors: log.Println("error:", err) @@ -255,7 +262,7 @@ func (v *Viper) WatchConfig() { } }() - watcher.Add(v.getConfigFile()) + watcher.Add(configDir) <-done }() }