Prefix matching splat

Fixes https://github.com/mikefarah/yq/issues/218
This commit is contained in:
Mike Farah 2019-05-13 09:32:08 +10:00
parent 323089eb64
commit c4e9516aa6
3 changed files with 40 additions and 7 deletions

View File

@ -4,15 +4,25 @@ import (
"fmt"
"reflect"
"strconv"
"strings"
yaml "gopkg.in/mikefarah/yaml.v2"
)
func entriesInSlice(context yaml.MapSlice, key interface{}) []*yaml.MapItem {
func matchesKey(key string, actual interface{}) bool {
var actualString = fmt.Sprintf("%v", actual)
var prefixMatch = strings.TrimSuffix(key, "*")
if prefixMatch != key {
return strings.HasPrefix(actualString, prefixMatch)
}
return actualString == key
}
func entriesInSlice(context yaml.MapSlice, key string) []*yaml.MapItem {
var matches = make([]*yaml.MapItem, 0)
for idx := range context {
var entry = &context[idx]
if key == "*" || fmt.Sprintf("%v", entry.Key) == key {
if matchesKey(key, entry.Key) {
matches = append(matches, entry)
}
}

View File

@ -31,12 +31,22 @@ func TestReadMap_splat(t *testing.T) {
mapSplat:
item1: things
item2: whatever
otherThing: cat
`)
res, _ := readMap(data, "mapSplat", []string{"*"})
result := res.([]interface{})
var actual = []string{result[0].(string), result[1].(string)}
sort.Strings(actual)
assertResult(t, "[things whatever]", fmt.Sprintf("%v", actual))
assertResult(t, "[things whatever cat]", fmt.Sprintf("%v", res))
}
func TestReadMap_prefixSplat(t *testing.T) {
var data = parseData(`
---
mapSplat:
item1: things
item2: whatever
otherThing: cat
`)
res, _ := readMap(data, "mapSplat", []string{"item*"})
assertResult(t, "[things whatever]", fmt.Sprintf("%v", res))
}
func TestReadMap_deep_splat(t *testing.T) {

View File

@ -1 +1,14 @@
b: dog
deep1:
hostA:
value: 1234
notRelevant:
value: bananas
hostB:
value: 5678
deep2:
hostC:
value: 1234
notRelevant:
value: bananas
hostD:
value: 5678