forked from bingoohuang/xlsx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
placeholder.go
127 lines (96 loc) · 2.28 KB
/
placeholder.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package xlsx
import "strings"
// PlaceholderValue represents a placeholder value.
type PlaceholderValue struct {
Content string
Parts []PlaceholderPart
}
// HasPlaceholders tells that the PlaceholderValue has any placeholders.
func (p *PlaceholderValue) HasPlaceholders() bool {
for _, p := range p.Parts {
if p.Var != "" {
return true
}
}
return false
}
// Interpolate interpolates placeholders with vars.
func (p *PlaceholderValue) Interpolate(vars map[string]string) string {
content := ""
for _, p := range p.Parts {
if p.Var != "" {
content += vars[p.Var]
} else {
content += p.Part
}
}
return content
}
// ParseVars parses the vars from the content.
func (p *PlaceholderValue) ParseVars(content string) (outVars map[string]string, matched bool) {
outVars = make(map[string]string)
for i := 0; i < len(p.Parts); i++ {
v := p.Parts[i]
if v.Var == "" {
if !strings.HasPrefix(content, v.Part) {
return nil, false
}
content = content[len(v.Part):]
continue
}
if i+1 >= len(p.Parts) {
outVars[v.Var] = content
continue
}
i++
v2 := p.Parts[i]
v2Pos := strings.Index(content, v2.Part)
if v2Pos < 0 {
return nil, false
}
outVars[v.Var] = content[:v2Pos]
content = content[v2Pos+len(v2.Part):]
}
return outVars, true
}
// PlaceholderPart is a placeholder sub Part after parsing.
type PlaceholderPart struct {
Part string
Var string
}
// ParsePlaceholder parses placeholders in the content.
func ParsePlaceholder(content string) PlaceholderValue {
pos := 0
parts := make([]PlaceholderPart, 0)
for {
contentPos := content[pos:]
lp := strings.Index(contentPos, "{{")
if lp < 0 {
if len(contentPos) > 0 {
parts = append(parts, PlaceholderPart{
Part: contentPos,
})
}
break
}
rp := strings.Index(content[pos+lp:], "}}")
if rp < 0 {
if len(contentPos) > 0 {
parts = append(parts, PlaceholderPart{
Part: contentPos,
})
}
break
}
if lp > 0 {
parts = append(parts, PlaceholderPart{
Part: contentPos[:lp],
})
}
pl := content[pos+lp : pos+lp+rp+2]
varName := strings.TrimSpace(pl[2 : len(pl)-2])
parts = append(parts, PlaceholderPart{Part: pl, Var: varName})
pos += lp + rp + 2 // nolint:gomnd
}
return PlaceholderValue{Content: content, Parts: parts}
}