-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
validator.go
76 lines (61 loc) · 1.57 KB
/
validator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package ffmpeg
import (
"fmt"
"regexp"
"strings"
)
// The Validator interface is for validating strings whether they are eligible
// as input or output for a ffmpeg process
type Validator interface {
// IsValid tests whether a text matches any expression of inputs
IsValid(text string) bool
}
type validator struct {
allow []*regexp.Regexp // List of compiled input expressions
block []*regexp.Regexp // List of compiled output expressions
}
// NewValidator creates a new Validator with the given input and output
// expressions. Empty expressions will be ignored. Returns an
// error if an expression can't be compiled.
func NewValidator(allow, block []string) (Validator, error) {
v := &validator{}
for _, expression := range allow {
expression = strings.TrimSpace(expression)
if len(expression) == 0 {
continue
}
re, err := regexp.Compile(expression)
if err != nil {
return nil, fmt.Errorf("invalid allow expression: '%s' (%w)", expression, err)
}
v.allow = append(v.allow, re)
}
for _, expression := range block {
expression = strings.TrimSpace(expression)
if len(expression) == 0 {
continue
}
re, err := regexp.Compile(expression)
if err != nil {
return nil, fmt.Errorf("invalid block expression: '%s' (%w)", expression, err)
}
v.block = append(v.block, re)
}
return v, nil
}
func (v *validator) IsValid(text string) bool {
for _, e := range v.block {
if e.MatchString(text) {
return false
}
}
if len(v.allow) == 0 {
return true
}
for _, e := range v.allow {
if e.MatchString(text) {
return true
}
}
return false
}