-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.go
More file actions
192 lines (162 loc) · 4.53 KB
/
template.go
File metadata and controls
192 lines (162 loc) · 4.53 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// Package pytemplate contains implementation of Python-like template, which allow to substitute variables (defined with dollar $) dynamically,
// using provided mappings.
package pytemplate
import (
"bytes"
"fmt"
"regexp"
"strings"
)
const delimiter = "$"
var (
pattern = regexp.MustCompile(`\$(?:(?P<escaped>\$)|(?P<named>[_a-zA-z][_a-zA-Z0-9]*)|` +
`\{(?P<braced>[_a-zA-Z][_a-zA-Z0-9]*)\}|(?P<invalid>))`)
escapedIdx = pattern.SubexpIndex("escaped")
namedIdx = pattern.SubexpIndex("named")
bracedIdx = pattern.SubexpIndex("braced")
invalidIdx = pattern.SubexpIndex("invalid")
)
// SubstitutionFailedError indicated that substitution of variable Variable failed (e.g., because there is no matching mapping)
type SubstitutionFailedError struct {
Variable string
}
func (e *SubstitutionFailedError) Error() string {
return "failed to substitute variable " + e.Variable
}
func (e *SubstitutionFailedError) Is(err error) bool {
sfe, ok := err.(*SubstitutionFailedError)
if !ok {
return false
}
return e.Variable == sfe.Variable
}
// Template represents template string, containing variables to substitute.
type Template struct {
parts []templatePart
}
// New builds Template using provided template string as base.
func New(template string) (*Template, error) {
parts, err := parseTemplate(template)
if err != nil {
return nil, err
}
return &Template{parts: parts}, nil
}
func parseTemplate(template string) ([]templatePart, error) {
var (
prevIdx int
parts []templatePart
)
for _, submatches := range pattern.FindAllStringSubmatchIndex(template, -1) {
var (
replacedName string
braced bool
)
switch {
case submatches[namedIdx*2] != -1:
replacedName = template[submatches[2*namedIdx]:submatches[2*namedIdx+1]]
case submatches[bracedIdx*2] != -1:
replacedName = template[submatches[2*bracedIdx]:submatches[2*bracedIdx+1]]
braced = true
case submatches[escapedIdx*2] != -1:
parts = append(parts, templatePart{
value: template[prevIdx:submatches[0]] + delimiter,
})
prevIdx = submatches[1]
continue
case submatches[invalidIdx*2] != -1:
return nil, fmt.Errorf("invalid placeholder in template string at index %d", submatches[invalidIdx*2])
}
constPrefix := template[prevIdx:submatches[0]]
if constPrefix != "" {
parts = append(parts, templatePart{
value: constPrefix,
})
}
parts = append(parts, templatePart{
value: replacedName,
isVariable: true,
braced: braced,
})
prevIdx = submatches[1]
}
if constSuffix := template[prevIdx:]; constSuffix != "" {
parts = append(parts, templatePart{value: constSuffix})
}
return parts, nil
}
// Substitute substitutes variables in Template, using mappings provided via options.
// If there is no matching mapping for a variable, a SubstitutionFailedError is returned.
func (t *Template) Substitute(opts ...SubstituteOption) (string, error) {
var so substituteOptions
for _, opt := range opts {
opt(&so)
}
var sb strings.Builder
for i := range t.parts {
if !t.parts[i].isVariable {
sb.WriteString(t.parts[i].value)
continue
}
mapped, ok := substituteVariable(&so, t.parts[i].value)
if !ok {
if so.safe {
sb.WriteString(t.parts[i].String())
} else {
return "", &SubstitutionFailedError{Variable: t.parts[i].value}
}
} else {
sb.WriteString(mapped)
}
}
return sb.String(), nil
}
// SafeSubstitute is similar to Substitute, but with preapplied WithSafeSubstitution
// option, meaning there won't be any error.
func (t *Template) SafeSubstitute(opts ...SubstituteOption) string {
result, _ := t.Substitute(append(opts, WithSafeSubstitution())...)
return result
}
func substituteVariable(so *substituteOptions, name string) (string, bool) {
var (
mapped string
ok bool
)
if so.mapping != nil {
mapped, ok = so.mapping[name]
}
if !ok && so.mapper != nil {
mapped, ok = so.mapper.Map(name)
}
return mapped, ok
}
func (t Template) MarshalText() (text []byte, err error) {
var bb bytes.Buffer
for i := range t.parts {
bb.WriteString(t.parts[i].String())
}
return bb.Bytes(), nil
}
func (t *Template) UnmarshalText(text []byte) error {
parts, err := parseTemplate(string(text))
if err != nil {
return err
}
t.parts = parts
return nil
}
type templatePart struct {
value string
isVariable bool
braced bool
}
func (tp templatePart) String() string {
switch {
case !tp.isVariable:
return strings.ReplaceAll(tp.value, delimiter, delimiter+delimiter)
case tp.braced:
return delimiter + "{" + tp.value + "}"
default:
return delimiter + tp.value
}
}