Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor names #31405

Merged
merged 2 commits into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 34 additions & 34 deletions modules/templates/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,16 @@ func NewFuncMap() template.FuncMap {
// -----------------------------------------------------------------
// html/template related functions
"dict": dict, // it's lowercase because this name has been widely used. Our other functions should have uppercase names.
"Iif": Iif,
"Eval": Eval,
"SafeHTML": SafeHTML,
"Iif": iif,
"Eval": evalTokens,
"SafeHTML": safeHTML,
"HTMLFormat": HTMLFormat,
"HTMLEscape": HTMLEscape,
"QueryEscape": QueryEscape,
"JSEscape": JSEscapeSafe,
"HTMLEscape": htmlEscape,
"QueryEscape": queryEscape,
"JSEscape": jsEscapeSafe,
"SanitizeHTML": SanitizeHTML,
"URLJoin": util.URLJoin,
"DotEscape": DotEscape,
"DotEscape": dotEscape,

"PathEscape": url.PathEscape,
"PathEscapeSegments": util.PathEscapeSegments,
Expand All @@ -59,9 +59,9 @@ func NewFuncMap() template.FuncMap {
// svg / avatar / icon / color
"svg": svg.RenderHTML,
"EntryIcon": base.EntryIcon,
"MigrationIcon": MigrationIcon,
"ActionIcon": ActionIcon,
"SortArrow": SortArrow,
"MigrationIcon": migrationIcon,
"ActionIcon": actionIcon,
"SortArrow": sortArrow,
"ContrastColor": util.ContrastColor,

// -----------------------------------------------------------------
Expand Down Expand Up @@ -139,7 +139,7 @@ func NewFuncMap() template.FuncMap {
"DisableImportLocal": func() bool {
return !setting.ImportLocalPaths
},
"UserThemeName": UserThemeName,
"UserThemeName": userThemeName,
"NotificationSettings": func() map[string]any {
return map[string]any{
"MinTimeout": int(setting.UI.Notification.MinTimeout / time.Millisecond),
Expand All @@ -155,28 +155,28 @@ func NewFuncMap() template.FuncMap {
// -----------------------------------------------------------------
// render
"RenderCommitMessage": RenderCommitMessage,
"RenderCommitMessageLinkSubject": RenderCommitMessageLinkSubject,
"RenderCommitMessageLinkSubject": renderCommitMessageLinkSubject,

"RenderCommitBody": RenderCommitBody,
"RenderCodeBlock": RenderCodeBlock,
"RenderIssueTitle": RenderIssueTitle,
"RenderEmoji": RenderEmoji,
"ReactionToEmoji": ReactionToEmoji,
"RenderCommitBody": renderCommitBody,
"RenderCodeBlock": renderCodeBlock,
"RenderIssueTitle": renderIssueTitle,
"RenderEmoji": renderEmoji,
"ReactionToEmoji": reactionToEmoji,

"RenderMarkdownToHtml": RenderMarkdownToHtml,
"RenderLabel": RenderLabel,
"RenderLabel": renderLabel,
"RenderLabels": RenderLabels,

// -----------------------------------------------------------------
// misc
"ShortSha": base.ShortSha,
"ActionContent2Commits": ActionContent2Commits,
"IsMultilineCommitMessage": IsMultilineCommitMessage,
"IsMultilineCommitMessage": isMultilineCommitMessage,
"CommentMustAsDiff": gitdiff.CommentMustAsDiff,
"MirrorRemoteAddress": mirrorRemoteAddress,

"FilenameIsImage": FilenameIsImage,
"TabSizeClass": TabSizeClass,
"FilenameIsImage": filenameIsImage,
"TabSizeClass": tabSizeClass,
}
}

Expand All @@ -197,8 +197,8 @@ func HTMLFormat(s string, rawArgs ...any) template.HTML {
return template.HTML(fmt.Sprintf(s, args...))
}

// SafeHTML render raw as HTML
func SafeHTML(s any) template.HTML {
// safeHTML render raw as HTML
func safeHTML(s any) template.HTML {
switch v := s.(type) {
case string:
return template.HTML(v)
Expand All @@ -213,7 +213,7 @@ func SanitizeHTML(s string) template.HTML {
return template.HTML(markup.Sanitize(s))
}

func HTMLEscape(s any) template.HTML {
func htmlEscape(s any) template.HTML {
switch v := s.(type) {
case string:
return template.HTML(html.EscapeString(v))
Expand All @@ -223,22 +223,22 @@ func HTMLEscape(s any) template.HTML {
panic(fmt.Sprintf("unexpected type %T", s))
}

func JSEscapeSafe(s string) template.HTML {
func jsEscapeSafe(s string) template.HTML {
return template.HTML(template.JSEscapeString(s))
}

func QueryEscape(s string) template.URL {
func queryEscape(s string) template.URL {
return template.URL(url.QueryEscape(s))
}

// 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 {
// dotEscape wraps a dots in names with ZWJ [U+200D] in order to prevent auto-linkers from detecting these as urls
func dotEscape(raw string) string {
return strings.ReplaceAll(raw, ".", "\u200d.\u200d")
}

// Iif is an "inline-if", similar util.Iif[T] but templates need the non-generic version,
// and it could be simply used as "{{Iif expr trueVal}}" (omit the falseVal).
func Iif(condition any, vals ...any) any {
// iif is an "inline-if", similar util.Iif[T] but templates need the non-generic version,
// and it could be simply used as "{{iif expr trueVal}}" (omit the falseVal).
func iif(condition any, vals ...any) any {
if isTemplateTruthy(condition) {
return vals[0]
} else if len(vals) > 1 {
Expand Down Expand Up @@ -273,19 +273,19 @@ func isTemplateTruthy(v any) bool {
}
}

// Eval the expression and return the result, see the comment of eval.Expr for details.
// evalTokens evaluates the expression by tokens and returns 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) {
func evalTokens(tokens ...any) (any, error) {
n, err := eval.Expr(tokens...)
return n.Value, err
}

func UserThemeName(user *user_model.User) string {
func userThemeName(user *user_model.User) string {
if user == nil || user.Theme == "" {
return setting.UI.DefaultTheme
}
Expand Down
4 changes: 2 additions & 2 deletions modules/templates/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func TestSubjectBodySeparator(t *testing.T) {
}

func TestJSEscapeSafe(t *testing.T) {
assert.EqualValues(t, `\u0026\u003C\u003E\'\"`, JSEscapeSafe(`&<>'"`))
assert.EqualValues(t, `\u0026\u003C\u003E\'\"`, jsEscapeSafe(`&<>'"`))
}

func TestHTMLFormat(t *testing.T) {
Expand All @@ -71,7 +71,7 @@ func TestSanitizeHTML(t *testing.T) {

func TestTemplateTruthy(t *testing.T) {
tmpl := template.New("test")
tmpl.Funcs(template.FuncMap{"Iif": Iif})
tmpl.Funcs(template.FuncMap{"Iif": iif})
template.Must(tmpl.Parse(`{{if .Value}}true{{else}}false{{end}}:{{Iif .Value "true" "false"}}`))

cases := []any{
Expand Down
2 changes: 1 addition & 1 deletion modules/templates/mailer.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ var mailSubjectSplit = regexp.MustCompile(`(?m)^-{3,}\s*$`)
func mailSubjectTextFuncMap() texttmpl.FuncMap {
return texttmpl.FuncMap{
"dict": dict,
"Eval": Eval,
"Eval": evalTokens,

"EllipsisString": base.EllipsisString,
"AppName": func() string {
Expand Down
18 changes: 9 additions & 9 deletions modules/templates/util_misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
"github.com/editorconfig/editorconfig-core-go/v2"
)

func SortArrow(normSort, revSort, urlSort string, isDefault bool) template.HTML {
func sortArrow(normSort, revSort, urlSort string, isDefault bool) template.HTML {
// if needed
if len(normSort) == 0 || len(urlSort) == 0 {
return ""
Expand All @@ -50,8 +50,8 @@ func SortArrow(normSort, revSort, urlSort string, isDefault bool) template.HTML
return ""
}

// IsMultilineCommitMessage checks to see if a commit message contains multiple lines.
func IsMultilineCommitMessage(msg string) bool {
// isMultilineCommitMessage checks to see if a commit message contains multiple lines.
func isMultilineCommitMessage(msg string) bool {
return strings.Count(strings.TrimSpace(msg), "\n") >= 1
}

Expand All @@ -69,8 +69,8 @@ type Actioner interface {
GetIssueInfos() []string
}

// ActionIcon accepts an action operation type and returns an icon class name.
func ActionIcon(opType activities_model.ActionType) string {
// actionIcon accepts an action operation type and returns an icon class name.
func actionIcon(opType activities_model.ActionType) string {
switch opType {
case activities_model.ActionCreateRepo, activities_model.ActionTransferRepo, activities_model.ActionRenameRepo:
return "repo"
Expand Down Expand Up @@ -126,8 +126,8 @@ func ActionContent2Commits(act Actioner) *repository.PushCommits {
return push
}

// MigrationIcon returns a SVG name matching the service an issue/comment was migrated from
func MigrationIcon(hostname string) string {
// migrationIcon returns a SVG name matching the service an issue/comment was migrated from
func migrationIcon(hostname string) string {
switch hostname {
case "github.com":
return "octicon-mark-github"
Expand Down Expand Up @@ -177,12 +177,12 @@ func mirrorRemoteAddress(ctx context.Context, m *repo_model.Repository, remoteNa
return ret
}

func FilenameIsImage(filename string) bool {
func filenameIsImage(filename string) bool {
mimeType := mime.TypeByExtension(filepath.Ext(filename))
return strings.HasPrefix(mimeType, "image/")
}

func TabSizeClass(ec *editorconfig.Editorconfig, filename string) string {
func tabSizeClass(ec *editorconfig.Editorconfig, filename string) string {
if ec != nil {
def, err := ec.GetDefinitionForFilename(filename)
if err == nil && def.TabWidth >= 1 && def.TabWidth <= 16 {
Expand Down
40 changes: 20 additions & 20 deletions modules/templates/util_render.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ func RenderCommitMessage(ctx context.Context, msg string, metas map[string]strin
if len(msgLines) == 0 {
return template.HTML("")
}
return RenderCodeBlock(template.HTML(msgLines[0]))
return renderCodeBlock(template.HTML(msgLines[0]))
}

// RenderCommitMessageLinkSubject renders commit message as a XSS-safe link to
// renderCommitMessageLinkSubject renders commit message as a XSS-safe link to
// the provided default url, handling for special links without email to links.
func RenderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML {
func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML {
msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace)
lineEnd := strings.IndexByte(msgLine, '\n')
if lineEnd > 0 {
Expand All @@ -68,11 +68,11 @@ func RenderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string,
log.Error("RenderCommitMessageSubject: %v", err)
return template.HTML("")
}
return RenderCodeBlock(template.HTML(renderedMessage))
return renderCodeBlock(template.HTML(renderedMessage))
}

// RenderCommitBody extracts the body of a commit message without its title.
func RenderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML {
// renderCommitBody extracts the body of a commit message without its title.
func renderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML {
msgLine := strings.TrimSpace(msg)
lineEnd := strings.IndexByte(msgLine, '\n')
if lineEnd > 0 {
Expand All @@ -99,14 +99,14 @@ func RenderCommitBody(ctx context.Context, msg string, metas map[string]string)
// Match text that is between back ticks.
var codeMatcher = regexp.MustCompile("`([^`]+)`")

// RenderCodeBlock renders "`…`" as highlighted "<code>" block, intended for issue and PR titles
func RenderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML {
// renderCodeBlock renders "`…`" as highlighted "<code>" block, intended for issue and PR titles
func renderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML {
htmlWithCodeTags := codeMatcher.ReplaceAllString(string(htmlEscapedTextToRender), `<code class="inline-code-block">$1</code>`) // replace with HTML <code> tags
return template.HTML(htmlWithCodeTags)
}

// RenderIssueTitle renders issue/pull title with defined post processors
func RenderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML {
// renderIssueTitle renders issue/pull title with defined post processors
func renderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML {
renderedText, err := markup.RenderIssueTitle(&markup.RenderContext{
Ctx: ctx,
Metas: metas,
Expand All @@ -118,9 +118,9 @@ func RenderIssueTitle(ctx context.Context, text string, metas map[string]string)
return template.HTML(renderedText)
}

// RenderLabel renders a label
// renderLabel renders a label
// locale is needed due to an import cycle with our context providing the `Tr` function
func RenderLabel(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML {
func renderLabel(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML {
var extraCSSClasses string
textColor := util.ContrastColor(label.Color)
labelScope := label.ExclusiveScope()
Expand All @@ -134,12 +134,12 @@ func RenderLabel(ctx context.Context, locale translation.Locale, label *issues_m
if labelScope == "" {
// Regular label
return HTMLFormat(`<div class="ui label %s" style="color: %s !important; background-color: %s !important;" data-tooltip-content title="%s">%s</div>`,
extraCSSClasses, textColor, label.Color, descriptionText, RenderEmoji(ctx, label.Name))
extraCSSClasses, textColor, label.Color, descriptionText, renderEmoji(ctx, label.Name))
}

// Scoped label
scopeHTML := RenderEmoji(ctx, labelScope)
itemHTML := RenderEmoji(ctx, label.Name[len(labelScope)+1:])
scopeHTML := renderEmoji(ctx, labelScope)
itemHTML := renderEmoji(ctx, label.Name[len(labelScope)+1:])

// Make scope and item background colors slightly darker and lighter respectively.
// More contrast needed with higher luminance, empirically tweaked.
Expand Down Expand Up @@ -176,8 +176,8 @@ func RenderLabel(ctx context.Context, locale translation.Locale, label *issues_m
textColor, itemColor, itemHTML)
}

// RenderEmoji renders html text with emoji post processors
func RenderEmoji(ctx context.Context, text string) template.HTML {
// renderEmoji renders html text with emoji post processors
func renderEmoji(ctx context.Context, text string) template.HTML {
renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ctx},
template.HTMLEscapeString(text))
if err != nil {
Expand All @@ -187,8 +187,8 @@ func RenderEmoji(ctx context.Context, text string) template.HTML {
return template.HTML(renderedText)
}

// ReactionToEmoji renders emoji for use in reactions
func ReactionToEmoji(reaction string) template.HTML {
// reactionToEmoji renders emoji for use in reactions
func reactionToEmoji(reaction string) template.HTML {
val := emoji.FromCode(reaction)
if val != nil {
return template.HTML(val.Emoji)
Expand Down Expand Up @@ -220,7 +220,7 @@ func RenderLabels(ctx context.Context, locale translation.Locale, labels []*issu
if label == nil {
continue
}
htmlCode += fmt.Sprintf(`<a href="%s?labels=%d">%s</a>`, baseLink, label.ID, RenderLabel(ctx, locale, label))
htmlCode += fmt.Sprintf(`<a href="%s?labels=%d">%s</a>`, baseLink, label.ID, renderLabel(ctx, locale, label))
}
htmlCode += "</span>"
return template.HTML(htmlCode)
Expand Down
8 changes: 4 additions & 4 deletions modules/templates/util_render_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func TestRenderCommitBody(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equalf(t, tt.want, RenderCommitBody(tt.args.ctx, tt.args.msg, tt.args.metas), "RenderCommitBody(%v, %v, %v)", tt.args.ctx, tt.args.msg, tt.args.metas)
assert.Equalf(t, tt.want, renderCommitBody(tt.args.ctx, tt.args.msg, tt.args.metas), "RenderCommitBody(%v, %v, %v)", tt.args.ctx, tt.args.msg, tt.args.metas)
})
}

Expand All @@ -127,7 +127,7 @@ com 88fc37a3c0a4dda553bdcfc80c178a58247f42fb mit
<a href="/user13/repo11/issues/123" class="ref-issue">#123</a>
space`

assert.EqualValues(t, expected, RenderCommitBody(context.Background(), testInput(), testMetas))
assert.EqualValues(t, expected, renderCommitBody(context.Background(), testInput(), testMetas))
}

func TestRenderCommitMessage(t *testing.T) {
Expand All @@ -139,7 +139,7 @@ func TestRenderCommitMessage(t *testing.T) {
func TestRenderCommitMessageLinkSubject(t *testing.T) {
expected := `<a href="https://example.com/link" class="default-link muted">space </a><a href="/mention-user" class="mention">@mention-user</a>`

assert.EqualValues(t, expected, RenderCommitMessageLinkSubject(context.Background(), testInput(), "https://example.com/link", testMetas))
assert.EqualValues(t, expected, renderCommitMessageLinkSubject(context.Background(), testInput(), "https://example.com/link", testMetas))
}

func TestRenderIssueTitle(t *testing.T) {
Expand All @@ -165,7 +165,7 @@ mail@domain.com
space<SPACE><SPACE>
`
expected = strings.ReplaceAll(expected, "<SPACE>", " ")
assert.EqualValues(t, expected, RenderIssueTitle(context.Background(), testInput(), testMetas))
assert.EqualValues(t, expected, renderIssueTitle(context.Background(), testInput(), testMetas))
}

func TestRenderMarkdownToHtml(t *testing.T) {
Expand Down
Loading