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
This commit is contained in:
Bjørn Erik Pedersen 2016-01-11 16:07:23 +01:00
parent cc70319ebc
commit a212099cbe
1 changed files with 13 additions and 6 deletions

View File

@ -237,11 +237,17 @@ func (v *Viper) WatchConfig() {
} }
defer watcher.Close() 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) done := make(chan bool)
go func() { go func() {
for { for {
select { select {
case event := <-watcher.Events: case event := <-watcher.Events:
// 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 { if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create {
err := v.ReadInConfig() err := v.ReadInConfig()
if err != nil { if err != nil {
@ -249,13 +255,14 @@ func (v *Viper) WatchConfig() {
} }
v.onConfigChange(event) v.onConfigChange(event)
} }
}
case err := <-watcher.Errors: case err := <-watcher.Errors:
log.Println("error:", err) log.Println("error:", err)
} }
} }
}() }()
watcher.Add(v.getConfigFile()) watcher.Add(configDir)
<-done <-done
}() }()
} }