-
Notifications
You must be signed in to change notification settings - Fork 0
/
regexp.go
77 lines (67 loc) · 2.04 KB
/
regexp.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
package nodes
import (
"fmt"
"regexp"
"strings"
oferrors "github.com/hackborn/onefunc/errors"
"github.com/hackborn/onefunc/pipeline"
)
type RegexpNode struct {
regexpData
}
type regexpData struct {
// Expr is the expression used for the regex matching.
// See godocs for a description.
// A quick example, the following strips only the beginning
// and end from a string if they match the pattern:
// Given the phrase "allis is tall is"
// and the expr "(^(all))|((is)$)"
// the result is "is is tall "
Expr string
// Target is the type of data I operate on. Supported:
// "content.name" -- a ContentData.Name
Target string
// The regex operation. Supported:
// "" -- default to "ReplaceAllString"
// "replace" -- "ReplaceAllString"
Operation string
// The replacement string when performing a "replace" operation.
Replace string
}
func (n *RegexpNode) Start(input pipeline.StartInput) error {
data := n.regexpData
input.SetNodeData(&data)
return nil
}
func (n *RegexpNode) Run(state *pipeline.State, input pipeline.RunInput, output *pipeline.RunOutput) error {
data := state.NodeData.(*regexpData)
re, runFn, setFn, err := n.prepare(data)
if err != nil {
return err
}
output.Pins = make([]pipeline.Pin, 0, len(input.Pins))
eb := &oferrors.FirstBlock{}
for _, pin := range input.Pins {
eb.AddError(setFn(pin.Payload, runFn, re, data))
output.Pins = append(output.Pins, pin)
}
return eb.Err
}
func (n *RegexpNode) prepare(data *regexpData) (*regexp.Regexp, regexpOperationFn, regexpTargetFn, error) {
if data.Expr == "" {
return nil, nil, nil, fmt.Errorf("regexp node: No expression")
}
re, err := regexp.Compile(data.Expr)
if err != nil {
return nil, nil, nil, err
}
runFn, ok := regexpOperations[strings.ToLower(data.Operation)]
if !ok {
return nil, nil, nil, fmt.Errorf("regexp node: No operation named \"%v\"", data.Operation)
}
setFn, ok := regexpTargets[strings.ToLower(data.Target)]
if !ok {
return nil, nil, nil, fmt.Errorf("regexp node: No target named \"%v\"", data.Target)
}
return re, runFn, setFn, nil
}