Skip to content

Commit 9ef65b3

Browse files
committed
Improve vars Expand
1 parent fa841ce commit 9ef65b3

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed

modules/templates/vars/vars.go

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -43,26 +43,25 @@ func IsErrNoMatchedVar(err error) bool {
4343
// Expand replaces all variables like {var} to match
4444
func Expand(template string, match map[string]string, subs ...string) (string, error) {
4545
var (
46-
buf strings.Builder
47-
key strings.Builder
48-
enter bool
46+
buf strings.Builder
47+
keyStartPos = -1
4948
)
50-
for _, c := range template {
49+
for i, c := range template {
5150
switch {
5251
case c == '{':
53-
if enter {
52+
if keyStartPos > -1 {
5453
return "", ErrWrongSyntax{
5554
Template: template,
5655
}
5756
}
58-
enter = true
57+
keyStartPos = i
5958
case c == '}':
60-
if !enter {
59+
if keyStartPos == -1 {
6160
return "", ErrWrongSyntax{
6261
Template: template,
6362
}
6463
}
65-
if key.Len() == 0 {
64+
if i-keyStartPos <= 1 {
6665
return "", ErrWrongSyntax{
6766
Template: template,
6867
}
@@ -71,16 +70,16 @@ func Expand(template string, match map[string]string, subs ...string) (string, e
7170
if len(match) == 0 {
7271
return "", ErrNoMatchedVar{
7372
Template: template,
74-
Var: key.String(),
73+
Var: template[keyStartPos+1 : i],
7574
}
7675
}
7776

78-
v, ok := match[key.String()]
77+
v, ok := match[template[keyStartPos+1:i]]
7978
if !ok {
8079
if len(subs) == 0 {
8180
return "", ErrNoMatchedVar{
8281
Template: template,
83-
Var: key.String(),
82+
Var: template[keyStartPos+1 : i],
8483
}
8584
}
8685
v = subs[0]
@@ -89,13 +88,9 @@ func Expand(template string, match map[string]string, subs ...string) (string, e
8988
if _, err := buf.WriteString(v); err != nil {
9089
return "", err
9190
}
92-
key.Reset()
9391

94-
enter = false
95-
case enter:
96-
if _, err := key.WriteRune(c); err != nil {
97-
return "", err
98-
}
92+
keyStartPos = -1
93+
case keyStartPos > -1:
9994
default:
10095
if _, err := buf.WriteRune(c); err != nil {
10196
return "", err

0 commit comments

Comments
 (0)