-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdedent_rule.go
70 lines (53 loc) · 1.23 KB
/
dedent_rule.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
package ptproc
import (
"context"
"regexp"
"strings"
"go.opentelemetry.io/otel"
)
var _ Rule = (*dedentRule)(nil)
var DefaultDedentSpaceRegEx = regexp.MustCompile(`^([\s]+)`)
type DedentRuleConfig struct {
SpaceRegExp *regexp.Regexp
}
func NewDedentRule(cfg *DedentRuleConfig) (Rule, error) {
if cfg == nil {
cfg = &DedentRuleConfig{}
}
return &dedentRule{
spaceRegExp: cfg.SpaceRegExp,
}, nil
}
type dedentRule struct {
spaceRegExp *regexp.Regexp
}
func (rule *dedentRule) Apply(ctx context.Context, opts *RuleOptions, ns []Node) (_ []Node, err error) {
ctx, span := otel.Tracer("ptproc").Start(ctx, "dedentRule.Apply")
defer func() {
if err != nil {
span.RecordError(err)
}
span.End()
}()
if len(ns) == 0 {
return nil, nil
}
spaceRegExp := rule.spaceRegExp
if spaceRegExp == nil {
spaceRegExp = DefaultDedentSpaceRegEx
}
newNodes := make([]Node, 0, len(ns))
h := ns[0]
txt := h.Text()
group := spaceRegExp.FindStringSubmatch(txt)
if len(group) != 2 {
return ns, nil
}
space := group[1]
newNodes = append(newNodes, &node{strings.TrimPrefix(txt, space)})
for _, n := range ns[1:] {
txt := n.Text()
newNodes = append(newNodes, &node{strings.TrimPrefix(txt, space)})
}
return newNodes, nil
}