-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreindent_rule.go
91 lines (74 loc) · 1.6 KB
/
reindent_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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package ptproc
import (
"context"
"strings"
"go.opentelemetry.io/otel"
)
var _ Rule = (*reindentRule)(nil)
const DefaultIndentLevel = 2
type ReindentRuleConfig struct {
IndentLevel int
}
func NewReindentRule(cfg *ReindentRuleConfig) (Rule, error) {
if cfg == nil {
cfg = &ReindentRuleConfig{}
}
return &reindentRule{
indentLevel: cfg.IndentLevel,
}, nil
}
type reindentRule struct {
indentLevel int
}
func (rule *reindentRule) Apply(ctx context.Context, opts *RuleOptions, ns []Node) (_ []Node, err error) {
ctx, span := otel.Tracer("ptproc").Start(ctx, "reindentRule.Apply")
defer func() {
if err != nil {
span.RecordError(err)
}
span.End()
}()
if len(ns) == 0 {
return nil, nil
}
indentLevel := rule.indentLevel
if indentLevel == 0 {
indentLevel = DefaultIndentLevel
}
newNodes := make([]Node, 0, len(ns))
var gcd func(a, b int) int
gcd = func(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
counts := make([]int, len(ns))
var gcdValue int
for idx, n := range ns {
var count int
for _, s := range n.Text() {
if s == ' ' {
count++
} else if s == '\t' {
count += indentLevel
} else {
break
}
}
counts[idx] = count
gcdValue = gcd(gcdValue, count)
}
if gcdValue == 0 {
return ns, nil
}
for idx, n := range ns {
count := counts[idx]
txt := n.Text()
txt = strings.ReplaceAll(txt, "\t", strings.Repeat(" ", indentLevel))
txt = strings.TrimPrefix(txt, strings.Repeat(" ", count))
txt = strings.Repeat(" ", (count/gcdValue)*indentLevel) + txt
newNodes = append(newNodes, &node{txt})
}
return newNodes, nil
}