summaryrefslogtreecommitdiffstats
path: root/modules/templates/htmlrenderer.go
blob: 81ea66016140ed1da7e673210ca2383e755bf722 (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
// Copyright 2022 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package templates

import (
	"bytes"
	"context"
	"fmt"
	"regexp"
	"strconv"
	"strings"

	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/watcher"

	"github.com/unrolled/render"
)

var (
	rendererKey interface{} = "templatesHtmlRenderer"

	templateError    = regexp.MustCompile(`^template: (.*):([0-9]+): (.*)`)
	notDefinedError  = regexp.MustCompile(`^template: (.*):([0-9]+): function "(.*)" not defined`)
	unexpectedError  = regexp.MustCompile(`^template: (.*):([0-9]+): unexpected "(.*)" in operand`)
	expectedEndError = regexp.MustCompile(`^template: (.*):([0-9]+): expected end; found (.*)`)
)

// 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, *render.Render) {
	rendererInterface := ctx.Value(rendererKey)
	if rendererInterface != nil {
		renderer, ok := rendererInterface.(*render.Render)
		if ok {
			return ctx, renderer
		}
	}

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

	compilingTemplates := true
	defer func() {
		if !compilingTemplates {
			return
		}

		panicked := recover()
		if panicked == nil {
			return
		}

		// OK try to handle the panic...
		err, ok := panicked.(error)
		if ok {
			handlePanicError(err)
		}
		log.Fatal("PANIC: Unable to compile templates!\n%v\n\nStacktrace:\n%s", panicked, log.Stack(2))
	}()

	renderer := render.New(render.Options{
		Extensions:                []string{".tmpl"},
		Directory:                 "templates",
		Funcs:                     NewFuncMap(),
		Asset:                     GetAsset,
		AssetNames:                GetTemplateAssetNames,
		UseMutexLock:              !setting.IsProd,
		IsDevelopment:             false,
		DisableHTTPErrorRendering: true,
	})
	compilingTemplates = false
	if !setting.IsProd {
		watcher.CreateWatcher(ctx, "HTML Templates", &watcher.CreateWatcherOpts{
			PathsCallback:   walkTemplateFiles,
			BetweenCallback: renderer.CompileTemplates,
		})
	}
	return context.WithValue(ctx, rendererKey, renderer), renderer
}

func handlePanicError(err error) {
	wrapFatal(handleNotDefinedPanicError(err))
	wrapFatal(handleUnexpected(err))
	wrapFatal(handleExpectedEnd(err))
	wrapFatal(handleGenericTemplateError(err))
}

func wrapFatal(format string, args []interface{}) {
	if format == "" {
		return
	}
	log.FatalWithSkip(1, format, args...)
}

func handleGenericTemplateError(err error) (string, []interface{}) {
	groups := templateError.FindStringSubmatch(err.Error())
	if len(groups) != 4 {
		return "", nil
	}

	templateName, lineNumberStr, message := groups[1], groups[2], groups[3]

	filename, assetErr := GetAssetFilename("templates/" + templateName + ".tmpl")
	if assetErr != nil {
		return "", nil
	}

	lineNumber, _ := strconv.Atoi(lineNumberStr)

	line := getLineFromAsset(templateName, lineNumber, "")

	return "PANIC: Unable to compile templates!\n%s in template file %s at line %d:\n\n%s\nStacktrace:\n\n%s", []interface{}{message, filename, lineNumber, log.NewColoredValue(line, log.Reset), log.Stack(2)}
}

func handleNotDefinedPanicError(err error) (string, []interface{}) {
	groups := notDefinedError.FindStringSubmatch(err.Error())
	if len(groups) != 4 {
		return "", nil
	}

	templateName, lineNumberStr, functionName := groups[1], groups[2], groups[3]

	functionName, _ = strconv.Unquote(`"` + functionName + `"`)

	filename, assetErr := GetAssetFilename("templates/" + templateName + ".tmpl")
	if assetErr != nil {
		return "", nil
	}

	lineNumber, _ := strconv.Atoi(lineNumberStr)

	line := getLineFromAsset(templateName, lineNumber, functionName)

	return "PANIC: Unable to compile templates!\nUndefined function %q in template file %s at line %d:\n\n%s", []interface{}{functionName, filename, lineNumber, log.NewColoredValue(line, log.Reset)}
}

