diff --git a/exists.go b/exists.go index 2fb3084..07aeda4 100644 --- a/exists.go +++ b/exists.go @@ -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 } diff --git a/exists_test.go b/exists_test.go index ea9a47c..bf7ce40 100644 --- a/exists_test.go +++ b/exists_test.go @@ -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") } } diff --git a/remove_test.go b/remove_test.go index 642d07c..b40a9af 100644 --- a/remove_test.go +++ b/remove_test.go @@ -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") } } diff --git a/rename.go b/rename.go index e95a963..4c655ed 100644 --- a/rename.go +++ b/rename.go @@ -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) diff --git a/rename_test.go b/rename_test.go index d712c20..090cb7b 100644 --- a/rename_test.go +++ b/rename_test.go @@ -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",