extended Has function to work with paths
This commit is contained in:
@@ -18,17 +18,38 @@ import (
|
|||||||
// This is the result of the parsing of a TOML file.
|
// This is the result of the parsing of a TOML file.
|
||||||
type TomlTree map[string]interface{}
|
type TomlTree map[string]interface{}
|
||||||
|
|
||||||
// Has returns a boolean indicating if the toplevel tree contains the given
|
// Has returns a boolean indicating if the given key exists.
|
||||||
// key.
|
|
||||||
func (t *TomlTree) Has(key string) bool {
|
func (t *TomlTree) Has(key string) bool {
|
||||||
mp := (map[string]interface{})(*t)
|
if key == "" {
|
||||||
for k, _ := range mp {
|
|
||||||
if k == key {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
return t.HasPath(strings.Split(key, "."))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns true if the given path of keys exists, false otherwise.
|
||||||
|
func (t *TomlTree) HasPath(keys []string) bool {
|
||||||
|
if len(keys) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
subtree := t
|
||||||
|
for _, intermediate_key := range keys[:len(keys)-1] {
|
||||||
|
_, exists := (*subtree)[intermediate_key]
|
||||||
|
if !exists {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
switch node := (*subtree)[intermediate_key].(type) {
|
||||||
|
case *TomlTree:
|
||||||
|
subtree = node
|
||||||
|
case []*TomlTree:
|
||||||
|
// go to most recent element
|
||||||
|
if len(node) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
subtree = node[len(node)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// Keys returns the keys of the toplevel tree.
|
// Keys returns the keys of the toplevel tree.
|
||||||
// Warning: this is a costly operation.
|
// Warning: this is a costly operation.
|
||||||
|
|||||||
@@ -4,6 +4,28 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestTomlHas(t *testing.T) {
|
||||||
|
tree, _ := Load(`
|
||||||
|
[test]
|
||||||
|
key = "value"
|
||||||
|
`)
|
||||||
|
|
||||||
|
if !tree.Has("test.key") {
|
||||||
|
t.Errorf("Has - expected test.key to exists")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTomlHasPath(t *testing.T) {
|
||||||
|
tree, _ := Load(`
|
||||||
|
[test]
|
||||||
|
key = "value"
|
||||||
|
`)
|
||||||
|
|
||||||
|
if !tree.HasPath([]string{"test", "key"}) {
|
||||||
|
t.Errorf("HasPath - expected test.key to exists")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestTomlGetPath(t *testing.T) {
|
func TestTomlGetPath(t *testing.T) {
|
||||||
node := make(TomlTree)
|
node := make(TomlTree)
|
||||||
//TODO: set other node data
|
//TODO: set other node data
|
||||||
|
|||||||
Reference in New Issue
Block a user