Skip to content

Commit

Permalink
fix(logql): properly count regexp captures
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed Jul 15, 2024
1 parent 75199df commit 86424df
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
22 changes: 19 additions & 3 deletions internal/logql/parser_pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,10 +292,20 @@ func (p *parser) parseRegexpLabelParser() (*RegexpLabelParser, error) {
Err: err,
}
}
if re.NumSubexp() == 0 {
return nil, &ParseError{
Pos: patternTok.Pos,
Err: errors.New("at least one capture expected"),
}
}

var (
captures = re.SubexpNames()
mapping = make(map[int]Label, len(captures))
unique = make(map[string]struct{}, len(captures))
)

mapping := map[int]Label{}
unique := map[string]struct{}{}
for i, name := range re.SubexpNames() {
for i, name := range captures {
// Not capturing.
if name == "" {
continue
Expand All @@ -317,6 +327,12 @@ func (p *parser) parseRegexpLabelParser() (*RegexpLabelParser, error) {
}
mapping[i] = Label(name)
}
if len(mapping) == 0 {
return nil, &ParseError{
Pos: patternTok.Pos,
Err: errors.New("at least one capture expected"),
}
}

return &RegexpLabelParser{
Regexp: re,
Expand Down
4 changes: 4 additions & 0 deletions internal/logql/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1186,6 +1186,9 @@ var tests = []TestCase{
{`{} | regexp "\\"`, nil, true},
{`{} | foo=~"\\"`, nil, true},
{`label_replace(rate({job="mysql"}[1m]), "dst", "replacement", "src", "\\")`, nil, true},
// No capture.
{`{} | regexp "a"`, nil, true},
{`{} | regexp "a (\\w+)"`, nil, true},
// Duplicate capture.
{`{} | regexp "(?P<method>\\w+)(?P<method>\\w+)"`, nil, true},
// Invalid capture name.
Expand All @@ -1195,6 +1198,7 @@ var tests = []TestCase{
//
// No capture.
{`{} | pattern "a"`, nil, true},
{`{} | pattern "a <_> a"`, nil, true},
// Duplicate capture.
{`{} | pattern "<a> foo <a>"`, nil, true},
// Consecutive capture.
Expand Down

0 comments on commit 86424df

Please sign in to comment.