hcl/ast: simplify API

This commit is contained in:
Mitchell Hashimoto 2015-11-07 10:25:22 -08:00
parent 32411ba6af
commit 9ca9a4e1c3
2 changed files with 39 additions and 21 deletions

View File

@ -309,7 +309,7 @@ func (d *decoder) decodeMap(name string, node ast.Node, result reflect.Value) er
// get the objectlist of only these keys.
itemVal := item.Val
if len(item.Keys) > 1 {
itemVal = n.Prefix(keyStr)
itemVal = n.Filter(keyStr)
done[keyStr] = struct{}{}
}
@ -533,8 +533,9 @@ func (d *decoder) decodeStruct(name string, node ast.Node, result reflect.Value)
// Determine the element we'll use to decode. If it is a single
// match (only object with the field), then we decode it exactly.
// If it is a prefix match, then we decode the matches.
prefixMatches := list.Prefix(fieldName)
matches := list.Get(fieldName)
filter := list.Filter(fieldName)
prefixMatches := filter.Children()
matches := filter.Elem()
if len(matches.Items) == 0 && len(prefixMatches.Items) == 0 {
continue
}

View File

@ -45,27 +45,18 @@ func (o *ObjectList) Add(item *ObjectItem) {
o.Items = append(o.Items, item)
}
func (o *ObjectList) Get(key string) *ObjectList {
var result ObjectList
for _, item := range o.Items {
if len(item.Keys) != 1 {
continue
}
text := item.Keys[0].Token.Text
if text == key || strings.EqualFold(text, key) {
result.Add(item)
}
}
return &result
}
func (o *ObjectList) Prefix(keys ...string) *ObjectList {
// Filter filters out the objects with the given key list as a prefix.
//
// The returned list of objects contain ObjectItems where the keys have
// this prefix already stripped off. This might result in objects with
// zero-length key lists if they have no children.
//
// If no matches are found, an empty ObjectList (non-nil) is returned.
func (o *ObjectList) Filter(keys ...string) *ObjectList {
var result ObjectList
for _, item := range o.Items {
// If there aren't enough keys, then ignore this
if len(item.Keys) < len(keys)+1 {
if len(item.Keys) < len(keys) {
continue
}
@ -90,6 +81,32 @@ func (o *ObjectList) Prefix(keys ...string) *ObjectList {
return &result
}
// Children returns further nested objects (key length > 0) within this
// ObjectList. This should be used with Filter to get at child items.
func (o *ObjectList) Children() *ObjectList {
var result ObjectList
for _, item := range o.Items {
if len(item.Keys) > 0 {
result.Add(item)
}
}
return &result
}
// Elem returns items in the list that are direct element assignments
// (key length == 0). This should be used with Filter to get at elements.
func (o *ObjectList) Elem() *ObjectList {
var result ObjectList
for _, item := range o.Items {
if len(item.Keys) == 0 {
result.Add(item)
}
}
return &result
}
func (o *ObjectList) Pos() token.Pos {
// always returns the uninitiliazed position
return o.Items[0].Pos()