aboutsummaryrefslogtreecommitdiffstats
path: root/modules/templates/htmlrenderer.go
blob: 833c2acdca6ae174ac59562ee2a509c893f09d97 (plain)
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
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package templates

import (
	"bufio"
	"bytes"
	"context"
	"errors"
	"fmt"
	"html/template"
	"io"
	"net/http"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"sync/atomic"
	texttemplate "text/template"

	"code.gitea.io/gitea/modules/assetfs"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/util"
)

var rendererKey interface{} = "templatesHtmlRenderer"

type HTMLRender struct {
	templates atomic.Pointer[template.Template]
}

var ErrTemplateNotInitialized = errors.New("template system is not initialized, check your log for errors")

func (h *HTMLRender) HTML(w io.Writer, status int, name string, data interface{}) error {
	if respWriter, ok := w.(http.ResponseWriter); ok {
		if respWriter.Header().Get("Content-Type") == "" {
			respWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
		}
		respWriter.WriteHeader(status)
	}
	t, err := h.TemplateLookup(name)
	if err != nil {
		return texttemplate.ExecError{Name: name, Err: err}
	}
	return t.Execute(w, data)
}

func (h *HTMLRender) TemplateLookup(name string) (*template.Template, error) {
	tmpls := h.templates.Load()
	if tmpls == nil {
		return nil, ErrTemplateNotInitialized
	}
	tmpl := tmpls.Lookup(name)
	if tmpl == nil {
		return nil, util.ErrNotExist
	}
	return tmpl, nil
}

func (h *HTMLRender) CompileTemplates() error {
	extSuffix := ".tmpl"
	tmpls := template.New("")
	assets := AssetFS()
	files, err := ListWebTemplateAssetNames(assets)
	if err != nil {
		return nil
	}
	for _, file := range files {
		if !strings.HasSuffix(file, extSuffix) {
			continue
		}
		name := strings.TrimSuffix(file, extSuffix)
		tmpl := tmpls.New(filepath.ToSlash(name))
		for _, fm := range NewFuncMap() {
			tmpl.Funcs(fm)
		}
		buf, err := assets.ReadFile(file)
		if err != nil {
			return err
		}
		if _, err = tmpl.Parse(string(buf)); err != nil {
			return err
		}
	}
	h.templates.Store(tmpls)
	return nil
}

// HTMLRenderer returns the current html renderer for the context or creates and stores one within the context for future use
func HTMLRenderer(ctx context.Context) (context.Context, *HTMLRender) {
	if renderer, ok := ctx.Value(rendererKey).(*HTMLRender); ok {
		return ctx, renderer
	}

	rendererType := "static"
	if !setting.IsProd {
		rendererType = "auto-reloading"
	}
	log.Log(1, log.DEBUG, "Creating "+rendererType+" HTML Renderer")

	renderer := &HTMLRender{}
	if err := renderer.CompileTemplates(); err != nil {
		p := &templateErrorPrettier{assets: AssetFS()}
		wrapFatal(p.handleFuncNotDefinedError(err))
		wrapFatal(p.handleUnexpectedOperandError(err))
		wrapFatal(p.handleExpectedEndError(err))
		wrapFatal(p.handleGenericTemplateError(err))
		log.Fatal("HTMLRenderer CompileTemplates error: %v", err)
	}
	if !setting.IsProd {
		go AssetFS().WatchLocalChanges(ctx, func() {
			if err := renderer.CompileTemplates(); err != nil {
				log.Error("Template error: %v\n%s", err, log.Stack(2))
			}
		})
	}
	return context.WithValue(ctx, rendererKey, renderer), renderer
}

func wrapFatal(msg string) {
	if msg == "" {
		return
	}
	log.FatalWithSkip(1, "Unable to compile templates, %s", msg)
}

type templateErrorPrettier struct {
	assets *assetfs.LayeredFS
}

var reGenericTemplateError = regexp.MustCompile(`^template: (.*):([0-9]+): (.*)`)

func (p *templateErrorPrettier) handleGenericTemplateError(err error) string {
	groups := reGenericTemplateError.FindStringSubmatch(err.Error())
	if len(groups) != 4 {
		return ""
	}
	tmplName, lineStr, message := groups[1], groups[2], groups[3]
	return p.makeDetailedError(message, tmplName, lineStr, -1, "")
}

var reFuncNotDefinedError = regexp.MustCompile(`^template: (.*):([0-9]+): (function "(.*)" not defined)`)

func (p *templateErrorPrettier) handleFuncNotDefinedError(err error) string {
	groups := reFuncNotDefinedError.FindStringSubmatch(err.Error())
	if len(groups) != 5 {
		return ""
	}
	tmplName, lineStr, message, funcName := groups[1], groups[2], groups[3], groups[4]
	funcName, _ = strconv.Unquote(`"` + funcName + `"`)
	return p.makeDetailedError(message, tmplName, lineStr, -1, funcName)
}