func handleUnexpected(err error) (string, []interface{}) {
	groups := unexpectedError.FindStringSubmatch(err.Error())
	if len(groups) != 4 {
		return "", nil
	}

	templateName, lineNumberStr, unexpected := groups[1], groups[2], groups[3]
	unexpected, _ = strconv.Unquote(`"` + unexpected + `"`)

	filename, assetErr := GetAssetFilename("templates/" + templateName + ".tmpl")
	if assetErr != nil {
		return "", nil
	}

	lineNumber, _ := strconv.Atoi(lineNumberStr)

	line := getLineFromAsset(templateName, lineNumber, unexpected)

	return "PANIC: Unable to compile templates!\nUnexpected %q in template file %s at line %d:\n\n%s", []interface{}{unexpected, filename, lineNumber, log.NewColoredValue(line, log.Reset)}
}

func handleExpectedEnd(err error) (string, []interface{}) {
	groups := expectedEndError.FindStringSubmatch(err.Error())
	if len(groups) != 4 {
		return "", nil
	}

	templateName, lineNumberStr, unexpected := groups[1], groups[2], groups[3]

	filename, assetErr := GetAssetFilename("templates/" + templateName + ".tmpl")
	if assetErr != nil {
		return "", nil
	}

	lineNumber, _ := strconv.Atoi(lineNumberStr)

	line := getLineFromAsset(templateName, lineNumber, unexpected)

	return "PANIC: Unable to compile templates!\nMissing end with unexpected %q in template file %s at line %d:\n\n%s", []interface{}{unexpected, filename, lineNumber, log.NewColoredValue(line, log.Reset)}
}

const dashSeparator = "----------------------------------------------------------------------\n"

func getLineFromAsset(templateName string, targetLineNum int, target string) string {
	bs, err := GetAsset("templates/" + templateName + ".tmpl")
	if err != nil {
		return fmt.Sprintf("(unable to read template file: %v)", err)
	}

	sb := &strings.Builder{}

	// Write the header
	sb.WriteString(dashSeparator)

	var lineBs []byte

	// Iterate through the lines from the asset file to find the target line
	for start, currentLineNum := 0, 1; currentLineNum <= targetLineNum && start < len(bs); currentLineNum++ {
		// Find the next new line
		end := bytes.IndexByte(bs[start:], '\n')

		// adjust the end to be a direct pointer in to []byte
		if end < 0 {
			end = len(bs)
		} else {
			end += start
		}

		// set lineBs to the current line []byte
		lineBs = bs[start:end]

		// move start to after the current new line position
		start = end + 1

		// Write 2 preceding lines + the target line
		if targetLineNum-currentLineNum < 3 {
			_, _ = sb.Write(lineBs)
			_ = sb.WriteByte('\n')
		}
	}

	// If there is a provided target to look for in the line add a pointer to it
	// e.g.                                                        ^^^^^^^
	if target != "" {
		idx := bytes.Index(lineBs, []byte(target))

		if idx >= 0 {
			// take the current line and replace preceding text with whitespace (except for tab)
			for i := range lineBs[:idx] {
				if lineBs[i] != '\t' {
					lineBs[i] = ' '
				}
			}

			// write the preceding "space"
			_, _ = sb.Write(lineBs[:idx])

			// Now write the ^^ pointer
			_, _ = sb.WriteString(strings.Repeat("^", len(target)))
			_ = sb.WriteByte('\n')
		}
	}

	// Finally write the footer
	sb.WriteString(dashSeparator)

	return sb.String()
}