From 3ed01693a6c5e2e1b48eceaefd413026515b714f Mon Sep 17 00:00:00 2001 From: Kilemonn Date: Wed, 18 Dec 2024 20:28:23 +0900 Subject: [PATCH] Add log when matches cannot parse the regex and make sure it fails from then onward. Update test to confirm invalid regex behaviour. --- condition/condition-action/condition_action.go | 2 +- .../condition-action/matches_condition_action.go | 15 ++++++++++++--- condition/condition_test.go | 2 +- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/condition/condition-action/condition_action.go b/condition/condition-action/condition_action.go index 09a39bd..24c0fab 100644 --- a/condition/condition-action/condition_action.go +++ b/condition/condition-action/condition_action.go @@ -24,7 +24,7 @@ func GetMatchesInstance(id string, pattern string) MatchesConditionAction { if entry, exists := matchesActionsMap[id]; exists { return entry } else { - matchesAction := NewMatchesConditionAction(pattern) + matchesAction := NewMatchesConditionAction(id, pattern) matchesActionsMap[id] = matchesAction return matchesAction } diff --git a/condition/condition-action/matches_condition_action.go b/condition/condition-action/matches_condition_action.go index 45aa25c..25235a8 100644 --- a/condition/condition-action/matches_condition_action.go +++ b/condition/condition-action/matches_condition_action.go @@ -1,13 +1,19 @@ package condition_action -import "regexp" +import ( + "fmt" + "regexp" +) type MatchesConditionAction struct { regex *regexp.Regexp } -func NewMatchesConditionAction(pattern string) MatchesConditionAction { - regex := regexp.MustCompile(pattern) +func NewMatchesConditionAction(id string, pattern string) MatchesConditionAction { + regex, err := regexp.Compile(pattern) + if err != nil { + fmt.Printf("Failed to initialise [Matches] condition's pattern with ID [%s], pattern [%s] with error [%s]. All condition checks will fail.", id, pattern, err.Error()) + } return MatchesConditionAction{ regex: regex, @@ -15,5 +21,8 @@ func NewMatchesConditionAction(pattern string) MatchesConditionAction { } func (a MatchesConditionAction) CheckCondition(input string, args []string) bool { + if a.regex == nil { + return false + } return a.regex.Match([]byte(input)) } diff --git a/condition/condition_test.go b/condition/condition_test.go index e618cc0..dfeace0 100644 --- a/condition/condition_test.go +++ b/condition/condition_test.go @@ -93,7 +93,7 @@ func TestApplyCondition(t *testing.T) { {"SomethingInvalid(arg1, arg2)", "invalid", true, []string{}, []string{"test test test", "1237532123", "true", "$!&@#($)"}}, {"Matches(\\d+)", "matches-regex", false, []string{"1234", "1", "testwith number 1"}, []string{"test", "no numbers++--"}}, - {"Matches([)", "invalid-regex", false, []string{"test"}, []string{"?"}}, + {"Matches([)", "invalid-regex", false, []string{}, []string{"everything should fail"}}, } for _, c := range cases {