-
Notifications
You must be signed in to change notification settings - Fork 1
/
template.go
129 lines (106 loc) · 1.97 KB
/
template.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
128
129
package main
import (
"crypto/sha1"
"fmt"
"strings"
)
type Template struct {
Name string `json:"name"`
Body []byte `json:"body"`
Sha1 string `json:"sha1"`
rendered []byte
}
func NewTemplateFromKey(key string) *Template {
pp := strings.Split(key, "/")
if len(pp) > 1 {
return &Template{Name: pp[1]}
}
return nil
}
func (t *Template) SetBody(b []byte) {
t.Body = b
t.rendered = b
if t.Body != nil {
t.Sha1 = fmt.Sprintf("%x", sha1.Sum(t.Body))
}
return
}
func (t *Template) Render(m map[string]string) ([]byte, error) {
out := make([]byte, 0)
sm := -1
var i int
for i = 0; i < len(t.Body); i++ {
switch t.Body[i] {
case '$':
if t.Body[i-1] != '\\' && t.Body[i+1] == '{' {
sm = i + 2
i++
continue
}
case '}':
if t.Body[i-1] != '\\' && sm > -1 {
key := string(t.Body[sm:i])
out = append(out, []byte(m[key])...)
sm = -1
continue
}
}
if sm < 0 {
out = append(out, t.Body[i])
}
}
err := validate(out)
if err == nil {
t.rendered = out
}
return out, err
}
func (t *Template) clearRendered() {
t.rendered = t.Body
}
// Extract keys from template
func (t *Template) Keys() (map[string]bool, error) {
//func parseKeys(contents string) (map[string]bool, error) {
if err := t.Validate(); err != nil {
return nil, err
}
tkeys := map[string]bool{}
sm := -1
var i int
for i = 0; i < len(t.Body); i++ {
switch t.Body[i] {
case '$':
if t.Body[i-1] != '\\' && t.Body[i+1] == '{' {
sm = i + 2
i++
continue
}
case '}':
if t.Body[i-1] != '\\' && sm > -1 {
tkeys[string(t.Body[sm:i])] = false
sm = -1
continue
}
}
}
return tkeys, nil
}
// Validate curly braces
func (t *Template) Validate() error {
return validate(t.Body)
}
func validate(in []byte) error {
st := []byte{}
for _, v := range in {
switch v {
case '{':
st = append(st, v)
case '}':
st = st[:len(st)-1]
}
}
if len(st) != 0 {
return fmt.Errorf("missing end brace: '%s'", st)
}
return nil
}