-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuiltin_validators.go
81 lines (68 loc) · 2.43 KB
/
builtin_validators.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
77
78
79
80
81
package anyi
import (
"encoding/json"
"errors"
"regexp"
"github.com/jieliu2000/anyi/flow"
)
type JsonValidator struct {
}
func (validator *JsonValidator) Init() error {
return nil
}
func (validator *JsonValidator) Validate(stepOutput string, Step *flow.Step) bool {
if stepOutput == "" {
return false
}
//check if the output is valid json
var js json.RawMessage
err := json.Unmarshal([]byte(stepOutput), &js)
return err == nil
}
// JsonValidator is a validator for string output. It can be used to check if the step's output matches a given regular expression or equals a specific string.
// Note that the EqualTo and MatchRegex fields are mutually exclusive. If both are set, an error is returned during initialization.
type StringValidator struct {
EqualTo string `json:"eqaulTo" mapstructure:"eqaulTo" yaml:"eqaulTo"`
MatchRegex string `json:"matchRegex" mapstructure:"matchRegex" yaml:"matchRegex"`
}
// Init initializes the StringValidator.
// It checks the validity of the regular expression and ensures that either EqualTo or MatchRegex is set, but not both.
// If any error occurs during initialization, the corresponding error message is returned.
func (validator *StringValidator) Init() error {
if validator.MatchRegex != "" {
_, err := regexp.Compile(validator.MatchRegex)
if err != nil {
return err
}
}
if validator.EqualTo == "" && validator.MatchRegex == "" {
return errors.New("StringValidator should have either EqualTo or MatchRegex set")
}
if validator.EqualTo != "" && validator.MatchRegex != "" {
return errors.New("StringValidator should have either EqualTo or MatchRegex set, not both")
}
return nil
}
// Validate function checks if the stepOutput matches the validation criteria set in the StringValidator struct.
// For regular expressions, see [Golang regexp documentation]
//
// Parameters:
// - stepOutput string: The output string to be validated.
// - Step *Step: The step object containing the validation information.
// Return value:
// - bool: True if the validation passes, false otherwise.
//
// [Golang regexp documentation]: https://pkg.go.dev/regexp
func (validator *StringValidator) Validate(stepOutput string, Step *flow.Step) bool {
if validator.EqualTo != "" && stepOutput == validator.EqualTo {
return true
}
if validator.MatchRegex != "" {
matched, err := regexp.MatchString(validator.MatchRegex, stepOutput)
if err != nil {
return false
}
return matched
}
return false
}