summaryrefslogtreecommitdiffstats
path: root/modules/templates/htmlrenderer.go
blob: 55a55dd7f4bc6427a2357bb0b4f3e446d4df771c (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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package templates

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

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

type TemplateExecutor scopedtmpl.TemplateExecutor

type HTMLRender struct {
	templates atomic.Pointer[scopedtmpl.ScopedTemplate]
}

var (
	htmlRender     *HTMLRender
	htmlRenderOnce sync.Once
)

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 any, ctx context.Context) error { //nolint:revive
	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, ctx)
	if err != nil {
		return texttemplate.ExecError{Name: name, Err: err}
	}
	return t.Execute(w, data)
}

func (h *HTMLRender) TemplateLookup(name string, ctx context.Context) (TemplateExecutor, error) { //nolint:revive
	tmpls := h.templates.Load()
	if tmpls == nil {
		return nil, ErrTemplateNotInitialized
	}
	m := NewFuncMap()
	m["ctx"] = func() any { return ctx }
	return tmpls.Executor(name, m)
}

func (h *HTMLRender) CompileTemplates() error {
	assets := AssetFS()
	extSuffix := ".tmpl"
	tmpls := scopedtmpl.NewScopedTemplate()
	tmpls.Funcs(NewFuncMap())
	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))
		buf, err := assets.ReadFile(file)
		if err != nil {
			return err
		}
		if _, err = tmpl.Parse(string(buf)); err != nil {
			return err
		}
	}
	tmpls.Freeze()
	h.templates.Store(tmpls)
	return nil
}

// HTMLRenderer init once and returns the globally shared html renderer
func HTMLRenderer() *HTMLRender {
	htmlRenderOnce.Do(initHTMLRenderer)
	return htmlRender
}

func ReloadHTMLTemplates() error {
	log.Trace("Reloading HTML templates")
	if err := htmlRender.CompileTemplates(); err != nil {
		log.Error("Template error: %v\n%s", err, log.Stack(2))
		return err
	}
	return nil
}

func initHTMLRenderer() {
	rendererType := "static"
	if !setting.IsProd {
		rendererType = "auto-reloading"
	}
	log.Debug("Creating %s HTML Renderer", rendererType)

	htmlRender = &HTMLRender{}
	if err := htmlRender.CompileTemplates(); err != nil {
		p := &templateErrorPrettier{assets: AssetFS()}
		wrapTmplErrMsg(p.handleFuncNotDefinedError(err))
		wrapTmplErrMsg(p.handleUnexpectedOperandError(err))
		wrapTmplErrMsg(p.handleExpectedEndError(err))
		wrapTmplErrMsg(p.handleGenericTemplateError(err))
		wrapTmplErrMsg(fmt.Sprintf("CompileTemplates error: %v", err))
	}

	if !setting.IsProd {
		go AssetFS().WatchLocalChanges(graceful.GetManager().ShutdownContext(), func() {
			_ = ReloadHTMLTemplates()
		})
	}
}

func wrapTmplErrMsg(msg string) {
	if msg == "" {
		return
	}
	if setting.IsProd {
		// in prod mode, Forgejo must have correct templates to run
		log.Fatal("Forgejo can't run with template errors: %s", msg)
	}
	// in dev mode, do not need to really exit, because the template errors could be fixed by developer soon and the templates get reloaded
	log.Error("There are template errors but Forgejo continues to run in dev mode: %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())
	}
	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")
}