var reUnexpectedOperandError = regexp.MustCompile(`^template: (.*):([0-9]+): (unexpected "(.*)" in operand)`)

func (p *templateErrorPrettier) handleUnexpectedOperandError(err error) string {
	groups := reUnexpectedOperandError.FindStringSubmatch(err.Error())
	if len(groups) != 5 {
		return ""
	}
	tmplName, lineStr, message, unexpected := groups[1], groups[2], groups[3], groups[4]
	unexpected, _ = strconv.Unquote(`"` + unexpected + `"`)
	return p.makeDetailedError(message, tmplName, lineStr, -1, unexpected)
}

var reExpectedEndError = regexp.MustCompile(`^template: (.*):([0-9]+): (expected end; found (.*))`)

func (p *templateErrorPrettier) handleExpectedEndError(err error) string {
	groups := reExpectedEndError.FindStringSubmatch(err.Error())
	if len(groups) != 5 {
		return ""
	}
	tmplName, lineStr, message, unexpected := groups[1], groups[2], groups[3], groups[4]
	return p.makeDetailedError(message, tmplName, lineStr, -1, unexpected)
}

var (
	reTemplateExecutingError    = regexp.MustCompile(`^template: (.*):([1-9][0-9]*):([1-9][0-9]*): (executing .*)`)
	reTemplateExecutingErrorMsg = regexp.MustCompile(`^executing "(.*)" at <(.*)>: `)
)

func (p *templateErrorPrettier) handleTemplateRenderingError(err error) string {
	if groups := reTemplateExecutingError.FindStringSubmatch(err.Error()); len(groups) > 0 {
		tmplName, lineStr, posStr, msgPart := groups[1], groups[2], groups[3], groups[4]
		target := ""
		if groups = reTemplateExecutingErrorMsg.FindStringSubmatch(msgPart); len(groups) > 0 {
			target = groups[2]
		}
		return p.makeDetailedError(msgPart, tmplName, lineStr, posStr, target)
	} else if execErr, ok := err.(texttemplate.ExecError); ok {
		layerName := p.assets.GetFileLayerName(execErr.Name + ".tmpl")
		return fmt.Sprintf("asset from: %s, %s", layerName, err.Error())
	} else {
		return err.Error()
	}
}

func HandleTemplateRenderingError(err error) string {
	p := &templateErrorPrettier{assets: AssetFS()}
	return p.handleTemplateRenderingError(err)
}

const dashSeparator = "----------------------------------------------------------------------"

func (p *templateErrorPrettier) makeDetailedError(errMsg, tmplName string, lineNum, posNum any, target string) string {
	code, layer, err := p.assets.ReadLayeredFile(tmplName + ".tmpl")
	if err != nil {
		return fmt.Sprintf("template error: %s, and unable to find template file %q", errMsg, tmplName)
	}
	line, err := util.ToInt64(lineNum)
	if err != nil {
		return fmt.Sprintf("template error: %s, unable to parse template %q line number %q", errMsg, tmplName, lineNum)
	}
	pos, err := util.ToInt64(posNum)
	if err != nil {
		return fmt.Sprintf("template error: %s, unable to parse template %q pos number %q", errMsg, tmplName, posNum)
	}
	detail := extractErrorLine(code, int(line), int(pos), target)

	var msg string
	if pos >= 0 {
		msg = fmt.Sprintf("template error: %s:%s:%d:%d : %s", layer, tmplName, line, pos, errMsg)
	} else {
		msg = fmt.Sprintf("template error: %s:%s:%d : %s", layer, tmplName, line, errMsg)
	}
	return msg + "\n" + dashSeparator + "\n" + detail + "\n" + dashSeparator
}

func extractErrorLine(code []byte, lineNum, posNum int, target string) string {
	b := bufio.NewReader(bytes.NewReader(code))
	var line []byte
	var err error
	for i := 0; i < lineNum; i++ {
		if line, err = b.ReadBytes('\n'); err != nil {
			if i == lineNum-1 && errors.Is(err, io.EOF) {
				err = nil
			}
			break
		}
	}
	if err != nil {
		return fmt.Sprintf("unable to find target line %d", lineNum)
	}

	line = bytes.TrimRight(line, "\r\n")
	var indicatorLine []byte
	targetBytes := []byte(target)
	targetLen := len(targetBytes)
	for i := 0; i < len(line); {
		if posNum == -1 && target != "" && bytes.HasPrefix(line[i:], targetBytes) {
			for j := 0; j < targetLen && i < len(line); j++ {
				indicatorLine = append(indicatorLine, '^')
				i++
			}
		} else if i == posNum {
			indicatorLine = append(indicatorLine, '^')
			i++
		} else {
			if line[i] == '\t' {
				indicatorLine = append(indicatorLine, '\t')
			} else {
				indicatorLine = append(indicatorLine, ' ')
			}
			i++
		}
	}
	// if the indicatorLine only contains spaces, trim it together
	return strings.TrimRight(string(line)+"\n"+string(indicatorLine), " \t\r\n")
}