Skip to content

Commit

Permalink
Handle parsing errors for mv.Exists argument
Browse files Browse the repository at this point in the history
  • Loading branch information
clbanning committed Dec 10, 2019
1 parent 1fcff08 commit 5c9dc14
Show file tree
Hide file tree
Showing 5 changed files with 20 additions and 9 deletions.
8 changes: 5 additions & 3 deletions exists.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package mxj

// Checks whether the path exists
func (mv Map) Exists(path string, subkeys ...string) bool {
// Checks whether the path exists. If err != nil then 'false' is returned
// along with the error encountered parsing either the "path" or "subkeys"
// argument.
func (mv Map) Exists(path string, subkeys ...string) (bool, error) {
v, err := mv.ValuesForPath(path, subkeys...)
return err == nil && len(v) > 0
return (err == nil && len(v) > 0), err
}
4 changes: 2 additions & 2 deletions exists_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ func TestExists(t *testing.T) {
}
mv := Map(m)

if !mv.Exists("Div.Colour") {
if v, _ := mv.Exists("Div.Colour"); !v {
t.Fatal("Haven't found an existing element")
}

if mv.Exists("Div.Color") {
if v, _ := mv.Exists("Div.Color"); v {
t.Fatal("Have found a non existing element")
}
}
Expand Down
2 changes: 1 addition & 1 deletion remove_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestRemove(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if mv.Exists("Div.Colour") {
if v, _ := mv.Exists("Div.Colour"); v {
t.Fatal("removed key still remain")
}
}
13 changes: 10 additions & 3 deletions rename.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,20 @@ import (
)

// RenameKey renames a key in a Map.
// It works only for nested maps. It doesn't work for cases when it buried in a list.
// It works only for nested maps.
// It doesn't work for cases when the key is in a list.
func (mv Map) RenameKey(path string, newName string) error {
if !mv.Exists(path) {
var v bool
var err error
if v, err = mv.Exists(path); err == nil && !v {
return errors.New("RenameKey: path not found: " + path)
} else if err != nil {
return err
}
if mv.Exists(parentPath(path) + "." + newName) {
if v, err = mv.Exists(parentPath(path) + "." + newName); err == nil && v {
return errors.New("RenameKey: key already exists: " + newName)
} else if err != nil {
return err
}

m := map[string]interface{}(mv)
Expand Down
2 changes: 2 additions & 0 deletions rename_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package mxj

import (
"fmt"
"testing"
)

func TestRenameKey(t *testing.T) {
fmt.Println("------------ rename_test.go")
m := map[string]interface{}{
"Div": map[string]interface{}{
"Colour": "blue",
Expand Down

0 comments on commit 5c9dc14

Please sign in to comment.