Repository navigation
Expand file tree
/
Copy pathfuncs.go
More file actions
357 lines (324 loc) · 10.9 KB
/
Copy pathfuncs.go
File metadata and controls
357 lines (324 loc) · 10.9 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package xtemplate
import (
"bytes"
"fmt"
"html/template"
"io"
"reflect"
"strconv"
"strings"
"time"
chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
"github.com/dustin/go-humanize"
"github.com/microcosm-cc/bluemonday"
"github.com/yuin/goldmark"
highlighting "github.com/yuin/goldmark-highlighting/v2"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
gmhtml "github.com/yuin/goldmark/renderer/html"
"go.abhg.dev/goldmark/frontmatter"
)
var xtemplateFuncs template.FuncMap = template.FuncMap{
"sanitizeHtml": FuncSanitizeHtml,
"markdown": FuncMarkdown,
"return": FuncReturn,
"failf": FuncFailf,
"humanize": FuncHumanize,
"trustHtml": FuncTrustHtml,
"trustAttr": FuncTrustAttr,
"trustJS": FuncTrustJS,
"trustJSStr": FuncTrustJSStr,
"trustSrcSet": FuncTrustSrcSet,
"idx": FuncIdx,
"try": FuncTry,
}
// blueMondayPolicies is the map of names of bluemonday policies available to
// templates.
var blueMondayPolicies map[string]*bluemonday.Policy = map[string]*bluemonday.Policy{
"strict": bluemonday.StrictPolicy(),
"ugc": bluemonday.UGCPolicy(),
"externalugc": bluemonday.UGCPolicy().
AddTargetBlankToFullyQualifiedLinks(true).
AllowRelativeURLs(false),
}
// AddBlueMondayPolicy adds a bluemonday policy to the global policy list available to all
// xtemplate instances.
func AddBlueMondayPolicy(name string, policy *bluemonday.Policy) {
if old, ok := blueMondayPolicies[name]; ok {
panic(fmt.Sprintf("bluemonday policy with name %s already exists: %v", name, old))
}
blueMondayPolicies[name] = policy
}
// sanitizeHtml Uses the BlueMonday library to sanitize strings with html content.
// First parameter is the name of the chosen sanitization policy.
func FuncSanitizeHtml(policyName string, html string) (template.HTML, error) {
policy, ok := blueMondayPolicies[policyName]
if !ok {
return "", fmt.Errorf("failed to find policy name '%s'", policyName)
}
return template.HTML(policy.Sanitize(html)), nil
}
var mdOpts = []goldmark.Option{
goldmark.WithExtensions(
extension.GFM,
extension.Footnote,
&frontmatter.Extender{},
highlighting.NewHighlighting(
highlighting.WithFormatOptions(
chromahtml.WithClasses(true),
),
),
),
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
),
}
var markdownConfigs map[string]goldmark.Markdown = map[string]goldmark.Markdown{
"default": goldmark.New(mdOpts...),
"unsafe": goldmark.New(append(mdOpts,
goldmark.WithRendererOptions(gmhtml.WithUnsafe()),
)...),
}
// AddMarkdownConfig adds a custom markdown configuration to xtemplate's
// markdown config map, shared by all xtemplate instances.
func AddMarkdownConfig(name string, md goldmark.Markdown) {
if old, ok := markdownConfigs[name]; ok {
panic(fmt.Sprintf("markdown policy with name %s already exists: %v", name, old))
}
markdownConfigs[name] = md
}
// MarkdownDoc is the result of rendering Markdown: the decoded front matter
// metadata and the rendered HTML body.
type MarkdownDoc struct {
Meta map[string]any `json:"meta,omitempty"`
Body template.HTML `json:"body,omitempty"`
}
// markdown parses front matter out of the input and renders the remaining
// Markdown to HTML in a single pass, returning both .Meta and .Body. input may
// be a string, []byte, or io.Reader. This uses the Goldmark library, which is
// CommonMark compliant. If an alternative markdown policy is not named, it uses
// the default policy which has these extensions enabled: YAML/TOML front matter,
// Github Flavored Markdown, Footnote, and syntax highlighting provided by Chroma.
func FuncMarkdown(input any, configName ...string) (MarkdownDoc, error) {
config := "default"
switch len(configName) {
case 0:
case 1:
config = configName[0]
default:
return MarkdownDoc{}, fmt.Errorf("too many configName arguments provided: %v", configName)
}
md, ok := markdownConfigs[config]
if !ok {
return MarkdownDoc{}, fmt.Errorf("unknown markdown config name: %s", config)
}
var src []byte
switch v := input.(type) {
case string:
src = []byte(v)
case []byte:
src = v
case io.Reader:
var err error
if src, err = io.ReadAll(v); err != nil {
return MarkdownDoc{}, err
}
default:
return MarkdownDoc{}, fmt.Errorf("markdown: unsupported input type %T (want string, []byte, or io.Reader)", input)
}
buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufPool.Put(buf)
ctx := parser.NewContext()
if err := md.Convert(src, buf, parser.WithContext(ctx)); err != nil {
return MarkdownDoc{}, err
}
doc := MarkdownDoc{Body: template.HTML(buf.String())}
if d := frontmatter.Get(ctx); d != nil {
if err := d.Decode(&doc.Meta); err != nil {
return MarkdownDoc{}, err
}
}
return doc, nil
}
// return causes the template to exit early with a success status.
func FuncReturn() (string, error) {
return "", ReturnError{}
}
func FuncFailf(format string, args ...any) (string, error) {
return "", fmt.Errorf(format, args...)
}
// trustHtml marks the string s as safe and does not escape its contents in
// html node context.
func FuncTrustHtml(s string) template.HTML {
return template.HTML(s)
}
// trustAttr marks the string s as safe and does not escape its contents in
// html attribute context.
func FuncTrustAttr(s string) template.HTMLAttr {
return template.HTMLAttr(s)
}
// trustJS marks the string s as safe and does not escape its contents in
// script tag context.
func FuncTrustJS(s string) template.JS {
return template.JS(s)
}
// trustJSStr marks the string s as safe and does not escape its contents in
// script expression context.
func FuncTrustJSStr(s string) template.JSStr {
return template.JSStr(s)
}
// trustSrcSet marks the string s as safe and does not escape its contents in
// script tag context.
func FuncTrustSrcSet(s string) template.Srcset {
return template.Srcset(s)
}
// idx gets an item from a list, similar to the built-in index, but with
// reversed args: index first, then array. This is useful to use index in a
// pipeline, for example:
//
// {{generate-list | idx 5}}
//
// Returns an error if the value is not indexable or the index is out of range.
func FuncIdx(idx int, arr any) (any, error) {
v := reflect.ValueOf(arr)
switch v.Kind() {
case reflect.Array, reflect.Slice, reflect.String:
default:
return nil, fmt.Errorf("idx: cannot index value of type %T", arr)
}
if idx < 0 || idx >= v.Len() {
return nil, fmt.Errorf("idx: index %d out of range (length %d)", idx, v.Len())
}
return v.Index(idx).Interface(), nil
}
// humanize transforms size and time inputs to a human readable format using
// the go-humanize library.
//
// Call with two parameters: format type and value to format. Supported format
// types are:
//
// "size" which turns an integer amount of bytes into a string like "2.3 MB",
// for example:
//
// {{humanize "size" "2048000"}}
//
// "time" which turns a time string into a relative time string like "2 weeks
// ago", for example:
//
// {{humanize "time" "Fri, 05 May 2022 15:04:05 +0200"}}
func FuncHumanize(formatType, data string) (string, error) {
// The format type can optionally be followed
// by a colon to provide arguments for the format
parts := strings.Split(formatType, ":")
switch parts[0] {
case "size":
dataint, dataerr := strconv.ParseUint(data, 10, 64)
if dataerr != nil {
return "", fmt.Errorf("humanize: size cannot be parsed: %s", dataerr.Error())
}
return humanize.Bytes(dataint), nil
case "time":
timelayout := time.RFC1123Z
if len(parts) > 1 {
timelayout = formatType[len(parts[0])+1:]
}
dataint, dataerr := time.Parse(timelayout, data)
if dataerr != nil {
return "", fmt.Errorf("humanize: time cannot be parsed: %s", dataerr.Error())
}
return humanize.Time(dataint), nil
}
return "", fmt.Errorf("humanize: unknown format type %q (want \"size\" or \"time\")", parts[0])
}
// The try template func accepts a fallible function object and calls it with
// the provided args. If the function and args are valid, try returns the result
// wrapped in a result object that exposes the return value and error to
// templates. Useful if you want to call a function and handle its error in a
// template. If the function value is invalid or the args cannot be used to call
// it then try raises an error that stops template execution.
func FuncTry(fn any, args ...any) (*result, error) {
if fn == nil {
return nil, fmt.Errorf("nil func")
}
fnv := reflect.ValueOf(fn)
if fnv.Kind() != reflect.Func {
if len(args) == 0 {
return nil, fmt.Errorf("not callable (no method name provided)")
}
methodName, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("not callable (non-string method name)")
}
method := fnv.MethodByName(methodName)
if method.IsValid() {
fnv = method
args = args[1:]
} else {
return nil, fmt.Errorf("not callable (method not found)")
}
}
n := fnv.Type().NumOut()
if n != 1 && n != 2 {
return nil, fmt.Errorf("cannot call func that has %d outputs", n)
} else if !fnv.Type().Out(n - 1).AssignableTo(reflect.TypeOf((*error)(nil)).Elem()) {
return nil, fmt.Errorf("cannot call func whose last arg is not error")
}
reflectArgs := []reflect.Value{}
for i, a := range args {
var arg reflect.Value
if a != nil {
arg = reflect.ValueOf(a)
} else {
arg = reflect.New(fnv.Type().In(i)).Elem()
}
reflectArgs = append(reflectArgs, arg)
}
out := fnv.Call(reflectArgs)
var err error
var value any
ierr := out[n-1].Interface()
if ierr != nil {
err = ierr.(error)
}
if n > 1 {
value = out[0].Interface()
}
return &result{
Value: value,
Error: err,
}, nil
}
type result struct {
Value any
Error error
}
func (r *result) OK() bool {
return r.Error == nil
}
// Skeleton versions of the built-in functions in templates. This is needed to
// make text/template/parse.Parse parse correctly because the number of
// arguments is checked at parse time, but they are never called and the
// argument types are not checked, just their number.
var builtinsSkeleton template.FuncMap = template.FuncMap{
"and": func(any, ...any) any { return nil },
"call": func(any, ...any) (any, error) { return nil, nil },
"html": template.HTMLEscaper,
"index": func(any, ...any) (any, error) { return nil, nil },
"slice": func(any, ...any) (any, error) { return nil, nil },
"js": template.JSEscaper,
"len": func(any) (int, error) { return 0, nil },
"not": func(any) bool { return false },
"or": func(any, ...any) any { return nil },
"print": fmt.Sprint,
"printf": fmt.Sprintf,
"println": fmt.Sprintln,
"urlquery": template.URLQueryEscaper,
// Comparisons
"eq": func(any, ...any) (bool, error) { return false, nil }, // ==
"ge": func(any, ...any) (bool, error) { return false, nil }, // >=
"gt": func(any, ...any) (bool, error) { return false, nil }, // >
"le": func(any, ...any) (bool, error) { return false, nil }, // <=
"lt": func(any, ...any) (bool, error) { return false, nil }, // <
"ne": func(any, ...any) (bool, error) { return false, nil }, // !=
}