From 7a31e0f9219255ead771009e1946b6091ee1501e Mon Sep 17 00:00:00 2001 From: Khushi Jain Date: Mon, 4 Nov 2024 15:53:44 +0530 Subject: [PATCH] Do not throw error if `alterFunc` does not change the original key (#249) * Do not throw error if alterfunc does not change the key * test case explanation * Update mapstr/mapstr_test.go Co-authored-by: Denis * update --------- Co-authored-by: Denis --- mapstr/mapstr.go | 10 ++++++++-- mapstr/mapstr_test.go | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/mapstr/mapstr.go b/mapstr/mapstr.go index 9d92b71..b3e16a1 100644 --- a/mapstr/mapstr.go +++ b/mapstr/mapstr.go @@ -218,6 +218,12 @@ func (m M) AlterPath(path string, mode TraversalMode, alterFunc AlterFunc) (err if newKey == "" { return fmt.Errorf("replacement key for %q cannot be empty", key) } + + // if altered key is equal to the original key, skip below delete/put func + if newKey == key { + return nil + } + _, exists := level[newKey] if exists { return fmt.Errorf("replacement key %q already exists: %w", newKey, ErrKeyCollision) @@ -271,7 +277,7 @@ func (m M) Traverse(path string, mode TraversalMode, visitor TraversalVisitor) ( for i, segment := range segments { if !found { - return ErrKeyNotFound + return fmt.Errorf("could not fetch value for key: %s, Error: %w ", path, ErrKeyNotFound) } found = false @@ -316,7 +322,7 @@ func (m M) Traverse(path string, mode TraversalMode, visitor TraversalVisitor) ( } if !found { - return ErrKeyNotFound + return fmt.Errorf("could not fetch value for key: %s, Error: %w", path, ErrKeyNotFound) } return nil diff --git a/mapstr/mapstr_test.go b/mapstr/mapstr_test.go index 2d3a791..8fbbf5d 100644 --- a/mapstr/mapstr_test.go +++ b/mapstr/mapstr_test.go @@ -1264,6 +1264,22 @@ func TestAlterPath(t *testing.T) { }, }, }, + { + name: "does not return an error if alterFunc returns the key unchanged", + from: "level1_field1.key", + mode: CaseInsensitiveMode, + alterFunc: lower, + m: M{ + "level1_field1": M{ + "Key": "value1", + }, + }, + exp: M{ + "level1_field1": M{ //first level is unchanged - already in lowercase + "key": "value1", + }, + }, + }, { name: "alters keys on all nested levels with case-insensitive matching", from: "level1_field1.level2_field1.level3_field1",