From 4d238ec5722d38485b58bc7cf0f29323b152613e Mon Sep 17 00:00:00 2001 From: akutz Date: Tue, 29 Sep 2015 00:05:36 -0500 Subject: [PATCH] Added method ReadConfigNoNil This patch adds a new method called ReadConfigNoNil that will read in a configuration file, but only set existing keys if they exist in the provided file. --- viper.go | 31 +++++++++++++++++++++++++++++++ viper_test.go | 20 ++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/viper.go b/viper.go index d9c5e67..97aea47 100644 --- a/viper.go +++ b/viper.go @@ -805,12 +805,43 @@ func (v *Viper) ReadInConfig() error { return v.unmarshalReader(bytes.NewReader(file), v.config) } +// Viper will discover and load the configuration file from disk +// and key/value stores, searching in one of the defined paths. +// This method will only set existing keys if they exist in the +// provided file. +func ReadInConfigNoNil() error { return v.ReadInConfigNoNil() } +func (v *Viper) ReadInConfigNoNil() error { + jww.INFO.Println("Attempting to read in config file") + if !stringInSlice(v.getConfigType(), SupportedExts) { + return UnsupportedConfigError(v.getConfigType()) + } + + file, err := ioutil.ReadFile(v.getConfigFile()) + if err != nil { + return err + } + + return v.ReadConfigNoNil(bytes.NewReader(file)) +} + +// Viper will read a configuration file, setting existing keys to nil if the +// key does not exist in the file. func ReadConfig(in io.Reader) error { return v.ReadConfig(in) } func (v *Viper) ReadConfig(in io.Reader) error { v.config = make(map[string]interface{}) return v.unmarshalReader(in, v.config) } +// Viper will read a configuration file, but only set existing keys if they +// exist in the provided file. +func ReadConfigNoNil(in io.Reader) error { return v.ReadConfigNoNil(in) } +func (v *Viper) ReadConfigNoNil(in io.Reader) error { + if v.config == nil { + v.config = make(map[string]interface{}) + } + return v.unmarshalReader(in, v.config) +} + // func ReadBufConfig(buf *bytes.Buffer) error { return v.ReadBufConfig(buf) } // func (v *Viper) ReadBufConfig(buf *bytes.Buffer) error { // v.config = make(map[string]interface{}) diff --git a/viper_test.go b/viper_test.go index d9aae00..52c1c24 100644 --- a/viper_test.go +++ b/viper_test.go @@ -37,6 +37,13 @@ eyes : brown beard: true `) +var yamlExample2 = []byte(`Hacker: false +name: robert +age: 40 +eyes : blue +height: 5' 8" +`) + var tomlExample = []byte(` title = "TOML Example" @@ -255,6 +262,19 @@ func TestYML(t *testing.T) { assert.Equal(t, "steve", Get("name")) } +func TestReadConfigNoNil(t *testing.T) { + initYAML() + assert.Equal(t, "steve", Get("name")) + + r := bytes.NewReader(yamlExample2) + + v.ReadConfigNoNil(r) + assert.Equal(t, "robert", Get("name")) + assert.Equal(t, 40, Get("age")) + assert.Equal(t, true, Get("beard")) + assert.Equal(t, "5' 8\"", Get("height")) +} + func TestJSON(t *testing.T) { initJSON() assert.Equal(t, "0001", Get("id"))