Skip to content

Commit

Permalink
read on nil config works (nil-go#189)
Browse files Browse the repository at this point in the history
  • Loading branch information
ktong authored Mar 1, 2024
1 parent ad7aa10 commit 08b2240
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ func (c *Config) Load(loader Loader) error {
// and decodes it into the given object pointed to by target.
// The path is case-insensitive.
func (c *Config) Unmarshal(path string, target any) error {
if c == nil {
return nil
}

c.nocopy.Check()

decodeHook := c.decodeHook
Expand Down Expand Up @@ -129,6 +133,10 @@ func (c *Config) split(key string) []string {
// from loaders for the given path. It blur sensitive information.
// The path is case-insensitive.
func (c *Config) Explain(path string) string {
if c == nil {
return path + " has no configuration.\n\n"
}

c.nocopy.Check()

explanation := &strings.Builder{}
Expand Down
10 changes: 10 additions & 0 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ import (
"github.com/nil-go/konf/provider/env"
)

func TestConfig_nil(t *testing.T) {
var config *konf.Config

assert.True(t, !config.Exists([]string{"key"}))
assert.Equal(t, "key has no configuration.\n\n", config.Explain("key"))
var value string
assert.NoError(t, config.Unmarshal("key", &value))
assert.Equal(t, "", value)
}

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

Expand Down
4 changes: 4 additions & 0 deletions provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ type Watcher interface {
//
// It's used by the loader to check if the configuration has been set by other loaders.
func (c *Config) Exists(path []string) bool {
if c == nil {
return false
}

c.nocopy.Check()

return maps.Sub(c.values, path) != nil
Expand Down

0 comments on commit 08b2240

Please sign in to comment.