Skip to content

Commit

Permalink
Remove Load* function (#47)
Browse files Browse the repository at this point in the history
We don't really need Load* functions, because users can use constructors directly to load files.
File name to load config, that is based on the environment variable is also too company specific.
  • Loading branch information
Alex authored Jul 31, 2017
1 parent 351a34e commit 7d6a5c6
Show file tree
Hide file tree
Showing 7 changed files with 31 additions and 162 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
- **[Breaking]** Try and As conversion helpers are removed in favor of using
other cast libraries.
- **[Breaking]** Removed `Value.IsDefault` method.
- **[Breaking]** Removed Load* functions.
- **[Breaking]** Removed NewYAMLProviderFromReader* functions.

## v1.0.0-rc1 (26 Jun 2017)

Expand Down
4 changes: 2 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,14 @@ func LoadFromFiles(dirs []string, files []FileInfo, lookUp LookUpFunc) (Provider
}

if info.Interpolate {
p, err := NewYAMLProviderFromReaderWithExpand(lookUp, f)
p, err := newYAMLProviderFromReaderWithExpand(lookUp, f)
if err != nil {
return nil, err
}

providers = append(providers, p)
} else {
p, err := NewYAMLProviderFromReader(f)
p, err := newYAMLProviderFromReader(f)
if err != nil {
return nil, err
}
Expand Down
149 changes: 8 additions & 141 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,7 @@ package config

import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"

"strconv"
Expand Down Expand Up @@ -88,112 +85,6 @@ type arrayOfStructs struct {
Things []nested `yaml:"things"`
}

func setEnv(key, value string) func() {
res := func() { os.Unsetenv(key) }
if oldVal, ok := os.LookupEnv(key); ok {
res = func() { os.Setenv(key, oldVal) }
}

os.Setenv(key, value)
return res
}

func TestDefaultLoad(t *testing.T) {
assert := assert.New(t)
require.NoError(t, os.Mkdir("config", os.ModePerm))
defer func() { assert.NoError(os.Remove("config")) }()

base, err := os.Create(filepath.Join("config", "base.yaml"))
require.NoError(t, err)
defer func() { assert.NoError(os.Remove(base.Name())) }()

defer setEnv("PORT", "80")()
base.WriteString("source: base\ninterpolated: ${PORT:17}\n")
base.Close()

// Setup development.yaml
dev, err := os.Create(filepath.Join("config", "development.yaml"))
require.NoError(t, err)
defer func() { assert.NoError(os.Remove(dev.Name())) }()
fmt.Fprint(dev, "development: loaded")

// Setup secrets.yaml
sec, err := os.Create(filepath.Join("config", "secrets.yaml"))
require.NoError(t, err)
defer func() { assert.NoError(os.Remove(sec.Name())) }()
fmt.Fprint(sec, "secret: ${password:1111}")

p, err := LoadDefaults()
require.NoError(t, err)

var val map[string]interface{}
require.NoError(t, p.Get(Root).Populate(&val))
assert.Equal(4, len(val))
assert.Equal("base", p.Get("source").String())
assert.Equal("80", p.Get("interpolated").String())
assert.Equal("loaded", p.Get("development").String())
assert.Equal("${password:1111}", p.Get("secret").String())
}

func TestDefaultLoadMultipleTimes(t *testing.T) {
assert := assert.New(t)
require.NoError(t, os.Mkdir("config", os.ModePerm))
defer func() { assert.NoError(os.Remove("config")) }()

base, err := os.Create(filepath.Join("config", "base.yaml"))
require.NoError(t, err)
defer func() { assert.NoError(os.Remove(base.Name())) }()

defer setEnv("PORT", "80")()
base.WriteString("source: base\ninterpolated: ${PORT:17}\n")
base.Close()

p, err := LoadDefaults()
require.NoError(t, err)
p, err = LoadDefaults()
require.NoError(t, err)

var val map[string]interface{}
require.NoError(t, p.Get(Root).Populate(&val))
assert.Equal(2, len(val))
assert.Equal("base", p.Get("source").String())
assert.Equal("80", p.Get("interpolated").String())
}

func TestLoadTestProvider(t *testing.T) {
assert := assert.New(t)
require.NoError(t, os.Mkdir("config", os.ModePerm))
defer func() { assert.NoError(os.Remove("config")) }()

base, err := os.Create(filepath.Join("config", "base.yaml"))
require.NoError(t, err)
defer func() { assert.NoError(os.Remove(base.Name())) }()

base.WriteString("source: base")
base.Close()

// Setup test.yaml
tst, err := os.Create(filepath.Join("config", "test.yaml"))
require.NoError(t, err)
defer func() { assert.NoError(os.Remove(tst.Name())) }()
fmt.Fprint(tst, "dir: ${CONFIG_DIR:test}")

p, err := LoadTestProvider()
require.NoError(t, err)
assert.Equal("base", p.Get("source").String())
assert.Equal("test", p.Get("dir").String())
}

func TestErrorWhenNoFilesLoaded(t *testing.T) {
dir, err := ioutil.TempDir("", "TestConfig")
require.NoError(t, err)
defer func() { assert.NoError(t, os.Remove(dir)) }()

_, err = LoadFromFiles(nil, nil, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "no providers were loaded")
}

func TestRootNodeConfig(t *testing.T) {
t.Parallel()
txt := []byte(`
Expand All @@ -214,6 +105,7 @@ func TestDirectAccess(t *testing.T) {
require.NoError(t, err, "Can't create a YAML provider")

provider := NewProviderGroup("test", p)
require.NoError(t, err)

v, err := provider.Get("n1.id1").WithDefault("xxx")
require.NoError(t, err, "Can't create a default value")
Expand All @@ -229,6 +121,7 @@ func TestScopedAccess(t *testing.T) {
require.NoError(t, err, "Can't create a YAML provider")

provider := NewProviderGroup("test", p)
require.NoError(t, err)

p1 := provider.Get("n1")

Expand All @@ -249,6 +142,7 @@ func TestSimpleConfigValues(t *testing.T) {
require.NoError(t, err, "Can't create a YAML provider")

provider := NewProviderGroup("test", p)
require.NoError(t, err)

assert.Equal(t, 123, provider.Get("int").Value())
assert.Equal(t, "test string", provider.Get("string").String())
Expand All @@ -272,6 +166,7 @@ func TestNestedStructs(t *testing.T) {
require.NoError(t, err, "Can't create a YAML provider")

provider := NewProviderGroup("test", p)
require.NoError(t, err)

str := &root{}

Expand All @@ -295,6 +190,7 @@ func TestArrayOfStructs(t *testing.T) {
require.NoError(t, err, "Can't create a YAML provider")

provider := NewProviderGroup("test", p)
require.NoError(t, err)

target := &arrayOfStructs{}

Expand All @@ -313,6 +209,8 @@ func TestDefault(t *testing.T) {
require.NoError(t, err, "Can't create a YAML provider")

provider := NewProviderGroup("test", p)
require.NoError(t, err)

target := &nested{}
v := provider.Get(Root)
assert.True(t, v.HasValue())
Expand Down Expand Up @@ -465,7 +363,7 @@ rpc:
return "4324", true
}

p, err := NewYAMLProviderFromReaderWithExpand(
p, err := newYAMLProviderFromReaderWithExpand(
lookup,
ioutil.NopCloser(bytes.NewBufferString(rpc)))

Expand All @@ -477,34 +375,3 @@ rpc:
require.NoError(t, v.Populate(cfg))
require.Equal(t, 4324, int(*cfg.Outbounds[0].TChannel.Port))
}

func TestLoadFromFiles(t *testing.T) {
t.Parallel()

withBase(t, func(dir string) {
_, err := LoadFromFiles(
[]string{dir},
[]FileInfo{{Name: "base.yaml", Interpolate: true}},
func(string) (string, bool) { return "", false },
)

require.Error(t, err)
assert.Contains(t, err.Error(), `default is empty for "Email"`)
}, "${Email}")
}

func withBase(t *testing.T, f func(dir string), contents string) {
dir, err := ioutil.TempDir("", "TestConfig")
require.NoError(t, err)

defer func() { require.NoError(t, os.Remove(dir)) }()

base, err := os.Create(fmt.Sprintf("%s/base.yaml", dir))
require.NoError(t, err)
defer os.Remove(base.Name())

base.WriteString(contents)
base.Close()

f(dir)
}
4 changes: 2 additions & 2 deletions static_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func NewStaticProvider(data interface{}) (Provider, error) {
return nil, err
}

p, err := NewYAMLProviderFromReader(c)
p, err := newYAMLProviderFromReader(c)
if err != nil {
return nil, err
}
Expand All @@ -59,7 +59,7 @@ func NewStaticProviderWithExpand(
return nil, err
}

p, err := NewYAMLProviderFromReaderWithExpand(mapping, reader)
p, err := newYAMLProviderFromReaderWithExpand(mapping, reader)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion static_provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ func TestInterpolatedBool(t *testing.T) {
return "", false
}

p, err := NewYAMLProviderFromReaderWithExpand(
p, err := newYAMLProviderFromReaderWithExpand(
f,
ioutil.NopCloser(strings.NewReader("val: ${interpolate:false}")))

Expand Down
8 changes: 4 additions & 4 deletions yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,12 @@ func NewYAMLProviderWithExpand(mapping func(string) (string, bool), files ...str
return nil, err
}

return NewYAMLProviderFromReaderWithExpand(mapping, readers...)
return newYAMLProviderFromReaderWithExpand(mapping, readers...)
}

// NewYAMLProviderFromReader creates a configuration provider from a list of io.ReadClosers.
// As above, all the objects are going to be merged and arrays/values overridden in the order of the files.
func NewYAMLProviderFromReader(readers ...io.ReadCloser) (Provider, error) {
func newYAMLProviderFromReader(readers ...io.ReadCloser) (Provider, error) {
p, err := newYAMLProviderCore(readers...)
if err != nil {
return nil, err
Expand All @@ -167,7 +167,7 @@ func NewYAMLProviderFromReader(readers ...io.ReadCloser) (Provider, error) {
// NewYAMLProviderFromReaderWithExpand creates a configuration provider from
// a list of `io.ReadClosers and uses the mapping function to expand values
// in the underlying provider.
func NewYAMLProviderFromReaderWithExpand(
func newYAMLProviderFromReaderWithExpand(
mapping func(string) (string, bool),
readers ...io.ReadCloser) (Provider, error) {
p, err := newYAMLProviderCore(readers...)
Expand Down Expand Up @@ -371,7 +371,7 @@ func unmarshalYAMLValue(reader io.ReadCloser, value interface{}) error {
// will be used.
//
// TODO: what if someone wanted a literal ${FOO} in config? need a small escape hatch
func replace(lookUp LookUpFunc) func(in string) string {
func replace(lookUp func(string) (string, bool)) func(in string) string {
return func(in string) string {
sep := strings.Index(in, _envSeparator)
var key string
Expand Down
Loading

0 comments on commit 7d6a5c6

Please sign in to comment.