From 49717d91b046eb9d0a327fe06c0034bfe71aa658 Mon Sep 17 00:00:00 2001 From: Simon Pasquier Date: Mon, 28 May 2018 11:36:47 +0200 Subject: [PATCH] parse: fix parsing for label values with commas (#1395) Signed-off-by: Simon Pasquier --- pkg/parse/parse.go | 22 ++++++++++++++++++++-- pkg/parse/parse_test.go | 16 +++++++++++++--- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/pkg/parse/parse.go b/pkg/parse/parse.go index adfe25dc..1a03592d 100644 --- a/pkg/parse/parse.go +++ b/pkg/parse/parse.go @@ -40,13 +40,31 @@ func Matchers(s string) ([]*labels.Matcher, error) { s = s[:len(s)-1] } - for _, toParse := range strings.Split(s, ",") { - m, err := Matcher(toParse) + var insideQuotes bool + var token string + var tokens []string + for _, r := range s { + if !insideQuotes && r == ',' { + tokens = append(tokens, token) + token = "" + continue + } + token += string(r) + if r == '"' { + insideQuotes = !insideQuotes + } + } + if token != "" { + tokens = append(tokens, token) + } + for _, token := range tokens { + m, err := Matcher(token) if err != nil { return nil, err } matchers = append(matchers, m) } + return matchers, nil } diff --git a/pkg/parse/parse_test.go b/pkg/parse/parse_test.go index d16f8055..84f3d6ad 100644 --- a/pkg/parse/parse_test.go +++ b/pkg/parse/parse_test.go @@ -24,6 +24,7 @@ func TestMatchers(t *testing.T) { testCases := []struct { input string want []*labels.Matcher + err error }{ { input: `{foo="bar"}`, @@ -122,15 +123,24 @@ func TestMatchers(t *testing.T) { return append(ms, m) }(), }, + { + input: `{foo="bar,quux", job="job1"}`, + want: func() []*labels.Matcher { + ms := []*labels.Matcher{} + m, _ := labels.NewMatcher(labels.MatchEqual, "foo", "bar,quux") + m2, _ := labels.NewMatcher(labels.MatchEqual, "job", "job1") + return append(ms, m, m2) + }(), + }, } for i, tc := range testCases { got, err := Matchers(tc.input) - if err != nil { - t.Fatalf("error (i=%d): %v", i, err) + if tc.err != err { + t.Fatalf("error not equal (i=%d):\ngot %v\nwant %v", i, err, tc.err) } if !reflect.DeepEqual(got, tc.want) { - t.Fatalf("error not equal (i=%d):\ngot %v\nwant %v", i, got, tc.want) + t.Fatalf("labels not equal (i=%d):\ngot %v\nwant %v", i, got, tc.want) } }