Skip to content

Commit 8820191

Browse files
Improve template helper functions: string/slice (#24266)
Follow #23328 The improvements: 1. The `contains` functions are covered by tests 2. The inconsistent behavior of `containGeneric` is replaced by `StringUtils.Contains` and `SliceUtils.Contains` 3. In the future we can move more help functions into XxxUtils to simplify the `helper.go` and reduce unnecessary global functions. FAQ: 1. Why it's called `StringUtils.Contains` but not `strings.Contains` like Golang? Because our `StringUtils` is not Golang's `strings` package. There will be our own string functions. --------- Co-authored-by: silverwind <[email protected]>
1 parent c0d1056 commit 8820191

File tree

11 files changed

+105
-40
lines changed

11 files changed

+105
-40
lines changed

modules/templates/helper.go

+5-31
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import (
1515
"mime"
1616
"net/url"
1717
"path/filepath"
18-
"reflect"
1918
"regexp"
2019
"strings"
2120
"time"
@@ -68,11 +67,15 @@ func NewFuncMap() []template.FuncMap {
6867
"PathEscape": url.PathEscape,
6968
"PathEscapeSegments": util.PathEscapeSegments,
7069

70+
// utils
71+
"StringUtils": NewStringUtils,
72+
"SliceUtils": NewSliceUtils,
73+
7174
// -----------------------------------------------------------------
7275
// string / json
76+
// TODO: move string helper functions to StringUtils
7377
"Join": strings.Join,
7478
"DotEscape": DotEscape,
75-
"HasPrefix": strings.HasPrefix,
7679
"EllipsisString": base.EllipsisString,
7780
"DumpVar": dumpVar,
7881

@@ -144,35 +147,6 @@ func NewFuncMap() []template.FuncMap {
144147
return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
145148
},
146149

147-
// -----------------------------------------------------------------
148-
// slice
149-
"containGeneric": func(arr, v interface{}) bool {
150-
arrV := reflect.ValueOf(arr)
151-
if arrV.Kind() == reflect.String && reflect.ValueOf(v).Kind() == reflect.String {
152-
return strings.Contains(arr.(string), v.(string))
153-
}
154-
if arrV.Kind() == reflect.Slice {
155-
for i := 0; i < arrV.Len(); i++ {
156-
iV := arrV.Index(i)
157-
if !iV.CanInterface() {
158-
continue
159-
}
160-
if iV.Interface() == v {
161-
return true
162-
}
163-
}
164-
}
165-
return false
166-
},
167-
"contain": func(s []int64, id int64) bool {
168-
for i := 0; i < len(s); i++ {
169-
if s[i] == id {
170-
return true
171-
}
172-
}
173-
return false
174-
},
175-
176150
// -----------------------------------------------------------------
177151
// setting
178152
"AppName": func() string {
File renamed without changes.

modules/templates/util_slice.go

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Copyright 2023 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package templates
5+
6+
import (
7+
"fmt"
8+
"reflect"
9+
)
10+
11+
type SliceUtils struct{}
12+
13+
func NewSliceUtils() *SliceUtils {
14+
return &SliceUtils{}
15+
}
16+
17+
func (su *SliceUtils) Contains(s, v any) bool {
18+
if s == nil {
19+
return false
20+
}
21+
sv := reflect.ValueOf(s)
22+
if sv.Kind() != reflect.Slice && sv.Kind() != reflect.Array {
23+
panic(fmt.Sprintf("invalid type, expected slice or array, but got: %T", s))
24+
}
25+
for i := 0; i < sv.Len(); i++ {
26+
it := sv.Index(i)
27+
if !it.CanInterface() {
28+
continue
29+
}
30+
if it.Interface() == v {
31+
return true
32+
}
33+
}
34+
return false
35+
}

modules/templates/util_string.go

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Copyright 2023 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package templates
5+
6+
import "strings"
7+
8+
type StringUtils struct{}
9+
10+
func NewStringUtils() *StringUtils {
11+
return &StringUtils{}
12+
}
13+
14+
func (su *StringUtils) HasPrefix(s, prefix string) bool {
15+
return strings.HasPrefix(s, prefix)
16+
}
17+
18+
func (su *StringUtils) Contains(s, substr string) bool {
19+
return strings.Contains(s, substr)
20+
}

modules/templates/util_test.go

+36
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
package templates
55

66
import (
7+
"html/template"
8+
"io"
9+
"strings"
710
"testing"
811

912
"github.com/stretchr/testify/assert"
@@ -41,3 +44,36 @@ func TestDict(t *testing.T) {
4144
assert.Error(t, err)
4245
}
4346
}
47+
48+
func TestUtils(t *testing.T) {
49+
execTmpl := func(code string, data any) string {
50+
tmpl := template.New("test")
51+
tmpl.Funcs(template.FuncMap{"SliceUtils": NewSliceUtils, "StringUtils": NewStringUtils})
52+
template.Must(tmpl.Parse(code))
53+
w := &strings.Builder{}
54+
assert.NoError(t, tmpl.Execute(w, data))
55+
return w.String()
56+
}
57+
58+
actual := execTmpl("{{SliceUtils.Contains .Slice .Value}}", map[string]any{"Slice": []string{"a", "b"}, "Value": "a"})
59+
assert.Equal(t, "true", actual)
60+
61+
actual = execTmpl("{{SliceUtils.Contains .Slice .Value}}", map[string]any{"Slice": []string{"a", "b"}, "Value": "x"})
62+
assert.Equal(t, "false", actual)
63+
64+
actual = execTmpl("{{SliceUtils.Contains .Slice .Value}}", map[string]any{"Slice": []int64{1, 2}, "Value": int64(2)})
65+
assert.Equal(t, "true", actual)
66+
67+
actual = execTmpl("{{StringUtils.Contains .String .Value}}", map[string]any{"String": "abc", "Value": "b"})
68+
assert.Equal(t, "true", actual)
69+
70+
actual = execTmpl("{{StringUtils.Contains .String .Value}}", map[string]any{"String": "abc", "Value": "x"})
71+
assert.Equal(t, "false", actual)
72+
73+
tmpl := template.New("test")
74+
tmpl.Funcs(template.FuncMap{"SliceUtils": NewSliceUtils, "StringUtils": NewStringUtils})
75+
template.Must(tmpl.Parse("{{SliceUtils.Contains .Slice .Value}}"))
76+
// error is like this: `template: test:1:12: executing "test" at <SliceUtils.Contains>: error calling Contains: ...`
77+
err := tmpl.Execute(io.Discard, map[string]any{"Slice": struct{}{}})
78+
assert.ErrorContains(t, err, "invalid type, expected slice or array")
79+
}

templates/repo/graph/commits.tmpl

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
{{range $commit.Refs}}
3636
{{$refGroup := .RefGroup}}
3737
{{if eq $refGroup "pull"}}
38-
{{if or (not $.HidePRRefs) (containGeneric $.SelectedBranches .Name)}}
38+
{{if or (not $.HidePRRefs) (SliceUtils.Contains $.SelectedBranches .Name)}}
3939
<!-- it's intended to use issues not pulls, if it's a pull you will get redirected -->
4040
<a class="ui labelled icon button basic tiny gt-mr-2" href="{{$.RepoLink}}/{{if $.Repository.UnitEnabled $.Context $.UnitTypePullRequests}}pulls{{else}}issues{{end}}/{{.ShortName|PathEscape}}">
4141
{{svg "octicon-git-pull-request" 16 "gt-mr-2"}}#{{.ShortName}}

templates/repo/header.tmpl

+1-1
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@
217217
{{end}}
218218

219219
{{if or (.Permission.CanRead $.UnitTypeWiki) (.Permission.CanRead $.UnitTypeExternalWiki)}}
220-
<a class="{{if .PageIsWiki}}active {{end}}item" href="{{.RepoLink}}/wiki" {{if and (.Permission.CanRead $.UnitTypeExternalWiki) (not (HasPrefix ((.Repository.MustGetUnit $.Context $.UnitTypeExternalWiki).ExternalWikiConfig.ExternalWikiURL) (.Repository.Link)))}} target="_blank" rel="noopener noreferrer" {{end}}>
220+
<a class="{{if .PageIsWiki}}active {{end}}item" href="{{.RepoLink}}/wiki" {{if and (.Permission.CanRead $.UnitTypeExternalWiki) (not (StringUtils.HasPrefix ((.Repository.MustGetUnit $.Context $.UnitTypeExternalWiki).ExternalWikiConfig.ExternalWikiURL) (.Repository.Link)))}} target="_blank" rel="noopener noreferrer" {{end}}>
221221
{{svg "octicon-book"}} {{.locale.Tr "repo.wiki"}}
222222
</a>
223223
{{end}}

templates/repo/issue/list.tmpl

+1-1
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@
227227
{{end}}
228228
{{$previousExclusiveScope = $exclusiveScope}}
229229
<div class="item issue-action" data-action="toggle" data-element-id="{{.ID}}" data-url="{{$.RepoLink}}/issues/labels">
230-
{{if contain $.SelLabelIDs .ID}}{{if $exclusiveScope}}{{svg "octicon-dot-fill"}}{{else}}{{svg "octicon-check"}}{{end}}{{end}} {{RenderLabel $.Context .}}
230+
{{if SliceUtils.Contains $.SelLabelIDs .ID}}{{if $exclusiveScope}}{{svg "octicon-dot-fill"}}{{else}}{{svg "octicon-check"}}{{end}}{{end}} {{RenderLabel $.Context .}}
231231
</div>
232232
{{end}}
233233
</div>

templates/repo/issue/milestone_issues.tmpl

+2-2
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@
6565
<span class="info">{{.locale.Tr "repo.issues.filter_label_exclude" | Safe}}</span>
6666
<a class="item" href="{{$.Link}}?q={{$.Keyword}}&type={{$.ViewType}}&sort={{$.SortType}}&state={{$.State}}&assignee={{$.AssigneeID}}&poster={{$.PosterID}}">{{.locale.Tr "repo.issues.filter_label_no_select"}}</a>
6767
{{range .Labels}}
68-
<a class="item label-filter-item" href="{{$.Link}}?q={{$.Keyword}}&type={{$.ViewType}}&sort={{$.SortType}}&state={{$.State}}&labels={{.QueryString}}&assignee={{$.AssigneeID}}&poster={{$.PosterID}}" data-label-id="{{.ID}}">{{if .IsExcluded}}{{svg "octicon-circle-slash"}}{{else if contain $.SelLabelIDs .ID}}{{svg "octicon-check"}}{{end}} {{RenderLabel $.Context .}}</a>
68+
<a class="item label-filter-item" href="{{$.Link}}?q={{$.Keyword}}&type={{$.ViewType}}&sort={{$.SortType}}&state={{$.State}}&labels={{.QueryString}}&assignee={{$.AssigneeID}}&poster={{$.PosterID}}" data-label-id="{{.ID}}">{{if .IsExcluded}}{{svg "octicon-circle-slash"}}{{else if SliceUtils.Contains $.SelLabelIDs .ID}}{{svg "octicon-check"}}{{end}} {{RenderLabel $.Context .}}</a>
6969
{{end}}
7070
</div>
7171
</div>
@@ -171,7 +171,7 @@
171171
<div class="menu">
172172
{{range .Labels}}
173173
<div class="item issue-action" data-action="toggle" data-element-id="{{.ID}}" data-url="{{$.RepoLink}}/issues/labels">
174-
{{if contain $.SelLabelIDs .ID}}{{svg "octicon-check"}}{{end}} {{RenderLabel $.Context .}}
174+
{{if SliceUtils.Contains $.SelLabelIDs .ID}}{{svg "octicon-check"}}{{end}} {{RenderLabel $.Context .}}
175175
</div>
176176
{{end}}
177177
</div>

templates/repo/issue/view_content/attachments.tmpl

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
<div class="gt-f1 gt-p-3">
99
<a target="_blank" rel="noopener noreferrer" href="{{.DownloadURL}}" title='{{$.ctxData.locale.Tr "repo.issues.attachment.open_tab" .Name}}'>
1010
{{if FilenameIsImage .Name}}
11-
{{if not (containGeneric $.Content .UUID)}}
11+
{{if not (StringUtils.Contains $.Content .UUID)}}
1212
{{$hasThumbnails = true}}
1313
{{end}}
1414
{{svg "octicon-file"}}
@@ -29,7 +29,7 @@
2929
<div class="ui small thumbnails">
3030
{{- range .Attachments -}}
3131
{{if FilenameIsImage .Name}}
32-
{{if not (containGeneric $.Content .UUID)}}
32+
{{if not (StringUtils.Contains $.Content .UUID)}}
3333
<a target="_blank" rel="noopener noreferrer" href="{{.DownloadURL}}">
3434
<img alt="{{.Name}}" src="{{.DownloadURL}}" title='{{$.ctxData.locale.Tr "repo.issues.attachment.open_tab" .Name}}'>
3535
</a>

templates/repo/settings/tags.tmpl

+2-2
Original file line numberDiff line numberDiff line change
@@ -92,14 +92,14 @@
9292
{{if or .AllowlistUserIDs (and $.Owner.IsOrganization .AllowlistTeamIDs)}}
9393
{{$userIDs := .AllowlistUserIDs}}
9494
{{range $.Users}}
95-
{{if contain $userIDs .ID}}
95+
{{if SliceUtils.Contains $userIDs .ID}}
9696
<a class="ui basic label" href="{{.HomeLink}}">{{avatar $.Context . 26}} {{.GetDisplayName}}</a>
9797
{{end}}
9898
{{end}}
9999
{{if $.Owner.IsOrganization}}
100100
{{$teamIDs := .AllowlistTeamIDs}}
101101
{{range $.Teams}}
102-
{{if contain $teamIDs .ID}}
102+
{{if SliceUtils.Contains $teamIDs .ID}}
103103
<a class="ui basic label" href="{{$.Owner.OrganisationLink}}/teams/{{PathEscape .LowerName}}">{{.Name}}</a>
104104
{{end}}
105105
{{end}}

0 commit comments

Comments
 (0)