From 135cef183c4612c976a1894181dd27dca271e53d Mon Sep 17 00:00:00 2001 From: brianpursley Date: Sun, 1 Nov 2020 10:41:19 -0500 Subject: [PATCH] Fix bug in JSON path parser where an error occurs when a range is empty Kubernetes-commit: 10634c6093c84acc78181a26c93d8785e12802e4 --- util/jsonpath/jsonpath.go | 16 +++++++++++++--- util/jsonpath/jsonpath_test.go | 15 +++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/util/jsonpath/jsonpath.go b/util/jsonpath/jsonpath.go index 9740fe69..49ecd146 100644 --- a/util/jsonpath/jsonpath.go +++ b/util/jsonpath/jsonpath.go @@ -103,13 +103,23 @@ func (j *JSONPath) FindResults(data interface{}) ([][]reflect.Value, error) { if j.beginRange > 0 { j.beginRange-- j.inRange++ - for _, value := range results { + if len(results) > 0 { + for _, value := range results { + j.parser.Root.Nodes = nodes[i+1:] + nextResults, err := j.FindResults(value.Interface()) + if err != nil { + return nil, err + } + fullResult = append(fullResult, nextResults...) + } + } else { + // If the range has no results, we still need to process the nodes within the range + // so the position will advance to the end node j.parser.Root.Nodes = nodes[i+1:] - nextResults, err := j.FindResults(value.Interface()) + _, err := j.FindResults(nil) if err != nil { return nil, err } - fullResult = append(fullResult, nextResults...) } j.inRange-- diff --git a/util/jsonpath/jsonpath_test.go b/util/jsonpath/jsonpath_test.go index e15c4097..34a0f9e7 100644 --- a/util/jsonpath/jsonpath_test.go +++ b/util/jsonpath/jsonpath_test.go @@ -393,6 +393,21 @@ func TestKubernetes(t *testing.T) { testJSONPathSortOutput(randomPrintOrderTests, t) } +func TestEmptyRange(t *testing.T) { + var input = []byte(`{"items":[]}`) + var emptyList interface{} + err := json.Unmarshal(input, &emptyList) + if err != nil { + t.Error(err) + } + + tests := []jsonpathTest{ + {"empty range", `{range .items[*]}{.metadata.name}{end}`, &emptyList, "", false}, + {"empty nested range", `{range .items[*]}{.metadata.name}{":"}{range @.spec.containers[*]}{.name}{","}{end}{"+"}{end}`, &emptyList, "", false}, + } + testJSONPath(tests, true, t) +} + func TestNestedRanges(t *testing.T) { var input = []byte(`{ "items": [