Skip to content

Commit 7a31e0f

Browse files
khushijain21rdner
andauthored
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 <[email protected]> * update --------- Co-authored-by: Denis <[email protected]>
1 parent 038fdc1 commit 7a31e0f

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

mapstr/mapstr.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,12 @@ func (m M) AlterPath(path string, mode TraversalMode, alterFunc AlterFunc) (err
218218
if newKey == "" {
219219
return fmt.Errorf("replacement key for %q cannot be empty", key)
220220
}
221+
222+
// if altered key is equal to the original key, skip below delete/put func
223+
if newKey == key {
224+
return nil
225+
}
226+
221227
_, exists := level[newKey]
222228
if exists {
223229
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) (
271277

272278
for i, segment := range segments {
273279
if !found {
274-
return ErrKeyNotFound
280+
return fmt.Errorf("could not fetch value for key: %s, Error: %w ", path, ErrKeyNotFound)
275281
}
276282
found = false
277283

@@ -316,7 +322,7 @@ func (m M) Traverse(path string, mode TraversalMode, visitor TraversalVisitor) (
316322
}
317323

318324
if !found {
319-
return ErrKeyNotFound
325+
return fmt.Errorf("could not fetch value for key: %s, Error: %w", path, ErrKeyNotFound)
320326
}
321327

322328
return nil

mapstr/mapstr_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1264,6 +1264,22 @@ func TestAlterPath(t *testing.T) {
12641264
},
12651265
},
12661266
},
1267+
{
1268+
name: "does not return an error if alterFunc returns the key unchanged",
1269+
from: "level1_field1.key",
1270+
mode: CaseInsensitiveMode,
1271+
alterFunc: lower,
1272+
m: M{
1273+
"level1_field1": M{
1274+
"Key": "value1",
1275+
},
1276+
},
1277+
exp: M{
1278+
"level1_field1": M{ //first level is unchanged - already in lowercase
1279+
"key": "value1",
1280+
},
1281+
},
1282+
},
12671283
{
12681284
name: "alters keys on all nested levels with case-insensitive matching",
12691285
from: "level1_field1.level2_field1.level3_field1",

0 commit comments

Comments
 (0)