2018-09-29 17:33:54 +09:00
|
|
|
// Copyright 2018 The Gitea Authors. All rights reserved.
|
2014-04-11 03:20:58 +09:00
|
|
|
// Copyright 2014 The Gogs Authors. All rights reserved.
|
2022-11-28 03:20:29 +09:00
|
|
|
// SPDX-License-Identifier: MIT
|
2014-04-11 03:20:58 +09:00
|
|
|
|
2016-12-07 02:58:31 +09:00
|
|
|
package templates
|
2014-04-11 03:20:58 +09:00
|
|
|
|
|
|
|
import (
|
2022-01-20 08:26:57 +09:00
|
|
|
"context"
|
2014-04-11 03:20:58 +09:00
|
|
|
"fmt"
|
2018-02-27 16:09:18 +09:00
|
|
|
"html"
|
2014-04-11 03:20:58 +09:00
|
|
|
"html/template"
|
2017-11-28 18:43:51 +09:00
|
|
|
"net/url"
|
2014-04-11 03:20:58 +09:00
|
|
|
"strings"
|
|
|
|
"time"
|
2014-05-26 09:11:25 +09:00
|
|
|
|
2022-10-17 08:29:26 +09:00
|
|
|
system_model "code.gitea.io/gitea/models/system"
|
2016-11-11 01:24:48 +09:00
|
|
|
"code.gitea.io/gitea/modules/base"
|
2020-04-29 03:05:39 +09:00
|
|
|
"code.gitea.io/gitea/modules/emoji"
|
2017-09-17 02:17:57 +09:00
|
|
|
"code.gitea.io/gitea/modules/markup"
|
2016-11-11 01:24:48 +09:00
|
|
|
"code.gitea.io/gitea/modules/setting"
|
2020-07-12 18:10:56 +09:00
|
|
|
"code.gitea.io/gitea/modules/svg"
|
Use a general Eval function for expressions in templates. (#23927)
One of the proposals in #23328
This PR introduces a simple expression calculator
(templates/eval/eval.go), it can do basic expression calculations.
Many untested template helper functions like `Mul` `Add` can be replaced
by this new approach.
Then these `Add` / `Mul` / `percentage` / `Subtract` / `DiffStatsWidth`
could all use this `Eval`.
And it provides enhancements for Golang templates, and improves
readability.
Some examples:
----
* Before: `{{Add (Mul $glyph.Row 12) 12}}`
* After: `{{Eval $glyph.Row "*" 12 "+" 12}}`
----
* Before: `{{if lt (Add $i 1) (len $.Topics)}}`
* After: `{{if Eval $i "+" 1 "<" (len $.Topics)}}`
## FAQ
### Why not use an existing expression package?
We need a highly customized expression engine:
* do the calculation on the fly, without pre-compiling
* deal with int/int64/float64 types, to make the result could be used in
Golang template.
* make the syntax could be used in the Golang template directly
* do not introduce too much complex or strange syntax, we just need a
simple calculator.
* it needs to strictly follow Golang template's behavior, for example,
Golang template treats all non-zero values as truth, but many 3rd
packages don't do so.
### What's the benefit?
* Developers don't need to add more `Add`/`Mul`/`Sub`-like functions,
they were getting more and more.
Now, only one `Eval` is enough for all cases.
* The new code reads better than old `{{Add (Mul $glyph.Row 12) 12}}`,
the old one isn't familiar to most procedural programming developers
(eg, the Golang expression syntax).
* The `Eval` is fully covered by tests, many old `Add`/`Mul`-like
functions were never tested.
### The performance?
It doesn't use `reflect`, it doesn't need to parse or compile when used
in Golang template, the performance is as fast as native Go template.
### Is it too complex? Could it be unstable?
The expression calculator program is a common homework for computer
science students, and it's widely used as a teaching and practicing
purpose for developers. The algorithm is pretty well-known.
The behavior can be clearly defined, it is stable.
2023-04-07 22:25:49 +09:00
|
|
|
"code.gitea.io/gitea/modules/templates/eval"
|
2019-08-15 23:46:21 +09:00
|
|
|
"code.gitea.io/gitea/modules/timeutil"
|
|
|
|
"code.gitea.io/gitea/modules/util"
|
2019-09-06 11:20:09 +09:00
|
|
|
"code.gitea.io/gitea/services/gitdiff"
|
2014-04-11 03:20:58 +09:00
|
|
|
)
|
|
|
|
|
2016-11-25 15:23:48 +09:00
|
|
|
// NewFuncMap returns functions for injecting to templates
|
2023-04-30 21:22:23 +09:00
|
|
|
func NewFuncMap() template.FuncMap {
|
|
|
|
return map[string]interface{}{
|
2023-04-29 21:02:29 +09:00
|
|
|
"DumpVar": dumpVar,
|
|
|
|
|
2023-04-08 22:15:22 +09:00
|
|
|
// -----------------------------------------------------------------
|
|
|
|
// html/template related functions
|
|
|
|
"dict": dict, // it's lowercase because this name has been widely used. Our other functions should have uppercase names.
|
|
|
|
"Eval": Eval,
|
|
|
|
"Safe": Safe,
|
|
|
|
"Escape": html.EscapeString,
|
|
|
|
"QueryEscape": url.QueryEscape,
|
|
|
|
"JSEscape": template.JSEscapeString,
|
|
|
|
"Str2html": Str2html, // TODO: rename it to SanitizeHTML
|
|
|
|
"URLJoin": util.URLJoin,
|
2023-04-29 21:02:29 +09:00
|
|
|
"DotEscape": DotEscape,
|
2023-04-08 22:15:22 +09:00
|
|
|
|
|
|
|
"PathEscape": url.PathEscape,
|
|
|
|
"PathEscapeSegments": util.PathEscapeSegments,
|
|
|
|
|
2023-04-23 03:16:22 +09:00
|
|
|
// utils
|
|
|
|
"StringUtils": NewStringUtils,
|
|
|
|
"SliceUtils": NewSliceUtils,
|
2023-04-29 21:02:29 +09:00
|
|
|
"JsonUtils": NewJsonUtils,
|
2023-04-08 22:15:22 +09:00
|
|
|
|
|
|
|
// -----------------------------------------------------------------
|
|
|
|
// svg / avatar / icon
|
|
|
|
"svg": svg.RenderHTML,
|
|
|
|
"avatar": Avatar,
|
|
|
|
"avatarHTML": AvatarHTML,
|
|
|
|
"avatarByAction": AvatarByAction,
|
|
|
|
"avatarByEmail": AvatarByEmail,
|
|
|
|
"repoAvatar": RepoAvatar,
|
|
|
|
"EntryIcon": base.EntryIcon,
|
|
|
|
"MigrationIcon": MigrationIcon,
|
|
|
|
"ActionIcon": ActionIcon,
|
|
|
|
|
2023-04-29 21:02:29 +09:00
|
|
|
"SortArrow": SortArrow,
|
2023-04-08 22:15:22 +09:00
|
|
|
|
|
|
|
// -----------------------------------------------------------------
|
|
|
|
// time / number / format
|
|
|
|
"FileSize": base.FileSize,
|
|
|
|
"CountFmt": base.FormatNumberSI,
|
|
|
|
"TimeSince": timeutil.TimeSince,
|
|
|
|
"TimeSinceUnix": timeutil.TimeSinceUnix,
|
2023-04-24 04:12:33 +09:00
|
|
|
"DateTime": timeutil.DateTime,
|
2023-04-08 22:15:22 +09:00
|
|
|
"Sec2Time": util.SecToTime,
|
|
|
|
"LoadTimes": func(startTime time.Time) string {
|
|
|
|
return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
|
|
|
|
},
|
|
|
|
|
|
|
|
// -----------------------------------------------------------------
|
|
|
|
// setting
|
2016-03-07 06:40:04 +09:00
|
|
|
"AppName": func() string {
|
|
|
|
return setting.AppName
|
|
|
|
},
|
|
|
|
"AppSubUrl": func() string {
|
2016-11-27 19:14:25 +09:00
|
|
|
return setting.AppSubURL
|
2016-03-07 06:40:04 +09:00
|
|
|
},
|
2021-05-08 23:27:25 +09:00
|
|
|
"AssetUrlPrefix": func() string {
|
2021-04-28 21:35:06 +09:00
|
|
|
return setting.StaticURLPrefix + "/assets"
|
2019-10-22 21:11:01 +09:00
|
|
|
},
|
2016-03-07 06:40:04 +09:00
|
|
|
"AppUrl": func() string {
|
2023-02-10 01:31:30 +09:00
|
|
|
// The usage of AppUrl should be avoided as much as possible,
|
|
|
|
// because the AppURL(ROOT_URL) may not match user's visiting site and the ROOT_URL in app.ini may be incorrect.
|
|
|
|
// And it's difficult for Gitea to guess absolute URL correctly with zero configuration,
|
|
|
|
// because Gitea doesn't know whether the scheme is HTTP or HTTPS unless the reverse proxy could tell Gitea.
|
2016-11-27 19:14:25 +09:00
|
|
|
return setting.AppURL
|
2016-03-07 06:40:04 +09:00
|
|
|
},
|
|
|
|
"AppVer": func() string {
|
|
|
|
return setting.AppVer
|
|
|
|
},
|
2023-04-07 16:31:41 +09:00
|
|
|
"AppDomain": func() string { // documented in mail-templates.md
|
2016-03-07 06:40:04 +09:00
|
|
|
return setting.Domain
|
|
|
|
},
|
2022-08-23 21:58:04 +09:00
|
|
|
"AssetVersion": func() string {
|
|
|
|
return setting.AssetVersion
|
|
|
|
},
|
Add context cache as a request level cache (#22294)
To avoid duplicated load of the same data in an HTTP request, we can set
a context cache to do that. i.e. Some pages may load a user from a
database with the same id in different areas on the same page. But the
code is hidden in two different deep logic. How should we share the
user? As a result of this PR, now if both entry functions accept
`context.Context` as the first parameter and we just need to refactor
`GetUserByID` to reuse the user from the context cache. Then it will not
be loaded twice on an HTTP request.
But of course, sometimes we would like to reload an object from the
database, that's why `RemoveContextData` is also exposed.
The core context cache is here. It defines a new context
```go
type cacheContext struct {
ctx context.Context
data map[any]map[any]any
lock sync.RWMutex
}
var cacheContextKey = struct{}{}
func WithCacheContext(ctx context.Context) context.Context {
return context.WithValue(ctx, cacheContextKey, &cacheContext{
ctx: ctx,
data: make(map[any]map[any]any),
})
}
```
Then you can use the below 4 methods to read/write/del the data within
the same context.
```go
func GetContextData(ctx context.Context, tp, key any) any
func SetContextData(ctx context.Context, tp, key, value any)
func RemoveContextData(ctx context.Context, tp, key any)
func GetWithContextCache[T any](ctx context.Context, cacheGroupKey string, cacheTargetID any, f func() (T, error)) (T, error)
```
Then let's take a look at how `system.GetString` implement it.
```go
func GetSetting(ctx context.Context, key string) (string, error) {
return cache.GetWithContextCache(ctx, contextCacheKey, key, func() (string, error) {
return cache.GetString(genSettingCacheKey(key), func() (string, error) {
res, err := GetSettingNoCache(ctx, key)
if err != nil {
return "", err
}
return res.SettingValue, nil
})
})
}
```
First, it will check if context data include the setting object with the
key. If not, it will query from the global cache which may be memory or
a Redis cache. If not, it will get the object from the database. In the
end, if the object gets from the global cache or database, it will be
set into the context cache.
An object stored in the context cache will only be destroyed after the
context disappeared.
2023-02-15 22:37:34 +09:00
|
|
|
"DisableGravatar": func(ctx context.Context) bool {
|
2023-02-24 19:23:13 +09:00
|
|
|
return system_model.GetSettingWithCacheBool(ctx, system_model.KeyPictureDisableGravatar)
|
2016-03-07 06:40:04 +09:00
|
|
|
},
|
2019-05-08 17:41:35 +09:00
|
|
|
"DefaultShowFullName": func() bool {
|
|
|
|
return setting.UI.DefaultShowFullName
|
|
|
|
},
|
2016-09-01 14:01:32 +09:00
|
|
|
"ShowFooterTemplateLoadTime": func() bool {
|
2023-04-23 08:38:25 +09:00
|
|
|
return setting.Other.ShowFooterTemplateLoadTime
|
2016-09-01 14:01:32 +09:00
|
|
|
},
|
2019-12-28 08:43:56 +09:00
|
|
|
"AllowedReactions": func() []string {
|
|
|
|
return setting.UI.Reactions
|
|
|
|
},
|
2021-06-29 23:28:38 +09:00
|
|
|
"CustomEmojis": func() map[string]string {
|
|
|
|
return setting.UI.CustomEmojisMap
|
|
|
|
},
|
2016-03-07 06:40:04 +09:00
|
|
|
"ThemeColorMetaTag": func() string {
|
2016-07-24 01:23:54 +09:00
|
|
|
return setting.UI.ThemeColorMetaTag
|
2016-03-07 06:40:04 +09:00
|
|
|
},
|
2017-04-01 10:03:01 +09:00
|
|
|
"MetaAuthor": func() string {
|
|
|
|
return setting.UI.Meta.Author
|
|
|
|
},
|
|
|
|
"MetaDescription": func() string {
|
|
|
|
return setting.UI.Meta.Description
|
|
|
|
},
|
|
|
|
"MetaKeywords": func() string {
|
|
|
|
return setting.UI.Meta.Keywords
|
|
|
|
},
|
2019-11-22 05:06:23 +09:00
|
|
|
"UseServiceWorker": func() bool {
|
|
|
|
return setting.UI.UseServiceWorker
|
|
|
|
},
|
2021-02-20 08:06:56 +09:00
|
|
|
"EnableTimetracking": func() bool {
|
|
|
|
return setting.Service.EnableTimetracking
|
|
|
|
},
|
2017-09-12 18:25:42 +09:00
|
|
|
"DisableGitHooks": func() bool {
|
|
|
|
return setting.DisableGitHooks
|
|
|
|
},
|
2021-02-12 02:34:34 +09:00
|
|
|
"DisableWebhooks": func() bool {
|
|
|
|
return setting.DisableWebhooks
|
|
|
|
},
|
2018-08-24 14:00:22 +09:00
|
|
|
"DisableImportLocal": func() bool {
|
|
|
|
return !setting.ImportLocalPaths
|
|
|
|
},
|
2018-07-06 06:25:04 +09:00
|
|
|
"DefaultTheme": func() string {
|
|
|
|
return setting.UI.DefaultTheme
|
|
|
|
},
|
2020-07-03 18:55:36 +09:00
|
|
|
"NotificationSettings": func() map[string]interface{} {
|
|
|
|
return map[string]interface{}{
|
2020-05-08 06:49:00 +09:00
|
|
|
"MinTimeout": int(setting.UI.Notification.MinTimeout / time.Millisecond),
|
|
|
|
"TimeoutStep": int(setting.UI.Notification.TimeoutStep / time.Millisecond),
|
|
|
|
"MaxTimeout": int(setting.UI.Notification.MaxTimeout / time.Millisecond),
|
|
|
|
"EventSourceUpdateTime": int(setting.UI.Notification.EventSourceUpdateTime / time.Millisecond),
|
2020-04-24 12:57:38 +09:00
|
|
|
}
|
|
|
|
},
|
2023-04-08 22:15:22 +09:00
|
|
|
"MermaidMaxSourceCharacters": func() int {
|
|
|
|
return setting.MermaidMaxSourceCharacters
|
|
|
|
},
|
2020-11-09 02:21:54 +09:00
|
|
|
|
2023-04-08 22:15:22 +09:00
|
|
|
// -----------------------------------------------------------------
|
|
|
|
// render
|
|
|
|
"RenderCommitMessage": RenderCommitMessage,
|
|
|
|
"RenderCommitMessageLinkSubject": RenderCommitMessageLinkSubject,
|
2020-11-09 02:21:54 +09:00
|
|
|
|
2023-04-08 22:15:22 +09:00
|
|
|
"RenderCommitBody": RenderCommitBody,
|
|
|
|
"RenderCodeBlock": RenderCodeBlock,
|
|
|
|
"RenderIssueTitle": RenderIssueTitle,
|
|
|
|
"RenderEmoji": RenderEmoji,
|
|
|
|
"RenderEmojiPlain": emoji.ReplaceAliases,
|
|
|
|
"ReactionToEmoji": ReactionToEmoji,
|
|
|
|
"RenderNote": RenderNote,
|
2020-06-25 07:23:05 +09:00
|
|
|
|
2023-04-29 21:02:29 +09:00
|
|
|
"RenderMarkdownToHtml": RenderMarkdownToHtml,
|
|
|
|
"RenderLabel": RenderLabel,
|
|
|
|
"RenderLabels": RenderLabels,
|
2023-04-08 22:15:22 +09:00
|
|
|
|
|
|
|
// -----------------------------------------------------------------
|
|
|
|
// misc
|
|
|
|
"DiffLineTypeToStr": DiffLineTypeToStr,
|
|
|
|
"ShortSha": base.ShortSha,
|
|
|
|
"ActionContent2Commits": ActionContent2Commits,
|
|
|
|
"IsMultilineCommitMessage": IsMultilineCommitMessage,
|
|
|
|
"CommentMustAsDiff": gitdiff.CommentMustAsDiff,
|
|
|
|
"MirrorRemoteAddress": mirrorRemoteAddress,
|
|
|
|
|
2023-04-29 21:02:29 +09:00
|
|
|
"FilenameIsImage": FilenameIsImage,
|
|
|
|
"TabSizeClass": TabSizeClass,
|
2023-04-30 21:22:23 +09:00
|
|
|
}
|
2019-11-07 22:34:28 +09:00
|
|
|
}
|
|
|
|
|
2016-11-25 15:23:48 +09:00
|
|
|
// Safe render raw as HTML
|
2015-08-08 18:10:34 +09:00
|
|
|
func Safe(raw string) template.HTML {
|
|
|
|
return template.HTML(raw)
|
|
|
|
}
|
|
|
|
|
2016-11-25 15:23:48 +09:00
|
|
|
// Str2html render Markdown text to HTML
|
2014-04-11 03:20:58 +09:00
|
|
|
func Str2html(raw string) template.HTML {
|
2017-09-17 02:17:57 +09:00
|
|
|
return template.HTML(markup.Sanitize(raw))
|
2014-04-11 03:20:58 +09:00
|
|
|
}
|
|
|
|
|
2022-03-23 21:34:20 +09:00
|
|
|
// DotEscape wraps a dots in names with ZWJ [U+200D] in order to prevent autolinkers from detecting these as urls
|
|
|
|
func DotEscape(raw string) string {
|
|
|
|
return strings.ReplaceAll(raw, ".", "\u200d.\u200d")
|
|
|
|
}
|
|
|
|
|
Use a general Eval function for expressions in templates. (#23927)
One of the proposals in #23328
This PR introduces a simple expression calculator
(templates/eval/eval.go), it can do basic expression calculations.
Many untested template helper functions like `Mul` `Add` can be replaced
by this new approach.
Then these `Add` / `Mul` / `percentage` / `Subtract` / `DiffStatsWidth`
could all use this `Eval`.
And it provides enhancements for Golang templates, and improves
readability.
Some examples:
----
* Before: `{{Add (Mul $glyph.Row 12) 12}}`
* After: `{{Eval $glyph.Row "*" 12 "+" 12}}`
----
* Before: `{{if lt (Add $i 1) (len $.Topics)}}`
* After: `{{if Eval $i "+" 1 "<" (len $.Topics)}}`
## FAQ
### Why not use an existing expression package?
We need a highly customized expression engine:
* do the calculation on the fly, without pre-compiling
* deal with int/int64/float64 types, to make the result could be used in
Golang template.
* make the syntax could be used in the Golang template directly
* do not introduce too much complex or strange syntax, we just need a
simple calculator.
* it needs to strictly follow Golang template's behavior, for example,
Golang template treats all non-zero values as truth, but many 3rd
packages don't do so.
### What's the benefit?
* Developers don't need to add more `Add`/`Mul`/`Sub`-like functions,
they were getting more and more.
Now, only one `Eval` is enough for all cases.
* The new code reads better than old `{{Add (Mul $glyph.Row 12) 12}}`,
the old one isn't familiar to most procedural programming developers
(eg, the Golang expression syntax).
* The `Eval` is fully covered by tests, many old `Add`/`Mul`-like
functions were never tested.
### The performance?
It doesn't use `reflect`, it doesn't need to parse or compile when used
in Golang template, the performance is as fast as native Go template.
### Is it too complex? Could it be unstable?
The expression calculator program is a common homework for computer
science students, and it's widely used as a teaching and practicing
purpose for developers. The algorithm is pretty well-known.
The behavior can be clearly defined, it is stable.
2023-04-07 22:25:49 +09:00
|
|
|
// Eval the expression and return the result, see the comment of eval.Expr for details.
|
|
|
|
// To use this helper function in templates, pass each token as a separate parameter.
|
|
|
|
//
|
|
|
|
// {{ $int64 := Eval $var "+" 1 }}
|
|
|
|
// {{ $float64 := Eval $var "+" 1.0 }}
|
|
|
|
//
|
|
|
|
// Golang's template supports comparable int types, so the int64 result can be used in later statements like {{if lt $int64 10}}
|
|
|
|
func Eval(tokens ...any) (any, error) {
|
|
|
|
n, err := eval.Expr(tokens...)
|
|
|
|
return n.Value, err
|
|
|
|
}
|