Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not throw error if alterFunc does not change the original key #249

Merged
merged 4 commits into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions mapstr/mapstr.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,12 +218,16 @@ func (m M) AlterPath(path string, mode TraversalMode, alterFunc AlterFunc) (err
if newKey == "" {
return fmt.Errorf("replacement key for %q cannot be empty", key)
}
_, exists := level[newKey]
if exists {
return fmt.Errorf("replacement key %q already exists: %w", newKey, ErrKeyCollision)

// if altered key is equal to the original key, skip below delete/put func
if newKey != key {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be more readable if it was just:

if newKey == key {
  return nil
}

_, exists := level[newKey]
if exists {
return fmt.Errorf("replacement key %q already exists: %w", newKey, ErrKeyCollision)
}
delete(level, key)
level[newKey] = val
}
delete(level, key)
level[newKey] = val

return nil
})
Expand Down Expand Up @@ -271,7 +275,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

Expand Down Expand Up @@ -316,7 +320,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
Expand Down
16 changes: 16 additions & 0 deletions mapstr/mapstr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading