Skip to content

Commit 671592b

Browse files
committed
Use a new vars template implementation
1 parent 572c63d commit 671592b

File tree

12 files changed

+243
-28
lines changed

12 files changed

+243
-28
lines changed

models/migrations/migrations_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import (
2424
"code.gitea.io/gitea/modules/util"
2525

2626
"github.com/stretchr/testify/assert"
27-
"github.com/unknwon/com"
2827
"xorm.io/xorm"
2928
"xorm.io/xorm/names"
3029
)
@@ -204,7 +203,7 @@ func prepareTestEnv(t *testing.T, skip int, syncModels ...interface{}) (*xorm.En
204203
deferFn := PrintCurrentTest(t, ourSkip)
205204
assert.NoError(t, os.RemoveAll(setting.RepoRootPath))
206205

207-
assert.NoError(t, com.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"),
206+
assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"),
208207
setting.RepoRootPath))
209208
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
210209
if err != nil {

modules/cache/cache_redis.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ import (
1010

1111
"code.gitea.io/gitea/modules/graceful"
1212
"code.gitea.io/gitea/modules/nosql"
13+
"code.gitea.io/gitea/modules/util"
1314

1415
"gitea.com/go-chi/cache"
1516
"github.com/go-redis/redis/v8"
16-
"github.com/unknwon/com"
1717
)
1818

1919
// RedisCacher represents a redis cache adapter implementation.
@@ -29,15 +29,15 @@ type RedisCacher struct {
2929
func (c *RedisCacher) Put(key string, val interface{}, expire int64) error {
3030
key = c.prefix + key
3131
if expire == 0 {
32-
if err := c.c.Set(graceful.GetManager().HammerContext(), key, com.ToStr(val), 0).Err(); err != nil {
32+
if err := c.c.Set(graceful.GetManager().HammerContext(), key, util.ToStr(val), 0).Err(); err != nil {
3333
return err
3434
}
3535
} else {
36-
dur, err := time.ParseDuration(com.ToStr(expire) + "s")
36+
dur, err := time.ParseDuration(util.ToStr(expire) + "s")
3737
if err != nil {
3838
return err
3939
}
40-
if err = c.c.Set(graceful.GetManager().HammerContext(), key, com.ToStr(val), dur).Err(); err != nil {
40+
if err = c.c.Set(graceful.GetManager().HammerContext(), key, util.ToStr(val), dur).Err(); err != nil {
4141
return err
4242
}
4343
}

modules/context/csrf.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"time"
2424

2525
"code.gitea.io/gitea/modules/setting"
26+
"code.gitea.io/gitea/modules/util"
2627
"code.gitea.io/gitea/modules/web/middleware"
2728

2829
"github.com/unknwon/com"
@@ -211,7 +212,7 @@ func Csrfer(opt CsrfOptions, ctx *Context) CSRF {
211212
x.ID = "0"
212213
uid := ctx.Session.Get(opt.SessionKey)
213214
if uid != nil {
214-
x.ID = com.ToStr(uid)
215+
x.ID = util.ToStr(uid)
215216
}
216217

217218
needsNew := false

modules/context/repo.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,11 @@ import (
2626
"code.gitea.io/gitea/modules/markup/markdown"
2727
"code.gitea.io/gitea/modules/setting"
2828
api "code.gitea.io/gitea/modules/structs"
29+
"code.gitea.io/gitea/modules/templates/vars"
2930
"code.gitea.io/gitea/modules/util"
3031
asymkey_service "code.gitea.io/gitea/services/asymkey"
3132

3233
"github.com/editorconfig/editorconfig-core-go/v2"
33-
"github.com/unknwon/com"
3434
)
3535

3636
// IssueTemplateDirCandidates issue templates directory
@@ -309,11 +309,17 @@ func EarlyResponseForGoGetMeta(ctx *Context) {
309309
ctx.PlainText(http.StatusBadRequest, "invalid repository path")
310310
return
311311
}
312-
ctx.PlainText(http.StatusOK, com.Expand(`<meta name="go-import" content="{GoGetImport} git {CloneLink}">`,
312+
res, err := vars.Expand(`<meta name="go-import" content="{GoGetImport} git {CloneLink}">`,
313313
map[string]string{
314314
"GoGetImport": ComposeGoGetImport(username, reponame),
315315
"CloneLink": repo_model.ComposeHTTPSCloneURL(username, reponame),
316-
}))
316+
})
317+
if err != nil {
318+
log.Error(err.Error())
319+
ctx.PlainText(http.StatusInternalServerError, "expand vars failed")
320+
return
321+
}
322+
ctx.PlainText(http.StatusOK, res)
317323
}
318324

319325
// RedirectToRepo redirect to a differently-named repository

modules/markup/html.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ import (
2121
"code.gitea.io/gitea/modules/markup/common"
2222
"code.gitea.io/gitea/modules/references"
2323
"code.gitea.io/gitea/modules/setting"
24+
"code.gitea.io/gitea/modules/templates/vars"
2425
"code.gitea.io/gitea/modules/util"
2526

26-
"github.com/unknwon/com"
2727
"golang.org/x/net/html"
2828
"golang.org/x/net/html/atom"
2929
"mvdan.cc/xurls/v2"
@@ -837,7 +837,14 @@ func issueIndexPatternProcessor(ctx *RenderContext, node *html.Node) {
837837
reftext := node.Data[ref.RefLocation.Start:ref.RefLocation.End]
838838
if exttrack && !ref.IsPull {
839839
ctx.Metas["index"] = ref.Issue
840-
link = createLink(com.Expand(ctx.Metas["format"], ctx.Metas), reftext, "ref-issue ref-external-issue")
840+
841+
res, err := vars.Expand(ctx.Metas["format"], ctx.Metas)
842+
if err != nil {
843+
log.Error(err.Error())
844+
return
845+
}
846+
847+
link = createLink(res, reftext, "ref-issue ref-external-issue")
841848
} else {
842849
// Path determines the type of link that will be rendered. It's unknown at this point whether
843850
// the linked item is actually a PR or an issue. Luckily it's of no real consequence because

modules/repository/init.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,9 @@ import (
1919
"code.gitea.io/gitea/modules/git"
2020
"code.gitea.io/gitea/modules/log"
2121
"code.gitea.io/gitea/modules/setting"
22+
"code.gitea.io/gitea/modules/templates/vars"
2223
"code.gitea.io/gitea/modules/util"
2324
asymkey_service "code.gitea.io/gitea/services/asymkey"
24-
25-
"github.com/unknwon/com"
2625
)
2726

2827
func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir, repoPath string, opts models.CreateRepoOptions) error {
@@ -61,8 +60,12 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir,
6160
"CloneURL.HTTPS": cloneLink.HTTPS,
6261
"OwnerName": repo.OwnerName,
6362
}
63+
res, err := vars.Expand(string(data), match)
64+
if err != nil {
65+
return fmt.Errorf("expand README.md: %v", err)
66+
}
6467
if err = os.WriteFile(filepath.Join(tmpDir, "README.md"),
65-
[]byte(com.Expand(string(data), match)), 0o644); err != nil {
68+
[]byte(res), 0o644); err != nil {
6669
return fmt.Errorf("write README.md: %v", err)
6770
}
6871

modules/sync/unique_queue.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,7 @@
55

66
package sync
77

8-
import (
9-
"github.com/unknwon/com"
10-
)
8+
import "code.gitea.io/gitea/modules/util"
119

1210
// UniqueQueue is a queue which guarantees only one instance of same
1311
// identity is in the line. Instances with same identity will be
@@ -73,13 +71,13 @@ func (q *UniqueQueue) Queue() <-chan string {
7371
// Exist returns true if there is an instance with given identity
7472
// exists in the queue.
7573
func (q *UniqueQueue) Exist(id interface{}) bool {
76-
return q.table.IsRunning(com.ToStr(id))
74+
return q.table.IsRunning(util.ToStr(id))
7775
}
7876

7977
// AddFunc adds new instance to the queue with a custom runnable function,
8078
// the queue is blocked until the function exits.
8179
func (q *UniqueQueue) AddFunc(id interface{}, fn func()) {
82-
idStr := com.ToStr(id)
80+
idStr := util.ToStr(id)
8381
q.table.lock.Lock()
8482
if _, ok := q.table.pool[idStr]; ok {
8583
q.table.lock.Unlock()
@@ -105,5 +103,5 @@ func (q *UniqueQueue) Add(id interface{}) {
105103

106104
// Remove removes instance from the queue.
107105
func (q *UniqueQueue) Remove(id interface{}) {
108-
q.table.Stop(com.ToStr(id))
106+
q.table.Stop(util.ToStr(id))
109107
}

modules/templates/vars/vars.go

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// Copyright 2022 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package vars
6+
7+
import (
8+
"fmt"
9+
"strings"
10+
)
11+
12+
// ErrWrongSyntax represents a wrong syntax with a tempate
13+
type ErrWrongSyntax struct {
14+
Template string
15+
}
16+
17+
func (err ErrWrongSyntax) Error() string {
18+
return fmt.Sprintf("Wrong syntax found in %s", err.Template)
19+
}
20+
21+
// IsErrWrongSyntax returns true if the error is ErrWrongSyntax
22+
func IsErrWrongSyntax(err error) bool {
23+
_, ok := err.(ErrWrongSyntax)
24+
return ok
25+
}
26+
27+
// ErrNoMatchedVar represents an error that no matched vars
28+
type ErrNoMatchedVar struct {
29+
Template string
30+
Var string
31+
}
32+
33+
func (err ErrNoMatchedVar) Error() string {
34+
return fmt.Sprintf("No matched variable %s found for %s", err.Var, err.Template)
35+
}
36+
37+
// IsErrNoMatchedVar returns true if the error is ErrNoMatchedVar
38+
func IsErrNoMatchedVar(err error) bool {
39+
_, ok := err.(ErrNoMatchedVar)
40+
return ok
41+
}
42+
43+
// Expand replaces all variables like {var} to match
44+
func Expand(template string, match map[string]string, subs ...string) (string, error) {
45+
var (
46+
buf strings.Builder
47+
key strings.Builder
48+
enter bool
49+
)
50+
for _, c := range template {
51+
switch {
52+
case c == '{':
53+
if enter {
54+
return "", ErrWrongSyntax{
55+
Template: template,
56+
}
57+
}
58+
enter = true
59+
case c == '}':
60+
if !enter {
61+
return "", ErrWrongSyntax{
62+
Template: template,
63+
}
64+
}
65+
if key.Len() == 0 {
66+
return "", ErrWrongSyntax{
67+
Template: template,
68+
}
69+
}
70+
71+
if len(match) == 0 {
72+
return "", ErrNoMatchedVar{
73+
Template: template,
74+
Var: key.String(),
75+
}
76+
}
77+
78+
v, ok := match[key.String()]
79+
if !ok {
80+
if len(subs) == 0 {
81+
return "", ErrNoMatchedVar{
82+
Template: template,
83+
Var: key.String(),
84+
}
85+
}
86+
v = subs[0]
87+
}
88+
89+
if _, err := buf.WriteString(v); err != nil {
90+
return "", err
91+
}
92+
key.Reset()
93+
94+
enter = false
95+
case enter:
96+
if _, err := key.WriteRune(c); err != nil {
97+
return "", err
98+
}
99+
default:
100+
if _, err := buf.WriteRune(c); err != nil {
101+
return "", err
102+
}
103+
}
104+
}
105+
return buf.String(), nil
106+
}

modules/templates/vars/vars_test.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Copyright 2022 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package vars
6+
7+
import (
8+
"testing"
9+
10+
"github.com/stretchr/testify/assert"
11+
)
12+
13+
func TestExpandVars(t *testing.T) {
14+
kases := []struct {
15+
template string
16+
maps map[string]string
17+
expected string
18+
fail bool
19+
}{
20+
{
21+
template: "{a}",
22+
maps: map[string]string{
23+
"a": "1",
24+
},
25+
expected: "1",
26+
},
27+
{
28+
template: "expand {a}, {b} and {c}",
29+
maps: map[string]string{
30+
"a": "1",
31+
"b": "2",
32+
"c": "3",
33+
},
34+
expected: "expand 1, 2 and 3",
35+
},
36+
{
37+
template: "中文内容 {一}, {二} 和 {三} 中文结尾",
38+
maps: map[string]string{
39+
"一": "11",
40+
"二": "22",
41+
"三": "33",
42+
},
43+
expected: "中文内容 11, 22 和 33 中文结尾",
44+
},
45+
{
46+
template: "expand {{a}, {b} and {c}",
47+
fail: true,
48+
},
49+
{
50+
template: "expand {}, {b} and {c}",
51+
fail: true,
52+
},
53+
{
54+
template: "expand }, {b} and {c}",
55+
fail: true,
56+
},
57+
}
58+
59+
for _, kase := range kases {
60+
t.Run(kase.template, func(t *testing.T) {
61+
res, err := Expand(kase.template, kase.maps)
62+
if kase.fail {
63+
assert.Error(t, err)
64+
} else {
65+
assert.NoError(t, err)
66+
}
67+
assert.EqualValues(t, kase.expected, res)
68+
})
69+
}
70+
}

modules/util/util.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import (
1111
"math/big"
1212
"strconv"
1313
"strings"
14+
15+
"github.com/unknwon/com"
1416
)
1517

1618
// OptionalBool a boolean that can be "null"
@@ -181,3 +183,8 @@ func ToUpperASCII(s string) string {
181183
}
182184
return string(b)
183185
}
186+
187+
// ToStr should be replaced
188+
func ToStr(value interface{}, args ...int) string {
189+
return com.ToStr(value, args...)
190+
}

0 commit comments

Comments
 (0)