Skip to content

Commit

Permalink
Merge pull request #32 from HRI-EU/fix_regex
Browse files Browse the repository at this point in the history
Fix regex for dependency handling
  • Loading branch information
vjeantet committed Dec 22, 2020
2 parents ed18c75 + 3e9cdc4 commit eb44353
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
14 changes: 10 additions & 4 deletions grok.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import (
)

var (
canonical = regexp.MustCompile(`%{(\w+(?::\w+(?::\w+)?)?)}`)
normal = regexp.MustCompile(`%{([\w-.]+(?::[\w-.]+(?::[\w-.]+)?)?)}`)
symbolic = regexp.MustCompile(`\W`)
valid = regexp.MustCompile(`^\w+([-.]\w+)*(:([-.\w]+)(:(string|float|int))?)?$`)
normal = regexp.MustCompile(`%{([\w-.]+(?::[\w-.]+(?::[\w-.]+)?)?)}`)
symbolic = regexp.MustCompile(`\W`)
)

// A Config structure is used to configure a Grok parser.
Expand Down Expand Up @@ -131,7 +131,10 @@ func (g *Grok) addPatternsFromMap(m map[string]string) error {
patternDeps := graph{}
for k, v := range m {
keys := []string{}
for _, key := range canonical.FindAllStringSubmatch(v, -1) {
for _, key := range normal.FindAllStringSubmatch(v, -1) {
if !valid.MatchString(key[1]) {
return fmt.Errorf("invalid pattern %%{%s}", key[1])
}
names := strings.Split(key[1], ":")
syntax := names[0]
if g.patterns[syntax] == nil {
Expand Down Expand Up @@ -331,6 +334,9 @@ func (g *Grok) compile(pattern string) (*gRegexp, error) {
func (g *Grok) denormalizePattern(pattern string, storedPatterns map[string]*gPattern) (string, semanticTypes, error) {
ti := semanticTypes{}
for _, values := range normal.FindAllStringSubmatch(pattern, -1) {
if !valid.MatchString(values[1]) {
return "", ti, fmt.Errorf("invalid pattern %%{%s}", values[1])
}
names := strings.Split(values[1], ":")

syntax, semantic, alias := names[0], names[0], names[0]
Expand Down
13 changes: 13 additions & 0 deletions grok_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,19 @@ func TestErrorCaptureUnknowPattern(t *testing.T) {
}
}

func TestErrorCaptureInvalidPattern(t *testing.T) {
g, _ := New()
pattern := "%{-InvalidPattern-}"
expectederr := "invalid pattern %{-InvalidPattern-}"
_, err := g.Parse(pattern, "")
if err == nil {
t.Fatal("Expected error not set")
}
if err.Error() != expectederr {
t.Fatalf("Expected error %q but got %q", expectederr, err.Error())
}
}

func TestParse(t *testing.T) {
g, _ := New()
g.AddPatternsFromPath("./patterns")
Expand Down

0 comments on commit eb44353

Please sign in to comment.