Skip to content

Commit 56ec85e

Browse files
authored
Add Set(key, val) shorthand for Merge(). (#192)
When there are multiple mutations to be made at many places, `Load(), Merge(), MergeAt()` requires a lot of boilerplate code. `Set(key string, val interface{})` is a new shorthand that allows a value to be directly merge at the given key without having to initialize a new Koanf{} object. Closes #191.
1 parent 7c73646 commit 56ec85e

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

koanf.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,16 @@ func (ko *Koanf) MergeAt(in *Koanf, path string) error {
218218
return ko.merge(n, new(options))
219219
}
220220

221+
// Set sets the value at a specific key.
222+
func (ko *Koanf) Set(key string, val interface{}) error {
223+
// Unflatten the config map with the given key path.
224+
n := maps.Unflatten(map[string]interface{}{
225+
key: val,
226+
}, ko.conf.Delim)
227+
228+
return ko.merge(n, new(options))
229+
}
230+
221231
// Marshal takes a Parser implementation and marshals the config map into bytes,
222232
// for example, to TOML or JSON bytes.
223233
func (ko *Koanf) Marshal(p Parser) ([]byte, error) {

koanf_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -870,6 +870,31 @@ func TestMergeAt(t *testing.T) {
870870
assert.Equal(expected.Get(""), reversed.Get(""), "conf map mismatch")
871871
}
872872

873+
func TestSet(t *testing.T) {
874+
var (
875+
assert = assert.New(t)
876+
k = koanf.New(delim)
877+
)
878+
assert.Nil(k.Load(file.Provider(mockYAML), yaml.Parser()),
879+
"error loading file")
880+
881+
assert.Nil(k.Set("parent1.name", "new"))
882+
assert.Equal(k.String("parent1.name"), "new")
883+
884+
assert.Nil(k.Set("parent1.child1.name", 123))
885+
assert.Equal(k.Int("parent1.child1.name"), 123)
886+
887+
assert.Nil(k.Set("parent1.child1.grandchild1.ids", []int{5}))
888+
assert.Equal(k.Ints("parent1.child1.grandchild1.ids"), []int{5})
889+
890+
assert.Nil(k.Set("parent1.child1.grandchild1", 123))
891+
assert.Equal(k.Int("parent1.child1.grandchild1"), 123)
892+
assert.Equal(k.Int("parent1.child1.grandchild1.ids"), 0)
893+
894+
assert.Nil(k.Set("parent1.child1.grandchild1", map[string]interface{}{"name": "new"}))
895+
assert.Equal(k.Get("parent1.child1.grandchild1"), map[string]interface{}{"name": "new"})
896+
}
897+
873898
func TestUnmarshal(t *testing.T) {
874899
assert := assert.New(t)
875900

0 commit comments

Comments
 (0)