-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathengine.go
More file actions
283 lines (236 loc) · 5.62 KB
/
engine.go
File metadata and controls
283 lines (236 loc) · 5.62 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package mold
import (
_ "embed"
"fmt"
"html/template"
"io"
"io/fs"
"path/filepath"
"strings"
)
// defaults
var (
//go:embed layout.html
defaultLayout string
// default filename extenstions for template files
defaultExts = []string{"html", "gohtml", "tpl", "tmpl"}
)
const (
// sections
bodySection = "body"
headSection = "head"
)
type (
templateSet map[string]*template.Template
moldEngine templateSet
)
func newEngine(fsys fs.FS, options ...Option) (Engine, error) {
c := Config{
fs: fsys,
}
if err := setup(&c, options...); err != nil {
return nil, fmt.Errorf("error creating new engine: %w", err)
}
m := moldEngine{}
// traverse to fetch all templates and populate the root template.
root, ts, err := walk(c.fs, c.exts.val, c.funcMap.val)
if err != nil {
return nil, fmt.Errorf("error creating new engine: %w", err)
}
// process layout
layout, err := parseLayout(root, c.layoutFile, c.funcMap.val)
if err != nil {
return nil, fmt.Errorf("error parsing layout: %w", err)
}
// process views
for _, t := range ts {
// ignore layout file
if t.name == c.layoutFile.name {
continue
}
view, err := parseView(root, layout, t.name, t.body)
if err != nil {
return nil, err
}
m[t.name] = view
}
return m, nil
}
// Render implements Layout.
func (m moldEngine) Render(w io.Writer, view string, data any) error {
layout, ok := m[view]
if !ok {
return ErrNotFound
}
if err := layout.Execute(w, data); err != nil {
return fmt.Errorf("error rendering '%s': %w", view, err)
}
return nil
}
func walk(fsys fs.FS, exts []string, funcMap template.FuncMap) (root templateSet, ts []templateFile, err error) {
root = templateSet{}
err = fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
// skip hidden files and directories.
if strings.HasPrefix(d.Name(), ".") && d.Name() != "." {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
if d.IsDir() {
return nil
}
ext := filepath.Ext(d.Name())
if !validExt(exts, ext) {
return nil
}
f, err := readFile(fsys, path)
if err != nil {
return err
}
if t, err := template.New(path).Funcs(funcMap).Parse(f); err != nil {
return fmt.Errorf("error parsing template '%s': %w", path, err)
} else {
root[path] = t
ts = append(ts, templateFile{name: path, body: f})
}
return nil
})
return
}
func setup(c *Config, options ...Option) error {
// apply options
for _, opt := range options {
opt(c)
}
// root
if c.root.set {
sub, err := fs.Sub(c.fs, c.root.val)
if err != nil {
return fmt.Errorf("error setting subdirectory '%s': %w", c.root.val, err)
}
c.fs = sub
}
// layout
if c.layout.set {
f, err := readFile(c.fs, c.layout.val)
if err != nil {
return fmt.Errorf("error reading layout file '%s': %w", c.layout.val, err)
}
c.layoutFile.body = f
c.layoutFile.name = c.layout.val
} else {
c.layoutFile.body = defaultLayout
c.layoutFile.name = "default_layout"
}
// extensions
if !c.exts.set {
c.exts.update(defaultExts)
}
// funcMap
funcMap := placeholderFuncs()
if c.funcMap.set {
for k, f := range c.funcMap.val {
funcMap[k] = f
}
}
c.funcMap.update(funcMap)
return nil
}
func parseLayout(root templateSet, t templateFile, funcMap template.FuncMap) (*template.Template, error) {
layout, err := template.New("layout").Funcs(funcMap).Parse(t.body)
if err != nil {
return nil, err
}
// process template tree for layout
refs, err := processTree(layout, t.body, true, true)
if err != nil {
return nil, fmt.Errorf("error processing layout: %w", err)
}
for _, ref := range refs {
t := root[ref.name]
if t == nil {
if ref.typ == partialFunc {
return nil, fmt.Errorf("error parsing template '%s': %w", ref.name, ErrNotFound)
}
t, _ = template.New(ref.name).Parse("")
}
layout.AddParseTree(ref.name, t.Tree)
}
return layout, nil
}
func parseView(root templateSet, layout *template.Template, name, raw string) (*template.Template, error) {
view, err := layout.Clone()
if err != nil {
return nil, fmt.Errorf("error creating layout for view '%s': %w", name, err)
}
body := root[name]
if body == nil {
return nil, ErrNotFound
}
// process template tree for body
refs, err := processTree(body, raw, false, true)
if err != nil {
return nil, fmt.Errorf("error parsing view '%s': %w", name, err)
}
for _, ref := range refs {
t := root[ref.name]
if t == nil {
return nil, fmt.Errorf("error parsing template '%s': %w", ref.name, ErrNotFound)
}
view.AddParseTree(ref.name, t.Tree)
}
// add defined templates to the layout
for _, t := range body.Templates() {
tName := t.Name()
if tName == name {
tName = bodySection
}
view.AddParseTree(tName, t.Tree)
}
return view, nil
}
func readFile(fsys fs.FS, name string) (string, error) {
f, err := fs.ReadFile(fsys, name)
if err != nil {
return "", fmt.Errorf("error reading file: %w", err)
}
return string(f), nil
}
func validExt(exts []string, ext string) bool {
if ext == "" {
return false
}
sanitize := func(ext string) string {
return strings.ToLower(strings.TrimPrefix(ext, "."))
}
for _, e := range exts {
if sanitize(e) == sanitize(ext) {
return true
}
}
return false
}
func placeholderFuncs() template.FuncMap {
return map[string]any{
renderFunc.String(): func(...string) string { return "" },
partialFunc.String(): func(string, ...any) string { return "" },
}
}
type templateFile struct {
name string
body string
}
type optionVal[T any] struct {
val T
set bool
}
func newVal[T any](val T) optionVal[T] {
return optionVal[T]{val: val, set: true}
}
func (o *optionVal[T]) update(val T) {
o.val = val
}