forked from open2b/scriggo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
templates.go
294 lines (275 loc) · 7.73 KB
/
templates.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
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
284
285
286
287
288
289
290
291
292
293
294
// Copyright 2019 The Scriggo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package scriggo
import (
"errors"
"fmt"
"io"
"io/fs"
"reflect"
"sort"
"github.com/open2b/scriggo/ast"
"github.com/open2b/scriggo/internal/compiler"
"github.com/open2b/scriggo/internal/runtime"
"github.com/open2b/scriggo/native"
)
// A Format represents a content format.
type Format int
// Formats.
const (
FormatText Format = iota
FormatHTML
FormatCSS
FormatJS
FormatJSON
FormatMarkdown
)
// String returns the name of the format.
func (format Format) String() string {
return ast.Format(format).String()
}
// Converter is implemented by format converters.
type Converter func(src []byte, out io.Writer) error
// Template is a template compiled with the BuildTemplate function.
type Template struct {
fn *runtime.Function
typeof runtime.TypeOfFunc
globals []compiler.Global
conv runtime.Converter
}
// FormatFS is the interface implemented by a file system that can determine
// the file format from a path name.
type FormatFS interface {
fs.FS
Format(name string) (Format, error)
}
// formatFS wraps a FormatFS value to conform to the FormatFS expected by the
// compiler.
type formatFS struct {
FormatFS
}
func (fsys formatFS) Format(name string) (ast.Format, error) {
format, err := fsys.FormatFS.Format(name)
return ast.Format(format), err
}
// formatTypes contains the format types added to the universe block.
var formatTypes = map[ast.Format]reflect.Type{
ast.FormatHTML: reflect.TypeOf((*native.HTML)(nil)).Elem(),
ast.FormatCSS: reflect.TypeOf((*native.CSS)(nil)).Elem(),
ast.FormatJS: reflect.TypeOf((*native.JS)(nil)).Elem(),
ast.FormatJSON: reflect.TypeOf((*native.JSON)(nil)).Elem(),
ast.FormatMarkdown: reflect.TypeOf((*native.Markdown)(nil)).Elem(),
}
// BuildTemplate builds the named template file rooted at the given file
// system. Imported, rendered and extended files are read from fsys.
//
// If fsys implements FormatFS, file formats are read with its Format method,
// otherwise it depends on the file name extension
//
// HTML : .html
// CSS : .css
// JavaScript : .js
// JSON : .json
// Markdown : .md .mkd .mkdn .mdown .markdown
// Text : all other extensions
//
// If the named file does not exist, BuildTemplate returns an error satisfying
// errors.Is(err, fs.ErrNotExist).
//
// If a build error occurs, it returns a *BuildError.
func BuildTemplate(fsys fs.FS, name string, options *BuildOptions) (*Template, error) {
if f, ok := fsys.(FormatFS); ok {
fsys = formatFS{f}
}
co := compiler.Options{
FormatTypes: formatTypes,
}
var conv Converter
if options != nil {
co.Globals = options.Globals
co.TreeTransformer = options.TreeTransformer
co.AllowGoStmt = options.AllowGoStmt
co.NoParseShortShowStmt = options.NoParseShortShowStmt
co.Importer = options.Packages
co.MDConverter = compiler.Converter(options.MarkdownConverter)
conv = options.MarkdownConverter
}
code, err := compiler.BuildTemplate(fsys, name, co)
if err != nil {
if e, ok := err.(compiler.Error); ok {
err = &BuildError{err: e}
}
return nil, err
}
return &Template{fn: code.Main, typeof: code.TypeOf, globals: code.Globals, conv: runtime.Converter(conv)}, nil
}
// Run runs the template and write the rendered code to out. vars contains
// the values of the global variables. It can be called concurrently by
// multiple goroutines.
//
// If the executed template panics, and it is not recovered, Run returns a
// *PanicError.
//
// If the Stop method of native.Env is called, Run returns the argument passed
// to Stop.
//
// If the Fatal method of native.Env is called, Run panics with the argument
// passed to Fatal.
//
// If the context has been canceled, Run returns the error returned by the Err
// method of the context.
//
// If a call to out.Write returns an error, a panic occurs. If the executed
// code does not recover the panic, Run returns the error returned by
// out.Write.
func (t *Template) Run(out io.Writer, vars map[string]interface{}, options *RunOptions) error {
if out == nil {
return errors.New("invalid nil out")
}
vm := runtime.NewVM()
if options != nil {
if options.Context != nil {
vm.SetContext(options.Context)
}
if options.Print != nil {
vm.SetPrint(runtime.PrintFunc(options.Print))
}
}
vm.SetRenderer(out, t.conv)
err := vm.Run(t.fn, t.typeof, initGlobalVariables(t.globals, vars))
if err != nil {
if p, ok := err.(*runtime.PanicError); ok {
err = &PanicError{p}
}
return err
}
return nil
}
// Disassemble disassembles a template and returns its assembly code.
//
// n determines the maximum length, in runes, of a disassembled text:
//
// n > 0: at most n runes; leading and trailing white space are removed
// n == 0: no text
// n < 0: all text
func (t *Template) Disassemble(n int) []byte {
assemblies := compiler.Disassemble(t.fn, t.globals, n)
return assemblies["main"]
}
// UsedVars returns the names of the global variables used in the template.
// A variable used in dead code may not be returned as used.
func (t *Template) UsedVars() []string {
vars := make([]string, len(t.globals))
for i, global := range t.globals {
vars[i] = global.Name
}
sort.Strings(vars)
return vars
}
var emptyInit = map[string]interface{}{}
// initGlobalVariables initializes the global variables and returns their
// values. It panics if init is not valid.
func initGlobalVariables(variables []compiler.Global, init map[string]interface{}) []reflect.Value {
n := len(variables)
if n == 0 {
return nil
}
if init == nil {
init = emptyInit
}
values := make([]reflect.Value, n)
for i, variable := range variables {
if variable.Pkg == "main" {
if value, ok := init[variable.Name]; ok {
if variable.Value.IsValid() {
panic(fmt.Sprintf("variable %q already initialized", variable.Name))
}
if value == nil {
panic(fmt.Sprintf("variable initializer %q cannot be nil", variable.Name))
}
val := reflect.ValueOf(value)
if typ := val.Type(); typ == variable.Type {
v := reflect.New(typ).Elem()
v.Set(val)
values[i] = v
} else {
if typ.Kind() != reflect.Ptr || typ.Elem() != variable.Type {
panic(fmt.Sprintf("variable initializer %q must have type %s or %s, but have %s",
variable.Name, variable.Type, reflect.PtrTo(variable.Type), typ))
}
if val.IsNil() {
panic(fmt.Sprintf("variable initializer %q cannot be a nil pointer", variable.Name))
}
values[i] = reflect.ValueOf(value).Elem()
}
continue
}
}
if variable.Value.IsValid() {
values[i] = variable.Value
} else {
values[i] = reflect.New(variable.Type).Elem()
}
}
return values
}
// HTMLEscape escapes s, replacing the characters <, >, &, " and ' and returns
// the escaped string as HTML type.
//
// Use HTMLEscape to put a trusted or untrusted string into an HTML element
// content or in a quoted attribute value. But don't use it with complex
// attributes like href, src, style, or any of the event handlers like
// onmouseover.
func HTMLEscape(s string) native.HTML {
n := 0
j := 0
for i := 0; i < len(s); i++ {
switch s[i] {
case '"', '\'', '&':
n += 4
case '<', '>':
n += 3
default:
continue
}
if n <= 4 {
j = i
}
}
if n == 0 {
return native.HTML(s)
}
b := make([]byte, len(s)+n)
if j > 0 {
copy(b[:j], s[:j])
}
for i := j; i < len(s); i++ {
switch c := s[i]; c {
case '"':
copy(b[j:], """)
j += 5
case '\'':
copy(b[j:], "'")
j += 5
case '&':
copy(b[j:], "&")
j += 5
case '<':
copy(b[j:], "<")
j += 4
case '>':
copy(b[j:], ">")
j += 4
default:
b[j] = c
j++
continue
}
if j == i+n {
copy(b[j:], s[i:])
break
}
}
return native.HTML(b)
}