diff --git a/modules/context/repo.go b/modules/context/repo.go index 5a9e38a1d9197..407bc99be807c 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -29,7 +29,6 @@ import ( asymkey_service "code.gitea.io/gitea/services/asymkey" "github.com/editorconfig/editorconfig-core-go/v2" - "github.com/unknwon/com" ) // IssueTemplateDirCandidates issue templates directory @@ -308,11 +307,11 @@ func EarlyResponseForGoGetMeta(ctx *Context) { ctx.PlainText(http.StatusBadRequest, "invalid repository path") return } - ctx.PlainText(http.StatusOK, com.Expand(``, - map[string]string{ - "GoGetImport": ComposeGoGetImport(username, reponame), - "CloneLink": repo_model.ComposeHTTPSCloneURL(username, reponame), - })) + + ctx.PlainText(http.StatusOK, fmt.Sprintf(``, + ComposeGoGetImport(username, reponame), + repo_model.ComposeHTTPSCloneURL(username, reponame), + )) } // RedirectToRepo redirect to a differently-named repository diff --git a/modules/markup/html.go b/modules/markup/html.go index 6673f52bf4d6b..7f83f08093a34 100644 --- a/modules/markup/html.go +++ b/modules/markup/html.go @@ -21,9 +21,9 @@ import ( "code.gitea.io/gitea/modules/markup/common" "code.gitea.io/gitea/modules/references" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/templates/vars" "code.gitea.io/gitea/modules/util" - "github.com/unknwon/com" "golang.org/x/net/html" "golang.org/x/net/html/atom" "mvdan.cc/xurls/v2" @@ -838,7 +838,14 @@ func issueIndexPatternProcessor(ctx *RenderContext, node *html.Node) { reftext := node.Data[ref.RefLocation.Start:ref.RefLocation.End] if exttrack && !ref.IsPull { ctx.Metas["index"] = ref.Issue - link = createLink(com.Expand(ctx.Metas["format"], ctx.Metas), reftext, "ref-issue ref-external-issue") + + res, err := vars.Expand(ctx.Metas["format"], ctx.Metas) + if err != nil { + log.Error(err.Error()) + return + } + + link = createLink(res, reftext, "ref-issue ref-external-issue") } else { // Path determines the type of link that will be rendered. It's unknown at this point whether // the linked item is actually a PR or an issue. Luckily it's of no real consequence because diff --git a/modules/repository/init.go b/modules/repository/init.go index d5a67df5d150c..958a98da88678 100644 --- a/modules/repository/init.go +++ b/modules/repository/init.go @@ -22,10 +22,9 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/options" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/templates/vars" "code.gitea.io/gitea/modules/util" asymkey_service "code.gitea.io/gitea/services/asymkey" - - "github.com/unknwon/com" ) var ( @@ -250,8 +249,12 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir, "CloneURL.HTTPS": cloneLink.HTTPS, "OwnerName": repo.OwnerName, } + res, err := vars.Expand(string(data), match) + if err != nil { + return fmt.Errorf("expand README.md: %v", err) + } if err = os.WriteFile(filepath.Join(tmpDir, "README.md"), - []byte(com.Expand(string(data), match)), 0o644); err != nil { + []byte(res), 0o644); err != nil { return fmt.Errorf("write README.md: %v", err) } diff --git a/modules/templates/vars/vars.go b/modules/templates/vars/vars.go new file mode 100644 index 0000000000000..f87fb842c5f9b --- /dev/null +++ b/modules/templates/vars/vars.go @@ -0,0 +1,105 @@ +// 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 vars + +import ( + "fmt" + "strings" +) + +// ErrWrongSyntax represents a syntax error within a template +type ErrWrongSyntax struct { + Template string + Reason string +} + +func (err ErrWrongSyntax) Error() string { + return fmt.Sprintf("Wrong syntax found in %s: %s", err.Template, err.Reason) +} + +// IsErrWrongSyntax returns true if the error is ErrWrongSyntax +func IsErrWrongSyntax(err error) bool { + _, ok := err.(ErrWrongSyntax) + return ok +} + +// ErrNoMatchedVar represents an error that no matched vars +type ErrNoMatchedVar struct { + Template string + Var string +} + +func (err ErrNoMatchedVar) Error() string { + return fmt.Sprintf("No matched variable %s found for %s", err.Var, err.Template) +} + +// IsErrNoMatchedVar returns true if the error is ErrNoMatchedVar +func IsErrNoMatchedVar(err error) bool { + _, ok := err.(ErrNoMatchedVar) + return ok +} + +// Expand replaces all variables like {var} to match +func Expand(template string, match map[string]string, subs ...string) (string, error) { + var ( + buf strings.Builder + keyStartPos = -1 + ) + for i, c := range template { + switch { + case c == '{': + if keyStartPos > -1 { + return "", ErrWrongSyntax{ + Template: template, + Reason: "\"{\" is not allowed to occur again before closing the variable", + } + } + keyStartPos = i + case c == '}': + if keyStartPos == -1 { + return "", ErrWrongSyntax{ + Template: template, + Reason: "\"}\" can only occur after an opening \"{\"", + } + } + if i-keyStartPos <= 1 { + return "", ErrWrongSyntax{ + Template: template, + Reason: "the empty variable (\"{}\") is not allowed", + } + } + + if len(match) == 0 { + return "", ErrNoMatchedVar{ + Template: template, + Var: template[keyStartPos+1 : i], + } + } + + v, ok := match[template[keyStartPos+1:i]] + if !ok { + if len(subs) == 0 { + return "", ErrNoMatchedVar{ + Template: template, + Var: template[keyStartPos+1 : i], + } + } + v = subs[0] + } + + if _, err := buf.WriteString(v); err != nil { + return "", err + } + + keyStartPos = -1 + case keyStartPos > -1: + default: + if _, err := buf.WriteRune(c); err != nil { + return "", err + } + } + } + return buf.String(), nil +} diff --git a/modules/templates/vars/vars_test.go b/modules/templates/vars/vars_test.go new file mode 100644 index 0000000000000..1e80ac2b2ff7b --- /dev/null +++ b/modules/templates/vars/vars_test.go @@ -0,0 +1,70 @@ +// 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 vars + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestExpandVars(t *testing.T) { + kases := []struct { + template string + maps map[string]string + expected string + fail bool + }{ + { + template: "{a}", + maps: map[string]string{ + "a": "1", + }, + expected: "1", + }, + { + template: "expand {a}, {b} and {c}", + maps: map[string]string{ + "a": "1", + "b": "2", + "c": "3", + }, + expected: "expand 1, 2 and 3", + }, + { + template: "中文内容 {一}, {二} 和 {三} 中文结尾", + maps: map[string]string{ + "一": "11", + "二": "22", + "三": "33", + }, + expected: "中文内容 11, 22 和 33 中文结尾", + }, + { + template: "expand {{a}, {b} and {c}", + fail: true, + }, + { + template: "expand {}, {b} and {c}", + fail: true, + }, + { + template: "expand }, {b} and {c}", + fail: true, + }, + } + + for _, kase := range kases { + t.Run(kase.template, func(t *testing.T) { + res, err := Expand(kase.template, kase.maps) + if kase.fail { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + assert.EqualValues(t, kase.expected, res) + }) + } +} diff --git a/routers/web/goget.go b/routers/web/goget.go index 4a31fcc2c51cc..98d357d5a335d 100644 --- a/routers/web/goget.go +++ b/routers/web/goget.go @@ -7,6 +7,7 @@ package web import ( "net/http" "net/url" + "os" "path" "strings" @@ -14,8 +15,6 @@ import ( "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" - - "github.com/unknwon/com" ) func goGet(ctx *context.Context) { @@ -67,21 +66,37 @@ func goGet(ctx *context.Context) { } ctx.RespHeader().Set("Content-Type", "text/html") ctx.Status(http.StatusOK) - _, _ = ctx.Write([]byte(com.Expand(` + res := os.Expand(` - - + + - go get {Insecure}{GoGetImport} + go get ${Insecure}${GoGetImport} -`, map[string]string{ - "GoGetImport": context.ComposeGoGetImport(ownerName, trimmedRepoName), - "CloneLink": repo_model.ComposeHTTPSCloneURL(ownerName, repoName), - "GoDocDirectory": prefix + "{/dir}", - "GoDocFile": prefix + "{/dir}/{file}#L{line}", - "Insecure": insecure, - }))) +`, func(key string) string { + switch key { + case "GoGetImport": + return context.ComposeGoGetImport(ownerName, trimmedRepoName) + case "CloneLink": + return repo_model.ComposeHTTPSCloneURL(ownerName, repoName) + case "GoDocDirectory": + return prefix + "{/dir}" + case "GoDocFile": + return prefix + "{/dir}/{file}#L{line}" + case "Insecure": + return insecure + default: + return ` + + + invalid import path + + + ` + } + }) + _, _ = ctx.Write([]byte(res)) } diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 486a63a9e105f..b27f97d242e49 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -35,6 +35,7 @@ import ( "code.gitea.io/gitea/modules/markup/markdown" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/templates/vars" "code.gitea.io/gitea/modules/upload" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/web" @@ -43,8 +44,6 @@ import ( "code.gitea.io/gitea/services/forms" issue_service "code.gitea.io/gitea/services/issue" pull_service "code.gitea.io/gitea/services/pull" - - "github.com/unknwon/com" ) const ( @@ -1113,7 +1112,12 @@ func ViewIssue(ctx *context.Context) { if extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == markup.IssueNameStyleNumeric || extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == "" { metas := ctx.Repo.Repository.ComposeMetas() metas["index"] = ctx.Params(":index") - ctx.Redirect(com.Expand(extIssueUnit.ExternalTrackerConfig().ExternalTrackerFormat, metas)) + res, err := vars.Expand(extIssueUnit.ExternalTrackerConfig().ExternalTrackerFormat, metas) + if err != nil { + ctx.ServerError("Expand", fmt.Errorf("unable to expand template vars for issue url. issue: %s, err: %s", metas["index"], err.Error())) + return + } + ctx.Redirect(res) return } } else if err != nil && !repo_model.IsErrUnitTypeNotExist(err) {