From c4e9516aa64361c34706f5040ec86e3d8ba93d17 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Mon, 13 May 2019 09:32:08 +1000 Subject: [PATCH] Prefix matching splat Fixes https://github.com/mikefarah/yq/issues/218 --- data_navigator.go | 14 ++++++++++++-- data_navigator_test.go | 18 ++++++++++++++---- examples/data3.yaml | 15 ++++++++++++++- 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/data_navigator.go b/data_navigator.go index d4548e6..93d2a13 100644 --- a/data_navigator.go +++ b/data_navigator.go @@ -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) } } diff --git a/data_navigator_test.go b/data_navigator_test.go index f14d561..873ff3e 100644 --- a/data_navigator_test.go +++ b/data_navigator_test.go @@ -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) { diff --git a/examples/data3.yaml b/examples/data3.yaml index fbe63d8..0aba4f1 100644 --- a/examples/data3.yaml +++ b/examples/data3.yaml @@ -1 +1,14 @@ -b: dog \ No newline at end of file +deep1: + hostA: + value: 1234 + notRelevant: + value: bananas + hostB: + value: 5678 +deep2: + hostC: + value: 1234 + notRelevant: + value: bananas + hostD: + value: 5678