mirror of
https://github.com/spf13/viper
synced 2025-05-15 00:27:18 +00:00
Merge ab4327a019
into a785a79f22
This commit is contained in:
commit
d95395a29d
1 changed files with 49 additions and 61 deletions
28
viper.go
28
viper.go
|
@ -31,7 +31,6 @@ import (
|
|||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
|
@ -386,19 +385,10 @@ func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) {
|
|||
func WatchConfig() { v.WatchConfig() }
|
||||
|
||||
func (v *Viper) WatchConfig() {
|
||||
initWG := sync.WaitGroup{}
|
||||
initWG.Add(1)
|
||||
go func() {
|
||||
watcher, err := newWatcher()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer watcher.Close()
|
||||
// we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
|
||||
filename, err := v.getConfigFile()
|
||||
if err != nil {
|
||||
log.Printf("error: %v\n", err)
|
||||
initWG.Done()
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -406,14 +396,18 @@ func (v *Viper) WatchConfig() {
|
|||
configDir, _ := filepath.Split(configFile)
|
||||
realConfigFile, _ := filepath.EvalSymlinks(filename)
|
||||
|
||||
eventsWG := sync.WaitGroup{}
|
||||
eventsWG.Add(1)
|
||||
watcher, err := newWatcher()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer watcher.Close()
|
||||
for {
|
||||
select {
|
||||
case event, ok := <-watcher.Events:
|
||||
if !ok { // 'Events' channel is closed
|
||||
eventsWG.Done()
|
||||
return
|
||||
}
|
||||
currentConfigFile, _ := filepath.EvalSymlinks(filename)
|
||||
|
@ -433,8 +427,7 @@ func (v *Viper) WatchConfig() {
|
|||
v.onConfigChange(event)
|
||||
}
|
||||
} else if filepath.Clean(event.Name) == configFile &&
|
||||
event.Op&fsnotify.Remove&fsnotify.Remove != 0 {
|
||||
eventsWG.Done()
|
||||
event.Op&fsnotify.Remove != 0 {
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -442,16 +435,11 @@ func (v *Viper) WatchConfig() {
|
|||
if ok { // 'Errors' channel is not closed
|
||||
log.Printf("watcher error: %v\n", err)
|
||||
}
|
||||
eventsWG.Done()
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
watcher.Add(configDir)
|
||||
initWG.Done() // done initializing 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...
|
||||
}()
|
||||
initWG.Wait() // make sure that the go routine above fully ended before returning
|
||||
}
|
||||
|
||||
// SetConfigFile explicitly defines the path, name and extension of the config file.
|
||||
|
|
Loading…
Add table
Reference in a new issue