Add proper error checking on regexps

This commit is contained in:
Ben Sarmiento
2023-11-21 16:26:41 +01:00
parent 0a781957b6
commit 400a015298
3 changed files with 21 additions and 8 deletions

View File

@@ -25,7 +25,7 @@ func LoadZurgConfig(filename string) (ConfigInterface, error) {
switch initialConfig.Version {
case "v1":
log.Debug("Detected config version: v1")
return loadV1Config(content)
return loadV1Config(content, log)
default:
return nil, fmt.Errorf("invalid config version: %s", initialConfig.Version)

View File

@@ -1,19 +1,21 @@
package config
import (
"fmt"
"regexp"
"sort"
"strings"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
)
func loadV1Config(content []byte) (*ZurgConfigV1, error) {
func loadV1Config(content []byte, log *zap.SugaredLogger) (*ZurgConfigV1, error) {
var configV1 ZurgConfigV1
if err := yaml.Unmarshal(content, &configV1); err != nil {
return nil, err
}
configV1.log = log
return &configV1, nil
}
@@ -84,7 +86,11 @@ func (z *ZurgConfigV1) matchFilter(torrentName string, torrentIDs, fileNames []s
}
}
if filter.RegexStr != "" {
regex := compilePattern(filter.RegexStr)
regex, err := compilePattern(filter.RegexStr)
if err != nil {
z.log.Errorf("Failed to compile regex: %v", err)
return false
}
if regex.MatchString(torrentName) {
return true
}
@@ -119,7 +125,11 @@ func (z *ZurgConfigV1) matchFilter(torrentName string, torrentIDs, fileNames []s
}
}
if filter.FileInsideRegexStr != "" {
regex := compilePattern(filter.FileInsideRegexStr)
regex, err := compilePattern(filter.FileInsideRegexStr)
if err != nil {
z.log.Errorf("Failed to compile regex: %v", err)
return false
}
for _, filename := range fileNames {
if regex.MatchString(filename) {
return true
@@ -143,7 +153,7 @@ func (z *ZurgConfigV1) matchFilter(torrentName string, torrentIDs, fileNames []s
return false
}
func compilePattern(pattern string) *regexp.Regexp {
func compilePattern(pattern string) (*regexp.Regexp, error) {
flags := map[rune]string{
'i': "(?i)",
'm': "(?m)",
@@ -173,8 +183,8 @@ func compilePattern(pattern string) *regexp.Regexp {
// Validate pattern
if finalPattern == "" || finalPattern == flagString {
return nil
return nil, fmt.Errorf("invalid regex pattern: %s", pattern)
}
return regexp.MustCompile(finalPattern)
return regexp.Compile(finalPattern)
}

View File

@@ -1,8 +1,11 @@
package config
import "go.uber.org/zap"
type ZurgConfigV1 struct {
ZurgConfig `yaml:",inline"`
Directories map[string]*DirectoryFilterConditionsV1 `yaml:"directories"`
log *zap.SugaredLogger
}
type DirectoryFilterConditionsV1 struct {
GroupOrder int `yaml:"group_order"`