diff --git a/.golangci.yml b/.golangci.yml
index 555fdca459..c176d2115c 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -13,14 +13,17 @@ linters:
- gocritic
- govet
- ineffassign
+ - mirror
- nakedret
- nolintlint
+ - perfsprint
- revive
- staticcheck
- testifylint
- unconvert
- unparam
- unused
+ - usestdlibvars
- usetesting
- wastedassign
settings:
diff --git a/cmd/dump.go b/cmd/dump.go
index ececc80f72..7d640b78fd 100644
--- a/cmd/dump.go
+++ b/cmd/dump.go
@@ -5,7 +5,6 @@
package cmd
import (
- "fmt"
"os"
"path"
"path/filepath"
@@ -93,7 +92,7 @@ var CmdDump = &cli.Command{
},
&cli.StringFlag{
Name: "type",
- Usage: fmt.Sprintf(`Dump output format, default to "zip", supported types: %s`, strings.Join(dump.SupportedOutputTypes, ", ")),
+ Usage: `Dump output format, default to "zip", supported types: ` + strings.Join(dump.SupportedOutputTypes, ", "),
},
},
}
diff --git a/cmd/main_test.go b/cmd/main_test.go
index a6b040ce0b..9573cacbd4 100644
--- a/cmd/main_test.go
+++ b/cmd/main_test.go
@@ -4,6 +4,7 @@
package cmd
import (
+ "errors"
"fmt"
"io"
"path/filepath"
@@ -127,7 +128,7 @@ func TestCliCmd(t *testing.T) {
}
func TestCliCmdError(t *testing.T) {
- app := newTestApp(func(ctx *cli.Context) error { return fmt.Errorf("normal error") })
+ app := newTestApp(func(ctx *cli.Context) error { return errors.New("normal error") })
r, err := runTestApp(app, "./gitea", "test-cmd")
assert.Error(t, err)
assert.Equal(t, 1, r.ExitCode)
diff --git a/cmd/serv.go b/cmd/serv.go
index 476fd9a2ea..b18508459f 100644
--- a/cmd/serv.go
+++ b/cmd/serv.go
@@ -173,7 +173,7 @@ func getLFSAuthToken(ctx context.Context, lfsVerb string, results *private.ServC
if err != nil {
return "", fail(ctx, "Failed to sign JWT Token", "Failed to sign JWT token: %v", err)
}
- return fmt.Sprintf("Bearer %s", tokenString), nil
+ return "Bearer " + tokenString, nil
}
func runServ(c *cli.Context) error {
@@ -372,9 +372,9 @@ func runServ(c *cli.Context) error {
repo_module.EnvPusherEmail+"="+results.UserEmail,
repo_module.EnvPusherID+"="+strconv.FormatInt(results.UserID, 10),
repo_module.EnvRepoID+"="+strconv.FormatInt(results.RepoID, 10),
- repo_module.EnvPRID+"="+fmt.Sprintf("%d", 0),
- repo_module.EnvDeployKeyID+"="+fmt.Sprintf("%d", results.DeployKeyID),
- repo_module.EnvKeyID+"="+fmt.Sprintf("%d", results.KeyID),
+ repo_module.EnvPRID+"="+strconv.Itoa(0),
+ repo_module.EnvDeployKeyID+"="+strconv.FormatInt(results.DeployKeyID, 10),
+ repo_module.EnvKeyID+"="+strconv.FormatInt(results.KeyID, 10),
repo_module.EnvAppURL+"="+setting.AppURL,
)
// to avoid breaking, here only use the minimal environment variables for the "gitea serv" command.
diff --git a/cmd/web_acme.go b/cmd/web_acme.go
index 172dde913b..5f7a308334 100644
--- a/cmd/web_acme.go
+++ b/cmd/web_acme.go
@@ -136,7 +136,7 @@ func runACME(listenAddr string, m http.Handler) error {
}
func runLetsEncryptFallbackHandler(w http.ResponseWriter, r *http.Request) {
- if r.Method != "GET" && r.Method != "HEAD" {
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "Use HTTPS", http.StatusBadRequest)
return
}
diff --git a/contrib/backport/backport.go b/contrib/backport/backport.go
index eb19437445..9b30480300 100644
--- a/contrib/backport/backport.go
+++ b/contrib/backport/backport.go
@@ -6,6 +6,7 @@ package main
import (
"context"
+ "errors"
"fmt"
"log"
"net/http"
@@ -158,7 +159,7 @@ func runBackport(c *cli.Context) error {
args := c.Args().Slice()
if len(args) == 0 && pr == "" {
- return fmt.Errorf("no PR number provided\nProvide a PR number to backport")
+ return errors.New("no PR number provided\nProvide a PR number to backport")
} else if len(args) != 1 && pr == "" {
return fmt.Errorf("multiple PRs provided %v\nOnly a single PR can be backported at a time", args)
}
diff --git a/models/actions/run.go b/models/actions/run.go
index 89f7f3e640..5f077940c5 100644
--- a/models/actions/run.go
+++ b/models/actions/run.go
@@ -5,6 +5,7 @@ package actions
import (
"context"
+ "errors"
"fmt"
"slices"
"strings"
@@ -245,7 +246,7 @@ func CancelPreviousJobs(ctx context.Context, repoID int64, ref, workflowID strin
// If the update affected 0 rows, it means the job has changed in the meantime, so we need to try again.
if n == 0 {
- return cancelledJobs, fmt.Errorf("job has changed, try again")
+ return cancelledJobs, errors.New("job has changed, try again")
}
cancelledJobs = append(cancelledJobs, job)
@@ -412,7 +413,7 @@ func UpdateRun(ctx context.Context, run *ActionRun, cols ...string) error {
return err
}
if affected == 0 {
- return fmt.Errorf("run has changed")
+ return errors.New("run has changed")
// It's impossible that the run is not found, since Gitea never deletes runs.
}
diff --git a/models/actions/task.go b/models/actions/task.go
index 9f13ff94c9..43f11b2730 100644
--- a/models/actions/task.go
+++ b/models/actions/task.go
@@ -6,6 +6,7 @@ package actions
import (
"context"
"crypto/subtle"
+ "errors"
"fmt"
"time"
@@ -361,7 +362,7 @@ func UpdateTaskByState(ctx context.Context, runnerID int64, state *runnerv1.Task
} else if !has {
return nil, util.ErrNotExist
} else if runnerID != task.RunnerID {
- return nil, fmt.Errorf("invalid runner for task")
+ return nil, errors.New("invalid runner for task")
}
if task.Status.IsDone() {
diff --git a/models/activities/action_list.go b/models/activities/action_list.go
index 6789ebcb99..b52cf7ee49 100644
--- a/models/activities/action_list.go
+++ b/models/activities/action_list.go
@@ -5,6 +5,7 @@ package activities
import (
"context"
+ "errors"
"fmt"
"strconv"
@@ -205,7 +206,7 @@ func (actions ActionList) LoadIssues(ctx context.Context) error {
// GetFeeds returns actions according to the provided options
func GetFeeds(ctx context.Context, opts GetFeedsOptions) (ActionList, int64, error) {
if opts.RequestedUser == nil && opts.RequestedTeam == nil && opts.RequestedRepo == nil {
- return nil, 0, fmt.Errorf("need at least one of these filters: RequestedUser, RequestedTeam, RequestedRepo")
+ return nil, 0, errors.New("need at least one of these filters: RequestedUser, RequestedTeam, RequestedRepo")
}
var err error
diff --git a/models/asymkey/error.go b/models/asymkey/error.go
index 1ed6edd71a..b765624579 100644
--- a/models/asymkey/error.go
+++ b/models/asymkey/error.go
@@ -132,7 +132,7 @@ func IsErrGPGKeyParsing(err error) bool {
}
func (err ErrGPGKeyParsing) Error() string {
- return fmt.Sprintf("failed to parse gpg key %s", err.ParseError.Error())
+ return "failed to parse gpg key " + err.ParseError.Error()
}
// ErrGPGKeyNotExist represents a "GPGKeyNotExist" kind of error.
diff --git a/models/asymkey/gpg_key.go b/models/asymkey/gpg_key.go
index 7f35a96a59..24c76f7b5c 100644
--- a/models/asymkey/gpg_key.go
+++ b/models/asymkey/gpg_key.go
@@ -5,6 +5,7 @@ package asymkey
import (
"context"
+ "errors"
"fmt"
"strings"
"time"
@@ -207,7 +208,7 @@ func parseGPGKey(ctx context.Context, ownerID int64, e *openpgp.Entity, verified
// deleteGPGKey does the actual key deletion
func deleteGPGKey(ctx context.Context, keyID string) (int64, error) {
if keyID == "" {
- return 0, fmt.Errorf("empty KeyId forbidden") // Should never happen but just to be sure
+ return 0, errors.New("empty KeyId forbidden") // Should never happen but just to be sure
}
// Delete imported key
n, err := db.GetEngine(ctx).Where("key_id=?", keyID).Delete(new(GPGKeyImport))
diff --git a/models/asymkey/gpg_key_commit_verification.go b/models/asymkey/gpg_key_commit_verification.go
index 1591cd5068..39ec893606 100644
--- a/models/asymkey/gpg_key_commit_verification.go
+++ b/models/asymkey/gpg_key_commit_verification.go
@@ -4,6 +4,7 @@
package asymkey
import (
+ "errors"
"fmt"
"hash"
@@ -68,7 +69,7 @@ const (
func verifySign(s *packet.Signature, h hash.Hash, k *GPGKey) error {
// Check if key can sign
if !k.CanSign {
- return fmt.Errorf("key can not sign")
+ return errors.New("key can not sign")
}
// Decode key
pkey, err := base64DecPubKey(k.Content)
diff --git a/models/asymkey/gpg_key_common.go b/models/asymkey/gpg_key_common.go
index 1291cbc542..76f52a3ca4 100644
--- a/models/asymkey/gpg_key_common.go
+++ b/models/asymkey/gpg_key_common.go
@@ -7,6 +7,7 @@ import (
"bytes"
"crypto"
"encoding/base64"
+ "errors"
"fmt"
"hash"
"io"
@@ -75,7 +76,7 @@ func base64DecPubKey(content string) (*packet.PublicKey, error) {
// Check type
pkey, ok := p.(*packet.PublicKey)
if !ok {
- return nil, fmt.Errorf("key is not a public key")
+ return nil, errors.New("key is not a public key")
}
return pkey, nil
}
@@ -122,15 +123,15 @@ func readArmoredSign(r io.Reader) (body io.Reader, err error) {
func ExtractSignature(s string) (*packet.Signature, error) {
r, err := readArmoredSign(strings.NewReader(s))
if err != nil {
- return nil, fmt.Errorf("Failed to read signature armor")
+ return nil, errors.New("Failed to read signature armor")
}
p, err := packet.Read(r)
if err != nil {
- return nil, fmt.Errorf("Failed to read signature packet")
+ return nil, errors.New("Failed to read signature packet")
}
sig, ok := p.(*packet.Signature)
if !ok {
- return nil, fmt.Errorf("Packet is not a signature")
+ return nil, errors.New("Packet is not a signature")
}
return sig, nil
}
diff --git a/models/asymkey/ssh_key_commit_verification.go b/models/asymkey/ssh_key_commit_verification.go
index 27c6df3578..4a858e2246 100644
--- a/models/asymkey/ssh_key_commit_verification.go
+++ b/models/asymkey/ssh_key_commit_verification.go
@@ -4,7 +4,6 @@
package asymkey
import (
- "bytes"
"context"
"fmt"
"strings"
@@ -65,7 +64,7 @@ func ParseCommitWithSSHSignature(ctx context.Context, c *git.Commit, committer *
}
func verifySSHCommitVerification(sig, payload string, k *PublicKey, committer, signer *user_model.User, email string) *CommitVerification {
- if err := sshsig.Verify(bytes.NewBuffer([]byte(payload)), []byte(sig), []byte(k.Content), "git"); err != nil {
+ if err := sshsig.Verify(strings.NewReader(payload), []byte(sig), []byte(k.Content), "git"); err != nil {
return nil
}
diff --git a/models/asymkey/ssh_key_parse.go b/models/asymkey/ssh_key_parse.go
index 94b1cf112b..c843525718 100644
--- a/models/asymkey/ssh_key_parse.go
+++ b/models/asymkey/ssh_key_parse.go
@@ -10,6 +10,7 @@ import (
"encoding/base64"
"encoding/binary"
"encoding/pem"
+ "errors"
"fmt"
"math/big"
"os"
@@ -93,7 +94,7 @@ func parseKeyString(content string) (string, error) {
block, _ := pem.Decode([]byte(content))
if block == nil {
- return "", fmt.Errorf("failed to parse PEM block containing the public key")
+ return "", errors.New("failed to parse PEM block containing the public key")
}
if strings.Contains(block.Type, "PRIVATE") {
return "", ErrKeyIsPrivate
diff --git a/models/asymkey/ssh_key_verify.go b/models/asymkey/ssh_key_verify.go
index 208288c77b..605ffe9096 100644
--- a/models/asymkey/ssh_key_verify.go
+++ b/models/asymkey/ssh_key_verify.go
@@ -4,8 +4,8 @@
package asymkey
import (
- "bytes"
"context"
+ "strings"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log"
@@ -30,11 +30,11 @@ func VerifySSHKey(ctx context.Context, ownerID int64, fingerprint, token, signat
return "", ErrKeyNotExist{}
}
- err = sshsig.Verify(bytes.NewBuffer([]byte(token)), []byte(signature), []byte(key.Content), "gitea")
+ err = sshsig.Verify(strings.NewReader(token), []byte(signature), []byte(key.Content), "gitea")
if err != nil {
// edge case for Windows based shells that will add CR LF if piped to ssh-keygen command
// see https://github.com/PowerShell/PowerShell/issues/5974
- if sshsig.Verify(bytes.NewBuffer([]byte(token+"\r\n")), []byte(signature), []byte(key.Content), "gitea") != nil {
+ if sshsig.Verify(strings.NewReader(token+"\r\n"), []byte(signature), []byte(key.Content), "gitea") != nil {
log.Error("Unable to validate token signature. Error: %v", err)
return "", ErrSSHInvalidTokenSignature{
Fingerprint: key.Fingerprint,
diff --git a/models/auth/access_token_scope_test.go b/models/auth/access_token_scope_test.go
index 9e4aa83633..b93c25528f 100644
--- a/models/auth/access_token_scope_test.go
+++ b/models/auth/access_token_scope_test.go
@@ -28,11 +28,11 @@ func TestAccessTokenScope_Normalize(t *testing.T) {
for _, scope := range GetAccessTokenCategories() {
tests = append(tests,
- scopeTestNormalize{AccessTokenScope(fmt.Sprintf("read:%s", scope)), AccessTokenScope(fmt.Sprintf("read:%s", scope)), nil},
- scopeTestNormalize{AccessTokenScope(fmt.Sprintf("write:%s", scope)), AccessTokenScope(fmt.Sprintf("write:%s", scope)), nil},
- scopeTestNormalize{AccessTokenScope(fmt.Sprintf("write:%[1]s,read:%[1]s", scope)), AccessTokenScope(fmt.Sprintf("write:%s", scope)), nil},
- scopeTestNormalize{AccessTokenScope(fmt.Sprintf("read:%[1]s,write:%[1]s", scope)), AccessTokenScope(fmt.Sprintf("write:%s", scope)), nil},
- scopeTestNormalize{AccessTokenScope(fmt.Sprintf("read:%[1]s,write:%[1]s,write:%[1]s", scope)), AccessTokenScope(fmt.Sprintf("write:%s", scope)), nil},
+ scopeTestNormalize{AccessTokenScope("read:" + scope), AccessTokenScope("read:" + scope), nil},
+ scopeTestNormalize{AccessTokenScope("write:" + scope), AccessTokenScope("write:" + scope), nil},
+ scopeTestNormalize{AccessTokenScope(fmt.Sprintf("write:%[1]s,read:%[1]s", scope)), AccessTokenScope("write:" + scope), nil},
+ scopeTestNormalize{AccessTokenScope(fmt.Sprintf("read:%[1]s,write:%[1]s", scope)), AccessTokenScope("write:" + scope), nil},
+ scopeTestNormalize{AccessTokenScope(fmt.Sprintf("read:%[1]s,write:%[1]s,write:%[1]s", scope)), AccessTokenScope("write:" + scope), nil},
)
}
@@ -63,20 +63,20 @@ func TestAccessTokenScope_HasScope(t *testing.T) {
for _, scope := range GetAccessTokenCategories() {
tests = append(tests,
scopeTestHasScope{
- AccessTokenScope(fmt.Sprintf("read:%s", scope)),
- AccessTokenScope(fmt.Sprintf("read:%s", scope)), true, nil,
+ AccessTokenScope("read:" + scope),
+ AccessTokenScope("read:" + scope), true, nil,
},
scopeTestHasScope{
- AccessTokenScope(fmt.Sprintf("write:%s", scope)),
- AccessTokenScope(fmt.Sprintf("write:%s", scope)), true, nil,
+ AccessTokenScope("write:" + scope),
+ AccessTokenScope("write:" + scope), true, nil,
},
scopeTestHasScope{
- AccessTokenScope(fmt.Sprintf("write:%s", scope)),
- AccessTokenScope(fmt.Sprintf("read:%s", scope)), true, nil,
+ AccessTokenScope("write:" + scope),
+ AccessTokenScope("read:" + scope), true, nil,
},
scopeTestHasScope{
- AccessTokenScope(fmt.Sprintf("read:%s", scope)),
- AccessTokenScope(fmt.Sprintf("write:%s", scope)), false, nil,
+ AccessTokenScope("read:" + scope),
+ AccessTokenScope("write:" + scope), false, nil,
},
)
}
diff --git a/models/db/engine.go b/models/db/engine.go
index 91015f7038..ba287d58f0 100755
--- a/models/db/engine.go
+++ b/models/db/engine.go
@@ -127,7 +127,7 @@ func IsTableNotEmpty(beanOrTableName any) (bool, error) {
// DeleteAllRecords will delete all the records of this table
func DeleteAllRecords(tableName string) error {
- _, err := xormEngine.Exec(fmt.Sprintf("DELETE FROM %s", tableName))
+ _, err := xormEngine.Exec("DELETE FROM " + tableName)
return err
}
diff --git a/models/db/error.go b/models/db/error.go
index 665e970e17..d47c7adac4 100644
--- a/models/db/error.go
+++ b/models/db/error.go
@@ -65,7 +65,7 @@ func (err ErrNotExist) Error() string {
if err.ID != 0 {
return fmt.Sprintf("%s does not exist [id: %d]", name, err.ID)
}
- return fmt.Sprintf("%s does not exist", name)
+ return name + " does not exist"
}
// Unwrap unwraps this as a ErrNotExist err
diff --git a/models/git/commit_status.go b/models/git/commit_status.go
index d1c94aa023..b978476c4b 100644
--- a/models/git/commit_status.go
+++ b/models/git/commit_status.go
@@ -222,7 +222,7 @@ func (status *CommitStatus) HideActionsURL(ctx context.Context) {
}
}
- prefix := fmt.Sprintf("%s/actions", status.Repo.Link())
+ prefix := status.Repo.Link() + "/actions"
if strings.HasPrefix(status.TargetURL, prefix) {
status.TargetURL = ""
}
diff --git a/models/issues/issue.go b/models/issues/issue.go
index 5204f27faf..a86d50ca9d 100644
--- a/models/issues/issue.go
+++ b/models/issues/issue.go
@@ -10,6 +10,7 @@ import (
"html/template"
"regexp"
"slices"
+ "strconv"
"code.gitea.io/gitea/models/db"
project_model "code.gitea.io/gitea/models/project"
@@ -815,7 +816,7 @@ func ChangeIssueTimeEstimate(ctx context.Context, issue *Issue, doer *user_model
Doer: doer,
Repo: issue.Repo,
Issue: issue,
- Content: fmt.Sprintf("%d", timeEstimate),
+ Content: strconv.FormatInt(timeEstimate, 10),
}
if _, err := CreateComment(ctx, opts); err != nil {
return fmt.Errorf("createComment: %w", err)
diff --git a/models/issues/issue_update.go b/models/issues/issue_update.go
index 7b3fe04aa5..746a59c6fd 100644
--- a/models/issues/issue_update.go
+++ b/models/issues/issue_update.go
@@ -5,6 +5,7 @@ package issues
import (
"context"
+ "errors"
"fmt"
"strings"
@@ -386,10 +387,10 @@ func NewIssueWithIndex(ctx context.Context, doer *user_model.User, opts NewIssue
}
if opts.Issue.Index <= 0 {
- return fmt.Errorf("no issue index provided")
+ return errors.New("no issue index provided")
}
if opts.Issue.ID > 0 {
- return fmt.Errorf("issue exist")
+ return errors.New("issue exist")
}
if _, err := e.Insert(opts.Issue); err != nil {
diff --git a/models/issues/pull.go b/models/issues/pull.go
index e3af00224d..016db9f75c 100644
--- a/models/issues/pull.go
+++ b/models/issues/pull.go
@@ -6,6 +6,7 @@ package issues
import (
"context"
+ "errors"
"fmt"
"io"
"regexp"
@@ -732,7 +733,7 @@ func (pr *PullRequest) GetWorkInProgressPrefix(ctx context.Context) string {
// UpdateCommitDivergence update Divergence of a pull request
func (pr *PullRequest) UpdateCommitDivergence(ctx context.Context, ahead, behind int) error {
if pr.ID == 0 {
- return fmt.Errorf("pull ID is 0")
+ return errors.New("pull ID is 0")
}
pr.CommitsAhead = ahead
pr.CommitsBehind = behind
@@ -925,7 +926,7 @@ func ParseCodeOwnersLine(ctx context.Context, tokens []string) (*CodeOwnerRule,
if strings.Contains(user, "/") {
s := strings.Split(user, "/")
if len(s) != 2 {
- warnings = append(warnings, fmt.Sprintf("incorrect codeowner group: %s", user))
+ warnings = append(warnings, "incorrect codeowner group: "+user)
continue
}
orgName := s[0]
@@ -933,12 +934,12 @@ func ParseCodeOwnersLine(ctx context.Context, tokens []string) (*CodeOwnerRule,
org, err := org_model.GetOrgByName(ctx, orgName)
if err != nil {
- warnings = append(warnings, fmt.Sprintf("incorrect codeowner organization: %s", user))
+ warnings = append(warnings, "incorrect codeowner organization: "+user)
continue
}
teams, err := org.LoadTeams(ctx)
if err != nil {
- warnings = append(warnings, fmt.Sprintf("incorrect codeowner team: %s", user))
+ warnings = append(warnings, "incorrect codeowner team: "+user)
continue
}
@@ -950,7 +951,7 @@ func ParseCodeOwnersLine(ctx context.Context, tokens []string) (*CodeOwnerRule,
} else {
u, err := user_model.GetUserByName(ctx, user)
if err != nil {
- warnings = append(warnings, fmt.Sprintf("incorrect codeowner user: %s", user))
+ warnings = append(warnings, "incorrect codeowner user: "+user)
continue
}
rule.Users = append(rule.Users, u)
diff --git a/models/issues/review.go b/models/issues/review.go
index 1c5c2ee30a..2667bdaa7b 100644
--- a/models/issues/review.go
+++ b/models/issues/review.go
@@ -5,6 +5,7 @@ package issues
import (
"context"
+ "errors"
"fmt"
"slices"
"strings"
@@ -374,7 +375,7 @@ func CreateReview(ctx context.Context, opts CreateReviewOptions) (*Review, error
review.Type = ReviewTypeRequest
review.ReviewerTeamID = opts.ReviewerTeam.ID
} else {
- return nil, fmt.Errorf("provide either reviewer or reviewer team")
+ return nil, errors.New("provide either reviewer or reviewer team")
}
if _, err := sess.Insert(review); err != nil {
@@ -933,7 +934,7 @@ func MarkConversation(ctx context.Context, comment *Comment, doer *user_model.Us
// the PR writer , official reviewer and poster can do it
func CanMarkConversation(ctx context.Context, issue *Issue, doer *user_model.User) (permResult bool, err error) {
if doer == nil || issue == nil {
- return false, fmt.Errorf("issue or doer is nil")
+ return false, errors.New("issue or doer is nil")
}
if err = issue.LoadRepo(ctx); err != nil {
@@ -972,11 +973,11 @@ func DeleteReview(ctx context.Context, r *Review) error {
defer committer.Close()
if r.ID == 0 {
- return fmt.Errorf("review is not allowed to be 0")
+ return errors.New("review is not allowed to be 0")
}
if r.Type == ReviewTypeRequest {
- return fmt.Errorf("review request can not be deleted using this method")
+ return errors.New("review request can not be deleted using this method")
}
opts := FindCommentsOptions{
diff --git a/models/migrations/base/db.go b/models/migrations/base/db.go
index eb1c44a79e..4ecc930f10 100644
--- a/models/migrations/base/db.go
+++ b/models/migrations/base/db.go
@@ -52,7 +52,7 @@ func RecreateTable(sess *xorm.Session, bean any) error {
// TODO: This will not work if there are foreign keys
tableName := sess.Engine().TableName(bean)
- tempTableName := fmt.Sprintf("tmp_recreate__%s", tableName)
+ tempTableName := "tmp_recreate__" + tableName
// We need to move the old table away and create a new one with the correct columns
// We will need to do this in stages to prevent data loss
@@ -82,7 +82,7 @@ func RecreateTable(sess *xorm.Session, bean any) error {
}
newTableColumns := table.Columns()
if len(newTableColumns) == 0 {
- return fmt.Errorf("no columns in new table")
+ return errors.New("no columns in new table")
}
hasID := false
for _, column := range newTableColumns {
@@ -552,11 +552,11 @@ func deleteDB() error {
}
defer db.Close()
- if _, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", setting.Database.Name)); err != nil {
+ if _, err = db.Exec("DROP DATABASE IF EXISTS " + setting.Database.Name); err != nil {
return err
}
- if _, err = db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", setting.Database.Name)); err != nil {
+ if _, err = db.Exec("CREATE DATABASE IF NOT EXISTS " + setting.Database.Name); err != nil {
return err
}
return nil
@@ -568,11 +568,11 @@ func deleteDB() error {
}
defer db.Close()
- if _, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", setting.Database.Name)); err != nil {
+ if _, err = db.Exec("DROP DATABASE IF EXISTS " + setting.Database.Name); err != nil {
return err
}
- if _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", setting.Database.Name)); err != nil {
+ if _, err = db.Exec("CREATE DATABASE " + setting.Database.Name); err != nil {
return err
}
db.Close()
@@ -594,7 +594,7 @@ func deleteDB() error {
if !schrows.Next() {
// Create and setup a DB schema
- _, err = db.Exec(fmt.Sprintf("CREATE SCHEMA %s", setting.Database.Schema))
+ _, err = db.Exec("CREATE SCHEMA " + setting.Database.Schema)
if err != nil {
return err
}
diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go
index 6e631f98c7..6a60067782 100644
--- a/models/migrations/migrations.go
+++ b/models/migrations/migrations.go
@@ -6,6 +6,7 @@ package migrations
import (
"context"
+ "errors"
"fmt"
"code.gitea.io/gitea/models/migrations/v1_10"
@@ -424,7 +425,7 @@ func EnsureUpToDate(ctx context.Context, x *xorm.Engine) error {
}
if currentDB < 0 {
- return fmt.Errorf("database has not been initialized")
+ return errors.New("database has not been initialized")
}
if minDBVersion > currentDB {
diff --git a/models/migrations/v1_13/v140.go b/models/migrations/v1_13/v140.go
index 2d3337012d..f3719e16f6 100644
--- a/models/migrations/v1_13/v140.go
+++ b/models/migrations/v1_13/v140.go
@@ -46,7 +46,7 @@ func FixLanguageStatsToSaveSize(x *xorm.Engine) error {
}
// Delete language stats
- if _, err := x.Exec(fmt.Sprintf("%s language_stat", truncExpr)); err != nil {
+ if _, err := x.Exec(truncExpr + " language_stat"); err != nil {
return err
}
diff --git a/models/migrations/v1_13/v145.go b/models/migrations/v1_13/v145.go
index 8acb29bf33..bb1f40baa7 100644
--- a/models/migrations/v1_13/v145.go
+++ b/models/migrations/v1_13/v145.go
@@ -42,7 +42,7 @@ func IncreaseLanguageField(x *xorm.Engine) error {
switch {
case setting.Database.Type.IsMySQL():
- if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE language_stat MODIFY COLUMN language %s", sqlType)); err != nil {
+ if _, err := sess.Exec("ALTER TABLE language_stat MODIFY COLUMN language " + sqlType); err != nil {
return err
}
case setting.Database.Type.IsMSSQL():
@@ -64,7 +64,7 @@ func IncreaseLanguageField(x *xorm.Engine) error {
return fmt.Errorf("Drop table `language_stat` constraint `%s`: %w", constraint, err)
}
}
- if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE language_stat ALTER COLUMN language %s", sqlType)); err != nil {
+ if _, err := sess.Exec("ALTER TABLE language_stat ALTER COLUMN language " + sqlType); err != nil {
return err
}
// Finally restore the constraint
@@ -72,7 +72,7 @@ func IncreaseLanguageField(x *xorm.Engine) error {
return err
}
case setting.Database.Type.IsPostgreSQL():
- if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE language_stat ALTER COLUMN language TYPE %s", sqlType)); err != nil {
+ if _, err := sess.Exec("ALTER TABLE language_stat ALTER COLUMN language TYPE " + sqlType); err != nil {
return err
}
}
diff --git a/models/migrations/v1_13/v151.go b/models/migrations/v1_13/v151.go
index 25af1d03ec..1865d58f04 100644
--- a/models/migrations/v1_13/v151.go
+++ b/models/migrations/v1_13/v151.go
@@ -5,6 +5,7 @@ package v1_13 //nolint
import (
"context"
+ "errors"
"fmt"
"strings"
@@ -113,7 +114,7 @@ func SetDefaultPasswordToArgon2(x *xorm.Engine) error {
newTableColumns := table.Columns()
if len(newTableColumns) == 0 {
- return fmt.Errorf("no columns in new table")
+ return errors.New("no columns in new table")
}
hasID := false
for _, column := range newTableColumns {
diff --git a/models/migrations/v1_14/v158.go b/models/migrations/v1_14/v158.go
index 1094d8abf7..a849ddf27e 100644
--- a/models/migrations/v1_14/v158.go
+++ b/models/migrations/v1_14/v158.go
@@ -4,7 +4,7 @@
package v1_14 //nolint
import (
- "fmt"
+ "errors"
"strconv"
"code.gitea.io/gitea/modules/log"
@@ -82,7 +82,7 @@ func UpdateCodeCommentReplies(x *xorm.Engine) error {
sqlCmd = "SELECT TOP " + strconv.Itoa(batchSize) + " * FROM #temp_comments WHERE " +
"(id NOT IN ( SELECT TOP " + strconv.Itoa(start) + " id FROM #temp_comments ORDER BY id )) ORDER BY id"
default:
- return fmt.Errorf("Unsupported database type")
+ return errors.New("Unsupported database type")
}
if err := sess.SQL(sqlCmd).Find(&comments); err != nil {
diff --git a/models/migrations/v1_17/v222.go b/models/migrations/v1_17/v222.go
index 2ffb94eb1c..6c28f8102b 100644
--- a/models/migrations/v1_17/v222.go
+++ b/models/migrations/v1_17/v222.go
@@ -5,6 +5,7 @@ package v1_17 //nolint
import (
"context"
+ "errors"
"fmt"
"code.gitea.io/gitea/models/migrations/base"
@@ -29,7 +30,7 @@ func DropOldCredentialIDColumn(x *xorm.Engine) error {
}
if !credentialIDBytesExists {
// looks like 221 hasn't properly run
- return fmt.Errorf("webauthn_credential does not have a credential_id_bytes column... it is not safe to run this migration")
+ return errors.New("webauthn_credential does not have a credential_id_bytes column... it is not safe to run this migration")
}
// Create webauthnCredential table
diff --git a/models/migrations/v1_20/v245.go b/models/migrations/v1_20/v245.go
index ab58d12880..5a195d2ccd 100644
--- a/models/migrations/v1_20/v245.go
+++ b/models/migrations/v1_20/v245.go
@@ -5,7 +5,6 @@ package v1_20 //nolint
import (
"context"
- "fmt"
"code.gitea.io/gitea/models/migrations/base"
"code.gitea.io/gitea/modules/setting"
@@ -57,7 +56,7 @@ func RenameWebhookOrgToOwner(x *xorm.Engine) error {
return err
}
sqlType := x.Dialect().SQLType(inferredTable.GetColumn("org_id"))
- if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `webhook` CHANGE org_id owner_id %s", sqlType)); err != nil {
+ if _, err := sess.Exec("ALTER TABLE `webhook` CHANGE org_id owner_id " + sqlType); err != nil {
return err
}
case setting.Database.Type.IsMSSQL():
diff --git a/models/migrations/v1_21/v264.go b/models/migrations/v1_21/v264.go
index e81a17ad6d..d737ef03b3 100644
--- a/models/migrations/v1_21/v264.go
+++ b/models/migrations/v1_21/v264.go
@@ -5,7 +5,7 @@ package v1_21 //nolint
import (
"context"
- "fmt"
+ "errors"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/timeutil"
@@ -57,7 +57,7 @@ func AddBranchTable(x *xorm.Engine) error {
if err != nil {
return err
} else if !has {
- return fmt.Errorf("no admin user found")
+ return errors.New("no admin user found")
}
branches := make([]Branch, 0, 100)
diff --git a/models/migrations/v1_22/v287_test.go b/models/migrations/v1_22/v287_test.go
index 9c7b10947d..58c3152ac3 100644
--- a/models/migrations/v1_22/v287_test.go
+++ b/models/migrations/v1_22/v287_test.go
@@ -4,7 +4,7 @@
package v1_22 //nolint
import (
- "fmt"
+ "strconv"
"testing"
"code.gitea.io/gitea/models/migrations/base"
@@ -50,7 +50,7 @@ func Test_UpdateBadgeColName(t *testing.T) {
for i, e := range oldBadges {
got := got[i+1] // 1 is in the badge.yml
assert.Equal(t, e.ID, got.ID)
- assert.Equal(t, fmt.Sprintf("%d", e.ID), got.Slug)
+ assert.Equal(t, strconv.FormatInt(e.ID, 10), got.Slug)
}
// TODO: check if badges have been updated
diff --git a/models/packages/descriptor.go b/models/packages/descriptor.go
index d251fcc4a9..c97bd46c9e 100644
--- a/models/packages/descriptor.go
+++ b/models/packages/descriptor.go
@@ -197,7 +197,7 @@ func GetPackageDescriptor(ctx context.Context, pv *PackageVersion) (*PackageDesc
case TypeVagrant:
metadata = &vagrant.Metadata{}
default:
- panic(fmt.Sprintf("unknown package type: %s", string(p.Type)))
+ panic("unknown package type: " + string(p.Type))
}
if metadata != nil {
if err := json.Unmarshal([]byte(pv.MetadataJSON), &metadata); err != nil {
diff --git a/models/packages/package.go b/models/packages/package.go
index 8935dbaa1c..38d1cdcf66 100644
--- a/models/packages/package.go
+++ b/models/packages/package.go
@@ -127,7 +127,7 @@ func (pt Type) Name() string {
case TypeVagrant:
return "Vagrant"
}
- panic(fmt.Sprintf("unknown package type: %s", string(pt)))
+ panic("unknown package type: " + string(pt))
}
// SVGName gets the name of the package type svg image
@@ -178,7 +178,7 @@ func (pt Type) SVGName() string {
case TypeVagrant:
return "gitea-vagrant"
}
- panic(fmt.Sprintf("unknown package type: %s", string(pt)))
+ panic("unknown package type: " + string(pt))
}
// Package represents a package
diff --git a/models/project/column.go b/models/project/column.go
index 77ff5ef83e..9b9d874997 100644
--- a/models/project/column.go
+++ b/models/project/column.go
@@ -147,7 +147,7 @@ func NewColumn(ctx context.Context, column *Column) error {
return err
}
if res.ColumnCount >= maxProjectColumns {
- return fmt.Errorf("NewBoard: maximum number of columns reached")
+ return errors.New("NewBoard: maximum number of columns reached")
}
column.Sorting = int8(util.Iif(res.ColumnCount > 0, res.MaxSorting+1, 0))
_, err := db.GetEngine(ctx).Insert(column)
@@ -172,7 +172,7 @@ func deleteColumnByID(ctx context.Context, columnID int64) error {
}
if column.Default {
- return fmt.Errorf("deleteColumnByID: cannot delete default column")
+ return errors.New("deleteColumnByID: cannot delete default column")
}
// move all issues to the default column
diff --git a/models/project/issue.go b/models/project/issue.go
index 98eed2a213..47d1537ec7 100644
--- a/models/project/issue.go
+++ b/models/project/issue.go
@@ -5,7 +5,7 @@ package project
import (
"context"
- "fmt"
+ "errors"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/util"
@@ -35,7 +35,7 @@ func deleteProjectIssuesByProjectID(ctx context.Context, projectID int64) error
func (c *Column) moveIssuesToAnotherColumn(ctx context.Context, newColumn *Column) error {
if c.ProjectID != newColumn.ProjectID {
- return fmt.Errorf("columns have to be in the same project")
+ return errors.New("columns have to be in the same project")
}
if c.ID == newColumn.ID {
diff --git a/models/repo/attachment.go b/models/repo/attachment.go
index fa4f6c47e6..835bee5402 100644
--- a/models/repo/attachment.go
+++ b/models/repo/attachment.go
@@ -224,7 +224,7 @@ func DeleteAttachmentsByComment(ctx context.Context, commentID int64, remove boo
// UpdateAttachmentByUUID Updates attachment via uuid
func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...string) error {
if attach.UUID == "" {
- return fmt.Errorf("attachment uuid should be not blank")
+ return errors.New("attachment uuid should be not blank")
}
_, err := db.GetEngine(ctx).Where("uuid=?", attach.UUID).Cols(cols...).Update(attach)
return err
diff --git a/models/repo/avatar.go b/models/repo/avatar.go
index ccfac12cad..eff64bd239 100644
--- a/models/repo/avatar.go
+++ b/models/repo/avatar.go
@@ -9,6 +9,7 @@ import (
"image/png"
"io"
"net/url"
+ "strconv"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/avatar"
@@ -37,7 +38,7 @@ func (repo *Repository) RelAvatarLink(ctx context.Context) string {
// generateRandomAvatar generates a random avatar for repository.
func generateRandomAvatar(ctx context.Context, repo *Repository) error {
- idToString := fmt.Sprintf("%d", repo.ID)
+ idToString := strconv.FormatInt(repo.ID, 10)
seed := idToString
img, err := avatar.RandomImage([]byte(seed))
diff --git a/models/repo/repo.go b/models/repo/repo.go
index 515c57916c..050be760d5 100644
--- a/models/repo/repo.go
+++ b/models/repo/repo.go
@@ -5,6 +5,7 @@ package repo
import (
"context"
+ "errors"
"fmt"
"html/template"
"maps"
@@ -59,7 +60,7 @@ type ErrRepoIsArchived struct {
}
func (err ErrRepoIsArchived) Error() string {
- return fmt.Sprintf("%s is archived", err.Repo.LogString())
+ return err.Repo.LogString() + " is archived"
}
type globalVarsStruct struct {
@@ -820,7 +821,7 @@ func GetRepositoryByName(ctx context.Context, ownerID int64, name string) (*Repo
func GetRepositoryByURL(ctx context.Context, repoURL string) (*Repository, error) {
ret, err := giturl.ParseRepositoryURL(ctx, repoURL)
if err != nil || ret.OwnerName == "" {
- return nil, fmt.Errorf("unknown or malformed repository URL")
+ return nil, errors.New("unknown or malformed repository URL")
}
return GetRepositoryByOwnerAndName(ctx, ret.OwnerName, ret.RepoName)
}
diff --git a/models/repo/repo_unit.go b/models/repo/repo_unit.go
index e83a3dc8c2..8a7dbfe340 100644
--- a/models/repo/repo_unit.go
+++ b/models/repo/repo_unit.go
@@ -5,7 +5,6 @@ package repo
import (
"context"
- "fmt"
"slices"
"strings"
@@ -33,7 +32,7 @@ func IsErrUnitTypeNotExist(err error) bool {
}
func (err ErrUnitTypeNotExist) Error() string {
- return fmt.Sprintf("Unit type does not exist: %s", err.UT.LogString())
+ return "Unit type does not exist: " + err.UT.LogString()
}
func (err ErrUnitTypeNotExist) Unwrap() error {
diff --git a/models/repo/wiki.go b/models/repo/wiki.go
index 4239a815b2..832e15ae0d 100644
--- a/models/repo/wiki.go
+++ b/models/repo/wiki.go
@@ -46,7 +46,7 @@ func IsErrWikiReservedName(err error) bool {
}
func (err ErrWikiReservedName) Error() string {
- return fmt.Sprintf("wiki title is reserved: %s", err.Title)
+ return "wiki title is reserved: " + err.Title
}
func (err ErrWikiReservedName) Unwrap() error {
@@ -65,7 +65,7 @@ func IsErrWikiInvalidFileName(err error) bool {
}
func (err ErrWikiInvalidFileName) Error() string {
- return fmt.Sprintf("Invalid wiki filename: %s", err.FileName)
+ return "Invalid wiki filename: " + err.FileName
}
func (err ErrWikiInvalidFileName) Unwrap() error {
diff --git a/models/unittest/fixtures_loader.go b/models/unittest/fixtures_loader.go
index 674f5cbe54..0560da8349 100644
--- a/models/unittest/fixtures_loader.go
+++ b/models/unittest/fixtures_loader.go
@@ -120,7 +120,7 @@ func (f *fixturesLoaderInternal) loadFixtures(tx *sql.Tx, fixture *FixtureItem)
}
}
- _, err = tx.Exec(fmt.Sprintf("DELETE FROM %s", fixture.tableNameQuoted)) // sqlite3 doesn't support truncate
+ _, err = tx.Exec("DELETE FROM " + fixture.tableNameQuoted) // sqlite3 doesn't support truncate
if err != nil {
return err
}
diff --git a/models/unittest/unit_tests.go b/models/unittest/unit_tests.go
index 1c5595aef8..4a4cec40ae 100644
--- a/models/unittest/unit_tests.go
+++ b/models/unittest/unit_tests.go
@@ -153,9 +153,9 @@ func DumpQueryResult(t require.TestingT, sqlOrBean any, sqlArgs ...any) {
goDB := x.DB().DB
sql, ok := sqlOrBean.(string)
if !ok {
- sql = fmt.Sprintf("SELECT * FROM %s", db.TableName(sqlOrBean))
+ sql = "SELECT * FROM " + db.TableName(sqlOrBean)
} else if !strings.Contains(sql, " ") {
- sql = fmt.Sprintf("SELECT * FROM %s", sql)
+ sql = "SELECT * FROM " + sql
}
rows, err := goDB.Query(sql, sqlArgs...)
require.NoError(t, err)
diff --git a/models/user/setting.go b/models/user/setting.go
index b4af0e5ccd..c65afae76c 100644
--- a/models/user/setting.go
+++ b/models/user/setting.go
@@ -5,6 +5,7 @@ package user
import (
"context"
+ "errors"
"fmt"
"strings"
@@ -114,10 +115,10 @@ func GetUserAllSettings(ctx context.Context, uid int64) (map[string]*Setting, er
func validateUserSettingKey(key string) error {
if len(key) == 0 {
- return fmt.Errorf("setting key must be set")
+ return errors.New("setting key must be set")
}
if strings.ToLower(key) != key {
- return fmt.Errorf("setting key should be lowercase")
+ return errors.New("setting key should be lowercase")
}
return nil
}
diff --git a/models/user/user.go b/models/user/user.go
index 3c72aa7cc4..3b268a6f41 100644
--- a/models/user/user.go
+++ b/models/user/user.go
@@ -1169,8 +1169,8 @@ func GetUsersByEmails(ctx context.Context, emails []string) (map[string]*User, e
needCheckEmails := make(container.Set[string])
needCheckUserNames := make(container.Set[string])
for _, email := range emails {
- if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
- username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
+ if strings.HasSuffix(email, "@"+setting.Service.NoReplyAddress) {
+ username := strings.TrimSuffix(email, "@"+setting.Service.NoReplyAddress)
needCheckUserNames.Add(username)
} else {
needCheckEmails.Add(strings.ToLower(email))
@@ -1232,8 +1232,8 @@ func GetUserByEmail(ctx context.Context, email string) (*User, error) {
}
// Finally, if email address is the protected email address:
- if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
- username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
+ if strings.HasSuffix(email, "@"+setting.Service.NoReplyAddress) {
+ username := strings.TrimSuffix(email, "@"+setting.Service.NoReplyAddress)
user := &User{}
has, err := db.GetEngine(ctx).Where("lower_name=?", username).Get(user)
if err != nil {
diff --git a/modules/avatar/identicon/identicon.go b/modules/avatar/identicon/identicon.go
index 63926d5f19..87bd87796e 100644
--- a/modules/avatar/identicon/identicon.go
+++ b/modules/avatar/identicon/identicon.go
@@ -8,6 +8,7 @@ package identicon
import (
"crypto/sha256"
+ "errors"
"fmt"
"image"
"image/color"
@@ -29,7 +30,7 @@ type Identicon struct {
// fore all possible foreground colors. only one foreground color will be picked randomly for one image
func New(size int, back color.Color, fore ...color.Color) (*Identicon, error) {
if len(fore) == 0 {
- return nil, fmt.Errorf("foreground is not set")
+ return nil, errors.New("foreground is not set")
}
if size < minImageSize {
diff --git a/modules/cache/cache.go b/modules/cache/cache.go
index f7828e3cae..a434c13b67 100644
--- a/modules/cache/cache.go
+++ b/modules/cache/cache.go
@@ -4,6 +4,8 @@
package cache
import (
+ "encoding/hex"
+ "errors"
"fmt"
"strconv"
"time"
@@ -48,10 +50,10 @@ const (
// returns
func Test() (time.Duration, error) {
if defaultCache == nil {
- return 0, fmt.Errorf("default cache not initialized")
+ return 0, errors.New("default cache not initialized")
}
- testData := fmt.Sprintf("%x", make([]byte, 500))
+ testData := hex.EncodeToString(make([]byte, 500))
start := time.Now()
@@ -63,10 +65,10 @@ func Test() (time.Duration, error) {
}
testVal, hit := defaultCache.Get(testCacheKey)
if !hit {
- return 0, fmt.Errorf("expect cache hit but got none")
+ return 0, errors.New("expect cache hit but got none")
}
if testVal != testData {
- return 0, fmt.Errorf("expect cache to return same value as stored but got other")
+ return 0, errors.New("expect cache to return same value as stored but got other")
}
return time.Since(start), nil
diff --git a/modules/cache/cache_test.go b/modules/cache/cache_test.go
index 2f6f329e88..d6ea2032ee 100644
--- a/modules/cache/cache_test.go
+++ b/modules/cache/cache_test.go
@@ -4,7 +4,7 @@
package cache
import (
- "fmt"
+ "errors"
"testing"
"time"
@@ -57,7 +57,7 @@ func TestGetString(t *testing.T) {
createTestCache()
data, err := GetString("key", func() (string, error) {
- return "", fmt.Errorf("some error")
+ return "", errors.New("some error")
})
assert.Error(t, err)
assert.Empty(t, data)
@@ -82,7 +82,7 @@ func TestGetString(t *testing.T) {
assert.Equal(t, "some data", data)
data, err = GetString("key", func() (string, error) {
- return "", fmt.Errorf("some error")
+ return "", errors.New("some error")
})
assert.NoError(t, err)
assert.Equal(t, "some data", data)
@@ -93,7 +93,7 @@ func TestGetInt64(t *testing.T) {
createTestCache()
data, err := GetInt64("key", func() (int64, error) {
- return 0, fmt.Errorf("some error")
+ return 0, errors.New("some error")
})
assert.Error(t, err)
assert.EqualValues(t, 0, data)
@@ -118,7 +118,7 @@ func TestGetInt64(t *testing.T) {
assert.EqualValues(t, 100, data)
data, err = GetInt64("key", func() (int64, error) {
- return 0, fmt.Errorf("some error")
+ return 0, errors.New("some error")
})
assert.NoError(t, err)
assert.EqualValues(t, 100, data)
diff --git a/modules/git/grep.go b/modules/git/grep.go
index 51ebcb832f..66711650c9 100644
--- a/modules/git/grep.go
+++ b/modules/git/grep.go
@@ -61,7 +61,7 @@ func GrepSearch(ctx context.Context, repo *Repository, search string, opts GrepO
*/
var results []*GrepResult
cmd := NewCommand("grep", "--null", "--break", "--heading", "--line-number", "--full-name")
- cmd.AddOptionValues("--context", fmt.Sprint(opts.ContextLineNumber))
+ cmd.AddOptionValues("--context", strconv.Itoa(opts.ContextLineNumber))
switch opts.GrepMode {
case GrepModeExact:
cmd.AddArguments("--fixed-strings")
diff --git a/modules/git/object_id.go b/modules/git/object_id.go
index 82d30184df..25dfef3ec5 100644
--- a/modules/git/object_id.go
+++ b/modules/git/object_id.go
@@ -99,5 +99,5 @@ type ErrInvalidSHA struct {
}
func (err ErrInvalidSHA) Error() string {
- return fmt.Sprintf("invalid sha: %s", err.SHA)
+ return "invalid sha: " + err.SHA
}
diff --git a/modules/git/repo_attribute.go b/modules/git/repo_attribute.go
index 8a5e5fa983..fde42d4730 100644
--- a/modules/git/repo_attribute.go
+++ b/modules/git/repo_attribute.go
@@ -6,6 +6,7 @@ package git
import (
"bytes"
"context"
+ "errors"
"fmt"
"io"
"os"
@@ -74,7 +75,7 @@ func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[
fields := bytes.Split(stdOut.Bytes(), []byte{'\000'})
if len(fields)%3 != 1 {
- return nil, fmt.Errorf("wrong number of fields in return from check-attr")
+ return nil, errors.New("wrong number of fields in return from check-attr")
}
name2attribute2info := make(map[string]map[string]string)
@@ -120,7 +121,7 @@ func (c *CheckAttributeReader) Init(ctx context.Context) error {
c.stdOut = lw
c.stdOut.Close()
- return fmt.Errorf("no provided Attributes to check")
+ return errors.New("no provided Attributes to check")
}
c.ctx, c.cancel = context.WithCancel(ctx)
diff --git a/modules/git/repo_branch.go b/modules/git/repo_branch.go
index 916391f167..20a347a040 100644
--- a/modules/git/repo_branch.go
+++ b/modules/git/repo_branch.go
@@ -36,7 +36,7 @@ type Branch struct {
// GetHEADBranch returns corresponding branch of HEAD.
func (repo *Repository) GetHEADBranch() (*Branch, error) {
if repo == nil {
- return nil, fmt.Errorf("nil repo")
+ return nil, errors.New("nil repo")
}
stdout, _, err := NewCommand("symbolic-ref", "HEAD").RunStdString(repo.Ctx, &RunOpts{Dir: repo.Path})
if err != nil {
diff --git a/modules/globallock/redis_locker.go b/modules/globallock/redis_locker.go
index 34ed9e389b..45dc769fd4 100644
--- a/modules/globallock/redis_locker.go
+++ b/modules/globallock/redis_locker.go
@@ -6,7 +6,6 @@ package globallock
import (
"context"
"errors"
- "fmt"
"sync"
"sync/atomic"
"time"
@@ -78,7 +77,7 @@ func (l *redisLocker) Close() error {
func (l *redisLocker) lock(ctx context.Context, key string, tries int) (ReleaseFunc, error) {
if l.closed.Load() {
- return func() {}, fmt.Errorf("locker is closed")
+ return func() {}, errors.New("locker is closed")
}
options := []redsync.Option{
diff --git a/modules/httplib/request.go b/modules/httplib/request.go
index 5e40922896..49ea6f4b73 100644
--- a/modules/httplib/request.go
+++ b/modules/httplib/request.go
@@ -108,7 +108,7 @@ func (r *Request) Body(data any) *Request {
switch t := data.(type) {
case nil: // do nothing
case string:
- bf := bytes.NewBufferString(t)
+ bf := strings.NewReader(t)
r.req.Body = io.NopCloser(bf)
r.req.ContentLength = int64(len(t))
case []byte:
@@ -143,13 +143,13 @@ func (r *Request) getResponse() (*http.Response, error) {
paramBody = paramBody[0 : len(paramBody)-1]
}
- if r.req.Method == "GET" && len(paramBody) > 0 {
+ if r.req.Method == http.MethodGet && len(paramBody) > 0 {
if strings.Contains(r.url, "?") {
r.url += "&" + paramBody
} else {
r.url = r.url + "?" + paramBody
}
- } else if r.req.Method == "POST" && r.req.Body == nil && len(paramBody) > 0 {
+ } else if r.req.Method == http.MethodPost && r.req.Body == nil && len(paramBody) > 0 {
r.Header("Content-Type", "application/x-www-form-urlencoded")
r.Body(paramBody) // string
}
diff --git a/modules/httplib/serve_test.go b/modules/httplib/serve_test.go
index 06c95bc594..78b88c9b5f 100644
--- a/modules/httplib/serve_test.go
+++ b/modules/httplib/serve_test.go
@@ -4,11 +4,11 @@
package httplib
import (
- "fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
+ "strconv"
"strings"
"testing"
@@ -23,14 +23,14 @@ func TestServeContentByReader(t *testing.T) {
_, rangeStr, _ := strings.Cut(t.Name(), "_range_")
r := &http.Request{Header: http.Header{}, Form: url.Values{}}
if rangeStr != "" {
- r.Header.Set("Range", fmt.Sprintf("bytes=%s", rangeStr))
+ r.Header.Set("Range", "bytes="+rangeStr)
}
reader := strings.NewReader(data)
w := httptest.NewRecorder()
ServeContentByReader(r, w, int64(len(data)), reader, &ServeHeaderOptions{})
assert.Equal(t, expectedStatusCode, w.Code)
if expectedStatusCode == http.StatusPartialContent || expectedStatusCode == http.StatusOK {
- assert.Equal(t, fmt.Sprint(len(expectedContent)), w.Header().Get("Content-Length"))
+ assert.Equal(t, strconv.Itoa(len(expectedContent)), w.Header().Get("Content-Length"))
assert.Equal(t, expectedContent, w.Body.String())
}
}
@@ -68,7 +68,7 @@ func TestServeContentByReadSeeker(t *testing.T) {
_, rangeStr, _ := strings.Cut(t.Name(), "_range_")
r := &http.Request{Header: http.Header{}, Form: url.Values{}}
if rangeStr != "" {
- r.Header.Set("Range", fmt.Sprintf("bytes=%s", rangeStr))
+ r.Header.Set("Range", "bytes="+rangeStr)
}
seekReader, err := os.OpenFile(tmpFile, os.O_RDONLY, 0o644)
@@ -79,7 +79,7 @@ func TestServeContentByReadSeeker(t *testing.T) {
ServeContentByReadSeeker(r, w, nil, seekReader, &ServeHeaderOptions{})
assert.Equal(t, expectedStatusCode, w.Code)
if expectedStatusCode == http.StatusPartialContent || expectedStatusCode == http.StatusOK {
- assert.Equal(t, fmt.Sprint(len(expectedContent)), w.Header().Get("Content-Length"))
+ assert.Equal(t, strconv.Itoa(len(expectedContent)), w.Header().Get("Content-Length"))
assert.Equal(t, expectedContent, w.Body.String())
}
}
diff --git a/modules/indexer/code/bleve/token/path/path.go b/modules/indexer/code/bleve/token/path/path.go
index 107e0da109..19f4b5bb5e 100644
--- a/modules/indexer/code/bleve/token/path/path.go
+++ b/modules/indexer/code/bleve/token/path/path.go
@@ -53,11 +53,11 @@ func generatePathTokens(input analysis.TokenStream, reversed bool) analysis.Toke
for i := 0; i < len(input); i++ {
var sb strings.Builder
- sb.WriteString(string(input[0].Term))
+ sb.Write(input[0].Term)
for j := 1; j < i; j++ {
sb.WriteString("/")
- sb.WriteString(string(input[j].Term))
+ sb.Write(input[j].Term)
}
term := sb.String()
diff --git a/modules/indexer/code/internal/indexer.go b/modules/indexer/code/internal/indexer.go
index 6c9a8af635..d58b028124 100644
--- a/modules/indexer/code/internal/indexer.go
+++ b/modules/indexer/code/internal/indexer.go
@@ -5,7 +5,7 @@ package internal
import (
"context"
- "fmt"
+ "errors"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
@@ -48,13 +48,13 @@ func (d *dummyIndexer) SupportedSearchModes() []indexer.SearchMode {
}
func (d *dummyIndexer) Index(ctx context.Context, repo *repo_model.Repository, sha string, changes *RepoChanges) error {
- return fmt.Errorf("indexer is not ready")
+ return errors.New("indexer is not ready")
}
func (d *dummyIndexer) Delete(ctx context.Context, repoID int64) error {
- return fmt.Errorf("indexer is not ready")
+ return errors.New("indexer is not ready")
}
func (d *dummyIndexer) Search(ctx context.Context, opts *SearchOptions) (int64, []*SearchResult, []*SearchResultLanguages, error) {
- return 0, nil, nil, fmt.Errorf("indexer is not ready")
+ return 0, nil, nil, errors.New("indexer is not ready")
}
diff --git a/modules/indexer/internal/bleve/indexer.go b/modules/indexer/internal/bleve/indexer.go
index 01e53ca636..9d1e24a874 100644
--- a/modules/indexer/internal/bleve/indexer.go
+++ b/modules/indexer/internal/bleve/indexer.go
@@ -5,7 +5,7 @@ package bleve
import (
"context"
- "fmt"
+ "errors"
"code.gitea.io/gitea/modules/indexer/internal"
"code.gitea.io/gitea/modules/log"
@@ -39,11 +39,11 @@ func NewIndexer(indexDir string, version int, mappingGetter func() (mapping.Inde
// Init initializes the indexer
func (i *Indexer) Init(_ context.Context) (bool, error) {
if i == nil {
- return false, fmt.Errorf("cannot init nil indexer")
+ return false, errors.New("cannot init nil indexer")
}
if i.Indexer != nil {
- return false, fmt.Errorf("indexer is already initialized")
+ return false, errors.New("indexer is already initialized")
}
indexer, version, err := openIndexer(i.indexDir, i.version)
@@ -83,10 +83,10 @@ func (i *Indexer) Init(_ context.Context) (bool, error) {
// Ping checks if the indexer is available
func (i *Indexer) Ping(_ context.Context) error {
if i == nil {
- return fmt.Errorf("cannot ping nil indexer")
+ return errors.New("cannot ping nil indexer")
}
if i.Indexer == nil {
- return fmt.Errorf("indexer is not initialized")
+ return errors.New("indexer is not initialized")
}
return nil
}
diff --git a/modules/indexer/internal/elasticsearch/indexer.go b/modules/indexer/internal/elasticsearch/indexer.go
index 395eea3bce..265ce26585 100644
--- a/modules/indexer/internal/elasticsearch/indexer.go
+++ b/modules/indexer/internal/elasticsearch/indexer.go
@@ -5,6 +5,7 @@ package elasticsearch
import (
"context"
+ "errors"
"fmt"
"code.gitea.io/gitea/modules/indexer/internal"
@@ -36,10 +37,10 @@ func NewIndexer(url, indexName string, version int, mapping string) *Indexer {
// Init initializes the indexer
func (i *Indexer) Init(ctx context.Context) (bool, error) {
if i == nil {
- return false, fmt.Errorf("cannot init nil indexer")
+ return false, errors.New("cannot init nil indexer")
}
if i.Client != nil {
- return false, fmt.Errorf("indexer is already initialized")
+ return false, errors.New("indexer is already initialized")
}
client, err := i.initClient()
@@ -66,10 +67,10 @@ func (i *Indexer) Init(ctx context.Context) (bool, error) {
// Ping checks if the indexer is available
func (i *Indexer) Ping(ctx context.Context) error {
if i == nil {
- return fmt.Errorf("cannot ping nil indexer")
+ return errors.New("cannot ping nil indexer")
}
if i.Client == nil {
- return fmt.Errorf("indexer is not initialized")
+ return errors.New("indexer is not initialized")
}
resp, err := i.Client.ClusterHealth().Do(ctx)
diff --git a/modules/indexer/internal/indexer.go b/modules/indexer/internal/indexer.go
index c7f356da1e..3442bbaff2 100644
--- a/modules/indexer/internal/indexer.go
+++ b/modules/indexer/internal/indexer.go
@@ -5,7 +5,7 @@ package internal
import (
"context"
- "fmt"
+ "errors"
)
// Indexer defines an basic indexer interface
@@ -27,11 +27,11 @@ func NewDummyIndexer() Indexer {
type dummyIndexer struct{}
func (d *dummyIndexer) Init(ctx context.Context) (bool, error) {
- return false, fmt.Errorf("indexer is not ready")
+ return false, errors.New("indexer is not ready")
}
func (d *dummyIndexer) Ping(ctx context.Context) error {
- return fmt.Errorf("indexer is not ready")
+ return errors.New("indexer is not ready")
}
func (d *dummyIndexer) Close() {}
diff --git a/modules/indexer/internal/meilisearch/indexer.go b/modules/indexer/internal/meilisearch/indexer.go
index 01bb49bbfc..65db75bb55 100644
--- a/modules/indexer/internal/meilisearch/indexer.go
+++ b/modules/indexer/internal/meilisearch/indexer.go
@@ -5,6 +5,7 @@ package meilisearch
import (
"context"
+ "errors"
"fmt"
"github.com/meilisearch/meilisearch-go"
@@ -33,11 +34,11 @@ func NewIndexer(url, apiKey, indexName string, version int, settings *meilisearc
// Init initializes the indexer
func (i *Indexer) Init(_ context.Context) (bool, error) {
if i == nil {
- return false, fmt.Errorf("cannot init nil indexer")
+ return false, errors.New("cannot init nil indexer")
}
if i.Client != nil {
- return false, fmt.Errorf("indexer is already initialized")
+ return false, errors.New("indexer is already initialized")
}
i.Client = meilisearch.New(i.url, meilisearch.WithAPIKey(i.apiKey))
@@ -62,10 +63,10 @@ func (i *Indexer) Init(_ context.Context) (bool, error) {
// Ping checks if the indexer is available
func (i *Indexer) Ping(ctx context.Context) error {
if i == nil {
- return fmt.Errorf("cannot ping nil indexer")
+ return errors.New("cannot ping nil indexer")
}
if i.Client == nil {
- return fmt.Errorf("indexer is not initialized")
+ return errors.New("indexer is not initialized")
}
resp, err := i.Client.Health()
if err != nil {
diff --git a/modules/indexer/issues/elasticsearch/elasticsearch.go b/modules/indexer/issues/elasticsearch/elasticsearch.go
index e3b1b17059..9d627466ef 100644
--- a/modules/indexer/issues/elasticsearch/elasticsearch.go
+++ b/modules/indexer/issues/elasticsearch/elasticsearch.go
@@ -5,7 +5,6 @@ package elasticsearch
import (
"context"
- "fmt"
"strconv"
"strings"
@@ -96,7 +95,7 @@ func (b *Indexer) Index(ctx context.Context, issues ...*internal.IndexerData) er
issue := issues[0]
_, err := b.inner.Client.Index().
Index(b.inner.VersionedIndexName()).
- Id(fmt.Sprintf("%d", issue.ID)).
+ Id(strconv.FormatInt(issue.ID, 10)).
BodyJson(issue).
Do(ctx)
return err
@@ -107,7 +106,7 @@ func (b *Indexer) Index(ctx context.Context, issues ...*internal.IndexerData) er
reqs = append(reqs,
elastic.NewBulkIndexRequest().
Index(b.inner.VersionedIndexName()).
- Id(fmt.Sprintf("%d", issue.ID)).
+ Id(strconv.FormatInt(issue.ID, 10)).
Doc(issue),
)
}
@@ -126,7 +125,7 @@ func (b *Indexer) Delete(ctx context.Context, ids ...int64) error {
} else if len(ids) == 1 {
_, err := b.inner.Client.Delete().
Index(b.inner.VersionedIndexName()).
- Id(fmt.Sprintf("%d", ids[0])).
+ Id(strconv.FormatInt(ids[0], 10)).
Do(ctx)
return err
}
@@ -136,7 +135,7 @@ func (b *Indexer) Delete(ctx context.Context, ids ...int64) error {
reqs = append(reqs,
elastic.NewBulkDeleteRequest().
Index(b.inner.VersionedIndexName()).
- Id(fmt.Sprintf("%d", id)),
+ Id(strconv.FormatInt(id, 10)),
)
}
diff --git a/modules/indexer/issues/internal/indexer.go b/modules/indexer/issues/internal/indexer.go
index 415f442d0c..59c6f48485 100644
--- a/modules/indexer/issues/internal/indexer.go
+++ b/modules/indexer/issues/internal/indexer.go
@@ -5,7 +5,7 @@ package internal
import (
"context"
- "fmt"
+ "errors"
"code.gitea.io/gitea/modules/indexer"
"code.gitea.io/gitea/modules/indexer/internal"
@@ -36,13 +36,13 @@ func (d *dummyIndexer) SupportedSearchModes() []indexer.SearchMode {
}
func (d *dummyIndexer) Index(_ context.Context, _ ...*IndexerData) error {
- return fmt.Errorf("indexer is not ready")
+ return errors.New("indexer is not ready")
}
func (d *dummyIndexer) Delete(_ context.Context, _ ...int64) error {
- return fmt.Errorf("indexer is not ready")
+ return errors.New("indexer is not ready")
}
func (d *dummyIndexer) Search(_ context.Context, _ *SearchOptions) (*SearchResult, error) {
- return nil, fmt.Errorf("indexer is not ready")
+ return nil, errors.New("indexer is not ready")
}
diff --git a/modules/indexer/stats/queue.go b/modules/indexer/stats/queue.go
index d002bd57cf..69cde321d8 100644
--- a/modules/indexer/stats/queue.go
+++ b/modules/indexer/stats/queue.go
@@ -4,7 +4,7 @@
package stats
import (
- "fmt"
+ "errors"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/graceful"
@@ -31,7 +31,7 @@ func handler(items ...int64) []int64 {
func initStatsQueue() error {
statsQueue = queue.CreateUniqueQueue(graceful.GetManager().ShutdownContext(), "repo_stats_update", handler)
if statsQueue == nil {
- return fmt.Errorf("unable to create repo_stats_update queue")
+ return errors.New("unable to create repo_stats_update queue")
}
go graceful.GetManager().RunWithCancel(statsQueue)
return nil
diff --git a/modules/issue/template/template.go b/modules/issue/template/template.go
index a2b9d6b33e..84ae90e4ed 100644
--- a/modules/issue/template/template.go
+++ b/modules/issue/template/template.go
@@ -4,6 +4,7 @@
package template
import (
+ "errors"
"fmt"
"net/url"
"regexp"
@@ -31,17 +32,17 @@ func Validate(template *api.IssueTemplate) error {
func validateMetadata(template *api.IssueTemplate) error {
if strings.TrimSpace(template.Name) == "" {
- return fmt.Errorf("'name' is required")
+ return errors.New("'name' is required")
}
if strings.TrimSpace(template.About) == "" {
- return fmt.Errorf("'about' is required")
+ return errors.New("'about' is required")
}
return nil
}
func validateYaml(template *api.IssueTemplate) error {
if len(template.Fields) == 0 {
- return fmt.Errorf("'body' is required")
+ return errors.New("'body' is required")
}
ids := make(container.Set[string])
for idx, field := range template.Fields {
@@ -401,7 +402,7 @@ func (f *valuedField) Render() string {
}
func (f *valuedField) Value() string {
- return strings.TrimSpace(f.Get(fmt.Sprintf("form-field-%s", f.ID)))
+ return strings.TrimSpace(f.Get("form-field-" + f.ID))
}
func (f *valuedField) Options() []*valuedOption {
@@ -444,7 +445,7 @@ func (o *valuedOption) Label() string {
func (o *valuedOption) IsChecked() bool {
switch o.field.Type {
case api.IssueFormFieldTypeDropdown:
- checks := strings.Split(o.field.Get(fmt.Sprintf("form-field-%s", o.field.ID)), ",")
+ checks := strings.Split(o.field.Get("form-field-"+o.field.ID), ",")
idx := strconv.Itoa(o.index)
for _, v := range checks {
if v == idx {
diff --git a/modules/lfs/http_client.go b/modules/lfs/http_client.go
index 0a27fb0c86..4b51193846 100644
--- a/modules/lfs/http_client.go
+++ b/modules/lfs/http_client.go
@@ -70,7 +70,7 @@ func (c *HTTPClient) transferNames() []string {
func (c *HTTPClient) batch(ctx context.Context, operation string, objects []Pointer) (*BatchResponse, error) {
log.Trace("BATCH operation with objects: %v", objects)
- url := fmt.Sprintf("%s/objects/batch", c.endpoint)
+ url := c.endpoint + "/objects/batch"
// Original: In some lfs server implementations, they require the ref attribute. #32838
// `ref` is an "optional object describing the server ref that the objects belong to"
diff --git a/modules/lfs/http_client_test.go b/modules/lfs/http_client_test.go
index 7869c0a21a..179bcdb29a 100644
--- a/modules/lfs/http_client_test.go
+++ b/modules/lfs/http_client_test.go
@@ -31,7 +31,7 @@ func (a *DummyTransferAdapter) Name() string {
}
func (a *DummyTransferAdapter) Download(ctx context.Context, l *Link) (io.ReadCloser, error) {
- return io.NopCloser(bytes.NewBufferString("dummy")), nil
+ return io.NopCloser(strings.NewReader("dummy")), nil
}
func (a *DummyTransferAdapter) Upload(ctx context.Context, l *Link, p Pointer, r io.Reader) error {
@@ -49,7 +49,7 @@ func lfsTestRoundtripHandler(req *http.Request) *http.Response {
if strings.Contains(url, "status-not-ok") {
return &http.Response{StatusCode: http.StatusBadRequest}
} else if strings.Contains(url, "invalid-json-response") {
- return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewBufferString("invalid json"))}
+ return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("invalid json"))}
} else if strings.Contains(url, "valid-batch-request-download") {
batchResponse = &BatchResponse{
Transfer: "dummy",
diff --git a/modules/lfs/transferadapter_test.go b/modules/lfs/transferadapter_test.go
index 8bbd45771a..ef72d76db4 100644
--- a/modules/lfs/transferadapter_test.go
+++ b/modules/lfs/transferadapter_test.go
@@ -32,7 +32,7 @@ func TestBasicTransferAdapter(t *testing.T) {
if strings.Contains(url, "download-request") {
assert.Equal(t, "GET", req.Method)
- return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewBufferString("dummy"))}
+ return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("dummy"))}
} else if strings.Contains(url, "upload-request") {
assert.Equal(t, "PUT", req.Method)
assert.Equal(t, "application/octet-stream", req.Header.Get("Content-Type"))
@@ -126,7 +126,7 @@ func TestBasicTransferAdapter(t *testing.T) {
}
for n, c := range cases {
- err := a.Upload(t.Context(), c.link, p, bytes.NewBufferString("dummy"))
+ err := a.Upload(t.Context(), c.link, p, strings.NewReader("dummy"))
if len(c.expectederror) > 0 {
assert.Contains(t, err.Error(), c.expectederror, "case %d: '%s' should contain '%s'", n, err.Error(), c.expectederror)
} else {
diff --git a/modules/lfstransfer/backend/backend.go b/modules/lfstransfer/backend/backend.go
index 1328d93a48..dd4108ea56 100644
--- a/modules/lfstransfer/backend/backend.go
+++ b/modules/lfstransfer/backend/backend.go
@@ -47,7 +47,7 @@ func New(ctx context.Context, repo, op, token string, logger transfer.Logger) (t
return nil, err
}
server = server.JoinPath("api/internal/repo", repo, "info/lfs")
- return &GiteaBackend{ctx: ctx, server: server, op: op, authToken: token, internalAuth: fmt.Sprintf("Bearer %s", setting.InternalToken), logger: logger}, nil
+ return &GiteaBackend{ctx: ctx, server: server, op: op, authToken: token, internalAuth: "Bearer " + setting.InternalToken, logger: logger}, nil
}
// Batch implements transfer.Backend
diff --git a/modules/lfstransfer/backend/lock.go b/modules/lfstransfer/backend/lock.go
index 639f8b184e..2c3c16a9bb 100644
--- a/modules/lfstransfer/backend/lock.go
+++ b/modules/lfstransfer/backend/lock.go
@@ -5,6 +5,7 @@ package backend
import (
"context"
+ "errors"
"fmt"
"io"
"net/http"
@@ -74,7 +75,7 @@ func (g *giteaLockBackend) Create(path, refname string) (transfer.Lock, error) {
if respBody.Lock == nil {
g.logger.Log("api returned nil lock")
- return nil, fmt.Errorf("api returned nil lock")
+ return nil, errors.New("api returned nil lock")
}
respLock := respBody.Lock
owner := userUnknown
@@ -263,7 +264,7 @@ func (g *giteaLock) CurrentUser() (string, error) {
// AsLockSpec implements transfer.Lock
func (g *giteaLock) AsLockSpec(ownerID bool) ([]string, error) {
msgs := []string{
- fmt.Sprintf("lock %s", g.ID()),
+ "lock " + g.ID(),
fmt.Sprintf("path %s %s", g.ID(), g.Path()),
fmt.Sprintf("locked-at %s %s", g.ID(), g.FormattedTimestamp()),
fmt.Sprintf("ownername %s %s", g.ID(), g.OwnerName()),
@@ -285,9 +286,9 @@ func (g *giteaLock) AsLockSpec(ownerID bool) ([]string, error) {
// AsArguments implements transfer.Lock
func (g *giteaLock) AsArguments() []string {
return []string{
- fmt.Sprintf("id=%s", g.ID()),
- fmt.Sprintf("path=%s", g.Path()),
- fmt.Sprintf("locked-at=%s", g.FormattedTimestamp()),
- fmt.Sprintf("ownername=%s", g.OwnerName()),
+ "id=" + g.ID(),
+ "path=" + g.Path(),
+ "locked-at=" + g.FormattedTimestamp(),
+ "ownername=" + g.OwnerName(),
}
}
diff --git a/modules/markup/common/footnote.go b/modules/markup/common/footnote.go
index 4406803694..9a4f18ed7f 100644
--- a/modules/markup/common/footnote.go
+++ b/modules/markup/common/footnote.go
@@ -53,7 +53,7 @@ type FootnoteLink struct {
// Dump implements Node.Dump.
func (n *FootnoteLink) Dump(source []byte, level int) {
m := map[string]string{}
- m["Index"] = fmt.Sprintf("%v", n.Index)
+ m["Index"] = strconv.Itoa(n.Index)
m["Name"] = fmt.Sprintf("%v", n.Name)
ast.DumpHelper(n, source, level, m, nil)
}
@@ -85,7 +85,7 @@ type FootnoteBackLink struct {
// Dump implements Node.Dump.
func (n *FootnoteBackLink) Dump(source []byte, level int) {
m := map[string]string{}
- m["Index"] = fmt.Sprintf("%v", n.Index)
+ m["Index"] = strconv.Itoa(n.Index)
m["Name"] = fmt.Sprintf("%v", n.Name)
ast.DumpHelper(n, source, level, m, nil)
}
@@ -151,7 +151,7 @@ type FootnoteList struct {
// Dump implements Node.Dump.
func (n *FootnoteList) Dump(source []byte, level int) {
m := map[string]string{}
- m["Count"] = fmt.Sprintf("%v", n.Count)
+ m["Count"] = strconv.Itoa(n.Count)
ast.DumpHelper(n, source, level, m, nil)
}
diff --git a/modules/markup/markdown/markdown.go b/modules/markup/markdown/markdown.go
index ace31eb540..35115991e8 100644
--- a/modules/markup/markdown/markdown.go
+++ b/modules/markup/markdown/markdown.go
@@ -5,7 +5,7 @@
package markdown
import (
- "fmt"
+ "errors"
"html/template"
"io"
"strings"
@@ -48,7 +48,7 @@ func (l *limitWriter) Write(data []byte) (int, error) {
if err != nil {
return n, err
}
- return n, fmt.Errorf("rendered content too large - truncating render")
+ return n, errors.New("rendered content too large - truncating render")
}
n, err := l.w.Write(data)
l.sum += int64(n)
diff --git a/modules/markup/markdown/toc.go b/modules/markup/markdown/toc.go
index ea1af83a3e..a11b9d0390 100644
--- a/modules/markup/markdown/toc.go
+++ b/modules/markup/markdown/toc.go
@@ -4,7 +4,6 @@
package markdown
import (
- "fmt"
"net/url"
"code.gitea.io/gitea/modules/translation"
@@ -50,7 +49,7 @@ func createTOCNode(toc []Header, lang string, detailsAttrs map[string]string) as
}
li := ast.NewListItem(currentLevel * 2)
a := ast.NewLink()
- a.Destination = []byte(fmt.Sprintf("#%s", url.QueryEscape(header.ID)))
+ a.Destination = []byte("#" + url.QueryEscape(header.ID))
a.AppendChild(a, ast.NewString([]byte(header.Text)))
li.AppendChild(li, a)
ul.AppendChild(ul, li)
diff --git a/modules/packages/goproxy/metadata.go b/modules/packages/goproxy/metadata.go
index 40f7d20508..a67b149f4d 100644
--- a/modules/packages/goproxy/metadata.go
+++ b/modules/packages/goproxy/metadata.go
@@ -5,7 +5,6 @@ package goproxy
import (
"archive/zip"
- "fmt"
"io"
"path"
"strings"
@@ -88,7 +87,7 @@ func ParsePackage(r io.ReaderAt, size int64) (*Package, error) {
return nil, ErrInvalidStructure
}
- p.GoMod = fmt.Sprintf("module %s", p.Name)
+ p.GoMod = "module " + p.Name
return p, nil
}
diff --git a/modules/private/internal.go b/modules/private/internal.go
index 35eed1d608..e599c6eb8e 100644
--- a/modules/private/internal.go
+++ b/modules/private/internal.go
@@ -6,7 +6,6 @@ package private
import (
"context"
"crypto/tls"
- "fmt"
"net"
"net/http"
"os"
@@ -47,7 +46,7 @@ Ensure you are running in the correct environment or set the correct configurati
req := httplib.NewRequest(url, method).
SetContext(ctx).
Header("X-Real-IP", getClientIP()).
- Header("X-Gitea-Internal-Auth", fmt.Sprintf("Bearer %s", setting.InternalToken)).
+ Header("X-Gitea-Internal-Auth", "Bearer "+setting.InternalToken).
SetTLSClientConfig(&tls.Config{
InsecureSkipVerify: true,
ServerName: setting.Domain,
diff --git a/modules/private/serv.go b/modules/private/serv.go
index 2ccc6c1129..10e9f7995c 100644
--- a/modules/private/serv.go
+++ b/modules/private/serv.go
@@ -55,7 +55,7 @@ func ServCommand(ctx context.Context, keyID int64, ownerName, repoName string, m
)
for _, verb := range verbs {
if verb != "" {
- reqURL += fmt.Sprintf("&verb=%s", url.QueryEscape(verb))
+ reqURL += "&verb=" + url.QueryEscape(verb)
}
}
req := newInternalRequestAPI(ctx, reqURL, "GET")
diff --git a/modules/proxyprotocol/errors.go b/modules/proxyprotocol/errors.go
index 5439a86bd8..f76c82b7f6 100644
--- a/modules/proxyprotocol/errors.go
+++ b/modules/proxyprotocol/errors.go
@@ -20,7 +20,7 @@ type ErrBadAddressType struct {
}
func (e *ErrBadAddressType) Error() string {
- return fmt.Sprintf("Unexpected proxy header address type: %s", e.Address)
+ return "Unexpected proxy header address type: " + e.Address
}
// ErrBadRemote is an error demonstrating a bad proxy header with bad Remote
diff --git a/modules/repository/env.go b/modules/repository/env.go
index e4f32092fc..78e06f86fb 100644
--- a/modules/repository/env.go
+++ b/modules/repository/env.go
@@ -4,8 +4,8 @@
package repository
import (
- "fmt"
"os"
+ "strconv"
"strings"
repo_model "code.gitea.io/gitea/models/repo"
@@ -72,9 +72,9 @@ func FullPushingEnvironment(author, committer *user_model.User, repo *repo_model
EnvRepoUsername+"="+repo.OwnerName,
EnvRepoIsWiki+"="+isWiki,
EnvPusherName+"="+committer.Name,
- EnvPusherID+"="+fmt.Sprintf("%d", committer.ID),
- EnvRepoID+"="+fmt.Sprintf("%d", repo.ID),
- EnvPRID+"="+fmt.Sprintf("%d", prID),
+ EnvPusherID+"="+strconv.FormatInt(committer.ID, 10),
+ EnvRepoID+"="+strconv.FormatInt(repo.ID, 10),
+ EnvPRID+"="+strconv.FormatInt(prID, 10),
EnvAppURL+"="+setting.AppURL,
"SSH_ORIGINAL_COMMAND=gitea-internal",
)
diff --git a/modules/setting/config_provider.go b/modules/setting/config_provider.go
index b34751e959..a0c53a1032 100644
--- a/modules/setting/config_provider.go
+++ b/modules/setting/config_provider.go
@@ -258,7 +258,7 @@ func (p *iniConfigProvider) Save() error {
}
filename := p.file
if filename == "" {
- return fmt.Errorf("config file path must not be empty")
+ return errors.New("config file path must not be empty")
}
if p.loadedFromEmpty {
if err := os.MkdirAll(filepath.Dir(filename), os.ModePerm); err != nil {
diff --git a/modules/setting/incoming_email.go b/modules/setting/incoming_email.go
index bf81f292a2..4e433dde60 100644
--- a/modules/setting/incoming_email.go
+++ b/modules/setting/incoming_email.go
@@ -4,6 +4,7 @@
package setting
import (
+ "errors"
"fmt"
"net/mail"
"strings"
@@ -50,7 +51,7 @@ func checkReplyToAddress() error {
}
if parsed.Name != "" {
- return fmt.Errorf("name must not be set")
+ return errors.New("name must not be set")
}
c := strings.Count(IncomingEmail.ReplyToAddress, IncomingEmail.TokenPlaceholder)
diff --git a/modules/ssh/ssh.go b/modules/ssh/ssh.go
index 7479cfbd95..ff0ad34a0d 100644
--- a/modules/ssh/ssh.go
+++ b/modules/ssh/ssh.go
@@ -11,7 +11,6 @@ import (
"crypto/x509"
"encoding/pem"
"errors"
- "fmt"
"io"
"net"
"os"
@@ -216,7 +215,7 @@ func publicKeyHandler(ctx ssh.Context, key ssh.PublicKey) bool {
ctx.Permissions().Permissions = &gossh.Permissions{}
setPermExt := func(keyID int64) {
ctx.Permissions().Permissions.Extensions = map[string]string{
- giteaPermissionExtensionKeyID: fmt.Sprint(keyID),
+ giteaPermissionExtensionKeyID: strconv.FormatInt(keyID, 10),
}
}
diff --git a/modules/storage/azureblob_test.go b/modules/storage/azureblob_test.go
index bac1414d3c..b3791b4916 100644
--- a/modules/storage/azureblob_test.go
+++ b/modules/storage/azureblob_test.go
@@ -4,9 +4,9 @@
package storage
import (
- "bytes"
"io"
"os"
+ "strings"
"testing"
"code.gitea.io/gitea/modules/setting"
@@ -76,7 +76,7 @@ func Test_azureBlobObject(t *testing.T) {
assert.NoError(t, err)
data := "Q2xTckt6Y1hDOWh0"
- _, err = s.Save("test.txt", bytes.NewBufferString(data), int64(len(data)))
+ _, err = s.Save("test.txt", strings.NewReader(data), int64(len(data)))
assert.NoError(t, err)
obj, err := s.Open("test.txt")
assert.NoError(t, err)
diff --git a/modules/storage/storage_test.go b/modules/storage/storage_test.go
index 7edde558f3..08f274e74b 100644
--- a/modules/storage/storage_test.go
+++ b/modules/storage/storage_test.go
@@ -4,7 +4,7 @@
package storage
import (
- "bytes"
+ "strings"
"testing"
"code.gitea.io/gitea/modules/setting"
@@ -26,7 +26,7 @@ func testStorageIterator(t *testing.T, typStr Type, cfg *setting.Storage) {
{"b/x 4.txt", "bx4"},
}
for _, f := range testFiles {
- _, err = l.Save(f[0], bytes.NewBufferString(f[1]), -1)
+ _, err = l.Save(f[0], strings.NewReader(f[1]), -1)
assert.NoError(t, err)
}
diff --git a/modules/templates/helper.go b/modules/templates/helper.go
index 3237f8b295..c9d93e089c 100644
--- a/modules/templates/helper.go
+++ b/modules/templates/helper.go
@@ -9,6 +9,7 @@ import (
"html"
"html/template"
"net/url"
+ "strconv"
"strings"
"time"
@@ -73,7 +74,7 @@ func NewFuncMap() template.FuncMap {
"TimeEstimateString": timeEstimateString,
"LoadTimes": func(startTime time.Time) string {
- return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
+ return strconv.FormatInt(time.Since(startTime).Nanoseconds()/1e6, 10) + "ms"
},
// -----------------------------------------------------------------
diff --git a/modules/templates/helper_test.go b/modules/templates/helper_test.go
index efe646ec9c..81f8235bd2 100644
--- a/modules/templates/helper_test.go
+++ b/modules/templates/helper_test.go
@@ -15,7 +15,7 @@ import (
func TestSubjectBodySeparator(t *testing.T) {
test := func(input, subject, body string) {
- loc := mailSubjectSplit.FindIndex([]byte(input))
+ loc := mailSubjectSplit.FindStringIndex(input)
if loc == nil {
assert.Empty(t, subject, "no subject found, but one expected")
assert.Equal(t, body, input)
diff --git a/modules/templates/util_avatar.go b/modules/templates/util_avatar.go
index 470e24fa61..73fde99f40 100644
--- a/modules/templates/util_avatar.go
+++ b/modules/templates/util_avatar.go
@@ -5,9 +5,9 @@ package templates
import (
"context"
- "fmt"
"html"
"html/template"
+ "strconv"
activities_model "code.gitea.io/gitea/models/activities"
"code.gitea.io/gitea/models/avatars"
@@ -28,7 +28,7 @@ func NewAvatarUtils(ctx context.Context) *AvatarUtils {
// AvatarHTML creates the HTML for an avatar
func AvatarHTML(src string, size int, class, name string) template.HTML {
- sizeStr := fmt.Sprintf(`%d`, size)
+ sizeStr := strconv.Itoa(size)
if name == "" {
name = "avatar"
diff --git a/modules/templates/util_date.go b/modules/templates/util_date.go
index 658691ee40..fc3f3f2339 100644
--- a/modules/templates/util_date.go
+++ b/modules/templates/util_date.go
@@ -99,7 +99,7 @@ func dateTimeFormat(format string, datetime any) template.HTML {
attrs = append(attrs, `format="datetime"`, `month="short"`, `day="numeric"`, `hour="numeric"`, `minute="numeric"`, `second="numeric"`, `data-tooltip-content`, `data-tooltip-interactive="true"`)
return template.HTML(fmt.Sprintf(`%s`, strings.Join(attrs, " "), datetimeEscaped, textEscaped))
default:
- panic(fmt.Sprintf("Unsupported format %s", format))
+ panic("Unsupported format " + format)
}
}
diff --git a/modules/templates/util_dict.go b/modules/templates/util_dict.go
index 8d6376b522..cc3018a71c 100644
--- a/modules/templates/util_dict.go
+++ b/modules/templates/util_dict.go
@@ -4,6 +4,7 @@
package templates
import (
+ "errors"
"fmt"
"html"
"html/template"
@@ -33,7 +34,7 @@ func dictMerge(base map[string]any, arg any) bool {
// The dot syntax is highly discouraged because it might cause unclear key conflicts. It's always good to use explicit keys.
func dict(args ...any) (map[string]any, error) {
if len(args)%2 != 0 {
- return nil, fmt.Errorf("invalid dict constructor syntax: must have key-value pairs")
+ return nil, errors.New("invalid dict constructor syntax: must have key-value pairs")
}
m := make(map[string]any, len(args)/2)
for i := 0; i < len(args); i += 2 {
diff --git a/modules/templates/util_format.go b/modules/templates/util_format.go
index bee6fb7b75..3485e3251e 100644
--- a/modules/templates/util_format.go
+++ b/modules/templates/util_format.go
@@ -5,6 +5,7 @@ package templates
import (
"fmt"
+ "strconv"
"code.gitea.io/gitea/modules/util"
)
@@ -24,7 +25,7 @@ func countFmt(data any) string {
return ""
}
if num < 1000 {
- return fmt.Sprintf("%d", num)
+ return strconv.FormatInt(num, 10)
} else if num < 1_000_000 {
num2 := float32(num) / 1000.0
return fmt.Sprintf("%.1fk", num2)
diff --git a/modules/templates/vars/vars.go b/modules/templates/vars/vars.go
index cc9d0e976f..500078d4b8 100644
--- a/modules/templates/vars/vars.go
+++ b/modules/templates/vars/vars.go
@@ -16,7 +16,7 @@ type ErrWrongSyntax struct {
}
func (err ErrWrongSyntax) Error() string {
- return fmt.Sprintf("wrong syntax found in %s", err.Template)
+ return "wrong syntax found in " + err.Template
}
// ErrVarMissing represents an error that no matched variable
diff --git a/modules/test/logchecker.go b/modules/test/logchecker.go
index 7bf234f560..829f735c7c 100644
--- a/modules/test/logchecker.go
+++ b/modules/test/logchecker.go
@@ -5,7 +5,7 @@ package test
import (
"context"
- "fmt"
+ "strconv"
"strings"
"sync"
"sync/atomic"
@@ -58,7 +58,7 @@ var checkerIndex int64
func NewLogChecker(namePrefix string) (logChecker *LogChecker, cancel func()) {
logger := log.GetManager().GetLogger(namePrefix)
newCheckerIndex := atomic.AddInt64(&checkerIndex, 1)
- writerName := namePrefix + "-" + fmt.Sprint(newCheckerIndex)
+ writerName := namePrefix + "-" + strconv.FormatInt(newCheckerIndex, 10)
lc := &LogChecker{}
lc.EventWriterBaseImpl = log.NewEventWriterBase(writerName, "test-log-checker", log.WriterMode{})
diff --git a/modules/test/utils.go b/modules/test/utils.go
index ec4c976388..3051d3d286 100644
--- a/modules/test/utils.go
+++ b/modules/test/utils.go
@@ -4,7 +4,6 @@
package test
import (
- "fmt"
"net/http"
"net/http/httptest"
"os"
@@ -57,7 +56,7 @@ func SetupGiteaRoot() string {
giteaRoot = filepath.Dir(filepath.Dir(filepath.Dir(filename)))
fixturesDir := filepath.Join(giteaRoot, "models", "fixtures")
if exist, _ := util.IsDir(fixturesDir); !exist {
- panic(fmt.Sprintf("fixtures directory not found: %s", fixturesDir))
+ panic("fixtures directory not found: " + fixturesDir)
}
_ = os.Setenv("GITEA_ROOT", giteaRoot)
return giteaRoot
diff --git a/modules/updatechecker/update_checker.go b/modules/updatechecker/update_checker.go
index 3c1e05d060..f0686c0f78 100644
--- a/modules/updatechecker/update_checker.go
+++ b/modules/updatechecker/update_checker.go
@@ -34,7 +34,7 @@ func GiteaUpdateChecker(httpEndpoint string) error {
},
}
- req, err := http.NewRequest("GET", httpEndpoint, nil)
+ req, err := http.NewRequest(http.MethodGet, httpEndpoint, nil)
if err != nil {
return err
}
diff --git a/modules/util/truncate_test.go b/modules/util/truncate_test.go
index a85ec70008..9f4ad7dc20 100644
--- a/modules/util/truncate_test.go
+++ b/modules/util/truncate_test.go
@@ -5,6 +5,7 @@ package util
import (
"fmt"
+ "strconv"
"strings"
"testing"
@@ -100,7 +101,7 @@ func TestEllipsisString(t *testing.T) {
{limit: 7, left: "\xef\x03\xfe\xef\x03\xfe", right: ""},
}
for _, c := range invalidCases {
- t.Run(fmt.Sprintf("%d", c.limit), func(t *testing.T) {
+ t.Run(strconv.Itoa(c.limit), func(t *testing.T) {
left, right := EllipsisDisplayStringX("\xef\x03\xfe\xef\x03\xfe", c.limit)
assert.Equal(t, c.left, left, "left")
assert.Equal(t, c.right, right, "right")
diff --git a/modules/validation/binding_test.go b/modules/validation/binding_test.go
index 28d0f57b5c..0cd328f312 100644
--- a/modules/validation/binding_test.go
+++ b/modules/validation/binding_test.go
@@ -47,7 +47,7 @@ func performValidationTest(t *testing.T, testCase validationTestCase) {
assert.Equal(t, testCase.expectedErrors, actual)
})
- req, err := http.NewRequest("POST", testRoute, nil)
+ req, err := http.NewRequest(http.MethodPost, testRoute, nil)
if err != nil {
panic(err)
}
diff --git a/modules/web/routemock_test.go b/modules/web/routemock_test.go
index 15af98e6b5..a0949bf622 100644
--- a/modules/web/routemock_test.go
+++ b/modules/web/routemock_test.go
@@ -30,7 +30,7 @@ func TestRouteMock(t *testing.T) {
// normal request
recorder := httptest.NewRecorder()
- req, err := http.NewRequest("GET", "http://localhost:8000/foo", nil)
+ req, err := http.NewRequest(http.MethodGet, "http://localhost:8000/foo", nil)
assert.NoError(t, err)
r.ServeHTTP(recorder, req)
assert.Len(t, recorder.Header(), 3)
@@ -45,7 +45,7 @@ func TestRouteMock(t *testing.T) {
resp.WriteHeader(http.StatusOK)
})
recorder = httptest.NewRecorder()
- req, err = http.NewRequest("GET", "http://localhost:8000/foo", nil)
+ req, err = http.NewRequest(http.MethodGet, "http://localhost:8000/foo", nil)
assert.NoError(t, err)
r.ServeHTTP(recorder, req)
assert.Len(t, recorder.Header(), 2)
@@ -59,7 +59,7 @@ func TestRouteMock(t *testing.T) {
resp.WriteHeader(http.StatusOK)
})
recorder = httptest.NewRecorder()
- req, err = http.NewRequest("GET", "http://localhost:8000/foo", nil)
+ req, err = http.NewRequest(http.MethodGet, "http://localhost:8000/foo", nil)
assert.NoError(t, err)
r.ServeHTTP(recorder, req)
assert.Len(t, recorder.Header(), 3)
diff --git a/modules/web/router_path.go b/modules/web/router_path.go
index b59948581a..baf1b522af 100644
--- a/modules/web/router_path.go
+++ b/modules/web/router_path.go
@@ -4,7 +4,6 @@
package web
import (
- "fmt"
"net/http"
"regexp"
"strings"
@@ -103,7 +102,7 @@ func newRouterPathMatcher(methods, pattern string, h ...any) *routerPathMatcher
for _, method := range strings.Split(methods, ",") {
method = strings.TrimSpace(method)
if !isValidMethod(method) {
- panic(fmt.Sprintf("invalid HTTP method: %s", method))
+ panic("invalid HTTP method: " + method)
}
p.methods.Add(method)
}
@@ -117,7 +116,7 @@ func newRouterPathMatcher(methods, pattern string, h ...any) *routerPathMatcher
}
end := strings.IndexByte(pattern[lastEnd+start:], '>')
if end == -1 {
- panic(fmt.Sprintf("invalid pattern: %s", pattern))
+ panic("invalid pattern: " + pattern)
}
re = append(re, pattern[lastEnd:lastEnd+start]...)
partName, partExp, _ := strings.Cut(pattern[lastEnd+start+1:lastEnd+start+end], ":")
diff --git a/modules/web/router_test.go b/modules/web/router_test.go
index 3f139336bf..21619012ea 100644
--- a/modules/web/router_test.go
+++ b/modules/web/router_test.go
@@ -51,7 +51,7 @@ func TestPathProcessor(t *testing.T) {
}
func TestRouter(t *testing.T) {
- buff := bytes.NewBufferString("")
+ buff := &bytes.Buffer{}
recorder := httptest.NewRecorder()
recorder.Body = buff
@@ -224,7 +224,7 @@ func TestRouteNormalizePath(t *testing.T) {
actualPaths.Path = req.URL.Path
})
- req, err := http.NewRequest("GET", reqPath, nil)
+ req, err := http.NewRequest(http.MethodGet, reqPath, nil)
assert.NoError(t, err)
r.ServeHTTP(recorder, req)
assert.Equal(t, expectedPaths, actualPaths, "req path = %q", reqPath)
diff --git a/routers/api/actions/artifacts_chunks.go b/routers/api/actions/artifacts_chunks.go
index 9d2b69820c..708931d1ac 100644
--- a/routers/api/actions/artifacts_chunks.go
+++ b/routers/api/actions/artifacts_chunks.go
@@ -51,7 +51,7 @@ func saveUploadChunkBase(st storage.ObjectStorage, ctx *ArtifactContext,
log.Info("[artifact] check chunk md5, sum: %s, header: %s", chunkMd5String, reqMd5String)
// if md5 not match, delete the chunk
if reqMd5String != chunkMd5String {
- checkErr = fmt.Errorf("md5 not match")
+ checkErr = errors.New("md5 not match")
}
}
if writtenSize != contentSize {
@@ -261,7 +261,7 @@ func mergeChunksForArtifact(ctx *ArtifactContext, chunks []*chunkFileItem, st st
return fmt.Errorf("save merged file error: %v", err)
}
if written != artifact.FileCompressedSize {
- return fmt.Errorf("merged file size is not equal to chunk length")
+ return errors.New("merged file size is not equal to chunk length")
}
defer func() {
diff --git a/routers/api/actions/artifactsv4.go b/routers/api/actions/artifactsv4.go
index 3d992ca2dd..9fb0a31549 100644
--- a/routers/api/actions/artifactsv4.go
+++ b/routers/api/actions/artifactsv4.go
@@ -170,7 +170,7 @@ func (r artifactV4Routes) buildSignature(endp, expires, artifactName string, tas
func (r artifactV4Routes) buildArtifactURL(ctx *ArtifactContext, endp, artifactName string, taskID, artifactID int64) string {
expires := time.Now().Add(60 * time.Minute).Format("2006-01-02 15:04:05.999999999 -0700 MST")
uploadURL := strings.TrimSuffix(httplib.GuessCurrentAppURL(ctx), "/") + strings.TrimSuffix(r.prefix, "/") +
- "/" + endp + "?sig=" + base64.URLEncoding.EncodeToString(r.buildSignature(endp, expires, artifactName, taskID, artifactID)) + "&expires=" + url.QueryEscape(expires) + "&artifactName=" + url.QueryEscape(artifactName) + "&taskID=" + fmt.Sprint(taskID) + "&artifactID=" + fmt.Sprint(artifactID)
+ "/" + endp + "?sig=" + base64.URLEncoding.EncodeToString(r.buildSignature(endp, expires, artifactName, taskID, artifactID)) + "&expires=" + url.QueryEscape(expires) + "&artifactName=" + url.QueryEscape(artifactName) + "&taskID=" + strconv.FormatInt(taskID, 10) + "&artifactID=" + strconv.FormatInt(artifactID, 10)
return uploadURL
}
diff --git a/routers/api/packages/api.go b/routers/api/packages/api.go
index 72db15dc26..ae4ea7ea87 100644
--- a/routers/api/packages/api.go
+++ b/routers/api/packages/api.go
@@ -552,10 +552,10 @@ func CommonRoutes() *web.Router {
r.Methods("HEAD,GET,PUT,DELETE", "*", func(ctx *context.Context) {
path := ctx.PathParam("*")
- isHead := ctx.Req.Method == "HEAD"
- isGetHead := ctx.Req.Method == "HEAD" || ctx.Req.Method == "GET"
- isPut := ctx.Req.Method == "PUT"
- isDelete := ctx.Req.Method == "DELETE"
+ isHead := ctx.Req.Method == http.MethodHead
+ isGetHead := ctx.Req.Method == http.MethodHead || ctx.Req.Method == http.MethodGet
+ isPut := ctx.Req.Method == http.MethodPut
+ isDelete := ctx.Req.Method == http.MethodDelete
m := repoPattern.FindStringSubmatch(path)
if len(m) == 2 && isGetHead {
diff --git a/routers/api/packages/chef/auth.go b/routers/api/packages/chef/auth.go
index a790e9a363..c6808300a2 100644
--- a/routers/api/packages/chef/auth.go
+++ b/routers/api/packages/chef/auth.go
@@ -12,6 +12,7 @@ import (
"crypto/x509"
"encoding/base64"
"encoding/pem"
+ "errors"
"fmt"
"hash"
"math/big"
@@ -121,7 +122,7 @@ func verifyTimestamp(req *http.Request) error {
}
if diff > maxTimeDifference {
- return fmt.Errorf("time difference")
+ return errors.New("time difference")
}
return nil
@@ -190,7 +191,7 @@ func getAuthorizationData(req *http.Request) ([]byte, error) {
tmp := make([]string, len(valueList))
for k, v := range valueList {
if k > len(tmp) {
- return nil, fmt.Errorf("invalid X-Ops-Authorization headers")
+ return nil, errors.New("invalid X-Ops-Authorization headers")
}
tmp[k-1] = v
}
@@ -267,7 +268,7 @@ func verifyDataOld(signature, data []byte, pub *rsa.PublicKey) error {
}
if !slices.Equal(out[skip:], data) {
- return fmt.Errorf("could not verify signature")
+ return errors.New("could not verify signature")
}
return nil
diff --git a/routers/api/packages/container/blob.go b/routers/api/packages/container/blob.go
index 671803788a..4a2320ab76 100644
--- a/routers/api/packages/container/blob.go
+++ b/routers/api/packages/container/blob.go
@@ -149,7 +149,7 @@ func getOrCreateUploadVersion(ctx context.Context, pi *packages_service.PackageI
}
func createFileForBlob(ctx context.Context, pv *packages_model.PackageVersion, pb *packages_model.PackageBlob) error {
- filename := strings.ToLower(fmt.Sprintf("sha256_%s", pb.HashSHA256))
+ filename := strings.ToLower("sha256_" + pb.HashSHA256)
pf := &packages_model.PackageFile{
VersionID: pv.ID,
diff --git a/routers/api/packages/container/manifest.go b/routers/api/packages/container/manifest.go
index ad035cf473..26faa7b024 100644
--- a/routers/api/packages/container/manifest.go
+++ b/routers/api/packages/container/manifest.go
@@ -406,7 +406,7 @@ func createFileFromBlobReference(ctx context.Context, pv, uploadVersion *package
}
if ref.Name == "" {
- ref.Name = strings.ToLower(fmt.Sprintf("sha256_%s", ref.File.Blob.HashSHA256))
+ ref.Name = strings.ToLower("sha256_" + ref.File.Blob.HashSHA256)
}
pf := &packages_model.PackageFile{
diff --git a/routers/api/packages/nuget/nuget.go b/routers/api/packages/nuget/nuget.go
index 07a8de0a68..fa5067a278 100644
--- a/routers/api/packages/nuget/nuget.go
+++ b/routers/api/packages/nuget/nuget.go
@@ -488,7 +488,7 @@ func UploadPackage(ctx *context.Context) {
pv,
&packages_service.PackageFileCreationInfo{
PackageFileInfo: packages_service.PackageFileInfo{
- Filename: strings.ToLower(fmt.Sprintf("%s.nuspec", np.ID)),
+ Filename: strings.ToLower(np.ID + ".nuspec"),
},
Data: nuspecBuf,
},
diff --git a/routers/api/v1/activitypub/reqsignature.go b/routers/api/v1/activitypub/reqsignature.go
index 957d593d89..4eff51782f 100644
--- a/routers/api/v1/activitypub/reqsignature.go
+++ b/routers/api/v1/activitypub/reqsignature.go
@@ -7,6 +7,7 @@ import (
"crypto"
"crypto/x509"
"encoding/pem"
+ "errors"
"fmt"
"io"
"net/http"
@@ -34,7 +35,7 @@ func getPublicKeyFromResponse(b []byte, keyID *url.URL) (p crypto.PublicKey, err
pubKeyPem := pubKey.PublicKeyPem
block, _ := pem.Decode([]byte(pubKeyPem))
if block == nil || block.Type != "PUBLIC KEY" {
- return nil, fmt.Errorf("could not decode publicKeyPem to PUBLIC KEY pem block type")
+ return nil, errors.New("could not decode publicKeyPem to PUBLIC KEY pem block type")
}
p, err = x509.ParsePKIXPublicKey(block.Bytes)
return p, err
diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go
index c4bb85de55..3ba77604ec 100644
--- a/routers/api/v1/admin/user.go
+++ b/routers/api/v1/admin/user.go
@@ -296,7 +296,7 @@ func DeleteUser(ctx *context.APIContext) {
// admin should not delete themself
if ctx.ContextUser.ID == ctx.Doer.ID {
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Errorf("you cannot delete yourself"))
+ ctx.APIError(http.StatusUnprocessableEntity, errors.New("you cannot delete yourself"))
return
}
diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go
index 3dcb87261b..5cd08a3618 100644
--- a/routers/api/v1/api.go
+++ b/routers/api/v1/api.go
@@ -307,7 +307,7 @@ func tokenRequiresScopes(requiredScopeCategories ...auth_model.AccessTokenScopeC
// use the http method to determine the access level
requiredScopeLevel := auth_model.Read
- if ctx.Req.Method == "POST" || ctx.Req.Method == "PUT" || ctx.Req.Method == "PATCH" || ctx.Req.Method == "DELETE" {
+ if ctx.Req.Method == http.MethodPost || ctx.Req.Method == http.MethodPut || ctx.Req.Method == http.MethodPatch || ctx.Req.Method == http.MethodDelete {
requiredScopeLevel = auth_model.Write
}
diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go
index 9c6e572fb4..c40ac0dee0 100644
--- a/routers/api/v1/repo/branch.go
+++ b/routers/api/v1/repo/branch.go
@@ -6,7 +6,6 @@ package repo
import (
"errors"
- "fmt"
"net/http"
"code.gitea.io/gitea/models/db"
@@ -157,9 +156,9 @@ func DeleteBranch(ctx *context.APIContext) {
case git.IsErrBranchNotExist(err):
ctx.APIErrorNotFound(err)
case errors.Is(err, repo_service.ErrBranchIsDefault):
- ctx.APIError(http.StatusForbidden, fmt.Errorf("can not delete default branch"))
+ ctx.APIError(http.StatusForbidden, errors.New("can not delete default branch"))
case errors.Is(err, git_model.ErrBranchIsProtected):
- ctx.APIError(http.StatusForbidden, fmt.Errorf("branch protected"))
+ ctx.APIError(http.StatusForbidden, errors.New("branch protected"))
default:
ctx.APIErrorInternal(err)
}
diff --git a/routers/api/v1/repo/commits.go b/routers/api/v1/repo/commits.go
index 03489d777b..c92fbeab09 100644
--- a/routers/api/v1/repo/commits.go
+++ b/routers/api/v1/repo/commits.go
@@ -5,7 +5,6 @@
package repo
import (
- "fmt"
"math"
"net/http"
"strconv"
@@ -65,7 +64,7 @@ func GetSingleCommit(ctx *context.APIContext) {
sha := ctx.PathParam("sha")
if !git.IsValidRefPattern(sha) {
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Sprintf("no valid ref or sha: %s", sha))
+ ctx.APIError(http.StatusUnprocessableEntity, "no valid ref or sha: "+sha)
return
}
diff --git a/routers/api/v1/repo/download.go b/routers/api/v1/repo/download.go
index 20901badfb..acd93ecf2e 100644
--- a/routers/api/v1/repo/download.go
+++ b/routers/api/v1/repo/download.go
@@ -4,7 +4,6 @@
package repo
import (
- "fmt"
"net/http"
"code.gitea.io/gitea/modules/git"
@@ -23,7 +22,7 @@ func DownloadArchive(ctx *context.APIContext) {
case "bundle":
tp = git.ArchiveBundle
default:
- ctx.APIError(http.StatusBadRequest, fmt.Sprintf("Unknown archive type: %s", ballType))
+ ctx.APIError(http.StatusBadRequest, "Unknown archive type: "+ballType)
return
}
diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go
index 1ba71aa8a3..d8e9fde2c0 100644
--- a/routers/api/v1/repo/file.go
+++ b/routers/api/v1/repo/file.go
@@ -661,7 +661,7 @@ func UpdateFile(ctx *context.APIContext) {
// "$ref": "#/responses/repoArchivedError"
apiOpts := web.GetForm(ctx).(*api.UpdateFileOptions)
if ctx.Repo.Repository.IsEmpty {
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Errorf("repo is empty"))
+ ctx.APIError(http.StatusUnprocessableEntity, errors.New("repo is empty"))
return
}
diff --git a/routers/api/v1/repo/issue_label.go b/routers/api/v1/repo/issue_label.go
index f8e14e0490..d5eee2d469 100644
--- a/routers/api/v1/repo/issue_label.go
+++ b/routers/api/v1/repo/issue_label.go
@@ -5,7 +5,7 @@
package repo
import (
- "fmt"
+ "errors"
"net/http"
"reflect"
@@ -321,7 +321,7 @@ func prepareForReplaceOrAdd(ctx *context.APIContext, form api.IssueLabelsOption)
if !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) {
ctx.APIError(http.StatusForbidden, "write permission is required")
- return nil, nil, fmt.Errorf("permission denied")
+ return nil, nil, errors.New("permission denied")
}
var (
@@ -337,12 +337,12 @@ func prepareForReplaceOrAdd(ctx *context.APIContext, form api.IssueLabelsOption)
labelNames = append(labelNames, rv.String())
default:
ctx.APIError(http.StatusBadRequest, "a label must be an integer or a string")
- return nil, nil, fmt.Errorf("invalid label")
+ return nil, nil, errors.New("invalid label")
}
}
if len(labelIDs) > 0 && len(labelNames) > 0 {
ctx.APIError(http.StatusBadRequest, "labels should be an array of strings or integers")
- return nil, nil, fmt.Errorf("invalid labels")
+ return nil, nil, errors.New("invalid labels")
}
if len(labelNames) > 0 {
repoLabelIDs, err := issues_model.GetLabelIDsInRepoByNames(ctx, ctx.Repo.Repository.ID, labelNames)
diff --git a/routers/api/v1/repo/issue_tracked_time.go b/routers/api/v1/repo/issue_tracked_time.go
index dbb2afa920..49531f1824 100644
--- a/routers/api/v1/repo/issue_tracked_time.go
+++ b/routers/api/v1/repo/issue_tracked_time.go
@@ -4,6 +4,7 @@
package repo
import (
+ "errors"
"fmt"
"net/http"
"time"
@@ -116,7 +117,7 @@ func ListTrackedTimes(ctx *context.APIContext) {
if opts.UserID == 0 {
opts.UserID = ctx.Doer.ID
} else {
- ctx.APIError(http.StatusForbidden, fmt.Errorf("query by user not allowed; not enough rights"))
+ ctx.APIError(http.StatusForbidden, errors.New("query by user not allowed; not enough rights"))
return
}
}
@@ -437,7 +438,7 @@ func ListTrackedTimesByUser(ctx *context.APIContext) {
}
if !ctx.IsUserRepoAdmin() && !ctx.Doer.IsAdmin && ctx.Doer.ID != user.ID {
- ctx.APIError(http.StatusForbidden, fmt.Errorf("query by user not allowed; not enough rights"))
+ ctx.APIError(http.StatusForbidden, errors.New("query by user not allowed; not enough rights"))
return
}
@@ -545,7 +546,7 @@ func ListTrackedTimesByRepository(ctx *context.APIContext) {
if opts.UserID == 0 {
opts.UserID = ctx.Doer.ID
} else {
- ctx.APIError(http.StatusForbidden, fmt.Errorf("query by user not allowed; not enough rights"))
+ ctx.APIError(http.StatusForbidden, errors.New("query by user not allowed; not enough rights"))
return
}
}
diff --git a/routers/api/v1/repo/migrate.go b/routers/api/v1/repo/migrate.go
index d7508684a1..87bb269031 100644
--- a/routers/api/v1/repo/migrate.go
+++ b/routers/api/v1/repo/migrate.go
@@ -115,12 +115,12 @@ func Migrate(ctx *context.APIContext) {
gitServiceType := convert.ToGitServiceType(form.Service)
if form.Mirror && setting.Mirror.DisableNewPull {
- ctx.APIError(http.StatusForbidden, fmt.Errorf("the site administrator has disabled the creation of new pull mirrors"))
+ ctx.APIError(http.StatusForbidden, errors.New("the site administrator has disabled the creation of new pull mirrors"))
return
}
if setting.Repository.DisableMigrations {
- ctx.APIError(http.StatusForbidden, fmt.Errorf("the site administrator has disabled migrations"))
+ ctx.APIError(http.StatusForbidden, errors.New("the site administrator has disabled migrations"))
return
}
diff --git a/routers/api/v1/repo/mirror.go b/routers/api/v1/repo/mirror.go
index b5f4c12c50..f11a1603c4 100644
--- a/routers/api/v1/repo/mirror.go
+++ b/routers/api/v1/repo/mirror.go
@@ -5,7 +5,6 @@ package repo
import (
"errors"
- "fmt"
"net/http"
"time"
@@ -367,7 +366,7 @@ func CreatePushMirror(ctx *context.APIContext, mirrorOption *api.CreatePushMirro
pushMirror := &repo_model.PushMirror{
RepoID: repo.ID,
Repo: repo,
- RemoteName: fmt.Sprintf("remote_mirror_%s", remoteSuffix),
+ RemoteName: "remote_mirror_" + remoteSuffix,
Interval: interval,
SyncOnCommit: mirrorOption.SyncOnCommit,
RemoteAddress: remoteAddress,
diff --git a/routers/api/v1/repo/notes.go b/routers/api/v1/repo/notes.go
index dcb512256c..eb048df6fe 100644
--- a/routers/api/v1/repo/notes.go
+++ b/routers/api/v1/repo/notes.go
@@ -4,7 +4,7 @@
package repo
import (
- "fmt"
+ "errors"
"net/http"
"code.gitea.io/gitea/modules/git"
@@ -54,7 +54,7 @@ func GetNote(ctx *context.APIContext) {
sha := ctx.PathParam("sha")
if !git.IsValidRefPattern(sha) {
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Sprintf("no valid ref or sha: %s", sha))
+ ctx.APIError(http.StatusUnprocessableEntity, "no valid ref or sha: "+sha)
return
}
getNote(ctx, sha)
@@ -62,7 +62,7 @@ func GetNote(ctx *context.APIContext) {
func getNote(ctx *context.APIContext, identifier string) {
if ctx.Repo.GitRepo == nil {
- ctx.APIErrorInternal(fmt.Errorf("no open git repo"))
+ ctx.APIErrorInternal(errors.New("no open git repo"))
return
}
diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go
index f5d0e37c65..c0b1810191 100644
--- a/routers/api/v1/repo/pull.go
+++ b/routers/api/v1/repo/pull.go
@@ -1054,9 +1054,9 @@ func MergePullRequest(ctx *context.APIContext) {
case git.IsErrBranchNotExist(err):
ctx.APIErrorNotFound(err)
case errors.Is(err, repo_service.ErrBranchIsDefault):
- ctx.APIError(http.StatusForbidden, fmt.Errorf("can not delete default branch"))
+ ctx.APIError(http.StatusForbidden, errors.New("can not delete default branch"))
case errors.Is(err, git_model.ErrBranchIsProtected):
- ctx.APIError(http.StatusForbidden, fmt.Errorf("branch protected"))
+ ctx.APIError(http.StatusForbidden, errors.New("branch protected"))
default:
ctx.APIErrorInternal(err)
}
diff --git a/routers/api/v1/repo/pull_review.go b/routers/api/v1/repo/pull_review.go
index fb35126a99..9421a052db 100644
--- a/routers/api/v1/repo/pull_review.go
+++ b/routers/api/v1/repo/pull_review.go
@@ -439,7 +439,7 @@ func SubmitPullReview(ctx *context.APIContext) {
}
if review.Type != issues_model.ReviewTypePending {
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Errorf("only a pending review can be submitted"))
+ ctx.APIError(http.StatusUnprocessableEntity, errors.New("only a pending review can be submitted"))
return
}
@@ -451,7 +451,7 @@ func SubmitPullReview(ctx *context.APIContext) {
// if review stay pending return
if reviewType == issues_model.ReviewTypePending {
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Errorf("review stay pending"))
+ ctx.APIError(http.StatusUnprocessableEntity, errors.New("review stay pending"))
return
}
@@ -496,7 +496,7 @@ func preparePullReviewType(ctx *context.APIContext, pr *issues_model.PullRequest
case api.ReviewStateApproved:
// can not approve your own PR
if pr.Issue.IsPoster(ctx.Doer.ID) {
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Errorf("approve your own pull is not allowed"))
+ ctx.APIError(http.StatusUnprocessableEntity, errors.New("approve your own pull is not allowed"))
return -1, true
}
reviewType = issues_model.ReviewTypeApprove
@@ -505,7 +505,7 @@ func preparePullReviewType(ctx *context.APIContext, pr *issues_model.PullRequest
case api.ReviewStateRequestChanges:
// can not reject your own PR
if pr.Issue.IsPoster(ctx.Doer.ID) {
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Errorf("reject your own pull is not allowed"))
+ ctx.APIError(http.StatusUnprocessableEntity, errors.New("reject your own pull is not allowed"))
return -1, true
}
reviewType = issues_model.ReviewTypeReject
diff --git a/routers/api/v1/repo/release.go b/routers/api/v1/repo/release.go
index 36fff126e1..b6f5a3ac9e 100644
--- a/routers/api/v1/repo/release.go
+++ b/routers/api/v1/repo/release.go
@@ -4,6 +4,7 @@
package repo
import (
+ "errors"
"fmt"
"net/http"
@@ -220,7 +221,7 @@ func CreateRelease(ctx *context.APIContext) {
form := web.GetForm(ctx).(*api.CreateReleaseOption)
if ctx.Repo.Repository.IsEmpty {
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Errorf("repo is empty"))
+ ctx.APIError(http.StatusUnprocessableEntity, errors.New("repo is empty"))
return
}
rel, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, form.TagName)
diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go
index 3d638cb05e..7caf004b4a 100644
--- a/routers/api/v1/repo/repo.go
+++ b/routers/api/v1/repo/repo.go
@@ -5,6 +5,7 @@
package repo
import (
+ "errors"
"fmt"
"net/http"
"slices"
@@ -711,7 +712,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err
visibilityChanged = repo.IsPrivate != *opts.Private
// when ForcePrivate enabled, you could change public repo to private, but only admin users can change private to public
if visibilityChanged && setting.Repository.ForcePrivate && !*opts.Private && !ctx.Doer.IsAdmin {
- err := fmt.Errorf("cannot change private repository to public")
+ err := errors.New("cannot change private repository to public")
ctx.APIError(http.StatusUnprocessableEntity, err)
return err
}
@@ -780,12 +781,12 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error {
if newHasIssues && opts.ExternalTracker != nil && !unit_model.TypeExternalTracker.UnitGlobalDisabled() {
// Check that values are valid
if !validation.IsValidExternalURL(opts.ExternalTracker.ExternalTrackerURL) {
- err := fmt.Errorf("External tracker URL not valid")
+ err := errors.New("External tracker URL not valid")
ctx.APIError(http.StatusUnprocessableEntity, err)
return err
}
if len(opts.ExternalTracker.ExternalTrackerFormat) != 0 && !validation.IsValidExternalTrackerURLFormat(opts.ExternalTracker.ExternalTrackerFormat) {
- err := fmt.Errorf("External tracker URL format not valid")
+ err := errors.New("External tracker URL format not valid")
ctx.APIError(http.StatusUnprocessableEntity, err)
return err
}
@@ -847,7 +848,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error {
if newHasWiki && opts.ExternalWiki != nil && !unit_model.TypeExternalWiki.UnitGlobalDisabled() {
// Check that values are valid
if !validation.IsValidExternalURL(opts.ExternalWiki.ExternalWikiURL) {
- err := fmt.Errorf("External wiki URL not valid")
+ err := errors.New("External wiki URL not valid")
ctx.APIError(http.StatusUnprocessableEntity, "Invalid external wiki URL")
return err
}
@@ -1038,7 +1039,7 @@ func updateRepoArchivedState(ctx *context.APIContext, opts api.EditRepoOption) e
// archive / un-archive
if opts.Archived != nil {
if repo.IsMirror {
- err := fmt.Errorf("repo is a mirror, cannot archive/un-archive")
+ err := errors.New("repo is a mirror, cannot archive/un-archive")
ctx.APIError(http.StatusUnprocessableEntity, err)
return err
}
diff --git a/routers/api/v1/user/gpg_key.go b/routers/api/v1/user/gpg_key.go
index 504e74ae10..b76bd8a1ee 100644
--- a/routers/api/v1/user/gpg_key.go
+++ b/routers/api/v1/user/gpg_key.go
@@ -4,7 +4,7 @@
package user
import (
- "fmt"
+ "errors"
"net/http"
"strings"
@@ -135,7 +135,7 @@ func GetGPGKey(ctx *context.APIContext) {
// CreateUserGPGKey creates new GPG key to given user by ID.
func CreateUserGPGKey(ctx *context.APIContext, form api.CreateGPGKeyOption, uid int64) {
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageGPGKeys) {
- ctx.APIErrorNotFound("Not Found", fmt.Errorf("gpg keys setting is not allowed to be visited"))
+ ctx.APIErrorNotFound("Not Found", errors.New("gpg keys setting is not allowed to be visited"))
return
}
@@ -205,7 +205,7 @@ func VerifyUserGPGKey(ctx *context.APIContext) {
if err != nil {
if asymkey_model.IsErrGPGInvalidTokenSignature(err) {
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Sprintf("The provided GPG key, signature and token do not match or token is out of date. Provide a valid signature for the token: %s", token))
+ ctx.APIError(http.StatusUnprocessableEntity, "The provided GPG key, signature and token do not match or token is out of date. Provide a valid signature for the token: "+token)
return
}
ctx.APIErrorInternal(err)
@@ -276,7 +276,7 @@ func DeleteGPGKey(ctx *context.APIContext) {
// "$ref": "#/responses/notFound"
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageGPGKeys) {
- ctx.APIErrorNotFound("Not Found", fmt.Errorf("gpg keys setting is not allowed to be visited"))
+ ctx.APIErrorNotFound("Not Found", errors.New("gpg keys setting is not allowed to be visited"))
return
}
@@ -302,9 +302,9 @@ func HandleAddGPGKeyError(ctx *context.APIContext, err error, token string) {
case asymkey_model.IsErrGPGKeyParsing(err):
ctx.APIError(http.StatusUnprocessableEntity, err)
case asymkey_model.IsErrGPGNoEmailFound(err):
- ctx.APIError(http.StatusNotFound, fmt.Sprintf("None of the emails attached to the GPG key could be found. It may still be added if you provide a valid signature for the token: %s", token))
+ ctx.APIError(http.StatusNotFound, "None of the emails attached to the GPG key could be found. It may still be added if you provide a valid signature for the token: "+token)
case asymkey_model.IsErrGPGInvalidTokenSignature(err):
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Sprintf("The provided GPG key, signature and token do not match or token is out of date. Provide a valid signature for the token: %s", token))
+ ctx.APIError(http.StatusUnprocessableEntity, "The provided GPG key, signature and token do not match or token is out of date. Provide a valid signature for the token: "+token)
default:
ctx.APIErrorInternal(err)
}
diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go
index 04854f2092..628f5d6cac 100644
--- a/routers/api/v1/user/key.go
+++ b/routers/api/v1/user/key.go
@@ -5,7 +5,7 @@ package user
import (
std_ctx "context"
- "fmt"
+ "errors"
"net/http"
asymkey_model "code.gitea.io/gitea/models/asymkey"
@@ -201,7 +201,7 @@ func GetPublicKey(ctx *context.APIContext) {
// CreateUserPublicKey creates new public key to given user by ID.
func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid int64) {
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys) {
- ctx.APIErrorNotFound("Not Found", fmt.Errorf("ssh keys setting is not allowed to be visited"))
+ ctx.APIErrorNotFound("Not Found", errors.New("ssh keys setting is not allowed to be visited"))
return
}
@@ -271,7 +271,7 @@ func DeletePublicKey(ctx *context.APIContext) {
// "$ref": "#/responses/notFound"
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys) {
- ctx.APIErrorNotFound("Not Found", fmt.Errorf("ssh keys setting is not allowed to be visited"))
+ ctx.APIErrorNotFound("Not Found", errors.New("ssh keys setting is not allowed to be visited"))
return
}
diff --git a/routers/api/v1/utils/git.go b/routers/api/v1/utils/git.go
index af672ba147..7d276d9d98 100644
--- a/routers/api/v1/utils/git.go
+++ b/routers/api/v1/utils/git.go
@@ -5,6 +5,7 @@ package utils
import (
gocontext "context"
+ "errors"
"fmt"
"net/http"
@@ -50,7 +51,7 @@ func ResolveRefOrSha(ctx *context.APIContext, ref string) string {
// GetGitRefs return git references based on filter
func GetGitRefs(ctx *context.APIContext, filter string) ([]*git.Reference, string, error) {
if ctx.Repo.GitRepo == nil {
- return nil, "", fmt.Errorf("no open git repo found in context")
+ return nil, "", errors.New("no open git repo found in context")
}
if len(filter) > 0 {
filter = "refs/" + filter
diff --git a/routers/api/v1/utils/hook.go b/routers/api/v1/utils/hook.go
index ce0c1b5097..532d157e35 100644
--- a/routers/api/v1/utils/hook.go
+++ b/routers/api/v1/utils/hook.go
@@ -4,7 +4,6 @@
package utils
import (
- "fmt"
"net/http"
"strconv"
"strings"
@@ -80,7 +79,7 @@ func GetRepoHook(ctx *context.APIContext, repoID, hookID int64) (*webhook.Webhoo
// write the appropriate error to `ctx`. Return whether the form is valid
func checkCreateHookOption(ctx *context.APIContext, form *api.CreateHookOption) bool {
if !webhook_service.IsValidHookTaskType(form.Type) {
- ctx.APIError(http.StatusUnprocessableEntity, fmt.Sprintf("Invalid hook type: %s", form.Type))
+ ctx.APIError(http.StatusUnprocessableEntity, "Invalid hook type: "+form.Type)
return false
}
for _, name := range []string{"url", "content_type"} {
diff --git a/routers/common/db.go b/routers/common/db.go
index cb163c867d..01c0261427 100644
--- a/routers/common/db.go
+++ b/routers/common/db.go
@@ -5,7 +5,7 @@ package common
import (
"context"
- "fmt"
+ "errors"
"time"
"code.gitea.io/gitea/models/db"
@@ -25,7 +25,7 @@ func InitDBEngine(ctx context.Context) (err error) {
for i := 0; i < setting.Database.DBConnectRetries; i++ {
select {
case <-ctx.Done():
- return fmt.Errorf("Aborted due to shutdown:\nin retry ORM engine initialization")
+ return errors.New("Aborted due to shutdown:\nin retry ORM engine initialization")
default:
}
log.Info("ORM engine initialization attempt #%d/%d...", i+1, setting.Database.DBConnectRetries)
diff --git a/routers/common/markup.go b/routers/common/markup.go
index 60bf0dba54..4c77ff33ed 100644
--- a/routers/common/markup.go
+++ b/routers/common/markup.go
@@ -88,7 +88,7 @@ func RenderMarkup(ctx *context.Base, ctxRepo *context.Repository, mode, text, ur
})
rctx = rctx.WithMarkupType("").WithRelativePath(filePath) // render the repo file content by its extension
default:
- ctx.HTTPError(http.StatusUnprocessableEntity, fmt.Sprintf("Unknown mode: %s", mode))
+ ctx.HTTPError(http.StatusUnprocessableEntity, "Unknown mode: "+mode)
return
}
rctx = rctx.WithUseAbsoluteLink(true)
diff --git a/routers/install/install.go b/routers/install/install.go
index e0613f12aa..2962f3948f 100644
--- a/routers/install/install.go
+++ b/routers/install/install.go
@@ -5,7 +5,6 @@
package install
import (
- "fmt"
"net/http"
"net/mail"
"os"
@@ -398,7 +397,7 @@ func SubmitInstall(ctx *context.Context) {
cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
} else {
cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
- cfg.Section("server").Key("SSH_PORT").SetValue(fmt.Sprint(form.SSHPort))
+ cfg.Section("server").Key("SSH_PORT").SetValue(strconv.Itoa(form.SSHPort))
}
if form.LFSRootPath != "" {
@@ -429,10 +428,10 @@ func SubmitInstall(ctx *context.Context) {
} else {
cfg.Section("mailer").Key("ENABLED").SetValue("false")
}
- cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(fmt.Sprint(form.RegisterConfirm))
- cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(fmt.Sprint(form.MailNotify))
+ cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(strconv.FormatBool(form.RegisterConfirm))
+ cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(strconv.FormatBool(form.MailNotify))
- cfg.Section("server").Key("OFFLINE_MODE").SetValue(fmt.Sprint(form.OfflineMode))
+ cfg.Section("server").Key("OFFLINE_MODE").SetValue(strconv.FormatBool(form.OfflineMode))
if err := system_model.SetSettings(ctx, map[string]string{
setting.Config().Picture.DisableGravatar.DynKey(): strconv.FormatBool(form.DisableGravatar),
setting.Config().Picture.EnableFederatedAvatar.DynKey(): strconv.FormatBool(form.EnableFederatedAvatar),
@@ -441,17 +440,17 @@ func SubmitInstall(ctx *context.Context) {
return
}
- cfg.Section("openid").Key("ENABLE_OPENID_SIGNIN").SetValue(fmt.Sprint(form.EnableOpenIDSignIn))
- cfg.Section("openid").Key("ENABLE_OPENID_SIGNUP").SetValue(fmt.Sprint(form.EnableOpenIDSignUp))
- cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(fmt.Sprint(form.DisableRegistration))
- cfg.Section("service").Key("ALLOW_ONLY_EXTERNAL_REGISTRATION").SetValue(fmt.Sprint(form.AllowOnlyExternalRegistration))
- cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(fmt.Sprint(form.EnableCaptcha))
- cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(fmt.Sprint(form.RequireSignInView))
- cfg.Section("service").Key("DEFAULT_KEEP_EMAIL_PRIVATE").SetValue(fmt.Sprint(form.DefaultKeepEmailPrivate))
- cfg.Section("service").Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").SetValue(fmt.Sprint(form.DefaultAllowCreateOrganization))
- cfg.Section("service").Key("DEFAULT_ENABLE_TIMETRACKING").SetValue(fmt.Sprint(form.DefaultEnableTimetracking))
- cfg.Section("service").Key("NO_REPLY_ADDRESS").SetValue(fmt.Sprint(form.NoReplyAddress))
- cfg.Section("cron.update_checker").Key("ENABLED").SetValue(fmt.Sprint(form.EnableUpdateChecker))
+ cfg.Section("openid").Key("ENABLE_OPENID_SIGNIN").SetValue(strconv.FormatBool(form.EnableOpenIDSignIn))
+ cfg.Section("openid").Key("ENABLE_OPENID_SIGNUP").SetValue(strconv.FormatBool(form.EnableOpenIDSignUp))
+ cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(strconv.FormatBool(form.DisableRegistration))
+ cfg.Section("service").Key("ALLOW_ONLY_EXTERNAL_REGISTRATION").SetValue(strconv.FormatBool(form.AllowOnlyExternalRegistration))
+ cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(strconv.FormatBool(form.EnableCaptcha))
+ cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(strconv.FormatBool(form.RequireSignInView))
+ cfg.Section("service").Key("DEFAULT_KEEP_EMAIL_PRIVATE").SetValue(strconv.FormatBool(form.DefaultKeepEmailPrivate))
+ cfg.Section("service").Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").SetValue(strconv.FormatBool(form.DefaultAllowCreateOrganization))
+ cfg.Section("service").Key("DEFAULT_ENABLE_TIMETRACKING").SetValue(strconv.FormatBool(form.DefaultEnableTimetracking))
+ cfg.Section("service").Key("NO_REPLY_ADDRESS").SetValue(form.NoReplyAddress)
+ cfg.Section("cron.update_checker").Key("ENABLED").SetValue(strconv.FormatBool(form.EnableUpdateChecker))
cfg.Section("session").Key("PROVIDER").SetValue("file")
diff --git a/routers/install/routes.go b/routers/install/routes.go
index 7309a405d4..bc7a0eb48c 100644
--- a/routers/install/routes.go
+++ b/routers/install/routes.go
@@ -36,7 +36,7 @@ func Routes() *web.Router {
func installNotFound(w http.ResponseWriter, req *http.Request) {
w.Header().Add("Content-Type", "text/html; charset=utf-8")
- w.Header().Add("Refresh", fmt.Sprintf("1; url=%s", setting.AppSubURL+"/"))
+ w.Header().Add("Refresh", "1; url="+setting.AppSubURL+"/")
// do not use 30x status, because the "post-install" page needs to use 404/200 to detect if Gitea has been installed.
// the fetch API could follow 30x requests to the page with 200 status.
w.WriteHeader(http.StatusNotFound)
diff --git a/routers/install/routes_test.go b/routers/install/routes_test.go
index 7325eb8145..e8902ba3f1 100644
--- a/routers/install/routes_test.go
+++ b/routers/install/routes_test.go
@@ -4,6 +4,7 @@
package install
import (
+ "net/http"
"net/http/httptest"
"testing"
@@ -17,18 +18,18 @@ func TestRoutes(t *testing.T) {
assert.NotNil(t, r)
w := httptest.NewRecorder()
- req := httptest.NewRequest("GET", "/", nil)
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
r.ServeHTTP(w, req)
assert.Equal(t, 200, w.Code)
assert.Contains(t, w.Body.String(), `class="page-content install"`)
w = httptest.NewRecorder()
- req = httptest.NewRequest("GET", "/no-such", nil)
+ req = httptest.NewRequest(http.MethodGet, "/no-such", nil)
r.ServeHTTP(w, req)
assert.Equal(t, 404, w.Code)
w = httptest.NewRecorder()
- req = httptest.NewRequest("GET", "/assets/img/gitea.svg", nil)
+ req = httptest.NewRequest(http.MethodGet, "/assets/img/gitea.svg", nil)
r.ServeHTTP(w, req)
assert.Equal(t, 200, w.Code)
}
diff --git a/routers/private/hook_pre_receive.go b/routers/private/hook_pre_receive.go
index 48fe591bbd..be9923c98f 100644
--- a/routers/private/hook_pre_receive.go
+++ b/routers/private/hook_pre_receive.go
@@ -311,13 +311,13 @@ func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID string, r
if isForcePush {
log.Warn("Forbidden: User %d is not allowed to force-push to protected branch: %s in %-v", ctx.opts.UserID, branchName, repo)
ctx.JSON(http.StatusForbidden, private.Response{
- UserMsg: fmt.Sprintf("Not allowed to force-push to protected branch %s", branchName),
+ UserMsg: "Not allowed to force-push to protected branch " + branchName,
})
return
}
log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v", ctx.opts.UserID, branchName, repo)
ctx.JSON(http.StatusForbidden, private.Response{
- UserMsg: fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
+ UserMsg: "Not allowed to push to protected branch " + branchName,
})
return
}
@@ -353,7 +353,7 @@ func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID string, r
if !allowedMerge {
log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v and is not allowed to merge pr #%d", ctx.opts.UserID, branchName, repo, pr.Index)
ctx.JSON(http.StatusForbidden, private.Response{
- UserMsg: fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
+ UserMsg: "Not allowed to push to protected branch " + branchName,
})
return
}
diff --git a/routers/private/hook_verification.go b/routers/private/hook_verification.go
index 7c06cf8557..57d0964ead 100644
--- a/routers/private/hook_verification.go
+++ b/routers/private/hook_verification.go
@@ -6,7 +6,6 @@ package private
import (
"bufio"
"context"
- "fmt"
"io"
"os"
@@ -113,7 +112,7 @@ type errUnverifiedCommit struct {
}
func (e *errUnverifiedCommit) Error() string {
- return fmt.Sprintf("Unverified commit: %s", e.sha)
+ return "Unverified commit: " + e.sha
}
func isErrUnverifiedCommit(err error) bool {
diff --git a/routers/private/manager.go b/routers/private/manager.go
index c712bbcf21..00e52d6511 100644
--- a/routers/private/manager.go
+++ b/routers/private/manager.go
@@ -180,7 +180,7 @@ func AddLogger(ctx *context.PrivateContext) {
writerOption.Addr, _ = opts.Config["address"].(string)
writerMode.WriterOption = writerOption
default:
- panic(fmt.Sprintf("invalid log writer mode: %s", writerType))
+ panic("invalid log writer mode: " + writerType)
}
writer, err := log.NewEventWriter(opts.Writer, writerType, writerMode)
if err != nil {
diff --git a/routers/web/admin/applications.go b/routers/web/admin/applications.go
index aec6349f21..79c3a08808 100644
--- a/routers/web/admin/applications.go
+++ b/routers/web/admin/applications.go
@@ -4,7 +4,6 @@
package admin
import (
- "fmt"
"net/http"
"code.gitea.io/gitea/models/auth"
@@ -23,8 +22,8 @@ var (
func newOAuth2CommonHandlers() *user_setting.OAuth2CommonHandlers {
return &user_setting.OAuth2CommonHandlers{
OwnerID: 0,
- BasePathList: fmt.Sprintf("%s/-/admin/applications", setting.AppSubURL),
- BasePathEditPrefix: fmt.Sprintf("%s/-/admin/applications/oauth2", setting.AppSubURL),
+ BasePathList: setting.AppSubURL + "/-/admin/applications",
+ BasePathEditPrefix: setting.AppSubURL + "/-/admin/applications/oauth2",
TplAppEdit: tplSettingsOauth2ApplicationEdit,
}
}
diff --git a/routers/web/auth/oauth2_provider.go b/routers/web/auth/oauth2_provider.go
index ff571fbf2c..1804b5b193 100644
--- a/routers/web/auth/oauth2_provider.go
+++ b/routers/web/auth/oauth2_provider.go
@@ -10,6 +10,7 @@ import (
"html/template"
"net/http"
"net/url"
+ "strconv"
"strings"
"code.gitea.io/gitea/models/auth"
@@ -98,7 +99,7 @@ func InfoOAuth(ctx *context.Context) {
}
response := &userInfoResponse{
- Sub: fmt.Sprint(ctx.Doer.ID),
+ Sub: strconv.FormatInt(ctx.Doer.ID, 10),
Name: ctx.Doer.DisplayName(),
PreferredUsername: ctx.Doer.Name,
Email: ctx.Doer.Email,
@@ -171,7 +172,7 @@ func IntrospectOAuth(ctx *context.Context) {
response.Scope = grant.Scope
response.Issuer = setting.AppURL
response.Audience = []string{app.ClientID}
- response.Subject = fmt.Sprint(grant.UserID)
+ response.Subject = strconv.FormatInt(grant.UserID, 10)
}
if user, err := user_model.GetUserByID(ctx, grant.UserID); err == nil {
response.Username = user.Name
diff --git a/routers/web/auth/openid.go b/routers/web/auth/openid.go
index c3415cccac..8c2d3276a8 100644
--- a/routers/web/auth/openid.go
+++ b/routers/web/auth/openid.go
@@ -4,7 +4,7 @@
package auth
import (
- "fmt"
+ "errors"
"net/http"
"net/url"
@@ -55,13 +55,13 @@ func allowedOpenIDURI(uri string) (err error) {
}
}
// must match one of this or be refused
- return fmt.Errorf("URI not allowed by whitelist")
+ return errors.New("URI not allowed by whitelist")
}
// A blacklist match expliclty forbids
for _, pat := range setting.Service.OpenIDBlacklist {
if pat.MatchString(uri) {
- return fmt.Errorf("URI forbidden by blacklist")
+ return errors.New("URI forbidden by blacklist")
}
}
@@ -99,7 +99,7 @@ func SignInOpenIDPost(ctx *context.Context) {
url, err := openid.RedirectURL(id, redirectTo, setting.AppURL)
if err != nil {
log.Error("Error in OpenID redirect URL: %s, %v", redirectTo, err.Error())
- ctx.RenderWithErr(fmt.Sprintf("Unable to find OpenID provider in %s", redirectTo), tplSignInOpenID, &form)
+ ctx.RenderWithErr("Unable to find OpenID provider in "+redirectTo, tplSignInOpenID, &form)
return
}
diff --git a/routers/web/auth/password.go b/routers/web/auth/password.go
index 8dbde85fe6..537ad4b994 100644
--- a/routers/web/auth/password.go
+++ b/routers/web/auth/password.go
@@ -5,7 +5,6 @@ package auth
import (
"errors"
- "fmt"
"net/http"
"code.gitea.io/gitea/models/auth"
@@ -108,14 +107,14 @@ func commonResetPassword(ctx *context.Context) (*user_model.User, *auth.TwoFacto
}
if len(code) == 0 {
- ctx.Flash.Error(ctx.Tr("auth.invalid_code_forgot_password", fmt.Sprintf("%s/user/forgot_password", setting.AppSubURL)), true)
+ ctx.Flash.Error(ctx.Tr("auth.invalid_code_forgot_password", setting.AppSubURL+"/user/forgot_password"), true)
return nil, nil
}
// Fail early, don't frustrate the user
u := user_model.VerifyUserTimeLimitCode(ctx, &user_model.TimeLimitCodeOptions{Purpose: user_model.TimeLimitCodeResetPassword}, code)
if u == nil {
- ctx.Flash.Error(ctx.Tr("auth.invalid_code_forgot_password", fmt.Sprintf("%s/user/forgot_password", setting.AppSubURL)), true)
+ ctx.Flash.Error(ctx.Tr("auth.invalid_code_forgot_password", setting.AppSubURL+"/user/forgot_password"), true)
return nil, nil
}
diff --git a/routers/web/base.go b/routers/web/base.go
index a284dd0288..e43f36a97b 100644
--- a/routers/web/base.go
+++ b/routers/web/base.go
@@ -25,7 +25,7 @@ func avatarStorageHandler(storageSetting *setting.Storage, prefix string, objSto
if storageSetting.ServeDirect() {
return func(w http.ResponseWriter, req *http.Request) {
- if req.Method != "GET" && req.Method != "HEAD" {
+ if req.Method != http.MethodGet && req.Method != http.MethodHead {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
@@ -56,7 +56,7 @@ func avatarStorageHandler(storageSetting *setting.Storage, prefix string, objSto
}
return func(w http.ResponseWriter, req *http.Request) {
- if req.Method != "GET" && req.Method != "HEAD" {
+ if req.Method != http.MethodGet && req.Method != http.MethodHead {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
diff --git a/routers/web/devtest/devtest.go b/routers/web/devtest/devtest.go
index 995f969426..765931a730 100644
--- a/routers/web/devtest/devtest.go
+++ b/routers/web/devtest/devtest.go
@@ -179,7 +179,7 @@ func prepareMockData(ctx *context.Context) {
func TmplCommon(ctx *context.Context) {
prepareMockData(ctx)
- if ctx.Req.Method == "POST" {
+ if ctx.Req.Method == http.MethodPost {
_ = ctx.Req.ParseForm()
ctx.Flash.Info("form: "+ctx.Req.Method+" "+ctx.Req.RequestURI+"
"+
"Form: "+ctx.Req.Form.Encode()+"
"+
diff --git a/routers/web/devtest/mock_actions.go b/routers/web/devtest/mock_actions.go
index 3ce75dfad2..023909aceb 100644
--- a/routers/web/devtest/mock_actions.go
+++ b/routers/web/devtest/mock_actions.go
@@ -4,9 +4,9 @@
package devtest
import (
- "fmt"
mathRand "math/rand/v2"
"net/http"
+ "strconv"
"strings"
"time"
@@ -38,8 +38,8 @@ func generateMockStepsLog(logCur actions.LogCursor) (stepsLog []*actions.ViewSte
for i := 0; i < mockCount; i++ {
logStr := mockedLogs[int(cur)%len(mockedLogs)]
cur++
- logStr = strings.ReplaceAll(logStr, "{step}", fmt.Sprintf("%d", logCur.Step))
- logStr = strings.ReplaceAll(logStr, "{cursor}", fmt.Sprintf("%d", cur))
+ logStr = strings.ReplaceAll(logStr, "{step}", strconv.Itoa(logCur.Step))
+ logStr = strings.ReplaceAll(logStr, "{cursor}", strconv.FormatInt(cur, 10))
stepsLog = append(stepsLog, &actions.ViewStepLog{
Step: logCur.Step,
Cursor: cur,
diff --git a/routers/web/feed/branch.go b/routers/web/feed/branch.go
index d3dae9503e..4a6fe9603d 100644
--- a/routers/web/feed/branch.go
+++ b/routers/web/feed/branch.go
@@ -4,7 +4,6 @@
package feed
import (
- "fmt"
"strings"
"time"
@@ -22,7 +21,7 @@ func ShowBranchFeed(ctx *context.Context, repo *repo.Repository, formatType stri
return
}
- title := fmt.Sprintf("Latest commits for branch %s", ctx.Repo.BranchName)
+ title := "Latest commits for branch " + ctx.Repo.BranchName
link := &feeds.Link{Href: repo.HTMLURL() + "/" + ctx.Repo.RefTypeNameSubURL()}
feed := &feeds.Feed{
diff --git a/routers/web/feed/file.go b/routers/web/feed/file.go
index 407e4fa2d5..026c15c43a 100644
--- a/routers/web/feed/file.go
+++ b/routers/web/feed/file.go
@@ -4,7 +4,6 @@
package feed
import (
- "fmt"
"strings"
"time"
@@ -33,7 +32,7 @@ func ShowFileFeed(ctx *context.Context, repo *repo.Repository, formatType string
return
}
- title := fmt.Sprintf("Latest commits for file %s", ctx.Repo.TreePath)
+ title := "Latest commits for file " + ctx.Repo.TreePath
link := &feeds.Link{Href: repo.HTMLURL() + "/" + ctx.Repo.RefTypeNameSubURL() + "/" + util.PathEscapeSegments(ctx.Repo.TreePath)}
diff --git a/routers/web/goget.go b/routers/web/goget.go
index 79d5c2b207..67e0bee866 100644
--- a/routers/web/goget.go
+++ b/routers/web/goget.go
@@ -18,7 +18,7 @@ import (
)
func goGet(ctx *context.Context) {
- if ctx.Req.Method != "GET" || len(ctx.Req.URL.RawQuery) < 8 || ctx.FormString("go-get") != "1" {
+ if ctx.Req.Method != http.MethodGet || len(ctx.Req.URL.RawQuery) < 8 || ctx.FormString("go-get") != "1" {
return
}
diff --git a/routers/web/nodeinfo.go b/routers/web/nodeinfo.go
index f1cc7bf530..47856bf98b 100644
--- a/routers/web/nodeinfo.go
+++ b/routers/web/nodeinfo.go
@@ -4,7 +4,6 @@
package web
import (
- "fmt"
"net/http"
"code.gitea.io/gitea/modules/setting"
@@ -24,7 +23,7 @@ type nodeInfoLink struct {
func NodeInfoLinks(ctx *context.Context) {
nodeinfolinks := &nodeInfoLinks{
Links: []nodeInfoLink{{
- fmt.Sprintf("%sapi/v1/nodeinfo", setting.AppURL),
+ setting.AppURL + "api/v1/nodeinfo",
"http://nodeinfo.diaspora.software/ns/schema/2.1",
}},
}
diff --git a/routers/web/org/setting.go b/routers/web/org/setting.go
index cb1c4213c9..a8a81e0ade 100644
--- a/routers/web/org/setting.go
+++ b/routers/web/org/setting.go
@@ -170,7 +170,7 @@ func SettingsDelete(ctx *context.Context) {
ctx.Data["PageIsOrgSettings"] = true
ctx.Data["PageIsSettingsDelete"] = true
- if ctx.Req.Method == "POST" {
+ if ctx.Req.Method == http.MethodPost {
if ctx.Org.Organization.Name != ctx.FormString("org_name") {
ctx.Data["Err_OrgName"] = true
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_org_name"), tplSettingsDelete, nil)
diff --git a/routers/web/repo/actions/view.go b/routers/web/repo/actions/view.go
index eb6fc6ded6..ec06c9233a 100644
--- a/routers/web/repo/actions/view.go
+++ b/routers/web/repo/actions/view.go
@@ -508,7 +508,7 @@ func Cancel(ctx *context_module.Context) {
return err
}
if n == 0 {
- return fmt.Errorf("job has changed, try again")
+ return errors.New("job has changed, try again")
}
if n > 0 {
updatedjobs = append(updatedjobs, job)
diff --git a/routers/web/repo/cherry_pick.go b/routers/web/repo/cherry_pick.go
index ec50e1435e..690b830bc2 100644
--- a/routers/web/repo/cherry_pick.go
+++ b/routers/web/repo/cherry_pick.go
@@ -6,6 +6,7 @@ package repo
import (
"bytes"
"errors"
+ "net/http"
"strings"
git_model "code.gitea.io/gitea/models/git"
@@ -59,7 +60,7 @@ func CherryPick(ctx *context.Context) {
ctx.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",")
ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.RefTypeNameSubURL()
- ctx.HTML(200, tplCherryPick)
+ ctx.HTML(http.StatusOK, tplCherryPick)
}
// CherryPickPost handles cherrypick POSTs
@@ -88,7 +89,7 @@ func CherryPickPost(ctx *context.Context) {
ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.RefTypeNameSubURL()
if ctx.HasError() {
- ctx.HTML(200, tplCherryPick)
+ ctx.HTML(http.StatusOK, tplCherryPick)
return
}
diff --git a/routers/web/repo/githttp.go b/routers/web/repo/githttp.go
index 89001ddf57..f4ac9d769b 100644
--- a/routers/web/repo/githttp.go
+++ b/routers/web/repo/githttp.go
@@ -78,7 +78,7 @@ func httpBase(ctx *context.Context) *serviceHandler {
strings.HasSuffix(ctx.Req.URL.Path, "git-upload-archive") {
isPull = true
} else {
- isPull = ctx.Req.Method == "HEAD" || ctx.Req.Method == "GET"
+ isPull = ctx.Req.Method == http.MethodHead || ctx.Req.Method == http.MethodGet
}
var accessMode perm.AccessMode
@@ -360,8 +360,8 @@ func setHeaderNoCache(ctx *context.Context) {
func setHeaderCacheForever(ctx *context.Context) {
now := time.Now().Unix()
expires := now + 31536000
- ctx.Resp.Header().Set("Date", fmt.Sprintf("%d", now))
- ctx.Resp.Header().Set("Expires", fmt.Sprintf("%d", expires))
+ ctx.Resp.Header().Set("Date", strconv.FormatInt(now, 10))
+ ctx.Resp.Header().Set("Expires", strconv.FormatInt(expires, 10))
ctx.Resp.Header().Set("Cache-Control", "public, max-age=31536000")
}
@@ -394,7 +394,7 @@ func (h *serviceHandler) sendFile(ctx *context.Context, contentType, file string
}
ctx.Resp.Header().Set("Content-Type", contentType)
- ctx.Resp.Header().Set("Content-Length", fmt.Sprintf("%d", fi.Size()))
+ ctx.Resp.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))
// http.TimeFormat required a UTC time, refer to https://pkg.go.dev/net/http#TimeFormat
ctx.Resp.Header().Set("Last-Modified", fi.ModTime().UTC().Format(http.TimeFormat))
http.ServeFile(ctx.Resp, ctx.Req, reqFile)
diff --git a/routers/web/repo/issue_list.go b/routers/web/repo/issue_list.go
index 5dc9e8a6b5..d8ab653584 100644
--- a/routers/web/repo/issue_list.go
+++ b/routers/web/repo/issue_list.go
@@ -502,7 +502,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption opt
case "mentioned":
mentionedID = ctx.Doer.ID
case "assigned":
- assigneeID = fmt.Sprint(ctx.Doer.ID)
+ assigneeID = strconv.FormatInt(ctx.Doer.ID, 10)
case "review_requested":
reviewRequestedID = ctx.Doer.ID
case "reviewed_by":
diff --git a/routers/web/repo/issue_new.go b/routers/web/repo/issue_new.go
index 9f52396414..d8863961ff 100644
--- a/routers/web/repo/issue_new.go
+++ b/routers/web/repo/issue_new.go
@@ -223,11 +223,11 @@ func DeleteIssue(ctx *context.Context) {
}
if issue.IsPull {
- ctx.Redirect(fmt.Sprintf("%s/pulls", ctx.Repo.Repository.Link()), http.StatusSeeOther)
+ ctx.Redirect(ctx.Repo.Repository.Link()+"/pulls", http.StatusSeeOther)
return
}
- ctx.Redirect(fmt.Sprintf("%s/issues", ctx.Repo.Repository.Link()), http.StatusSeeOther)
+ ctx.Redirect(ctx.Repo.Repository.Link()+"/issues", http.StatusSeeOther)
}
func toSet[ItemType any, KeyType comparable](slice []ItemType, keyFunc func(ItemType) KeyType) container.Set[KeyType] {
diff --git a/routers/web/repo/patch.go b/routers/web/repo/patch.go
index 120b3469f6..ca346b7e6c 100644
--- a/routers/web/repo/patch.go
+++ b/routers/web/repo/patch.go
@@ -4,6 +4,7 @@
package repo
import (
+ "net/http"
"strings"
git_model "code.gitea.io/gitea/models/git"
@@ -39,7 +40,7 @@ func NewDiffPatch(ctx *context.Context) {
ctx.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",")
ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.RefTypeNameSubURL()
- ctx.HTML(200, tplPatchFile)
+ ctx.HTML(http.StatusOK, tplPatchFile)
}
// NewDiffPatchPost response for sending patch page
@@ -62,7 +63,7 @@ func NewDiffPatchPost(ctx *context.Context) {
ctx.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",")
if ctx.HasError() {
- ctx.HTML(200, tplPatchFile)
+ ctx.HTML(http.StatusOK, tplPatchFile)
return
}
diff --git a/routers/web/repo/setting/protected_branch.go b/routers/web/repo/setting/protected_branch.go
index 75de2ba1e7..f241242f02 100644
--- a/routers/web/repo/setting/protected_branch.go
+++ b/routers/web/repo/setting/protected_branch.go
@@ -8,6 +8,7 @@ import (
"fmt"
"net/http"
"net/url"
+ "strconv"
"strings"
"time"
@@ -110,7 +111,7 @@ func SettingsProtectedBranchPost(ctx *context.Context) {
var protectBranch *git_model.ProtectedBranch
if f.RuleName == "" {
ctx.Flash.Error(ctx.Tr("repo.settings.protected_branch_required_rule_name"))
- ctx.Redirect(fmt.Sprintf("%s/settings/branches/edit", ctx.Repo.RepoLink))
+ ctx.Redirect(ctx.Repo.RepoLink + "/settings/branches/edit")
return
}
@@ -283,32 +284,32 @@ func SettingsProtectedBranchPost(ctx *context.Context) {
func DeleteProtectedBranchRulePost(ctx *context.Context) {
ruleID := ctx.PathParamInt64("id")
if ruleID <= 0 {
- ctx.Flash.Error(ctx.Tr("repo.settings.remove_protected_branch_failed", fmt.Sprintf("%d", ruleID)))
- ctx.JSONRedirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
+ ctx.Flash.Error(ctx.Tr("repo.settings.remove_protected_branch_failed", strconv.FormatInt(ruleID, 10)))
+ ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/branches")
return
}
rule, err := git_model.GetProtectedBranchRuleByID(ctx, ctx.Repo.Repository.ID, ruleID)
if err != nil {
- ctx.Flash.Error(ctx.Tr("repo.settings.remove_protected_branch_failed", fmt.Sprintf("%d", ruleID)))
- ctx.JSONRedirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
+ ctx.Flash.Error(ctx.Tr("repo.settings.remove_protected_branch_failed", strconv.FormatInt(ruleID, 10)))
+ ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/branches")
return
}
if rule == nil {
- ctx.Flash.Error(ctx.Tr("repo.settings.remove_protected_branch_failed", fmt.Sprintf("%d", ruleID)))
- ctx.JSONRedirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
+ ctx.Flash.Error(ctx.Tr("repo.settings.remove_protected_branch_failed", strconv.FormatInt(ruleID, 10)))
+ ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/branches")
return
}
if err := git_model.DeleteProtectedBranch(ctx, ctx.Repo.Repository, ruleID); err != nil {
ctx.Flash.Error(ctx.Tr("repo.settings.remove_protected_branch_failed", rule.RuleName))
- ctx.JSONRedirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
+ ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/branches")
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.remove_protected_branch_success", rule.RuleName))
- ctx.JSONRedirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
+ ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/branches")
}
func UpdateBranchProtectionPriories(ctx *context.Context) {
@@ -332,7 +333,7 @@ func RenameBranchPost(ctx *context.Context) {
if ctx.HasError() {
ctx.Flash.Error(ctx.GetErrMsg())
- ctx.Redirect(fmt.Sprintf("%s/branches", ctx.Repo.RepoLink))
+ ctx.Redirect(ctx.Repo.RepoLink + "/branches")
return
}
@@ -341,13 +342,13 @@ func RenameBranchPost(ctx *context.Context) {
switch {
case repo_model.IsErrUserDoesNotHaveAccessToRepo(err):
ctx.Flash.Error(ctx.Tr("repo.branch.rename_default_or_protected_branch_error"))
- ctx.Redirect(fmt.Sprintf("%s/branches", ctx.Repo.RepoLink))
+ ctx.Redirect(ctx.Repo.RepoLink + "/branches")
case git_model.IsErrBranchAlreadyExists(err):
ctx.Flash.Error(ctx.Tr("repo.branch.branch_already_exists", form.To))
- ctx.Redirect(fmt.Sprintf("%s/branches", ctx.Repo.RepoLink))
+ ctx.Redirect(ctx.Repo.RepoLink + "/branches")
case errors.Is(err, git_model.ErrBranchIsProtected):
ctx.Flash.Error(ctx.Tr("repo.branch.rename_protected_branch_failed"))
- ctx.Redirect(fmt.Sprintf("%s/branches", ctx.Repo.RepoLink))
+ ctx.Redirect(ctx.Repo.RepoLink + "/branches")
default:
ctx.ServerError("RenameBranch", err)
}
@@ -356,16 +357,16 @@ func RenameBranchPost(ctx *context.Context) {
if msg == "target_exist" {
ctx.Flash.Error(ctx.Tr("repo.settings.rename_branch_failed_exist", form.To))
- ctx.Redirect(fmt.Sprintf("%s/branches", ctx.Repo.RepoLink))
+ ctx.Redirect(ctx.Repo.RepoLink + "/branches")
return
}
if msg == "from_not_exist" {
ctx.Flash.Error(ctx.Tr("repo.settings.rename_branch_failed_not_exist", form.From))
- ctx.Redirect(fmt.Sprintf("%s/branches", ctx.Repo.RepoLink))
+ ctx.Redirect(ctx.Repo.RepoLink + "/branches")
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.rename_branch_success", form.From, form.To))
- ctx.Redirect(fmt.Sprintf("%s/branches", ctx.Repo.RepoLink))
+ ctx.Redirect(ctx.Repo.RepoLink + "/branches")
}
diff --git a/routers/web/repo/setting/setting.go b/routers/web/repo/setting/setting.go
index e30986e86e..380fec9d4a 100644
--- a/routers/web/repo/setting/setting.go
+++ b/routers/web/repo/setting/setting.go
@@ -6,7 +6,6 @@ package setting
import (
"errors"
- "fmt"
"net/http"
"strings"
"time"
@@ -474,7 +473,7 @@ func handleSettingsPostPushMirrorAdd(ctx *context.Context) {
m := &repo_model.PushMirror{
RepoID: repo.ID,
Repo: repo,
- RemoteName: fmt.Sprintf("remote_mirror_%s", remoteSuffix),
+ RemoteName: "remote_mirror_" + remoteSuffix,
SyncOnCommit: form.PushMirrorSyncOnCommit,
Interval: interval,
RemoteAddress: remoteAddress,
diff --git a/routers/web/repo/view_home.go b/routers/web/repo/view_home.go
index d538406035..3561db9101 100644
--- a/routers/web/repo/view_home.go
+++ b/routers/web/repo/view_home.go
@@ -76,7 +76,7 @@ func prepareOpenWithEditorApps(ctx *context.Context) {
schema, _, _ := strings.Cut(app.OpenURL, ":")
var iconHTML template.HTML
if schema == "vscode" || schema == "vscodium" || schema == "jetbrains" {
- iconHTML = svg.RenderHTML(fmt.Sprintf("gitea-%s", schema), 16)
+ iconHTML = svg.RenderHTML("gitea-"+schema, 16)
} else {
iconHTML = svg.RenderHTML("gitea-git", 16) // TODO: it could support user's customized icon in the future
}
diff --git a/routers/web/repo/wiki.go b/routers/web/repo/wiki.go
index 20c8c2b406..d70760bc36 100644
--- a/routers/web/repo/wiki.go
+++ b/routers/web/repo/wiki.go
@@ -7,7 +7,6 @@ package repo
import (
"bytes"
gocontext "context"
- "fmt"
"io"
"net/http"
"net/url"
@@ -581,7 +580,7 @@ func Wiki(ctx *context.Context) {
wikiPath := entry.Name()
if markup.DetectMarkupTypeByFileName(wikiPath) != markdown.MarkupName {
ext := strings.ToUpper(filepath.Ext(wikiPath))
- ctx.Data["FormatWarning"] = fmt.Sprintf("%s rendering is not supported at the moment. Rendered as Markdown.", ext)
+ ctx.Data["FormatWarning"] = ext + " rendering is not supported at the moment. Rendered as Markdown."
}
// Get last change information.
lastCommit, err := wikiRepo.GetCommitByPath(wikiPath)
diff --git a/routers/web/user/home.go b/routers/web/user/home.go
index f90d9df897..77f9cb8cca 100644
--- a/routers/web/user/home.go
+++ b/routers/web/user/home.go
@@ -699,7 +699,7 @@ func ShowGPGKeys(ctx *context.Context) {
headers := make(map[string]string)
if len(failedEntitiesID) > 0 { // If some key need re-import to be exported
- headers["Note"] = fmt.Sprintf("The keys with the following IDs couldn't be exported and need to be reuploaded %s", strings.Join(failedEntitiesID, ", "))
+ headers["Note"] = "The keys with the following IDs couldn't be exported and need to be reuploaded " + strings.Join(failedEntitiesID, ", ")
} else if len(entities) == 0 {
headers["Note"] = "This user hasn't uploaded any GPG keys."
}
diff --git a/routers/web/user/setting/account.go b/routers/web/user/setting/account.go
index 94577832a9..b124d5e1de 100644
--- a/routers/web/user/setting/account.go
+++ b/routers/web/user/setting/account.go
@@ -6,7 +6,6 @@ package setting
import (
"errors"
- "fmt"
"net/http"
"time"
@@ -37,7 +36,7 @@ const (
// Account renders change user's password, user's email and user suicide page
func Account(ctx *context.Context) {
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageCredentials, setting.UserFeatureDeletion) && !setting.Service.EnableNotifyMail {
- ctx.NotFound(fmt.Errorf("account setting are not allowed to be changed"))
+ ctx.NotFound(errors.New("account setting are not allowed to be changed"))
return
}
@@ -54,7 +53,7 @@ func Account(ctx *context.Context) {
// AccountPost response for change user's password
func AccountPost(ctx *context.Context) {
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageCredentials) {
- ctx.NotFound(fmt.Errorf("password setting is not allowed to be changed"))
+ ctx.NotFound(errors.New("password setting is not allowed to be changed"))
return
}
@@ -105,7 +104,7 @@ func AccountPost(ctx *context.Context) {
// EmailPost response for change user's email
func EmailPost(ctx *context.Context) {
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageCredentials) {
- ctx.NotFound(fmt.Errorf("emails are not allowed to be changed"))
+ ctx.NotFound(errors.New("emails are not allowed to be changed"))
return
}
@@ -239,7 +238,7 @@ func EmailPost(ctx *context.Context) {
// DeleteEmail response for delete user's email
func DeleteEmail(ctx *context.Context) {
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageCredentials) {
- ctx.NotFound(fmt.Errorf("emails are not allowed to be changed"))
+ ctx.NotFound(errors.New("emails are not allowed to be changed"))
return
}
email, err := user_model.GetEmailAddressByID(ctx, ctx.Doer.ID, ctx.FormInt64("id"))
diff --git a/routers/web/user/setting/keys.go b/routers/web/user/setting/keys.go
index 17e32f5403..6b5a7a2e2a 100644
--- a/routers/web/user/setting/keys.go
+++ b/routers/web/user/setting/keys.go
@@ -5,7 +5,7 @@
package setting
import (
- "fmt"
+ "errors"
"net/http"
asymkey_model "code.gitea.io/gitea/models/asymkey"
@@ -26,7 +26,7 @@ const (
// Keys render user's SSH/GPG public keys page
func Keys(ctx *context.Context) {
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys, setting.UserFeatureManageGPGKeys) {
- ctx.NotFound(fmt.Errorf("keys setting is not allowed to be changed"))
+ ctx.NotFound(errors.New("keys setting is not allowed to be changed"))
return
}
@@ -87,7 +87,7 @@ func KeysPost(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL + "/user/settings/keys")
case "gpg":
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageGPGKeys) {
- ctx.NotFound(fmt.Errorf("gpg keys setting is not allowed to be visited"))
+ ctx.NotFound(errors.New("gpg keys setting is not allowed to be visited"))
return
}
@@ -168,7 +168,7 @@ func KeysPost(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL + "/user/settings/keys")
case "ssh":
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys) {
- ctx.NotFound(fmt.Errorf("ssh keys setting is not allowed to be visited"))
+ ctx.NotFound(errors.New("ssh keys setting is not allowed to be visited"))
return
}
@@ -212,7 +212,7 @@ func KeysPost(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL + "/user/settings/keys")
case "verify_ssh":
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys) {
- ctx.NotFound(fmt.Errorf("ssh keys setting is not allowed to be visited"))
+ ctx.NotFound(errors.New("ssh keys setting is not allowed to be visited"))
return
}
@@ -249,7 +249,7 @@ func DeleteKey(ctx *context.Context) {
switch ctx.FormString("type") {
case "gpg":
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageGPGKeys) {
- ctx.NotFound(fmt.Errorf("gpg keys setting is not allowed to be visited"))
+ ctx.NotFound(errors.New("gpg keys setting is not allowed to be visited"))
return
}
if err := asymkey_model.DeleteGPGKey(ctx, ctx.Doer, ctx.FormInt64("id")); err != nil {
@@ -259,7 +259,7 @@ func DeleteKey(ctx *context.Context) {
}
case "ssh":
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys) {
- ctx.NotFound(fmt.Errorf("ssh keys setting is not allowed to be visited"))
+ ctx.NotFound(errors.New("ssh keys setting is not allowed to be visited"))
return
}
diff --git a/routers/web/web.go b/routers/web/web.go
index 84043e0bfb..7948c5f5ff 100644
--- a/routers/web/web.go
+++ b/routers/web/web.go
@@ -178,7 +178,7 @@ func verifyAuthWithOptions(options *common.VerifyOptions) func(ctx *context.Cont
return
}
- if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == "POST" {
+ if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == http.MethodPost {
ctx.Csrf.Validate(ctx)
if ctx.Written() {
return
diff --git a/routers/web/webfinger.go b/routers/web/webfinger.go
index afcfdc8252..a4c9bf902b 100644
--- a/routers/web/webfinger.go
+++ b/routers/web/webfinger.go
@@ -7,6 +7,7 @@ import (
"fmt"
"net/http"
"net/url"
+ "strconv"
"strings"
user_model "code.gitea.io/gitea/models/user"
@@ -85,10 +86,10 @@ func WebfingerQuery(ctx *context.Context) {
aliases := []string{
u.HTMLURL(),
- appURL.String() + "api/v1/activitypub/user-id/" + fmt.Sprint(u.ID),
+ appURL.String() + "api/v1/activitypub/user-id/" + strconv.FormatInt(u.ID, 10),
}
if !u.KeepEmailPrivate {
- aliases = append(aliases, fmt.Sprintf("mailto:%s", u.Email))
+ aliases = append(aliases, "mailto:"+u.Email)
}
links := []*webfingerLink{
@@ -104,7 +105,7 @@ func WebfingerQuery(ctx *context.Context) {
{
Rel: "self",
Type: "application/activity+json",
- Href: appURL.String() + "api/v1/activitypub/user-id/" + fmt.Sprint(u.ID),
+ Href: appURL.String() + "api/v1/activitypub/user-id/" + strconv.FormatInt(u.ID, 10),
},
{
Rel: "http://openid.net/specs/connect/1.0/issuer",
diff --git a/services/actions/auth.go b/services/actions/auth.go
index 1ef21f6e0e..12a8fba53f 100644
--- a/services/actions/auth.go
+++ b/services/actions/auth.go
@@ -4,6 +4,7 @@
package actions
import (
+ "errors"
"fmt"
"net/http"
"strings"
@@ -80,7 +81,7 @@ func ParseAuthorizationToken(req *http.Request) (int64, error) {
parts := strings.SplitN(h, " ", 2)
if len(parts) != 2 {
log.Error("split token failed: %s", h)
- return 0, fmt.Errorf("split token failed")
+ return 0, errors.New("split token failed")
}
return TokenToTaskID(parts[1])
@@ -100,7 +101,7 @@ func TokenToTaskID(token string) (int64, error) {
c, ok := parsedToken.Claims.(*actionsClaims)
if !parsedToken.Valid || !ok {
- return 0, fmt.Errorf("invalid token claim")
+ return 0, errors.New("invalid token claim")
}
return c.TaskID, nil
diff --git a/services/actions/commit_status.go b/services/actions/commit_status.go
index 94ab89a3b7..eb15d16061 100644
--- a/services/actions/commit_status.go
+++ b/services/actions/commit_status.go
@@ -5,6 +5,7 @@ package actions
import (
"context"
+ "errors"
"fmt"
"path"
@@ -51,7 +52,7 @@ func createCommitStatus(ctx context.Context, job *actions_model.ActionRunJob) er
return fmt.Errorf("GetPushEventPayload: %w", err)
}
if payload.HeadCommit == nil {
- return fmt.Errorf("head commit is missing in event payload")
+ return errors.New("head commit is missing in event payload")
}
sha = payload.HeadCommit.ID
case // pull_request
@@ -71,9 +72,9 @@ func createCommitStatus(ctx context.Context, job *actions_model.ActionRunJob) er
return fmt.Errorf("GetPullRequestEventPayload: %w", err)
}
if payload.PullRequest == nil {
- return fmt.Errorf("pull request is missing in event payload")
+ return errors.New("pull request is missing in event payload")
} else if payload.PullRequest.Head == nil {
- return fmt.Errorf("head of pull request is missing in event payload")
+ return errors.New("head of pull request is missing in event payload")
}
sha = payload.PullRequest.Head.Sha
case webhook_module.HookEventRelease:
diff --git a/services/actions/context.go b/services/actions/context.go
index d14728fae4..2667e18337 100644
--- a/services/actions/context.go
+++ b/services/actions/context.go
@@ -6,6 +6,7 @@ package actions
import (
"context"
"fmt"
+ "strconv"
actions_model "code.gitea.io/gitea/models/actions"
"code.gitea.io/gitea/models/db"
@@ -68,7 +69,7 @@ func GenerateGiteaContext(run *actions_model.ActionRun, job *actions_model.Actio
"repositoryUrl": run.Repo.HTMLURL(), // string, The Git URL to the repository. For example, git://github.com/codertocat/hello-world.git.
"retention_days": "", // string, The number of days that workflow run logs and artifacts are kept.
"run_id": "", // string, A unique number for each workflow run within a repository. This number does not change if you re-run the workflow run.
- "run_number": fmt.Sprint(run.Index), // string, A unique number for each run of a particular workflow in a repository. This number begins at 1 for the workflow's first run, and increments with each new run. This number does not change if you re-run the workflow run.
+ "run_number": strconv.FormatInt(run.Index, 10), // string, A unique number for each run of a particular workflow in a repository. This number begins at 1 for the workflow's first run, and increments with each new run. This number does not change if you re-run the workflow run.
"run_attempt": "", // string, A unique number for each attempt of a particular workflow run in a repository. This number begins at 1 for the workflow run's first attempt, and increments with each re-run.
"secret_source": "Actions", // string, The source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces.
"server_url": setting.AppURL, // string, The URL of the GitHub server. For example: https://github.com.
@@ -83,8 +84,8 @@ func GenerateGiteaContext(run *actions_model.ActionRun, job *actions_model.Actio
if job != nil {
gitContext["job"] = job.JobID
- gitContext["run_id"] = fmt.Sprint(job.RunID)
- gitContext["run_attempt"] = fmt.Sprint(job.Attempt)
+ gitContext["run_id"] = strconv.FormatInt(job.RunID, 10)
+ gitContext["run_attempt"] = strconv.FormatInt(job.Attempt, 10)
}
return gitContext
diff --git a/services/actions/task.go b/services/actions/task.go
index 9c8198206a..6a547c1c12 100644
--- a/services/actions/task.go
+++ b/services/actions/task.go
@@ -5,6 +5,7 @@ package actions
import (
"context"
+ "errors"
"fmt"
actions_model "code.gitea.io/gitea/models/actions"
@@ -39,7 +40,7 @@ func PickTask(ctx context.Context, runner *actions_model.ActionRunner) (*runnerv
if err != nil {
return nil, false, err
}
- return nil, false, fmt.Errorf("runner has been removed")
+ return nil, false, errors.New("runner has been removed")
}
}
diff --git a/services/auth/auth.go b/services/auth/auth.go
index f7deeb4c50..fb6612290b 100644
--- a/services/auth/auth.go
+++ b/services/auth/auth.go
@@ -62,14 +62,14 @@ func (a *authPathDetector) isAPIPath() bool {
// isAttachmentDownload check if request is a file download (GET) with URL to an attachment
func (a *authPathDetector) isAttachmentDownload() bool {
- return strings.HasPrefix(a.req.URL.Path, "/attachments/") && a.req.Method == "GET"
+ return strings.HasPrefix(a.req.URL.Path, "/attachments/") && a.req.Method == http.MethodGet
}
func (a *authPathDetector) isFeedRequest(req *http.Request) bool {
if !setting.Other.EnableFeed {
return false
}
- if req.Method != "GET" {
+ if req.Method != http.MethodGet {
return false
}
return a.vars.feedPathRe.MatchString(req.URL.Path) || a.vars.feedRefPathRe.MatchString(req.URL.Path)
diff --git a/services/auth/auth_test.go b/services/auth/auth_test.go
index b8d3396163..c45f312c90 100644
--- a/services/auth/auth_test.go
+++ b/services/auth/auth_test.go
@@ -97,7 +97,7 @@ func Test_isGitRawOrLFSPath(t *testing.T) {
defer test.MockVariableValue(&setting.LFS.StartServer)()
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
- req, _ := http.NewRequest("POST", "http://localhost"+tt.path, nil)
+ req, _ := http.NewRequest(http.MethodPost, "http://localhost"+tt.path, nil)
setting.LFS.StartServer = false
assert.Equal(t, tt.want, newAuthPathDetector(req).isGitRawOrAttachOrLFSPath())
@@ -119,7 +119,7 @@ func Test_isGitRawOrLFSPath(t *testing.T) {
}
for _, tt := range lfsTests {
t.Run(tt, func(t *testing.T) {
- req, _ := http.NewRequest("POST", tt, nil)
+ req, _ := http.NewRequest(http.MethodPost, tt, nil)
setting.LFS.StartServer = false
got := newAuthPathDetector(req).isGitRawOrAttachOrLFSPath()
assert.Equalf(t, setting.LFS.StartServer, got, "isGitOrLFSPath(%q) = %v, want %v, %v", tt, got, setting.LFS.StartServer, globalVars().gitRawOrAttachPathRe.MatchString(tt))
@@ -148,7 +148,7 @@ func Test_isFeedRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
- req, _ := http.NewRequest("GET", "http://localhost"+tt.path, nil)
+ req, _ := http.NewRequest(http.MethodGet, "http://localhost"+tt.path, nil)
assert.Equal(t, tt.want, newAuthPathDetector(req).isFeedRequest(req))
})
}
diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go
index 83a36bef23..25e96ff32d 100644
--- a/services/auth/httpsign.go
+++ b/services/auth/httpsign.go
@@ -134,7 +134,7 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) {
// Check if it's really a ssh certificate
cert, ok := pk.(*ssh.Certificate)
if !ok {
- return nil, fmt.Errorf("no certificate found")
+ return nil, errors.New("no certificate found")
}
c := &ssh.CertChecker{
@@ -153,7 +153,7 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) {
// check the CA of the cert
if !c.IsUserAuthority(cert.SignatureKey) {
- return nil, fmt.Errorf("CA check failed")
+ return nil, errors.New("CA check failed")
}
// Create a verifier
@@ -191,7 +191,7 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) {
}
// No public key matching a principal in the certificate is registered in gitea
- return nil, fmt.Errorf("no valid principal found")
+ return nil, errors.New("no valid principal found")
}
// doVerify iterates across the provided public keys attempting the verify the current request against each key in turn
diff --git a/services/auth/source/ldap/source_authenticate.go b/services/auth/source/ldap/source_authenticate.go
index 6a6c60cd40..7aee761d0d 100644
--- a/services/auth/source/ldap/source_authenticate.go
+++ b/services/auth/source/ldap/source_authenticate.go
@@ -5,7 +5,6 @@ package ldap
import (
"context"
- "fmt"
"strings"
asymkey_model "code.gitea.io/gitea/models/asymkey"
@@ -41,7 +40,7 @@ func (source *Source) Authenticate(ctx context.Context, user *user_model.User, u
sr.Username = userName
}
if sr.Mail == "" {
- sr.Mail = fmt.Sprintf("%s@localhost.local", sr.Username)
+ sr.Mail = sr.Username + "@localhost.local"
}
isAttributeSSHPublicKeySet := strings.TrimSpace(source.AttributeSSHPublicKey) != ""
diff --git a/services/auth/source/ldap/source_sync.go b/services/auth/source/ldap/source_sync.go
index e817bf1fa9..ff36db2955 100644
--- a/services/auth/source/ldap/source_sync.go
+++ b/services/auth/source/ldap/source_sync.go
@@ -5,7 +5,6 @@ package ldap
import (
"context"
- "fmt"
"strings"
asymkey_model "code.gitea.io/gitea/models/asymkey"
@@ -106,7 +105,7 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
}
if su.Mail == "" {
- su.Mail = fmt.Sprintf("%s@localhost.local", su.Username)
+ su.Mail = su.Username + "@localhost.local"
}
fullName := composeFullName(su.Name, su.Surname, su.Username)
diff --git a/services/automerge/automerge.go b/services/automerge/automerge.go
index 62d560ff94..9d2f7f4857 100644
--- a/services/automerge/automerge.go
+++ b/services/automerge/automerge.go
@@ -36,7 +36,7 @@ func Init() error {
prAutoMergeQueue = queue.CreateUniqueQueue(graceful.GetManager().ShutdownContext(), "pr_auto_merge", handler)
if prAutoMergeQueue == nil {
- return fmt.Errorf("unable to create pr_auto_merge queue")
+ return errors.New("unable to create pr_auto_merge queue")
}
go graceful.GetManager().RunWithCancel(prAutoMergeQueue)
return nil
diff --git a/services/context/access_log.go b/services/context/access_log.go
index 925e4a3056..caade113a7 100644
--- a/services/context/access_log.go
+++ b/services/context/access_log.go
@@ -5,7 +5,6 @@ package context
import (
"bytes"
- "fmt"
"net"
"net/http"
"strings"
@@ -47,7 +46,7 @@ func parseRequestIDFromRequestHeader(req *http.Request) string {
}
}
if len(requestID) > maxRequestIDByteLength {
- requestID = fmt.Sprintf("%s...", requestID[:maxRequestIDByteLength])
+ requestID = requestID[:maxRequestIDByteLength] + "..."
}
return requestID
}
diff --git a/services/context/access_log_test.go b/services/context/access_log_test.go
index c40ef9acd1..139a6eb217 100644
--- a/services/context/access_log_test.go
+++ b/services/context/access_log_test.go
@@ -59,7 +59,7 @@ func TestAccessLogger(t *testing.T) {
recorder.logger = mockLogger
req := &http.Request{
RemoteAddr: "remote-addr",
- Method: "GET",
+ Method: http.MethodGet,
Proto: "https",
URL: &url.URL{Path: "/path"},
}
diff --git a/services/context/api.go b/services/context/api.go
index 10fad419ba..6e3b635ce3 100644
--- a/services/context/api.go
+++ b/services/context/api.go
@@ -9,6 +9,7 @@ import (
"fmt"
"net/http"
"net/url"
+ "strconv"
"strings"
"code.gitea.io/gitea/models/unit"
@@ -168,7 +169,7 @@ func genAPILinks(curURL *url.URL, total, pageSize, curPage int) []string {
if paginater.HasNext() {
u := *curURL
queries := u.Query()
- queries.Set("page", fmt.Sprintf("%d", paginater.Next()))
+ queries.Set("page", strconv.Itoa(paginater.Next()))
u.RawQuery = queries.Encode()
links = append(links, fmt.Sprintf("<%s%s>; rel=\"next\"", setting.AppURL, u.RequestURI()[1:]))
@@ -176,7 +177,7 @@ func genAPILinks(curURL *url.URL, total, pageSize, curPage int) []string {
if !paginater.IsLast() {
u := *curURL
queries := u.Query()
- queries.Set("page", fmt.Sprintf("%d", paginater.TotalPages()))
+ queries.Set("page", strconv.Itoa(paginater.TotalPages()))
u.RawQuery = queries.Encode()
links = append(links, fmt.Sprintf("<%s%s>; rel=\"last\"", setting.AppURL, u.RequestURI()[1:]))
@@ -192,7 +193,7 @@ func genAPILinks(curURL *url.URL, total, pageSize, curPage int) []string {
if paginater.HasPrevious() {
u := *curURL
queries := u.Query()
- queries.Set("page", fmt.Sprintf("%d", paginater.Previous()))
+ queries.Set("page", strconv.Itoa(paginater.Previous()))
u.RawQuery = queries.Encode()
links = append(links, fmt.Sprintf("<%s%s>; rel=\"prev\"", setting.AppURL, u.RequestURI()[1:]))
@@ -225,7 +226,7 @@ func APIContexter() func(http.Handler) http.Handler {
ctx.SetContextValue(apiContextKey, ctx)
// If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
- if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
+ if ctx.Req.Method == http.MethodPost && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
if err := ctx.Req.ParseMultipartForm(setting.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
ctx.APIErrorInternal(err)
return
@@ -297,7 +298,7 @@ func RepoRefForAPI(next http.Handler) http.Handler {
}
if ctx.Repo.GitRepo == nil {
- ctx.APIErrorInternal(fmt.Errorf("no open git repo"))
+ ctx.APIErrorInternal(errors.New("no open git repo"))
return
}
diff --git a/services/context/base.go b/services/context/base.go
index 3701668bf6..f3f92b7eeb 100644
--- a/services/context/base.go
+++ b/services/context/base.go
@@ -8,6 +8,7 @@ import (
"html/template"
"io"
"net/http"
+ "strconv"
"strings"
"code.gitea.io/gitea/modules/httplib"
@@ -53,7 +54,7 @@ func (b *Base) AppendAccessControlExposeHeaders(names ...string) {
// SetTotalCountHeader set "X-Total-Count" header
func (b *Base) SetTotalCountHeader(total int64) {
- b.RespHeader().Set("X-Total-Count", fmt.Sprint(total))
+ b.RespHeader().Set("X-Total-Count", strconv.FormatInt(total, 10))
b.AppendAccessControlExposeHeaders("X-Total-Count")
}
diff --git a/services/context/base_test.go b/services/context/base_test.go
index b936b76f58..2a4f86dddf 100644
--- a/services/context/base_test.go
+++ b/services/context/base_test.go
@@ -15,7 +15,7 @@ import (
func TestRedirect(t *testing.T) {
setting.IsInTesting = true
- req, _ := http.NewRequest("GET", "/", nil)
+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
cases := []struct {
url string
@@ -36,7 +36,7 @@ func TestRedirect(t *testing.T) {
assert.Equal(t, c.keep, has, "url = %q", c.url)
}
- req, _ = http.NewRequest("GET", "/", nil)
+ req, _ = http.NewRequest(http.MethodGet, "/", nil)
resp := httptest.NewRecorder()
req.Header.Add("HX-Request", "true")
b := NewBaseContextForTest(resp, req)
diff --git a/services/context/context.go b/services/context/context.go
index 79bc5da920..3c0ac54fc1 100644
--- a/services/context/context.go
+++ b/services/context/context.go
@@ -184,7 +184,7 @@ func Contexter() func(next http.Handler) http.Handler {
})
// If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
- if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
+ if ctx.Req.Method == http.MethodPost && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
if err := ctx.Req.ParseMultipartForm(setting.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
ctx.ServerError("ParseMultipartForm", err)
return
diff --git a/services/context/private.go b/services/context/private.go
index 51857da8fe..3f7637518b 100644
--- a/services/context/private.go
+++ b/services/context/private.go
@@ -5,7 +5,6 @@ package context
import (
"context"
- "fmt"
"net/http"
"time"
@@ -82,7 +81,7 @@ func OverrideContext() func(http.Handler) http.Handler {
// We now need to override the request context as the base for our work because even if the request is cancelled we have to continue this work
ctx := GetPrivateContext(req)
var finished func()
- ctx.Override, _, finished = process.GetManager().AddTypedContext(graceful.GetManager().HammerContext(), fmt.Sprintf("PrivateContext: %s", ctx.Req.RequestURI), process.RequestProcessType, true)
+ ctx.Override, _, finished = process.GetManager().AddTypedContext(graceful.GetManager().HammerContext(), "PrivateContext: "+ctx.Req.RequestURI, process.RequestProcessType, true)
defer finished()
next.ServeHTTP(ctx.Resp, ctx.Req)
})
diff --git a/services/doctor/authorizedkeys.go b/services/doctor/authorizedkeys.go
index 8d6fc9cb5e..46e7099dce 100644
--- a/services/doctor/authorizedkeys.go
+++ b/services/doctor/authorizedkeys.go
@@ -7,6 +7,7 @@ import (
"bufio"
"bytes"
"context"
+ "errors"
"fmt"
"os"
"path/filepath"
@@ -78,7 +79,7 @@ func checkAuthorizedKeys(ctx context.Context, logger log.Logger, autofix bool) e
fPath,
"gitea admin regenerate keys",
"gitea doctor --run authorized-keys --fix")
- return fmt.Errorf(`authorized_keys is out of date and should be regenerated with "gitea admin regenerate keys" or "gitea doctor --run authorized-keys --fix"`)
+ return errors.New(`authorized_keys is out of date and should be regenerated with "gitea admin regenerate keys" or "gitea doctor --run authorized-keys --fix"`)
}
logger.Warn("authorized_keys is out of date. Attempting rewrite...")
err = asymkey_service.RewriteAllPublicKeys(ctx)
diff --git a/services/doctor/lfs.go b/services/doctor/lfs.go
index 5f110b8f97..a90f394450 100644
--- a/services/doctor/lfs.go
+++ b/services/doctor/lfs.go
@@ -5,7 +5,7 @@ package doctor
import (
"context"
- "fmt"
+ "errors"
"time"
"code.gitea.io/gitea/modules/log"
@@ -27,7 +27,7 @@ func init() {
func garbageCollectLFSCheck(ctx context.Context, logger log.Logger, autofix bool) error {
if !setting.LFS.StartServer {
- return fmt.Errorf("LFS support is disabled")
+ return errors.New("LFS support is disabled")
}
if err := repository.GarbageCollectLFSMetaObjects(ctx, repository.GarbageCollectLFSMetaObjectsOptions{
diff --git a/services/externalaccount/link.go b/services/externalaccount/link.go
index d6e2ea7e94..ab853140cb 100644
--- a/services/externalaccount/link.go
+++ b/services/externalaccount/link.go
@@ -5,7 +5,7 @@ package externalaccount
import (
"context"
- "fmt"
+ "errors"
user_model "code.gitea.io/gitea/models/user"
@@ -23,7 +23,7 @@ type Store interface {
func LinkAccountFromStore(ctx context.Context, store Store, user *user_model.User) error {
gothUser := store.Get("linkAccountGothUser")
if gothUser == nil {
- return fmt.Errorf("not in LinkAccount session")
+ return errors.New("not in LinkAccount session")
}
return LinkAccountToUser(ctx, user, gothUser.(goth.User))
diff --git a/services/feed/feed.go b/services/feed/feed.go
index 214e9b5765..38a4e25308 100644
--- a/services/feed/feed.go
+++ b/services/feed/feed.go
@@ -6,6 +6,7 @@ package feed
import (
"context"
"fmt"
+ "strconv"
activities_model "code.gitea.io/gitea/models/activities"
"code.gitea.io/gitea/models/db"
@@ -86,7 +87,7 @@ func notifyWatchers(ctx context.Context, act *activities_model.Action, watchers
return fmt.Errorf("count user feeds: %w", err)
}
- _ = cache.GetCache().Put(userFeedCacheKey(act.UserID), fmt.Sprintf("%d", total), setting.CacheService.TTLSeconds())
+ _ = cache.GetCache().Put(userFeedCacheKey(act.UserID), strconv.FormatInt(total, 10), setting.CacheService.TTLSeconds())
}
return nil
diff --git a/services/gitdiff/git_diff_tree.go b/services/gitdiff/git_diff_tree.go
index 035210a31d..ed94bfbfe4 100644
--- a/services/gitdiff/git_diff_tree.go
+++ b/services/gitdiff/git_diff_tree.go
@@ -6,6 +6,7 @@ package gitdiff
import (
"bufio"
"context"
+ "errors"
"fmt"
"io"
"strconv"
@@ -71,7 +72,7 @@ func runGitDiffTree(ctx context.Context, gitRepo *git.Repository, useMergeBase b
func validateGitDiffTreeArguments(gitRepo *git.Repository, useMergeBase bool, baseSha, headSha string) (shouldUseMergeBase bool, resolvedBaseSha, resolvedHeadSha string, err error) {
// if the head is empty its an error
if headSha == "" {
- return false, "", "", fmt.Errorf("headSha is empty")
+ return false, "", "", errors.New("headSha is empty")
}
// if the head commit doesn't exist its and error
@@ -207,7 +208,7 @@ func parseGitDiffTreeLine(line string) (*DiffTreeRecord, error) {
func statusFromLetter(rawStatus string) (status string, score uint8, err error) {
if len(rawStatus) < 1 {
- return "", 0, fmt.Errorf("empty status letter")
+ return "", 0, errors.New("empty status letter")
}
switch rawStatus[0] {
case 'A':
@@ -235,7 +236,7 @@ func statusFromLetter(rawStatus string) (status string, score uint8, err error)
func tryParseStatusScore(rawStatus string) (uint8, error) {
if len(rawStatus) < 2 {
- return 0, fmt.Errorf("status score missing")
+ return 0, errors.New("status score missing")
}
score, err := strconv.ParseUint(rawStatus[1:], 10, 8)
diff --git a/services/issue/comments.go b/services/issue/comments.go
index 46f92f7cd2..10c81198d5 100644
--- a/services/issue/comments.go
+++ b/services/issue/comments.go
@@ -5,6 +5,7 @@ package issue
import (
"context"
+ "errors"
"fmt"
"code.gitea.io/gitea/models/db"
@@ -22,7 +23,7 @@ import (
// CreateRefComment creates a commit reference comment to issue.
func CreateRefComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, content, commitSHA string) error {
if len(commitSHA) == 0 {
- return fmt.Errorf("cannot create reference with empty commit SHA")
+ return errors.New("cannot create reference with empty commit SHA")
}
if user_model.IsUserBlockedBy(ctx, doer, issue.PosterID, repo.OwnerID) {
diff --git a/services/issue/milestone.go b/services/issue/milestone.go
index beb6f131a9..afca70794d 100644
--- a/services/issue/milestone.go
+++ b/services/issue/milestone.go
@@ -5,6 +5,7 @@ package issue
import (
"context"
+ "errors"
"fmt"
"code.gitea.io/gitea/models/db"
@@ -21,7 +22,7 @@ func changeMilestoneAssign(ctx context.Context, doer *user_model.User, issue *is
return fmt.Errorf("HasMilestoneByRepoID: %w", err)
}
if !has {
- return fmt.Errorf("HasMilestoneByRepoID: issue doesn't exist")
+ return errors.New("HasMilestoneByRepoID: issue doesn't exist")
}
}
diff --git a/services/lfs/server.go b/services/lfs/server.go
index 1e7608b781..0a99287ed9 100644
--- a/services/lfs/server.go
+++ b/services/lfs/server.go
@@ -572,15 +572,15 @@ func handleLFSToken(ctx stdCtx.Context, tokenSHA string, target *repo_model.Repo
claims, claimsOk := token.Claims.(*Claims)
if !token.Valid || !claimsOk {
- return nil, fmt.Errorf("invalid token claim")
+ return nil, errors.New("invalid token claim")
}
if claims.RepoID != target.ID {
- return nil, fmt.Errorf("invalid token claim")
+ return nil, errors.New("invalid token claim")
}
if mode == perm_model.AccessModeWrite && claims.Op != "upload" {
- return nil, fmt.Errorf("invalid token claim")
+ return nil, errors.New("invalid token claim")
}
u, err := user_model.GetUserByID(ctx, claims.UserID)
@@ -593,12 +593,12 @@ func handleLFSToken(ctx stdCtx.Context, tokenSHA string, target *repo_model.Repo
func parseToken(ctx stdCtx.Context, authorization string, target *repo_model.Repository, mode perm_model.AccessMode) (*user_model.User, error) {
if authorization == "" {
- return nil, fmt.Errorf("no token")
+ return nil, errors.New("no token")
}
parts := strings.SplitN(authorization, " ", 2)
if len(parts) != 2 {
- return nil, fmt.Errorf("no token")
+ return nil, errors.New("no token")
}
tokenSHA := parts[1]
switch strings.ToLower(parts[0]) {
@@ -607,7 +607,7 @@ func parseToken(ctx stdCtx.Context, authorization string, target *repo_model.Rep
case "token":
return handleLFSToken(ctx, tokenSHA, target, mode)
}
- return nil, fmt.Errorf("token not found")
+ return nil, errors.New("token not found")
}
func requireAuth(ctx *context.Context) {
diff --git a/services/mailer/mail.go b/services/mailer/mail.go
index f7e5b0c9f0..aa51cbdbcf 100644
--- a/services/mailer/mail.go
+++ b/services/mailer/mail.go
@@ -8,6 +8,7 @@ import (
"bytes"
"context"
"encoding/base64"
+ "errors"
"fmt"
"html/template"
"io"
@@ -117,7 +118,7 @@ func (b64embedder *mailAttachmentBase64Embedder) AttachmentSrcToBase64DataURI(ct
attachmentUUID, ok = strings.CutPrefix(parsedSrc.RepoSubPath, "/attachments/")
}
if !ok {
- return "", fmt.Errorf("not an attachment")
+ return "", errors.New("not an attachment")
}
}
attachment, err := repo_model.GetAttachmentByUUID(ctx, attachmentUUID)
@@ -126,10 +127,10 @@ func (b64embedder *mailAttachmentBase64Embedder) AttachmentSrcToBase64DataURI(ct
}
if attachment.RepoID != b64embedder.repo.ID {
- return "", fmt.Errorf("attachment does not belong to the repository")
+ return "", errors.New("attachment does not belong to the repository")
}
if attachment.Size+b64embedder.estimateSize > b64embedder.maxSize {
- return "", fmt.Errorf("total embedded images exceed max limit")
+ return "", errors.New("total embedded images exceed max limit")
}
fr, err := storage.Attachments.Open(attachment.RelativePath())
@@ -146,7 +147,7 @@ func (b64embedder *mailAttachmentBase64Embedder) AttachmentSrcToBase64DataURI(ct
mimeType := typesniffer.DetectContentType(content)
if !mimeType.IsImage() {
- return "", fmt.Errorf("not an image")
+ return "", errors.New("not an image")
}
encoded := base64.StdEncoding.EncodeToString(content)
diff --git a/services/mailer/mail_team_invite.go b/services/mailer/mail_team_invite.go
index 1fbade7e23..f4aa788dec 100644
--- a/services/mailer/mail_team_invite.go
+++ b/services/mailer/mail_team_invite.go
@@ -6,6 +6,7 @@ package mailer
import (
"bytes"
"context"
+ "errors"
"fmt"
"net/url"
@@ -38,10 +39,10 @@ func MailTeamInvite(ctx context.Context, inviter *user_model.User, team *org_mod
if err != nil && !user_model.IsErrUserNotExist(err) {
return err
} else if user != nil && user.ProhibitLogin {
- return fmt.Errorf("login is prohibited for the invited user")
+ return errors.New("login is prohibited for the invited user")
}
- inviteRedirect := url.QueryEscape(fmt.Sprintf("/org/invite/%s", invite.Token))
+ inviteRedirect := url.QueryEscape("/org/invite/" + invite.Token)
inviteURL := fmt.Sprintf("%suser/sign_up?redirect_to=%s", setting.AppURL, inviteRedirect)
if (err == nil && user != nil) || setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration {
diff --git a/services/mailer/sender/smtp.go b/services/mailer/sender/smtp.go
index c53c3da997..8dc1b40b74 100644
--- a/services/mailer/sender/smtp.go
+++ b/services/mailer/sender/smtp.go
@@ -5,6 +5,7 @@ package sender
import (
"crypto/tls"
+ "errors"
"fmt"
"io"
"net"
@@ -99,7 +100,7 @@ func (s *SMTPSender) Send(from string, to []string, msg io.WriterTo) error {
canAuth, options := client.Extension("AUTH")
if len(opts.User) > 0 {
if !canAuth {
- return fmt.Errorf("SMTP server does not support AUTH, but credentials provided")
+ return errors.New("SMTP server does not support AUTH, but credentials provided")
}
var auth smtp.Auth
diff --git a/services/mailer/sender/smtp_auth.go b/services/mailer/sender/smtp_auth.go
index 260b12437b..c60e0dbfbb 100644
--- a/services/mailer/sender/smtp_auth.go
+++ b/services/mailer/sender/smtp_auth.go
@@ -4,6 +4,7 @@
package sender
import (
+ "errors"
"fmt"
"github.com/Azure/go-ntlmssp"
@@ -60,7 +61,7 @@ func (a *ntlmAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
func (a *ntlmAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
if len(fromServer) == 0 {
- return nil, fmt.Errorf("ntlm ChallengeMessage is empty")
+ return nil, errors.New("ntlm ChallengeMessage is empty")
}
authenticateMessage, err := ntlmssp.ProcessChallenge(fromServer, a.username, a.password, a.domainNeeded)
return authenticateMessage, err
diff --git a/services/markup/renderhelper_codepreview.go b/services/markup/renderhelper_codepreview.go
index d638af7ff0..28d1120984 100644
--- a/services/markup/renderhelper_codepreview.go
+++ b/services/markup/renderhelper_codepreview.go
@@ -6,7 +6,7 @@ package markup
import (
"bufio"
"context"
- "fmt"
+ "errors"
"html/template"
"strings"
@@ -38,7 +38,7 @@ func renderRepoFileCodePreview(ctx context.Context, opts markup.RenderCodePrevie
webCtx := gitea_context.GetWebContext(ctx)
if webCtx == nil {
- return "", fmt.Errorf("context is not a web context")
+ return "", errors.New("context is not a web context")
}
doer := webCtx.Doer
@@ -68,7 +68,7 @@ func renderRepoFileCodePreview(ctx context.Context, opts markup.RenderCodePrevie
}
if blob.Size() > setting.UI.MaxDisplayFileSize {
- return "", fmt.Errorf("file is too large")
+ return "", errors.New("file is too large")
}
dataRc, err := blob.DataAsync()
diff --git a/services/markup/renderhelper_issueicontitle.go b/services/markup/renderhelper_issueicontitle.go
index fd8f9d43fa..27b5595fa9 100644
--- a/services/markup/renderhelper_issueicontitle.go
+++ b/services/markup/renderhelper_issueicontitle.go
@@ -5,6 +5,7 @@ package markup
import (
"context"
+ "errors"
"fmt"
"html/template"
@@ -20,7 +21,7 @@ import (
func renderRepoIssueIconTitle(ctx context.Context, opts markup.RenderIssueIconTitleOptions) (_ template.HTML, err error) {
webCtx := gitea_context.GetWebContext(ctx)
if webCtx == nil {
- return "", fmt.Errorf("context is not a web context")
+ return "", errors.New("context is not a web context")
}
textIssueIndex := fmt.Sprintf("(#%d)", opts.IssueIndex)
diff --git a/services/markup/renderhelper_mention_test.go b/services/markup/renderhelper_mention_test.go
index d05fbb6fba..d54ab13a48 100644
--- a/services/markup/renderhelper_mention_test.go
+++ b/services/markup/renderhelper_mention_test.go
@@ -37,7 +37,7 @@ func TestRenderHelperMention(t *testing.T) {
assert.False(t, FormalRenderHelperFuncs().IsUsernameMentionable(t.Context(), userNoSuch))
// when using web context, use user.IsUserVisibleToViewer to check
- req, err := http.NewRequest("GET", "/", nil)
+ req, err := http.NewRequest(http.MethodGet, "/", nil)
assert.NoError(t, err)
base := gitea_context.NewBaseContextForTest(httptest.NewRecorder(), req)
giteaCtx := gitea_context.NewWebContext(base, &contexttest.MockRender{}, nil)
diff --git a/services/migrations/codebase.go b/services/migrations/codebase.go
index 880dd21497..240c7bcdc9 100644
--- a/services/migrations/codebase.go
+++ b/services/migrations/codebase.go
@@ -134,7 +134,7 @@ func (d *CodebaseDownloader) callAPI(ctx context.Context, endpoint string, param
u.RawQuery = query.Encode()
}
- req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return err
}
diff --git a/services/migrations/codecommit.go b/services/migrations/codecommit.go
index c45f9e5943..4b2634ef8a 100644
--- a/services/migrations/codecommit.go
+++ b/services/migrations/codecommit.go
@@ -5,7 +5,7 @@ package migrations
import (
"context"
- "fmt"
+ "errors"
"net/url"
"strconv"
"strings"
@@ -42,13 +42,13 @@ func (c *CodeCommitDownloaderFactory) New(ctx context.Context, opts base.Migrate
hostElems := strings.Split(u.Host, ".")
if len(hostElems) != 4 {
- return nil, fmt.Errorf("cannot get the region from clone URL")
+ return nil, errors.New("cannot get the region from clone URL")
}
region := hostElems[1]
pathElems := strings.Split(u.Path, "/")
if len(pathElems) == 0 {
- return nil, fmt.Errorf("cannot get the repo name from clone URL")
+ return nil, errors.New("cannot get the repo name from clone URL")
}
repoName := pathElems[len(pathElems)-1]
diff --git a/services/migrations/gitea_downloader.go b/services/migrations/gitea_downloader.go
index f92f318293..5d48d2f003 100644
--- a/services/migrations/gitea_downloader.go
+++ b/services/migrations/gitea_downloader.go
@@ -298,7 +298,7 @@ func (g *GiteaDownloader) convertGiteaRelease(rel *gitea_sdk.Release) *base.Rele
}
// FIXME: for a private download?
- req, err := http.NewRequest("GET", assetDownloadURL, nil)
+ req, err := http.NewRequest(http.MethodGet, assetDownloadURL, nil)
if err != nil {
return nil, err
}
diff --git a/services/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go
index b17cc3ce41..cd5af39910 100644
--- a/services/migrations/gitea_uploader.go
+++ b/services/migrations/gitea_uploader.go
@@ -1017,7 +1017,7 @@ func (g *GiteaLocalUploader) remapLocalUser(ctx context.Context, source user_mod
func (g *GiteaLocalUploader) remapExternalUser(ctx context.Context, source user_model.ExternalUserMigrated) (userid int64, err error) {
userid, ok := g.userMap[source.GetExternalID()]
if !ok {
- userid, err = user_model.GetUserIDByExternalUserID(ctx, g.gitServiceType.Name(), fmt.Sprintf("%d", source.GetExternalID()))
+ userid, err = user_model.GetUserIDByExternalUserID(ctx, g.gitServiceType.Name(), strconv.FormatInt(source.GetExternalID(), 10))
if err != nil {
log.Error("GetUserIDByExternalUserID: %v", err)
return 0, err
diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go
index 5a5875e15d..1970c0550c 100644
--- a/services/migrations/gitea_uploader_test.go
+++ b/services/migrations/gitea_uploader_test.go
@@ -239,7 +239,7 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) {
assert.NoError(t, git.InitRepository(git.DefaultContext, fromRepo.RepoPath(), false, fromRepo.ObjectFormatName))
err := git.NewCommand("symbolic-ref").AddDynamicArguments("HEAD", git.BranchPrefix+baseRef).Run(git.DefaultContext, &git.RunOpts{Dir: fromRepo.RepoPath()})
assert.NoError(t, err)
- assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", fromRepo.RepoPath())), 0o644))
+ assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte("# Testing Repository\n\nOriginally created in: "+fromRepo.RepoPath()), 0o644))
assert.NoError(t, git.AddChanges(fromRepo.RepoPath(), true))
signature := git.Signature{
Email: "test@example.com",
@@ -287,7 +287,7 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) {
}))
_, _, err = git.NewCommand("checkout", "-b").AddDynamicArguments(forkHeadRef).RunStdString(git.DefaultContext, &git.RunOpts{Dir: forkRepo.RepoPath()})
assert.NoError(t, err)
- assert.NoError(t, os.WriteFile(filepath.Join(forkRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# branch2 %s", forkRepo.RepoPath())), 0o644))
+ assert.NoError(t, os.WriteFile(filepath.Join(forkRepo.RepoPath(), "README.md"), []byte("# branch2 "+forkRepo.RepoPath()), 0o644))
assert.NoError(t, git.AddChanges(forkRepo.RepoPath(), true))
assert.NoError(t, git.CommitChanges(forkRepo.RepoPath(), git.CommitChangesOptions{
Committer: &signature,
diff --git a/services/migrations/github.go b/services/migrations/github.go
index b00d6ed27f..e512ebc24a 100644
--- a/services/migrations/github.go
+++ b/services/migrations/github.go
@@ -358,7 +358,7 @@ func (g *GithubDownloaderV3) convertGithubRelease(ctx context.Context, rel *gith
}
g.waitAndPickClient(ctx)
- req, err := http.NewRequestWithContext(ctx, "GET", redirectURL, nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, redirectURL, nil)
if err != nil {
return nil, err
}
diff --git a/services/migrations/gitlab.go b/services/migrations/gitlab.go
index 4bed8e2f6c..a19a04bc44 100644
--- a/services/migrations/gitlab.go
+++ b/services/migrations/gitlab.go
@@ -341,7 +341,7 @@ func (g *GitlabDownloader) convertGitlabRelease(ctx context.Context, rel *gitlab
return io.NopCloser(strings.NewReader(link.URL)), nil
}
- req, err := http.NewRequest("GET", link.URL, nil)
+ req, err := http.NewRequest(http.MethodGet, link.URL, nil)
if err != nil {
return nil, err
}
diff --git a/services/migrations/migrate.go b/services/migrations/migrate.go
index 5dda12286f..961abe16f4 100644
--- a/services/migrations/migrate.go
+++ b/services/migrations/migrate.go
@@ -6,6 +6,7 @@ package migrations
import (
"context"
+ "errors"
"fmt"
"net"
"net/url"
@@ -211,7 +212,7 @@ func migrateRepository(ctx context.Context, doer *user_model.User, downloader ba
if cloneURL.Scheme == "file" || cloneURL.Scheme == "" {
if cloneAddrURL.Scheme != "file" && cloneAddrURL.Scheme != "" {
- return fmt.Errorf("repo info has changed from external to local filesystem")
+ return errors.New("repo info has changed from external to local filesystem")
}
}
diff --git a/services/migrations/onedev.go b/services/migrations/onedev.go
index 4ce35dd12e..e052cba0cc 100644
--- a/services/migrations/onedev.go
+++ b/services/migrations/onedev.go
@@ -128,7 +128,7 @@ func (d *OneDevDownloader) callAPI(ctx context.Context, endpoint string, paramet
u.RawQuery = query.Encode()
}
- req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return err
}
diff --git a/services/mirror/mirror.go b/services/mirror/mirror.go
index e029bbb1d6..7fb7fabb75 100644
--- a/services/mirror/mirror.go
+++ b/services/mirror/mirror.go
@@ -5,7 +5,7 @@ package mirror
import (
"context"
- "fmt"
+ "errors"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/log"
@@ -29,7 +29,7 @@ func doMirrorSync(ctx context.Context, req *SyncRequest) {
}
}
-var errLimit = fmt.Errorf("reached limit")
+var errLimit = errors.New("reached limit")
// Update checks and updates mirror repositories.
func Update(ctx context.Context, pullLimit, pushLimit int) error {
@@ -68,7 +68,7 @@ func Update(ctx context.Context, pullLimit, pushLimit int) error {
// Check we've not been cancelled
select {
case <-ctx.Done():
- return fmt.Errorf("aborted")
+ return errors.New("aborted")
default:
}
diff --git a/services/oauth2_provider/access_token.go b/services/oauth2_provider/access_token.go
index 5cb6fb64c5..52a73c9572 100644
--- a/services/oauth2_provider/access_token.go
+++ b/services/oauth2_provider/access_token.go
@@ -7,6 +7,7 @@ import (
"context"
"fmt"
"slices"
+ "strconv"
"strings"
auth "code.gitea.io/gitea/models/auth"
@@ -177,7 +178,7 @@ func NewAccessTokenResponse(ctx context.Context, grant *auth.OAuth2Grant, server
ExpiresAt: jwt.NewNumericDate(expirationDate.AsTime()),
Issuer: setting.AppURL,
Audience: []string{app.ClientID},
- Subject: fmt.Sprint(grant.UserID),
+ Subject: strconv.FormatInt(grant.UserID, 10),
},
Nonce: grant.Nonce,
}
diff --git a/services/oauth2_provider/jwtsigningkey.go b/services/oauth2_provider/jwtsigningkey.go
index 6c668db463..3bc4f49410 100644
--- a/services/oauth2_provider/jwtsigningkey.go
+++ b/services/oauth2_provider/jwtsigningkey.go
@@ -31,7 +31,7 @@ type ErrInvalidAlgorithmType struct {
}
func (err ErrInvalidAlgorithmType) Error() string {
- return fmt.Sprintf("JWT signing algorithm is not supported: %s", err.Algorithm)
+ return "JWT signing algorithm is not supported: " + err.Algorithm
}
// JWTSigningKey represents a algorithm/key pair to sign JWTs
diff --git a/services/oauth2_provider/token.go b/services/oauth2_provider/token.go
index b71b11906e..383bcdb3eb 100644
--- a/services/oauth2_provider/token.go
+++ b/services/oauth2_provider/token.go
@@ -4,6 +4,7 @@
package oauth2_provider //nolint
import (
+ "errors"
"fmt"
"time"
@@ -44,12 +45,12 @@ func ParseToken(jwtToken string, signingKey JWTSigningKey) (*Token, error) {
return nil, err
}
if !parsedToken.Valid {
- return nil, fmt.Errorf("invalid token")
+ return nil, errors.New("invalid token")
}
var token *Token
var ok bool
if token, ok = parsedToken.Claims.(*Token); !ok || !parsedToken.Valid {
- return nil, fmt.Errorf("invalid token")
+ return nil, errors.New("invalid token")
}
return token, nil
}
diff --git a/services/packages/alpine/repository.go b/services/packages/alpine/repository.go
index 27e6391980..277c188874 100644
--- a/services/packages/alpine/repository.go
+++ b/services/packages/alpine/repository.go
@@ -290,7 +290,7 @@ func buildPackagesIndex(ctx context.Context, ownerID int64, repoVersion *package
privPem, _ := pem.Decode([]byte(priv))
if privPem == nil {
- return fmt.Errorf("failed to decode private key pem")
+ return errors.New("failed to decode private key pem")
}
privKey, err := x509.ParsePKCS1PrivateKey(privPem.Bytes)
diff --git a/services/packages/arch/repository.go b/services/packages/arch/repository.go
index a12af82ba5..438bb10837 100644
--- a/services/packages/arch/repository.go
+++ b/services/packages/arch/repository.go
@@ -13,6 +13,7 @@ import (
"fmt"
"io"
"os"
+ "strconv"
"strings"
packages_model "code.gitea.io/gitea/models/packages"
@@ -372,8 +373,8 @@ func writeDescription(tw *tar.Writer, opts *entryOptions) error {
{"MD5SUM", opts.Blob.HashMD5},
{"SHA256SUM", opts.Blob.HashSHA256},
{"PGPSIG", opts.Signature},
- {"CSIZE", fmt.Sprintf("%d", opts.Blob.Size)},
- {"ISIZE", fmt.Sprintf("%d", opts.FileMetadata.InstalledSize)},
+ {"CSIZE", strconv.FormatInt(opts.Blob.Size, 10)},
+ {"ISIZE", strconv.FormatInt(opts.FileMetadata.InstalledSize, 10)},
{"NAME", opts.Package.Name},
{"BASE", opts.FileMetadata.Base},
{"ARCH", opts.FileMetadata.Architecture},
@@ -382,7 +383,7 @@ func writeDescription(tw *tar.Writer, opts *entryOptions) error {
{"URL", opts.VersionMetadata.ProjectURL},
{"LICENSE", strings.Join(opts.VersionMetadata.Licenses, "\n")},
{"GROUPS", strings.Join(opts.FileMetadata.Groups, "\n")},
- {"BUILDDATE", fmt.Sprintf("%d", opts.FileMetadata.BuildDate)},
+ {"BUILDDATE", strconv.FormatInt(opts.FileMetadata.BuildDate, 10)},
{"PACKAGER", opts.FileMetadata.Packager},
{"PROVIDES", strings.Join(opts.FileMetadata.Provides, "\n")},
{"REPLACES", strings.Join(opts.FileMetadata.Replaces, "\n")},
diff --git a/services/packages/auth.go b/services/packages/auth.go
index 4526a8e303..6e87643e29 100644
--- a/services/packages/auth.go
+++ b/services/packages/auth.go
@@ -4,6 +4,7 @@
package packages
import (
+ "errors"
"fmt"
"net/http"
"strings"
@@ -58,7 +59,7 @@ func ParseAuthorizationRequest(req *http.Request) (*PackageMeta, error) {
parts := strings.SplitN(h, " ", 2)
if len(parts) != 2 {
log.Error("split token failed: %s", h)
- return nil, fmt.Errorf("split token failed")
+ return nil, errors.New("split token failed")
}
return ParseAuthorizationToken(parts[1])
@@ -77,7 +78,7 @@ func ParseAuthorizationToken(tokenStr string) (*PackageMeta, error) {
c, ok := token.Claims.(*packageClaims)
if !token.Valid || !ok {
- return nil, fmt.Errorf("invalid token claim")
+ return nil, errors.New("invalid token claim")
}
return &c.PackageMeta, nil
diff --git a/services/projects/issue.go b/services/projects/issue.go
index 090d19d2f4..590fe960d5 100644
--- a/services/projects/issue.go
+++ b/services/projects/issue.go
@@ -5,7 +5,7 @@ package project
import (
"context"
- "fmt"
+ "errors"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
@@ -29,7 +29,7 @@ func MoveIssuesOnProjectColumn(ctx context.Context, doer *user_model.User, colum
return err
}
if int(count) != len(sortedIssueIDs) {
- return fmt.Errorf("all issues have to be added to a project first")
+ return errors.New("all issues have to be added to a project first")
}
issues, err := issues_model.GetIssuesByIDs(ctx, issueIDs)
diff --git a/services/pull/check.go b/services/pull/check.go
index 9b159891d7..b036970fbf 100644
--- a/services/pull/check.go
+++ b/services/pull/check.go
@@ -400,7 +400,7 @@ func Init() error {
prPatchCheckerQueue = queue.CreateUniqueQueue(graceful.GetManager().ShutdownContext(), "pr_patch_checker", handler)
if prPatchCheckerQueue == nil {
- return fmt.Errorf("unable to create pr_patch_checker queue")
+ return errors.New("unable to create pr_patch_checker queue")
}
go graceful.GetManager().RunWithCancel(prPatchCheckerQueue)
diff --git a/services/pull/merge.go b/services/pull/merge.go
index 1e1ca55bc1..9804d8aac1 100644
--- a/services/pull/merge.go
+++ b/services/pull/merge.go
@@ -6,6 +6,7 @@ package pull
import (
"context"
+ "errors"
"fmt"
"os"
"path/filepath"
@@ -59,7 +60,7 @@ func getMergeMessage(ctx context.Context, baseGitRepo *git.Repository, pr *issue
issueReference = "!"
}
- reviewedOn := fmt.Sprintf("Reviewed-on: %s", httplib.MakeAbsoluteURL(ctx, pr.Issue.Link()))
+ reviewedOn := "Reviewed-on: " + httplib.MakeAbsoluteURL(ctx, pr.Issue.Link())
reviewedBy := pr.GetApprovers(ctx)
if mergeStyle != "" {
@@ -621,13 +622,13 @@ func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *use
objectFormat := git.ObjectFormatFromName(pr.BaseRepo.ObjectFormatName)
if len(commitID) != objectFormat.FullLength() {
- return fmt.Errorf("Wrong commit ID")
+ return errors.New("Wrong commit ID")
}
commit, err := baseGitRepo.GetCommit(commitID)
if err != nil {
if git.IsErrNotExist(err) {
- return fmt.Errorf("Wrong commit ID")
+ return errors.New("Wrong commit ID")
}
return err
}
@@ -638,14 +639,14 @@ func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *use
return err
}
if !ok {
- return fmt.Errorf("Wrong commit ID")
+ return errors.New("Wrong commit ID")
}
var merged bool
if merged, err = SetMerged(ctx, pr, commitID, timeutil.TimeStamp(commit.Author.When.Unix()), doer, issues_model.PullRequestStatusManuallyMerged); err != nil {
return err
} else if !merged {
- return fmt.Errorf("SetMerged failed")
+ return errors.New("SetMerged failed")
}
return nil
})
diff --git a/services/pull/merge_squash.go b/services/pull/merge_squash.go
index 076189fd7a..72660cd3c5 100644
--- a/services/pull/merge_squash.go
+++ b/services/pull/merge_squash.go
@@ -66,8 +66,8 @@ func doMergeStyleSquash(ctx *mergeContext, message string) error {
if setting.Repository.PullRequest.AddCoCommitterTrailers && ctx.committer.String() != sig.String() {
// add trailer
- if !strings.Contains(message, fmt.Sprintf("Co-authored-by: %s", sig.String())) {
- message += fmt.Sprintf("\nCo-authored-by: %s", sig.String())
+ if !strings.Contains(message, "Co-authored-by: "+sig.String()) {
+ message += "\nCo-authored-by: " + sig.String()
}
message += fmt.Sprintf("\nCo-committed-by: %s\n", sig.String())
}
diff --git a/services/pull/patch.go b/services/pull/patch.go
index 29f2f992ab..68f3f02669 100644
--- a/services/pull/patch.go
+++ b/services/pull/patch.go
@@ -134,7 +134,7 @@ type errMergeConflict struct {
}
func (e *errMergeConflict) Error() string {
- return fmt.Sprintf("conflict detected at: %s", e.filename)
+ return "conflict detected at: " + e.filename
}
func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, filesToRemove *[]string, filesToAdd *[]git.IndexObjectInfo) error {
diff --git a/services/pull/review.go b/services/pull/review.go
index 78723a58ae..5c80e7b338 100644
--- a/services/pull/review.go
+++ b/services/pull/review.go
@@ -395,7 +395,7 @@ func DismissReview(ctx context.Context, reviewID, repoID int64, message string,
}
if review.Type != issues_model.ReviewTypeApprove && review.Type != issues_model.ReviewTypeReject {
- return nil, fmt.Errorf("not need to dismiss this review because it's type is not Approve or change request")
+ return nil, errors.New("not need to dismiss this review because it's type is not Approve or change request")
}
// load data for notify
@@ -405,7 +405,7 @@ func DismissReview(ctx context.Context, reviewID, repoID int64, message string,
// Check if the review's repoID is the one we're currently expecting.
if review.Issue.RepoID != repoID {
- return nil, fmt.Errorf("reviews's repository is not the same as the one we expect")
+ return nil, errors.New("reviews's repository is not the same as the one we expect")
}
issue := review.Issue
diff --git a/services/pull/update.go b/services/pull/update.go
index 3e00dd4e65..5cc5e2b134 100644
--- a/services/pull/update.go
+++ b/services/pull/update.go
@@ -5,6 +5,7 @@ package pull
import (
"context"
+ "errors"
"fmt"
git_model "code.gitea.io/gitea/models/git"
@@ -23,7 +24,7 @@ import (
func Update(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, message string, rebase bool) error {
if pr.Flow == issues_model.PullRequestFlowAGit {
// TODO: update of agit flow pull request's head branch is unsupported
- return fmt.Errorf("update of agit flow pull request's head branch is unsupported")
+ return errors.New("update of agit flow pull request's head branch is unsupported")
}
releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(pr.ID))
diff --git a/services/repository/archiver/archiver.go b/services/repository/archiver/archiver.go
index d39acc080d..a657e3884c 100644
--- a/services/repository/archiver/archiver.go
+++ b/services/repository/archiver/archiver.go
@@ -44,7 +44,7 @@ type ErrUnknownArchiveFormat struct {
// Error implements error
func (err ErrUnknownArchiveFormat) Error() string {
- return fmt.Sprintf("unknown format: %s", err.RequestNameType)
+ return "unknown format: " + err.RequestNameType
}
// Is implements error
@@ -60,7 +60,7 @@ type RepoRefNotFoundError struct {
// Error implements error.
func (e RepoRefNotFoundError) Error() string {
- return fmt.Sprintf("unrecognized repository reference: %s", e.RefShortName)
+ return "unrecognized repository reference: " + e.RefShortName
}
func (e RepoRefNotFoundError) Is(err error) bool {
diff --git a/services/repository/branch.go b/services/repository/branch.go
index 8804778bd5..94c47ffdc4 100644
--- a/services/repository/branch.go
+++ b/services/repository/branch.go
@@ -303,7 +303,7 @@ func SyncBranchesToDB(ctx context.Context, repoID, pusherID int64, branchNames,
// For other batches, it will hit optimization 4.
if len(branchNames) != len(commitIDs) {
- return fmt.Errorf("branchNames and commitIDs length not match")
+ return errors.New("branchNames and commitIDs length not match")
}
return db.WithTx(ctx, func(ctx context.Context) error {
diff --git a/services/repository/files/cherry_pick.go b/services/repository/files/cherry_pick.go
index 0e069fb2ce..6818bb343d 100644
--- a/services/repository/files/cherry_pick.go
+++ b/services/repository/files/cherry_pick.go
@@ -5,6 +5,7 @@ package files
import (
"context"
+ "errors"
"fmt"
"strings"
@@ -100,7 +101,7 @@ func CherryPick(ctx context.Context, repo *repo_model.Repository, doer *user_mod
}
if conflict {
- return nil, fmt.Errorf("failed to merge due to conflicts")
+ return nil, errors.New("failed to merge due to conflicts")
}
treeHash, err := t.WriteTree(ctx)
diff --git a/services/repository/files/file.go b/services/repository/files/file.go
index 2caa1b4946..a8ad5889cb 100644
--- a/services/repository/files/file.go
+++ b/services/repository/files/file.go
@@ -5,6 +5,7 @@ package files
import (
"context"
+ "errors"
"fmt"
"net/url"
"strings"
@@ -62,10 +63,10 @@ func GetFileResponseFromFilesResponse(filesResponse *api.FilesResponse, index in
// GetFileCommitResponse Constructs a FileCommitResponse from a Commit object
func GetFileCommitResponse(repo *repo_model.Repository, commit *git.Commit) (*api.FileCommitResponse, error) {
if repo == nil {
- return nil, fmt.Errorf("repo cannot be nil")
+ return nil, errors.New("repo cannot be nil")
}
if commit == nil {
- return nil, fmt.Errorf("commit cannot be nil")
+ return nil, errors.New("commit cannot be nil")
}
commitURL, _ := url.Parse(repo.APIURL() + "/git/commits/" + url.PathEscape(commit.ID.String()))
commitTreeURL, _ := url.Parse(repo.APIURL() + "/git/trees/" + url.PathEscape(commit.Tree.ID.String()))
diff --git a/services/repository/files/temp_repo.go b/services/repository/files/temp_repo.go
index d2c70a7a34..1969676ab4 100644
--- a/services/repository/files/temp_repo.go
+++ b/services/repository/files/temp_repo.go
@@ -6,6 +6,7 @@ package files
import (
"bytes"
"context"
+ "errors"
"fmt"
"io"
"os"
@@ -414,7 +415,7 @@ func (t *TemporaryUploadRepository) DiffIndex(ctx context.Context) (*gitdiff.Dif
// GetBranchCommit Gets the commit object of the given branch
func (t *TemporaryUploadRepository) GetBranchCommit(branch string) (*git.Commit, error) {
if t.gitRepo == nil {
- return nil, fmt.Errorf("repository has not been cloned")
+ return nil, errors.New("repository has not been cloned")
}
return t.gitRepo.GetBranchCommit(branch)
}
@@ -422,7 +423,7 @@ func (t *TemporaryUploadRepository) GetBranchCommit(branch string) (*git.Commit,
// GetCommit Gets the commit object of the given commit ID
func (t *TemporaryUploadRepository) GetCommit(commitID string) (*git.Commit, error) {
if t.gitRepo == nil {
- return nil, fmt.Errorf("repository has not been cloned")
+ return nil, errors.New("repository has not been cloned")
}
return t.gitRepo.GetCommit(commitID)
}
diff --git a/services/repository/license_test.go b/services/repository/license_test.go
index 9e74a268f5..eb897f3c03 100644
--- a/services/repository/license_test.go
+++ b/services/repository/license_test.go
@@ -4,7 +4,6 @@
package repository
import (
- "fmt"
"strings"
"testing"
@@ -45,7 +44,7 @@ func Test_detectLicense(t *testing.T) {
assert.NoError(t, err)
tests = append(tests, DetectLicenseTest{
- name: fmt.Sprintf("single license test: %s", licenseName),
+ name: "single license test: " + licenseName,
arg: string(license),
want: []string{licenseName},
})
diff --git a/services/repository/push.go b/services/repository/push.go
index 6d3b9dd252..7d4e24188d 100644
--- a/services/repository/push.go
+++ b/services/repository/push.go
@@ -66,7 +66,7 @@ func PushUpdates(opts []*repo_module.PushUpdateOptions) error {
for _, opt := range opts {
if opt.IsNewRef() && opt.IsDelRef() {
- return fmt.Errorf("Old and new revisions are both NULL")
+ return errors.New("Old and new revisions are both NULL")
}
}
diff --git a/services/repository/repository.go b/services/repository/repository.go
index fcc617979e..10f175d989 100644
--- a/services/repository/repository.go
+++ b/services/repository/repository.go
@@ -5,6 +5,7 @@ package repository
import (
"context"
+ "errors"
"fmt"
"code.gitea.io/gitea/models/db"
@@ -72,10 +73,10 @@ func PushCreateRepo(ctx context.Context, authUser, owner *user_model.User, repoN
if ok, err := organization.CanCreateOrgRepo(ctx, owner.ID, authUser.ID); err != nil {
return nil, err
} else if !ok {
- return nil, fmt.Errorf("cannot push-create repository for org")
+ return nil, errors.New("cannot push-create repository for org")
}
} else if authUser.ID != owner.ID {
- return nil, fmt.Errorf("cannot push-create repository for another user")
+ return nil, errors.New("cannot push-create repository for another user")
}
}
@@ -94,7 +95,7 @@ func PushCreateRepo(ctx context.Context, authUser, owner *user_model.User, repoN
func Init(ctx context.Context) error {
licenseUpdaterQueue = queue.CreateUniqueQueue(graceful.GetManager().ShutdownContext(), "repo_license_updater", repoLicenseUpdater)
if licenseUpdaterQueue == nil {
- return fmt.Errorf("unable to create repo_license_updater queue")
+ return errors.New("unable to create repo_license_updater queue")
}
go graceful.GetManager().RunWithCancel(licenseUpdaterQueue)
diff --git a/services/task/task.go b/services/task/task.go
index c90ee91270..105aee2a25 100644
--- a/services/task/task.go
+++ b/services/task/task.go
@@ -5,6 +5,7 @@ package task
import (
"context"
+ "errors"
"fmt"
admin_model "code.gitea.io/gitea/models/admin"
@@ -41,7 +42,7 @@ func Run(ctx context.Context, t *admin_model.Task) error {
func Init() error {
taskQueue = queue.CreateSimpleQueue(graceful.GetManager().ShutdownContext(), "task", handler)
if taskQueue == nil {
- return fmt.Errorf("unable to create task queue")
+ return errors.New("unable to create task queue")
}
go graceful.GetManager().RunWithCancel(taskQueue)
return nil
diff --git a/services/webhook/deliver.go b/services/webhook/deliver.go
index df32d5741e..e8e6ed19c1 100644
--- a/services/webhook/deliver.go
+++ b/services/webhook/deliver.go
@@ -10,6 +10,7 @@ import (
"crypto/sha256"
"crypto/tls"
"encoding/hex"
+ "errors"
"fmt"
"io"
"net/http"
@@ -41,7 +42,7 @@ func newDefaultRequest(ctx context.Context, w *webhook_model.Webhook, t *webhook
case http.MethodPost:
switch w.ContentType {
case webhook_model.ContentTypeJSON:
- req, err = http.NewRequest("POST", w.URL, strings.NewReader(t.PayloadContent))
+ req, err = http.NewRequest(http.MethodPost, w.URL, strings.NewReader(t.PayloadContent))
if err != nil {
return nil, nil, err
}
@@ -52,7 +53,7 @@ func newDefaultRequest(ctx context.Context, w *webhook_model.Webhook, t *webhook
"payload": []string{t.PayloadContent},
}
- req, err = http.NewRequest("POST", w.URL, strings.NewReader(forms.Encode()))
+ req, err = http.NewRequest(http.MethodPost, w.URL, strings.NewReader(forms.Encode()))
if err != nil {
return nil, nil, err
}
@@ -69,7 +70,7 @@ func newDefaultRequest(ctx context.Context, w *webhook_model.Webhook, t *webhook
vals := u.Query()
vals["payload"] = []string{t.PayloadContent}
u.RawQuery = vals.Encode()
- req, err = http.NewRequest("GET", u.String(), nil)
+ req, err = http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return nil, nil, err
}
@@ -81,7 +82,7 @@ func newDefaultRequest(ctx context.Context, w *webhook_model.Webhook, t *webhook
return nil, nil, err
}
url := fmt.Sprintf("%s/%s", w.URL, url.PathEscape(txnID))
- req, err = http.NewRequest("PUT", url, strings.NewReader(t.PayloadContent))
+ req, err = http.NewRequest(http.MethodPut, url, strings.NewReader(t.PayloadContent))
if err != nil {
return nil, nil, err
}
@@ -328,7 +329,7 @@ func Init() error {
hookQueue = queue.CreateUniqueQueue(graceful.GetManager().ShutdownContext(), "webhook_sender", handler)
if hookQueue == nil {
- return fmt.Errorf("unable to create webhook_sender queue")
+ return errors.New("unable to create webhook_sender queue")
}
go graceful.GetManager().RunWithCancel(hookQueue)
diff --git a/services/webhook/deliver_test.go b/services/webhook/deliver_test.go
index be1347c07b..1d32d7b772 100644
--- a/services/webhook/deliver_test.go
+++ b/services/webhook/deliver_test.go
@@ -64,7 +64,7 @@ func TestWebhookProxy(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.req, func(t *testing.T) {
- req, err := http.NewRequest("POST", tt.req, nil)
+ req, err := http.NewRequest(http.MethodPost, tt.req, nil)
require.NoError(t, err)
u, err := webhookProxy(allowedHostMatcher)(req)
@@ -91,7 +91,7 @@ func TestWebhookDeliverAuthorizationHeader(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/webhook", r.URL.Path)
assert.Equal(t, "Bearer s3cr3t-t0ken", r.Header.Get("Authorization"))
- w.WriteHeader(200)
+ w.WriteHeader(http.StatusOK)
done <- struct{}{}
}))
t.Cleanup(s.Close)
@@ -152,11 +152,11 @@ func TestWebhookDeliverHookTask(t *testing.T) {
assert.Len(t, body, 2147)
default:
- w.WriteHeader(404)
+ w.WriteHeader(http.StatusNotFound)
t.Fatalf("unexpected url path %s", r.URL.Path)
return
}
- w.WriteHeader(200)
+ w.WriteHeader(http.StatusOK)
done <- struct{}{}
}))
t.Cleanup(s.Close)
diff --git a/services/webhook/dingtalk.go b/services/webhook/dingtalk.go
index 5afca8d65a..ce907bf0cb 100644
--- a/services/webhook/dingtalk.go
+++ b/services/webhook/dingtalk.go
@@ -30,7 +30,7 @@ func (dc dingtalkConvertor) Create(p *api.CreatePayload) (DingtalkPayload, error
refName := git.RefName(p.Ref).ShortName()
title := fmt.Sprintf("[%s] %s %s created", p.Repo.FullName, p.RefType, refName)
- return createDingtalkPayload(title, title, fmt.Sprintf("view ref %s", refName), p.Repo.HTMLURL+"/src/"+util.PathEscapeSegments(refName)), nil
+ return createDingtalkPayload(title, title, "view ref "+refName, p.Repo.HTMLURL+"/src/"+util.PathEscapeSegments(refName)), nil
}
// Delete implements PayloadConvertor Delete method
@@ -39,14 +39,14 @@ func (dc dingtalkConvertor) Delete(p *api.DeletePayload) (DingtalkPayload, error
refName := git.RefName(p.Ref).ShortName()
title := fmt.Sprintf("[%s] %s %s deleted", p.Repo.FullName, p.RefType, refName)
- return createDingtalkPayload(title, title, fmt.Sprintf("view ref %s", refName), p.Repo.HTMLURL+"/src/"+util.PathEscapeSegments(refName)), nil
+ return createDingtalkPayload(title, title, "view ref "+refName, p.Repo.HTMLURL+"/src/"+util.PathEscapeSegments(refName)), nil
}
// Fork implements PayloadConvertor Fork method
func (dc dingtalkConvertor) Fork(p *api.ForkPayload) (DingtalkPayload, error) {
title := fmt.Sprintf("%s is forked to %s", p.Forkee.FullName, p.Repo.FullName)
- return createDingtalkPayload(title, title, fmt.Sprintf("view forked repo %s", p.Repo.FullName), p.Repo.HTMLURL), nil
+ return createDingtalkPayload(title, title, "view forked repo "+p.Repo.FullName, p.Repo.HTMLURL), nil
}
// Push implements PayloadConvertor Push method
diff --git a/services/webhook/general.go b/services/webhook/general.go
index c58f83354d..251659e75e 100644
--- a/services/webhook/general.go
+++ b/services/webhook/general.go
@@ -43,16 +43,16 @@ func getPullRequestInfo(p *api.PullRequestPayload) (title, link, by, operator, o
case api.HookIssueAssigned:
operateResult = fmt.Sprintf("%s assign this to %s", p.Sender.UserName, assignList[len(assignList)-1].UserName)
case api.HookIssueUnassigned:
- operateResult = fmt.Sprintf("%s unassigned this for someone", p.Sender.UserName)
+ operateResult = p.Sender.UserName + " unassigned this for someone"
case api.HookIssueMilestoned:
operateResult = fmt.Sprintf("%s/milestone/%d", p.Repository.HTMLURL, p.PullRequest.Milestone.ID)
}
link = p.PullRequest.HTMLURL
- by = fmt.Sprintf("PullRequest by %s", p.PullRequest.Poster.UserName)
+ by = "PullRequest by " + p.PullRequest.Poster.UserName
if len(assignStringList) > 0 {
- assignees = fmt.Sprintf("Assignees: %s", strings.Join(assignStringList, ", "))
+ assignees = "Assignees: " + strings.Join(assignStringList, ", ")
}
- operator = fmt.Sprintf("Operator: %s", p.Sender.UserName)
+ operator = "Operator: " + p.Sender.UserName
return title, link, by, operator, operateResult, assignees
}
@@ -69,16 +69,16 @@ func getIssuesInfo(p *api.IssuePayload) (issueTitle, link, by, operator, operate
case api.HookIssueAssigned:
operateResult = fmt.Sprintf("%s assign this to %s", p.Sender.UserName, assignList[len(assignList)-1].UserName)
case api.HookIssueUnassigned:
- operateResult = fmt.Sprintf("%s unassigned this for someone", p.Sender.UserName)
+ operateResult = p.Sender.UserName + " unassigned this for someone"
case api.HookIssueMilestoned:
operateResult = fmt.Sprintf("%s/milestone/%d", p.Repository.HTMLURL, p.Issue.Milestone.ID)
}
link = p.Issue.HTMLURL
- by = fmt.Sprintf("Issue by %s", p.Issue.Poster.UserName)
+ by = "Issue by " + p.Issue.Poster.UserName
if len(assignStringList) > 0 {
- assignees = fmt.Sprintf("Assignees: %s", strings.Join(assignStringList, ", "))
+ assignees = "Assignees: " + strings.Join(assignStringList, ", ")
}
- operator = fmt.Sprintf("Operator: %s", p.Sender.UserName)
+ operator = "Operator: " + p.Sender.UserName
return issueTitle, link, by, operator, operateResult, assignees
}
@@ -87,11 +87,11 @@ func getIssuesCommentInfo(p *api.IssueCommentPayload) (title, link, by, operator
title = fmt.Sprintf("[Comment-%s #%d]: %s\n%s", p.Repository.FullName, p.Issue.Index, p.Action, p.Issue.Title)
link = p.Issue.HTMLURL
if p.IsPull {
- by = fmt.Sprintf("PullRequest by %s", p.Issue.Poster.UserName)
+ by = "PullRequest by " + p.Issue.Poster.UserName
} else {
- by = fmt.Sprintf("Issue by %s", p.Issue.Poster.UserName)
+ by = "Issue by " + p.Issue.Poster.UserName
}
- operator = fmt.Sprintf("Operator: %s", p.Sender.UserName)
+ operator = "Operator: " + p.Sender.UserName
return title, link, by, operator
}
@@ -135,7 +135,7 @@ func getIssuesPayloadInfo(p *api.IssuePayload, linkFormatter linkFormatter, with
text = fmt.Sprintf("[%s] Issue milestone cleared: %s", repoLink, titleLink)
}
if withSender {
- text += fmt.Sprintf(" by %s", linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName))
+ text += " by " + linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName)
}
if p.Action == api.HookIssueOpened || p.Action == api.HookIssueEdited {
@@ -200,7 +200,7 @@ func getPullRequestPayloadInfo(p *api.PullRequestPayload, linkFormatter linkForm
text = fmt.Sprintf("[%s] Pull request review request removed: %s", repoLink, titleLink)
}
if withSender {
- text += fmt.Sprintf(" by %s", linkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName))
+ text += " by " + linkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
}
return text, issueTitle, extraMarkdown, color
@@ -222,7 +222,7 @@ func getReleasePayloadInfo(p *api.ReleasePayload, linkFormatter linkFormatter, w
color = redColor
}
if withSender {
- text += fmt.Sprintf(" by %s", linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName))
+ text += " by " + linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName)
}
return text, color
@@ -251,7 +251,7 @@ func getWikiPayloadInfo(p *api.WikiPayload, linkFormatter linkFormatter, withSen
}
if withSender {
- text += fmt.Sprintf(" by %s", linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName))
+ text += " by " + linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName)
}
return text, color, pageLink
@@ -287,7 +287,7 @@ func getIssueCommentPayloadInfo(p *api.IssueCommentPayload, linkFormatter linkFo
color = redColor
}
if withSender {
- text += fmt.Sprintf(" by %s", linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName))
+ text += " by " + linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName)
}
return text, issueTitle, color
@@ -298,14 +298,14 @@ func getPackagePayloadInfo(p *api.PackagePayload, linkFormatter linkFormatter, w
switch p.Action {
case api.HookPackageCreated:
- text = fmt.Sprintf("Package created: %s", refLink)
+ text = "Package created: " + refLink
color = greenColor
case api.HookPackageDeleted:
- text = fmt.Sprintf("Package deleted: %s", refLink)
+ text = "Package deleted: " + refLink
color = redColor
}
if withSender {
- text += fmt.Sprintf(" by %s", linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName))
+ text += " by " + linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName)
}
return text, color
@@ -318,9 +318,9 @@ func getStatusPayloadInfo(p *api.CommitStatusPayload, linkFormatter linkFormatte
color = greenColor
if withSender {
if user_model.IsGiteaActionsUserName(p.Sender.UserName) {
- text += fmt.Sprintf(" by %s", p.Sender.FullName)
+ text += " by " + p.Sender.FullName
} else {
- text += fmt.Sprintf(" by %s", linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName))
+ text += " by " + linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName)
}
}
@@ -352,7 +352,7 @@ func getWorkflowJobPayloadInfo(p *api.WorkflowJobPayload, linkFormatter linkForm
color = greyColor
}
if withSender {
- text += fmt.Sprintf(" by %s", linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName))
+ text += " by " + linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName)
}
return text, color
diff --git a/services/webhook/msteams.go b/services/webhook/msteams.go
index f70e235f20..07d28c3867 100644
--- a/services/webhook/msteams.go
+++ b/services/webhook/msteams.go
@@ -8,6 +8,7 @@ import (
"fmt"
"net/http"
"net/url"
+ "strconv"
"strings"
webhook_model "code.gitea.io/gitea/models/webhook"
@@ -73,7 +74,7 @@ func (m msteamsConvertor) Create(p *api.CreatePayload) (MSTeamsPayload, error) {
"",
p.Repo.HTMLURL+"/src/"+util.PathEscapeSegments(refName),
greenColor,
- &MSTeamsFact{fmt.Sprintf("%s:", p.RefType), refName},
+ &MSTeamsFact{p.RefType + ":", refName},
), nil
}
@@ -90,7 +91,7 @@ func (m msteamsConvertor) Delete(p *api.DeletePayload) (MSTeamsPayload, error) {
"",
p.Repo.HTMLURL+"/src/"+util.PathEscapeSegments(refName),
yellowColor,
- &MSTeamsFact{fmt.Sprintf("%s:", p.RefType), refName},
+ &MSTeamsFact{p.RefType + ":", refName},
), nil
}
@@ -148,7 +149,7 @@ func (m msteamsConvertor) Push(p *api.PushPayload) (MSTeamsPayload, error) {
text,
titleLink,
greenColor,
- &MSTeamsFact{"Commit count:", fmt.Sprintf("%d", p.TotalCommits)},
+ &MSTeamsFact{"Commit count:", strconv.Itoa(p.TotalCommits)},
), nil
}
@@ -163,7 +164,7 @@ func (m msteamsConvertor) Issue(p *api.IssuePayload) (MSTeamsPayload, error) {
extraMarkdown,
p.Issue.HTMLURL,
color,
- &MSTeamsFact{"Issue #:", fmt.Sprintf("%d", p.Issue.ID)},
+ &MSTeamsFact{"Issue #:", strconv.FormatInt(p.Issue.ID, 10)},
), nil
}
@@ -178,7 +179,7 @@ func (m msteamsConvertor) IssueComment(p *api.IssueCommentPayload) (MSTeamsPaylo
p.Comment.Body,
p.Comment.HTMLURL,
color,
- &MSTeamsFact{"Issue #:", fmt.Sprintf("%d", p.Issue.ID)},
+ &MSTeamsFact{"Issue #:", strconv.FormatInt(p.Issue.ID, 10)},
), nil
}
@@ -193,7 +194,7 @@ func (m msteamsConvertor) PullRequest(p *api.PullRequestPayload) (MSTeamsPayload
extraMarkdown,
p.PullRequest.HTMLURL,
color,
- &MSTeamsFact{"Pull request #:", fmt.Sprintf("%d", p.PullRequest.ID)},
+ &MSTeamsFact{"Pull request #:", strconv.FormatInt(p.PullRequest.ID, 10)},
), nil
}
@@ -230,7 +231,7 @@ func (m msteamsConvertor) Review(p *api.PullRequestPayload, event webhook_module
text,
p.PullRequest.HTMLURL,
color,
- &MSTeamsFact{"Pull request #:", fmt.Sprintf("%d", p.PullRequest.ID)},
+ &MSTeamsFact{"Pull request #:", strconv.FormatInt(p.PullRequest.ID, 10)},
), nil
}
diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go
index ece136be50..af631ca8fd 100644
--- a/tests/e2e/e2e_test.go
+++ b/tests/e2e/e2e_test.go
@@ -94,7 +94,7 @@ func TestE2e(t *testing.T) {
onGiteaRun(t, func(*testing.T, *url.URL) {
cmd := exec.Command(runArgs[0], runArgs...)
cmd.Env = os.Environ()
- cmd.Env = append(cmd.Env, fmt.Sprintf("GITEA_URL=%s", setting.AppURL))
+ cmd.Env = append(cmd.Env, "GITEA_URL="+setting.AppURL)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
diff --git a/tests/integration/actions_job_test.go b/tests/integration/actions_job_test.go
index 89c93e7a75..4f4456a4e5 100644
--- a/tests/integration/actions_job_test.go
+++ b/tests/integration/actions_job_test.go
@@ -9,6 +9,7 @@ import (
"net/http"
"net/url"
"reflect"
+ "strconv"
"testing"
"time"
@@ -137,9 +138,9 @@ jobs:
runner.registerAsRepoRunner(t, user2.Name, apiRepo.Name, "mock-runner", []string{"ubuntu-latest"}, false)
for _, tc := range testCases {
- t.Run(fmt.Sprintf("test %s", tc.treePath), func(t *testing.T) {
+ t.Run("test "+tc.treePath, func(t *testing.T) {
// create the workflow file
- opts := getWorkflowCreateFileOptions(user2, apiRepo.DefaultBranch, fmt.Sprintf("create %s", tc.treePath), tc.fileContent)
+ opts := getWorkflowCreateFileOptions(user2, apiRepo.DefaultBranch, "create "+tc.treePath, tc.fileContent)
fileResp := createWorkflowFile(t, token, user2.Name, apiRepo.Name, tc.treePath, opts)
// fetch and execute task
@@ -320,8 +321,8 @@ jobs:
runner.registerAsRepoRunner(t, user2.Name, apiRepo.Name, "mock-runner", []string{"ubuntu-latest"}, false)
for _, tc := range testCases {
- t.Run(fmt.Sprintf("test %s", tc.treePath), func(t *testing.T) {
- opts := getWorkflowCreateFileOptions(user2, apiRepo.DefaultBranch, fmt.Sprintf("create %s", tc.treePath), tc.fileContent)
+ t.Run("test "+tc.treePath, func(t *testing.T) {
+ opts := getWorkflowCreateFileOptions(user2, apiRepo.DefaultBranch, "create "+tc.treePath, tc.fileContent)
createWorkflowFile(t, token, user2.Name, apiRepo.Name, tc.treePath, opts)
for i := 0; i < len(tc.outcomes); i++ {
@@ -371,7 +372,7 @@ jobs:
steps:
- run: echo 'test the pull'
`
- opts := getWorkflowCreateFileOptions(user2, baseRepo.DefaultBranch, fmt.Sprintf("create %s", wfTreePath), wfFileContent)
+ opts := getWorkflowCreateFileOptions(user2, baseRepo.DefaultBranch, "create "+wfTreePath, wfFileContent)
createWorkflowFile(t, user2Token, baseRepo.OwnerName, baseRepo.Name, wfTreePath, opts)
// user2 creates a pull request
doAPICreateFile(user2APICtx, "user2-patch.txt", &api.CreateFileOptions{
@@ -418,9 +419,9 @@ jobs:
assert.Equal(t, actionRun.Repo.OwnerName+"/"+actionRun.Repo.Name, gtCtx["repository"].GetStringValue())
assert.Equal(t, actionRun.Repo.OwnerName, gtCtx["repository_owner"].GetStringValue())
assert.Equal(t, actionRun.Repo.HTMLURL(), gtCtx["repositoryUrl"].GetStringValue())
- assert.Equal(t, fmt.Sprint(actionRunJob.RunID), gtCtx["run_id"].GetStringValue())
- assert.Equal(t, fmt.Sprint(actionRun.Index), gtCtx["run_number"].GetStringValue())
- assert.Equal(t, fmt.Sprint(actionRunJob.Attempt), gtCtx["run_attempt"].GetStringValue())
+ assert.Equal(t, strconv.FormatInt(actionRunJob.RunID, 10), gtCtx["run_id"].GetStringValue())
+ assert.Equal(t, strconv.FormatInt(actionRun.Index, 10), gtCtx["run_number"].GetStringValue())
+ assert.Equal(t, strconv.FormatInt(actionRunJob.Attempt, 10), gtCtx["run_attempt"].GetStringValue())
assert.Equal(t, "Actions", gtCtx["secret_source"].GetStringValue())
assert.Equal(t, setting.AppURL, gtCtx["server_url"].GetStringValue())
assert.Equal(t, actionRun.CommitSHA, gtCtx["sha"].GetStringValue())
@@ -463,7 +464,7 @@ jobs:
steps:
- run: echo 'test the pull'
`
- opts := getWorkflowCreateFileOptions(user2, baseRepo.DefaultBranch, fmt.Sprintf("create %s", wfTreePath), wfFileContent)
+ opts := getWorkflowCreateFileOptions(user2, baseRepo.DefaultBranch, "create "+wfTreePath, wfFileContent)
createWorkflowFile(t, user2Token, baseRepo.OwnerName, baseRepo.Name, wfTreePath, opts)
// user2 creates a pull request
doAPICreateFile(user2APICtx, "user2-patch.txt", &api.CreateFileOptions{
@@ -510,9 +511,9 @@ jobs:
assert.Equal(t, actionRun.Repo.OwnerName+"/"+actionRun.Repo.Name, gtCtx["repository"].GetStringValue())
assert.Equal(t, actionRun.Repo.OwnerName, gtCtx["repository_owner"].GetStringValue())
assert.Equal(t, actionRun.Repo.HTMLURL(), gtCtx["repositoryUrl"].GetStringValue())
- assert.Equal(t, fmt.Sprint(actionRunJob.RunID), gtCtx["run_id"].GetStringValue())
- assert.Equal(t, fmt.Sprint(actionRun.Index), gtCtx["run_number"].GetStringValue())
- assert.Equal(t, fmt.Sprint(actionRunJob.Attempt), gtCtx["run_attempt"].GetStringValue())
+ assert.Equal(t, strconv.FormatInt(actionRunJob.RunID, 10), gtCtx["run_id"].GetStringValue())
+ assert.Equal(t, strconv.FormatInt(actionRun.Index, 10), gtCtx["run_number"].GetStringValue())
+ assert.Equal(t, strconv.FormatInt(actionRunJob.Attempt, 10), gtCtx["run_attempt"].GetStringValue())
assert.Equal(t, "Actions", gtCtx["secret_source"].GetStringValue())
assert.Equal(t, setting.AppURL, gtCtx["server_url"].GetStringValue())
assert.Equal(t, actionRun.CommitSHA, gtCtx["sha"].GetStringValue())
diff --git a/tests/integration/actions_log_test.go b/tests/integration/actions_log_test.go
index cd20604b84..503bda97c9 100644
--- a/tests/integration/actions_log_test.go
+++ b/tests/integration/actions_log_test.go
@@ -156,7 +156,7 @@ jobs:
runner.registerAsRepoRunner(t, user2.Name, repo.Name, "mock-runner", []string{"ubuntu-latest"}, false)
for _, tc := range testCases {
- t.Run(fmt.Sprintf("test %s", tc.treePath), func(t *testing.T) {
+ t.Run("test "+tc.treePath, func(t *testing.T) {
var resetFunc func()
if tc.zstdEnabled {
resetFunc = test.MockVariableValue(&setting.Actions.LogCompression, "zstd")
@@ -167,7 +167,7 @@ jobs:
}
// create the workflow file
- opts := getWorkflowCreateFileOptions(user2, repo.DefaultBranch, fmt.Sprintf("create %s", tc.treePath), tc.fileContent)
+ opts := getWorkflowCreateFileOptions(user2, repo.DefaultBranch, "create "+tc.treePath, tc.fileContent)
createWorkflowFile(t, token, user2.Name, repo.Name, tc.treePath, opts)
// fetch and execute tasks
diff --git a/tests/integration/actions_runner_test.go b/tests/integration/actions_runner_test.go
index ee92032e9f..75402929a1 100644
--- a/tests/integration/actions_runner_test.go
+++ b/tests/integration/actions_runner_test.go
@@ -37,7 +37,7 @@ func newMockRunner() *mockRunner {
}
func newMockRunnerClient(uuid, token string) *mockRunnerClient {
- baseURL := fmt.Sprintf("%sapi/actions", setting.AppURL)
+ baseURL := setting.AppURL + "api/actions"
opt := connect.WithInterceptors(connect.UnaryInterceptorFunc(func(next connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
diff --git a/tests/integration/actions_trigger_test.go b/tests/integration/actions_trigger_test.go
index 096f51dfc0..28d1b3ff42 100644
--- a/tests/integration/actions_trigger_test.go
+++ b/tests/integration/actions_trigger_test.go
@@ -286,7 +286,7 @@ jobs:
ContentReader: strings.NewReader("bar"),
},
},
- Message: fmt.Sprintf("%s add bar", setting.Actions.SkipWorkflowStrings[0]),
+ Message: setting.Actions.SkipWorkflowStrings[0] + " add bar",
OldBranch: "master",
NewBranch: "master",
Author: &files_service.IdentityOptions{
diff --git a/tests/integration/api_activitypub_person_test.go b/tests/integration/api_activitypub_person_test.go
index 17d628a483..9bb1f2736e 100644
--- a/tests/integration/api_activitypub_person_test.go
+++ b/tests/integration/api_activitypub_person_test.go
@@ -72,10 +72,10 @@ func TestActivityPubPerson(t *testing.T) {
ctx := t.Context()
user1, err := user_model.GetUserByName(ctx, username1)
assert.NoError(t, err)
- user1url := fmt.Sprintf("%s/api/v1/activitypub/user-id/1#main-key", srv.URL)
+ user1url := srv.URL + "/api/v1/activitypub/user-id/1#main-key"
c, err := activitypub.NewClient(db.DefaultContext, user1, user1url)
assert.NoError(t, err)
- user2inboxurl := fmt.Sprintf("%s/api/v1/activitypub/user-id/2/inbox", srv.URL)
+ user2inboxurl := srv.URL + "/api/v1/activitypub/user-id/2/inbox"
// Signed request succeeds
resp, err := c.Post([]byte{}, user2inboxurl)
diff --git a/tests/integration/api_admin_test.go b/tests/integration/api_admin_test.go
index 56013d2bd3..d28a103e59 100644
--- a/tests/integration/api_admin_test.go
+++ b/tests/integration/api_admin_test.go
@@ -88,7 +88,7 @@ func TestAPISudoUser(t *testing.T) {
normalUsername := "user2"
token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeReadUser)
- req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user?sudo=%s", normalUsername)).
+ req := NewRequest(t, "GET", "/api/v1/user?sudo="+normalUsername).
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
var user api.User
@@ -103,7 +103,7 @@ func TestAPISudoUserForbidden(t *testing.T) {
normalUsername := "user2"
token := getUserToken(t, normalUsername, auth_model.AccessTokenScopeReadAdmin)
- req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user?sudo=%s", adminUsername)).
+ req := NewRequest(t, "GET", "/api/v1/user?sudo="+adminUsername).
AddTokenAuth(token)
MakeRequest(t, req, http.StatusForbidden)
}
@@ -193,7 +193,7 @@ func TestAPIEditUser(t *testing.T) {
defer tests.PrepareTestEnv(t)()
adminUsername := "user1"
token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin)
- urlStr := fmt.Sprintf("/api/v1/admin/users/%s", "user2")
+ urlStr := "/api/v1/admin/users/" + "user2"
fullNameToChange := "Full Name User 2"
req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{
@@ -374,7 +374,7 @@ func TestAPIEditUser_NotAllowedEmailDomain(t *testing.T) {
adminUsername := "user1"
token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin)
- urlStr := fmt.Sprintf("/api/v1/admin/users/%s", "user2")
+ urlStr := "/api/v1/admin/users/" + "user2"
newEmail := "user2@example1.com"
req := NewRequestWithJSON(t, "PATCH", urlStr, api.EditUserOption{
diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go
index 4b96568cad..9842c358f6 100644
--- a/tests/integration/api_comment_test.go
+++ b/tests/integration/api_comment_test.go
@@ -174,7 +174,7 @@ func TestAPIGetSystemUserComment(t *testing.T) {
user_model.NewGhostUser(),
user_model.NewActionsUser(),
} {
- body := fmt.Sprintf("Hello %s", systemUser.Name)
+ body := "Hello " + systemUser.Name
comment, err := issues_model.CreateComment(db.DefaultContext, &issues_model.CreateCommentOptions{
Type: issues_model.CommentTypeComment,
Doer: systemUser,
diff --git a/tests/integration/api_gitignore_templates_test.go b/tests/integration/api_gitignore_templates_test.go
index c58f5eebfe..1c56d51344 100644
--- a/tests/integration/api_gitignore_templates_test.go
+++ b/tests/integration/api_gitignore_templates_test.go
@@ -4,7 +4,6 @@
package integration
import (
- "fmt"
"net/http"
"testing"
@@ -38,7 +37,7 @@ func TestAPIGetGitignoreTemplateInfo(t *testing.T) {
// Use the first template for the test
templateName := repo_module.Gitignores[0]
- urlStr := fmt.Sprintf("/api/v1/gitignore/templates/%s", templateName)
+ urlStr := "/api/v1/gitignore/templates/" + templateName
req := NewRequest(t, "GET", urlStr)
resp := MakeRequest(t, req, http.StatusOK)
diff --git a/tests/integration/api_keys_test.go b/tests/integration/api_keys_test.go
index 2276b955cf..3162051acc 100644
--- a/tests/integration/api_keys_test.go
+++ b/tests/integration/api_keys_test.go
@@ -143,7 +143,7 @@ func TestCreateUserKey(t *testing.T) {
})
// Search by fingerprint
- req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/keys?fingerprint=%s", newPublicKey.Fingerprint)).
+ req = NewRequest(t, "GET", "/api/v1/user/keys?fingerprint="+newPublicKey.Fingerprint).
AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusOK)
@@ -183,7 +183,7 @@ func TestCreateUserKey(t *testing.T) {
token2 := getTokenForLoggedInUser(t, session2, auth_model.AccessTokenScopeWriteUser)
// Should find key even though not ours, but we shouldn't know whose it is
- req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/keys?fingerprint=%s", newPublicKey.Fingerprint)).
+ req = NewRequest(t, "GET", "/api/v1/user/keys?fingerprint="+newPublicKey.Fingerprint).
AddTokenAuth(token2)
resp = MakeRequest(t, req, http.StatusOK)
diff --git a/tests/integration/api_label_templates_test.go b/tests/integration/api_label_templates_test.go
index 007e979011..3e637daba6 100644
--- a/tests/integration/api_label_templates_test.go
+++ b/tests/integration/api_label_templates_test.go
@@ -4,7 +4,6 @@
package integration
import (
- "fmt"
"net/http"
"net/url"
"strings"
@@ -42,7 +41,7 @@ func TestAPIGetLabelTemplateInfo(t *testing.T) {
// Use the first template for the test
templateName := repo_module.LabelTemplateFiles[0].DisplayName
- urlStr := fmt.Sprintf("/api/v1/label/templates/%s", url.PathEscape(templateName))
+ urlStr := "/api/v1/label/templates/" + url.PathEscape(templateName)
req := NewRequest(t, "GET", urlStr)
resp := MakeRequest(t, req, http.StatusOK)
diff --git a/tests/integration/api_license_templates_test.go b/tests/integration/api_license_templates_test.go
index e12aab7c2c..52e240f9a7 100644
--- a/tests/integration/api_license_templates_test.go
+++ b/tests/integration/api_license_templates_test.go
@@ -4,7 +4,6 @@
package integration
import (
- "fmt"
"net/http"
"net/url"
"testing"
@@ -39,7 +38,7 @@ func TestAPIGetLicenseTemplateInfo(t *testing.T) {
// Use the first template for the test
licenseName := repo_module.Licenses[0]
- urlStr := fmt.Sprintf("/api/v1/licenses/%s", url.PathEscape(licenseName))
+ urlStr := "/api/v1/licenses/" + url.PathEscape(licenseName)
req := NewRequest(t, "GET", urlStr)
resp := MakeRequest(t, req, http.StatusOK)
diff --git a/tests/integration/api_notification_test.go b/tests/integration/api_notification_test.go
index 72aa7cf281..e6bc142476 100644
--- a/tests/integration/api_notification_test.go
+++ b/tests/integration/api_notification_test.go
@@ -35,7 +35,7 @@ func TestAPINotification(t *testing.T) {
// -- GET /notifications --
// test filter
since := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801
- req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?since=%s", since)).
+ req := NewRequest(t, "GET", "/api/v1/notifications?since="+since).
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
var apiNL []api.NotificationThread
diff --git a/tests/integration/api_packages_arch_test.go b/tests/integration/api_packages_arch_test.go
index b9064ca3d1..e5778b4203 100644
--- a/tests/integration/api_packages_arch_test.go
+++ b/tests/integration/api_packages_arch_test.go
@@ -163,7 +163,7 @@ license = MIT`)
assert.Condition(t, func() bool {
seen := false
expectedFilename := fmt.Sprintf("%s-%s-aarch64.pkg.tar.%s", packageName, packageVersion, compression)
- expectedCompositeKey := fmt.Sprintf("%s|aarch64", repository)
+ expectedCompositeKey := repository + "|aarch64"
for _, pf := range pfs {
if pf.Name == expectedFilename && pf.CompositeKey == expectedCompositeKey {
if seen {
@@ -321,7 +321,7 @@ license = MIT`)
_, has = content["gitea-test-1.0.1/desc"]
assert.True(t, has)
- req = NewRequest(t, "DELETE", fmt.Sprintf("%s/gitea-test/1.0.1/aarch64", rootURL)).
+ req = NewRequest(t, "DELETE", rootURL+"/gitea-test/1.0.1/aarch64").
AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusNoContent)
diff --git a/tests/integration/api_packages_cargo_test.go b/tests/integration/api_packages_cargo_test.go
index 3fb9687653..8b5caa7ea7 100644
--- a/tests/integration/api_packages_cargo_test.go
+++ b/tests/integration/api_packages_cargo_test.go
@@ -94,7 +94,7 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) {
}
root := fmt.Sprintf("%sapi/packages/%s/cargo", setting.AppURL, user.Name)
- url := fmt.Sprintf("%s/api/v1/crates", root)
+ url := root + "/api/v1/crates"
t.Run("Index", func(t *testing.T) {
t.Run("Git/Config", func(t *testing.T) {
diff --git a/tests/integration/api_packages_chef_test.go b/tests/integration/api_packages_chef_test.go
index 6efb2708af..86b3be9d0c 100644
--- a/tests/integration/api_packages_chef_test.go
+++ b/tests/integration/api_packages_chef_test.go
@@ -274,7 +274,7 @@ nwIDAQAB
uploadPackage := func(t *testing.T, version string, expectedStatus int) {
var body bytes.Buffer
mpw := multipart.NewWriter(&body)
- part, _ := mpw.CreateFormFile("tarball", fmt.Sprintf("%s.tar.gz", version))
+ part, _ := mpw.CreateFormFile("tarball", version+".tar.gz")
zw := gzip.NewWriter(part)
tw := tar.NewWriter(zw)
@@ -320,7 +320,7 @@ nwIDAQAB
pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID)
assert.NoError(t, err)
assert.Len(t, pfs, 1)
- assert.Equal(t, fmt.Sprintf("%s.tar.gz", packageVersion), pfs[0].Name)
+ assert.Equal(t, packageVersion+".tar.gz", pfs[0].Name)
assert.True(t, pfs[0].IsLead)
uploadPackage(t, packageVersion, http.StatusConflict)
diff --git a/tests/integration/api_packages_composer_test.go b/tests/integration/api_packages_composer_test.go
index bc858c7476..54f61d91d9 100644
--- a/tests/integration/api_packages_composer_test.go
+++ b/tests/integration/api_packages_composer_test.go
@@ -64,7 +64,7 @@ func TestPackageComposer(t *testing.T) {
t.Run("ServiceIndex", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%s/packages.json", url)).
+ req := NewRequest(t, "GET", url+"/packages.json").
AddBasicAuth(user.Name)
resp := MakeRequest(t, req, http.StatusOK)
diff --git a/tests/integration/api_packages_conan_test.go b/tests/integration/api_packages_conan_test.go
index 9ab3e1c46b..4e83c998b8 100644
--- a/tests/integration/api_packages_conan_test.go
+++ b/tests/integration/api_packages_conan_test.go
@@ -91,18 +91,18 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha
AddTokenAuth(token)
MakeRequest(t, req, http.StatusNotFound)
- req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", recipeURL)).
+ req = NewRequest(t, "GET", recipeURL+"/digest").
AddTokenAuth(token)
MakeRequest(t, req, http.StatusNotFound)
- req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", recipeURL)).
+ req = NewRequest(t, "GET", recipeURL+"/download_urls").
AddTokenAuth(token)
MakeRequest(t, req, http.StatusNotFound)
- req = NewRequest(t, "POST", fmt.Sprintf("%s/upload_urls", recipeURL))
+ req = NewRequest(t, "POST", recipeURL+"/upload_urls")
MakeRequest(t, req, http.StatusUnauthorized)
- req = NewRequestWithJSON(t, "POST", fmt.Sprintf("%s/upload_urls", recipeURL), map[string]int64{
+ req = NewRequestWithJSON(t, "POST", recipeURL+"/upload_urls", map[string]int64{
conanfileName: int64(len(contentConanfile)),
"removed.txt": 0,
}).AddTokenAuth(token)
@@ -127,18 +127,18 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha
AddTokenAuth(token)
MakeRequest(t, req, http.StatusNotFound)
- req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", packageURL)).
+ req = NewRequest(t, "GET", packageURL+"/digest").
AddTokenAuth(token)
MakeRequest(t, req, http.StatusNotFound)
- req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", packageURL)).
+ req = NewRequest(t, "GET", packageURL+"/download_urls").
AddTokenAuth(token)
MakeRequest(t, req, http.StatusNotFound)
- req = NewRequest(t, "POST", fmt.Sprintf("%s/upload_urls", packageURL))
+ req = NewRequest(t, "POST", packageURL+"/upload_urls")
MakeRequest(t, req, http.StatusUnauthorized)
- req = NewRequestWithJSON(t, "POST", fmt.Sprintf("%s/upload_urls", packageURL), map[string]int64{
+ req = NewRequestWithJSON(t, "POST", packageURL+"/upload_urls", map[string]int64{
conaninfoName: int64(len(contentConaninfo)),
"removed.txt": 0,
}).AddTokenAuth(token)
@@ -167,7 +167,7 @@ func uploadConanPackageV2(t *testing.T, baseURL, token, name, version, user, cha
AddTokenAuth(token)
MakeRequest(t, req, http.StatusCreated)
- req = NewRequest(t, "GET", fmt.Sprintf("%s/files", recipeURL)).
+ req = NewRequest(t, "GET", recipeURL+"/files").
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
@@ -180,7 +180,7 @@ func uploadConanPackageV2(t *testing.T, baseURL, token, name, version, user, cha
packageURL := fmt.Sprintf("%s/packages/%s/revisions/%s", recipeURL, conanPackageReference, packageRevision)
- req = NewRequest(t, "GET", fmt.Sprintf("%s/files", packageURL)).
+ req = NewRequest(t, "GET", packageURL+"/files").
AddTokenAuth(token)
MakeRequest(t, req, http.StatusNotFound)
@@ -188,7 +188,7 @@ func uploadConanPackageV2(t *testing.T, baseURL, token, name, version, user, cha
AddTokenAuth(token)
MakeRequest(t, req, http.StatusCreated)
- req = NewRequest(t, "GET", fmt.Sprintf("%s/files", packageURL)).
+ req = NewRequest(t, "GET", packageURL+"/files").
AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusOK)
@@ -219,7 +219,7 @@ func TestPackageConan(t *testing.T) {
t.Run("Ping", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/ping", url))
+ req := NewRequest(t, "GET", url+"/v1/ping")
resp := MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "revisions", resp.Header().Get("X-Conan-Server-Capabilities"))
@@ -230,7 +230,7 @@ func TestPackageConan(t *testing.T) {
t.Run("UserName/Password Authenticate", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/users/authenticate", url)).
+ req := NewRequest(t, "GET", url+"/v1/users/authenticate").
AddBasicAuth(user.Name)
resp := MakeRequest(t, req, http.StatusOK)
@@ -256,7 +256,7 @@ func TestPackageConan(t *testing.T) {
token := getTokenForLoggedInUser(t, session, scope)
- req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/users/authenticate", url)).
+ req := NewRequest(t, "GET", url+"/v1/users/authenticate").
AddTokenAuth(token)
resp := MakeRequest(t, req, expectedAuthStatusCode)
if expectedAuthStatusCode != http.StatusOK {
@@ -273,7 +273,7 @@ func TestPackageConan(t *testing.T) {
recipeURL := fmt.Sprintf("%s/v1/conans/%s/%s/%s/%s", url, "TestScope", version1, "testing", channel1)
- req = NewRequestWithJSON(t, "POST", fmt.Sprintf("%s/upload_urls", recipeURL), map[string]int64{
+ req = NewRequestWithJSON(t, "POST", recipeURL+"/upload_urls", map[string]int64{
conanfileName: 64,
"removed.txt": 0,
}).AddTokenAuth(token)
@@ -308,7 +308,7 @@ func TestPackageConan(t *testing.T) {
t.Run("CheckCredentials", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/users/check_credentials", url)).
+ req := NewRequest(t, "GET", url+"/v1/users/check_credentials").
AddTokenAuth(token)
MakeRequest(t, req, http.StatusOK)
})
@@ -376,14 +376,14 @@ func TestPackageConan(t *testing.T) {
assert.Contains(t, fileHashes, conanfileName)
assert.Equal(t, "7abc52241c22090782c54731371847a8", fileHashes[conanfileName])
- req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", recipeURL))
+ req = NewRequest(t, "GET", recipeURL+"/digest")
resp = MakeRequest(t, req, http.StatusOK)
downloadURLs := make(map[string]string)
DecodeJSON(t, resp, &downloadURLs)
assert.Contains(t, downloadURLs, conanfileName)
- req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", recipeURL))
+ req = NewRequest(t, "GET", recipeURL+"/download_urls")
resp = MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &downloadURLs)
@@ -404,14 +404,14 @@ func TestPackageConan(t *testing.T) {
assert.Contains(t, fileHashes, conaninfoName)
assert.Equal(t, "7628bfcc5b17f1470c468621a78df394", fileHashes[conaninfoName])
- req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", packageURL))
+ req = NewRequest(t, "GET", packageURL+"/digest")
resp = MakeRequest(t, req, http.StatusOK)
downloadURLs = make(map[string]string)
DecodeJSON(t, resp, &downloadURLs)
assert.Contains(t, downloadURLs, conaninfoName)
- req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", packageURL))
+ req = NewRequest(t, "GET", packageURL+"/download_urls")
resp = MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &downloadURLs)
@@ -550,7 +550,7 @@ func TestPackageConan(t *testing.T) {
t.Run("Ping", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/ping", url))
+ req := NewRequest(t, "GET", url+"/v2/ping")
resp := MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "revisions", resp.Header().Get("X-Conan-Server-Capabilities"))
@@ -561,7 +561,7 @@ func TestPackageConan(t *testing.T) {
t.Run("UserName/Password Authenticate", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/users/authenticate", url)).
+ req := NewRequest(t, "GET", url+"/v2/users/authenticate").
AddBasicAuth(user.Name)
resp := MakeRequest(t, req, http.StatusOK)
@@ -573,7 +573,7 @@ func TestPackageConan(t *testing.T) {
assert.Equal(t, user.ID, pkgMeta.UserID)
assert.Equal(t, auth_model.AccessTokenScopeAll, pkgMeta.Scope)
- token = fmt.Sprintf("Bearer %s", body)
+ token = "Bearer " + body
})
badToken := ""
@@ -590,7 +590,7 @@ func TestPackageConan(t *testing.T) {
token := getTokenForLoggedInUser(t, session, scope)
- req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/users/authenticate", url)).
+ req := NewRequest(t, "GET", url+"/v2/users/authenticate").
AddTokenAuth(token)
resp := MakeRequest(t, req, expectedAuthStatusCode)
if expectedAuthStatusCode != http.StatusOK {
@@ -640,7 +640,7 @@ func TestPackageConan(t *testing.T) {
t.Run("CheckCredentials", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/users/check_credentials", url)).
+ req := NewRequest(t, "GET", url+"/v2/users/check_credentials").
AddTokenAuth(token)
MakeRequest(t, req, http.StatusOK)
})
@@ -664,7 +664,7 @@ func TestPackageConan(t *testing.T) {
recipeURL := fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s", url, name, version1, user1, channel1)
- req := NewRequest(t, "GET", fmt.Sprintf("%s/latest", recipeURL))
+ req := NewRequest(t, "GET", recipeURL+"/latest")
resp := MakeRequest(t, req, http.StatusOK)
obj := make(map[string]string)
diff --git a/tests/integration/api_packages_conda_test.go b/tests/integration/api_packages_conda_test.go
index 272a660d45..32f55e5435 100644
--- a/tests/integration/api_packages_conda_test.go
+++ b/tests/integration/api_packages_conda_test.go
@@ -193,19 +193,19 @@ func TestPackageConda(t *testing.T) {
Removed map[string]*PackageInfo `json:"removed"`
}
- req := NewRequest(t, "GET", fmt.Sprintf("%s/noarch/repodata.json", root))
+ req := NewRequest(t, "GET", root+"/noarch/repodata.json")
resp := MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "application/json", resp.Header().Get("Content-Type"))
- req = NewRequest(t, "GET", fmt.Sprintf("%s/noarch/repodata.json.bz2", root))
+ req = NewRequest(t, "GET", root+"/noarch/repodata.json.bz2")
resp = MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "application/x-bzip2", resp.Header().Get("Content-Type"))
- req = NewRequest(t, "GET", fmt.Sprintf("%s/noarch/current_repodata.json", root))
+ req = NewRequest(t, "GET", root+"/noarch/current_repodata.json")
resp = MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "application/json", resp.Header().Get("Content-Type"))
- req = NewRequest(t, "GET", fmt.Sprintf("%s/noarch/current_repodata.json.bz2", root))
+ req = NewRequest(t, "GET", root+"/noarch/current_repodata.json.bz2")
resp = MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "application/x-bzip2", resp.Header().Get("Content-Type"))
@@ -218,7 +218,7 @@ func TestPackageConda(t *testing.T) {
pd, err := packages.GetPackageDescriptor(db.DefaultContext, pv)
assert.NoError(t, err)
- req := NewRequest(t, "GET", fmt.Sprintf("%s/noarch/repodata.json", root))
+ req := NewRequest(t, "GET", root+"/noarch/repodata.json")
resp := MakeRequest(t, req, http.StatusOK)
var result RepoData
diff --git a/tests/integration/api_packages_container_test.go b/tests/integration/api_packages_container_test.go
index 11058a1c2d..b2db77685d 100644
--- a/tests/integration/api_packages_container_test.go
+++ b/tests/integration/api_packages_container_test.go
@@ -9,6 +9,7 @@ import (
"encoding/base64"
"fmt"
"net/http"
+ "strconv"
"strings"
"sync"
"testing"
@@ -92,12 +93,12 @@ func TestPackageContainer(t *testing.T) {
t.Run("Anonymous", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL))
+ req := NewRequest(t, "GET", setting.AppURL+"v2")
resp := MakeRequest(t, req, http.StatusUnauthorized)
assert.ElementsMatch(t, defaultAuthenticateValues, resp.Header().Values("WWW-Authenticate"))
- req = NewRequest(t, "GET", fmt.Sprintf("%sv2/token", setting.AppURL))
+ req = NewRequest(t, "GET", setting.AppURL+"v2/token")
resp = MakeRequest(t, req, http.StatusOK)
tokenResponse := &TokenResponse{}
@@ -105,18 +106,18 @@ func TestPackageContainer(t *testing.T) {
assert.NotEmpty(t, tokenResponse.Token)
- anonymousToken = fmt.Sprintf("Bearer %s", tokenResponse.Token)
+ anonymousToken = "Bearer " + tokenResponse.Token
- req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)).
+ req = NewRequest(t, "GET", setting.AppURL+"v2").
AddTokenAuth(anonymousToken)
MakeRequest(t, req, http.StatusOK)
defer test.MockVariableValue(&setting.Service.RequireSignInViewStrict, true)()
- req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL))
+ req = NewRequest(t, "GET", setting.AppURL+"v2")
MakeRequest(t, req, http.StatusUnauthorized)
- req = NewRequest(t, "GET", fmt.Sprintf("%sv2/token", setting.AppURL))
+ req = NewRequest(t, "GET", setting.AppURL+"v2/token")
MakeRequest(t, req, http.StatusUnauthorized)
defer test.MockVariableValue(&setting.AppURL, "https://domain:8443/sub-path/")()
@@ -129,12 +130,12 @@ func TestPackageContainer(t *testing.T) {
t.Run("UserName/Password", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL))
+ req := NewRequest(t, "GET", setting.AppURL+"v2")
resp := MakeRequest(t, req, http.StatusUnauthorized)
assert.ElementsMatch(t, defaultAuthenticateValues, resp.Header().Values("WWW-Authenticate"))
- req = NewRequest(t, "GET", fmt.Sprintf("%sv2/token", setting.AppURL)).
+ req = NewRequest(t, "GET", setting.AppURL+"v2/token").
AddBasicAuth(user.Name)
resp = MakeRequest(t, req, http.StatusOK)
@@ -147,9 +148,9 @@ func TestPackageContainer(t *testing.T) {
assert.Equal(t, user.ID, pkgMeta.UserID)
assert.Equal(t, auth_model.AccessTokenScopeAll, pkgMeta.Scope)
- userToken = fmt.Sprintf("Bearer %s", tokenResponse.Token)
+ userToken = "Bearer " + tokenResponse.Token
- req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)).
+ req = NewRequest(t, "GET", setting.AppURL+"v2").
AddTokenAuth(userToken)
MakeRequest(t, req, http.StatusOK)
})
@@ -161,23 +162,23 @@ func TestPackageContainer(t *testing.T) {
session := loginUser(t, user.Name)
readToken = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadPackage)
- req := NewRequest(t, "GET", fmt.Sprintf("%sv2/token", setting.AppURL))
+ req := NewRequest(t, "GET", setting.AppURL+"v2/token")
req.Request.SetBasicAuth(user.Name, readToken)
resp := MakeRequest(t, req, http.StatusOK)
tokenResponse := &TokenResponse{}
DecodeJSON(t, resp, &tokenResponse)
- readToken = fmt.Sprintf("Bearer %s", tokenResponse.Token)
+ readToken = "Bearer " + tokenResponse.Token
badToken = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadNotification)
- req = NewRequest(t, "GET", fmt.Sprintf("%sv2/token", setting.AppURL))
+ req = NewRequest(t, "GET", setting.AppURL+"v2/token")
req.Request.SetBasicAuth(user.Name, badToken)
MakeRequest(t, req, http.StatusUnauthorized)
testCase := func(scope auth_model.AccessTokenScope, expectedAuthStatus, expectedStatus int) {
token := getTokenForLoggedInUser(t, session, scope)
- req := NewRequest(t, "GET", fmt.Sprintf("%sv2/token", setting.AppURL))
+ req := NewRequest(t, "GET", setting.AppURL+"v2/token")
req.SetBasicAuth(user.Name, token)
resp := MakeRequest(t, req, expectedAuthStatus)
@@ -190,8 +191,8 @@ func TestPackageContainer(t *testing.T) {
assert.NotEmpty(t, tokenResponse.Token)
- req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)).
- AddTokenAuth(fmt.Sprintf("Bearer %s", tokenResponse.Token))
+ req = NewRequest(t, "GET", setting.AppURL+"v2").
+ AddTokenAuth("Bearer " + tokenResponse.Token)
MakeRequest(t, req, expectedStatus)
}
testCase(auth_model.AccessTokenScopeReadPackage, http.StatusOK, http.StatusOK)
@@ -204,17 +205,17 @@ func TestPackageContainer(t *testing.T) {
t.Run("DetermineSupport", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)).
+ req := NewRequest(t, "GET", setting.AppURL+"v2").
AddTokenAuth(userToken)
resp := MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "registry/2.0", resp.Header().Get("Docker-Distribution-Api-Version"))
- req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)).
+ req = NewRequest(t, "GET", setting.AppURL+"v2").
AddTokenAuth(readToken)
resp = MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "registry/2.0", resp.Header().Get("Docker-Distribution-Api-Version"))
- req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)).
+ req = NewRequest(t, "GET", setting.AppURL+"v2").
AddTokenAuth(badToken)
MakeRequest(t, req, http.StatusUnauthorized)
})
@@ -226,15 +227,15 @@ func TestPackageContainer(t *testing.T) {
t.Run("UploadBlob/Monolithic", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)).
+ req := NewRequest(t, "POST", url+"/blobs/uploads").
AddTokenAuth(anonymousToken)
MakeRequest(t, req, http.StatusUnauthorized)
- req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)).
+ req = NewRequest(t, "POST", url+"/blobs/uploads").
AddTokenAuth(readToken)
MakeRequest(t, req, http.StatusUnauthorized)
- req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)).
+ req = NewRequest(t, "POST", url+"/blobs/uploads").
AddTokenAuth(badToken)
MakeRequest(t, req, http.StatusUnauthorized)
@@ -264,15 +265,15 @@ func TestPackageContainer(t *testing.T) {
t.Run("UploadBlob/Chunked", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)).
+ req := NewRequest(t, "POST", url+"/blobs/uploads").
AddTokenAuth(readToken)
MakeRequest(t, req, http.StatusUnauthorized)
- req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)).
+ req = NewRequest(t, "POST", url+"/blobs/uploads").
AddTokenAuth(badToken)
MakeRequest(t, req, http.StatusUnauthorized)
- req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)).
+ req = NewRequest(t, "POST", url+"/blobs/uploads").
AddTokenAuth(userToken)
resp := MakeRequest(t, req, http.StatusAccepted)
@@ -325,7 +326,7 @@ func TestPackageContainer(t *testing.T) {
t.Run("Cancel", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)).
+ req := NewRequest(t, "POST", url+"/blobs/uploads").
AddTokenAuth(userToken)
resp := MakeRequest(t, req, http.StatusAccepted)
@@ -467,7 +468,7 @@ func TestPackageContainer(t *testing.T) {
t.Run("HeadManifest", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/unknown-tag", url)).
+ req := NewRequest(t, "HEAD", url+"/manifests/unknown-tag").
AddTokenAuth(userToken)
MakeRequest(t, req, http.StatusNotFound)
@@ -475,14 +476,14 @@ func TestPackageContainer(t *testing.T) {
AddTokenAuth(userToken)
resp := MakeRequest(t, req, http.StatusOK)
- assert.Equal(t, fmt.Sprintf("%d", len(manifestContent)), resp.Header().Get("Content-Length"))
+ assert.Equal(t, strconv.Itoa(len(manifestContent)), resp.Header().Get("Content-Length"))
assert.Equal(t, manifestDigest, resp.Header().Get("Docker-Content-Digest"))
})
t.Run("GetManifest", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%s/manifests/unknown-tag", url)).
+ req := NewRequest(t, "GET", url+"/manifests/unknown-tag").
AddTokenAuth(userToken)
MakeRequest(t, req, http.StatusNotFound)
@@ -490,7 +491,7 @@ func TestPackageContainer(t *testing.T) {
AddTokenAuth(userToken)
resp := MakeRequest(t, req, http.StatusOK)
- assert.Equal(t, fmt.Sprintf("%d", len(manifestContent)), resp.Header().Get("Content-Length"))
+ assert.Equal(t, strconv.Itoa(len(manifestContent)), resp.Header().Get("Content-Length"))
assert.Equal(t, oci.MediaTypeImageManifest, resp.Header().Get("Content-Type"))
assert.Equal(t, manifestDigest, resp.Header().Get("Docker-Content-Digest"))
assert.Equal(t, manifestContent, resp.Body.String())
@@ -512,7 +513,7 @@ func TestPackageContainer(t *testing.T) {
AddTokenAuth(userToken)
resp = MakeRequest(t, req, http.StatusOK)
- assert.Equal(t, fmt.Sprintf("%d", len(untaggedManifestContent)), resp.Header().Get("Content-Length"))
+ assert.Equal(t, strconv.Itoa(len(untaggedManifestContent)), resp.Header().Get("Content-Length"))
assert.Equal(t, untaggedManifestDigest, resp.Header().Get("Docker-Content-Digest"))
pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, untaggedManifestDigest)
@@ -598,7 +599,7 @@ func TestPackageContainer(t *testing.T) {
AddTokenAuth(userToken)
resp := MakeRequest(t, req, http.StatusOK)
- assert.Equal(t, fmt.Sprintf("%d", len(blobContent)), resp.Header().Get("Content-Length"))
+ assert.Equal(t, strconv.Itoa(len(blobContent)), resp.Header().Get("Content-Length"))
assert.Equal(t, blobDigest, resp.Header().Get("Docker-Content-Digest"))
req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)).
@@ -617,7 +618,7 @@ func TestPackageContainer(t *testing.T) {
AddTokenAuth(userToken)
resp := MakeRequest(t, req, http.StatusOK)
- assert.Equal(t, fmt.Sprintf("%d", len(blobContent)), resp.Header().Get("Content-Length"))
+ assert.Equal(t, strconv.Itoa(len(blobContent)), resp.Header().Get("Content-Length"))
assert.Equal(t, blobDigest, resp.Header().Get("Docker-Content-Digest"))
assert.Equal(t, blobContent, resp.Body.Bytes())
})
@@ -631,27 +632,27 @@ func TestPackageContainer(t *testing.T) {
ExpectedLink string
}{
{
- URL: fmt.Sprintf("%s/tags/list", url),
+ URL: url + "/tags/list",
ExpectedTags: []string{"latest", "main", "multi"},
ExpectedLink: fmt.Sprintf(`; rel="next"`, user.Name, image),
},
{
- URL: fmt.Sprintf("%s/tags/list?n=0", url),
+ URL: url + "/tags/list?n=0",
ExpectedTags: []string{},
ExpectedLink: "",
},
{
- URL: fmt.Sprintf("%s/tags/list?n=2", url),
+ URL: url + "/tags/list?n=2",
ExpectedTags: []string{"latest", "main"},
ExpectedLink: fmt.Sprintf(`; rel="next"`, user.Name, image),
},
{
- URL: fmt.Sprintf("%s/tags/list?last=main", url),
+ URL: url + "/tags/list?last=main",
ExpectedTags: []string{"multi"},
ExpectedLink: fmt.Sprintf(`; rel="next"`, user.Name, image),
},
{
- URL: fmt.Sprintf("%s/tags/list?n=1&last=latest", url),
+ URL: url + "/tags/list?n=1&last=latest",
ExpectedTags: []string{"main"},
ExpectedLink: fmt.Sprintf(`; rel="next"`, user.Name, image),
},
@@ -757,7 +758,7 @@ func TestPackageContainer(t *testing.T) {
return func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%sv2/_catalog", setting.AppURL)).
+ req := NewRequest(t, "GET", setting.AppURL+"v2/_catalog").
AddTokenAuth(userToken)
resp := MakeRequest(t, req, http.StatusOK)
diff --git a/tests/integration/api_packages_cran_test.go b/tests/integration/api_packages_cran_test.go
index 667ba0908c..bd4a99f331 100644
--- a/tests/integration/api_packages_cran_test.go
+++ b/tests/integration/api_packages_cran_test.go
@@ -133,8 +133,8 @@ func TestPackageCran(t *testing.T) {
assert.Contains(t, resp.Header().Get("Content-Type"), "text/plain")
body := resp.Body.String()
- assert.Contains(t, body, fmt.Sprintf("Package: %s", packageName))
- assert.Contains(t, body, fmt.Sprintf("Version: %s", packageVersion))
+ assert.Contains(t, body, "Package: "+packageName)
+ assert.Contains(t, body, "Version: "+packageVersion)
req = NewRequest(t, "GET", url+"/src/contrib/PACKAGES.gz").
AddBasicAuth(user.Name)
@@ -230,8 +230,8 @@ func TestPackageCran(t *testing.T) {
assert.Contains(t, resp.Header().Get("Content-Type"), "text/plain")
body := resp.Body.String()
- assert.Contains(t, body, fmt.Sprintf("Package: %s", packageName))
- assert.Contains(t, body, fmt.Sprintf("Version: %s", packageVersion))
+ assert.Contains(t, body, "Package: "+packageName)
+ assert.Contains(t, body, "Version: "+packageVersion)
req = NewRequest(t, "GET", url+"/bin/windows/contrib/4.2/PACKAGES.gz").
AddBasicAuth(user.Name)
diff --git a/tests/integration/api_packages_helm_test.go b/tests/integration/api_packages_helm_test.go
index 76285add11..8f5c6ac571 100644
--- a/tests/integration/api_packages_helm_test.go
+++ b/tests/integration/api_packages_helm_test.go
@@ -52,7 +52,7 @@ dependencies:
zw := gzip.NewWriter(&buf)
archive := tar.NewWriter(zw)
archive.WriteHeader(&tar.Header{
- Name: fmt.Sprintf("%s/Chart.yaml", packageName),
+ Name: packageName + "/Chart.yaml",
Mode: 0o600,
Size: int64(len(chartContent)),
})
@@ -122,7 +122,7 @@ dependencies:
t.Run("Index", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%s/index.yaml", url)).
+ req := NewRequest(t, "GET", url+"/index.yaml").
AddBasicAuth(user.Name)
resp := MakeRequest(t, req, http.StatusOK)
diff --git a/tests/integration/api_packages_npm_test.go b/tests/integration/api_packages_npm_test.go
index ae1dd876f7..a190ed679d 100644
--- a/tests/integration/api_packages_npm_test.go
+++ b/tests/integration/api_packages_npm_test.go
@@ -28,7 +28,7 @@ func TestPackageNpm(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
- token := fmt.Sprintf("Bearer %s", getTokenForLoggedInUser(t, loginUser(t, user.Name), auth_model.AccessTokenScopeWritePackage))
+ token := "Bearer " + getTokenForLoggedInUser(t, loginUser(t, user.Name), auth_model.AccessTokenScopeWritePackage)
packageName := "@scope/test-package"
packageVersion := "1.0.1-pre"
diff --git a/tests/integration/api_packages_nuget_test.go b/tests/integration/api_packages_nuget_test.go
index 164fe04725..c0e69a82cd 100644
--- a/tests/integration/api_packages_nuget_test.go
+++ b/tests/integration/api_packages_nuget_test.go
@@ -198,7 +198,7 @@ func TestPackageNuGet(t *testing.T) {
t.Run(c.Owner, func(t *testing.T) {
url := fmt.Sprintf("/api/packages/%s/nuget", c.Owner)
- req := NewRequest(t, "GET", fmt.Sprintf("%s/index.json", url))
+ req := NewRequest(t, "GET", url+"/index.json")
if c.UseBasicAuth {
req.AddBasicAuth(user.Name)
} else if c.token != "" {
@@ -273,7 +273,7 @@ func TestPackageNuGet(t *testing.T) {
pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID)
assert.NoError(t, err)
assert.Equal(t, int64(len(content)), pb.Size)
- case fmt.Sprintf("%s.nuspec", packageName):
+ case packageName + ".nuspec":
assert.False(t, pf.IsLead)
default:
assert.Fail(t, "unexpected filename", "unexpected filename: %v", pf.Name)
@@ -319,7 +319,7 @@ func TestPackageNuGet(t *testing.T) {
pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID)
assert.NoError(t, err)
assert.Equal(t, int64(len(content)), pb.Size)
- case fmt.Sprintf("%s.nuspec", packageName):
+ case packageName + ".nuspec":
assert.False(t, pf.IsLead)
default:
assert.Fail(t, "unexpected filename", "unexpected filename: %v", pf.Name)
@@ -360,15 +360,15 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`)
return &buf
}
- req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage("unknown-package", "SymbolsPackage")).
+ req := NewRequestWithBody(t, "PUT", url+"/symbolpackage", createSymbolPackage("unknown-package", "SymbolsPackage")).
AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusNotFound)
- req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "DummyPackage")).
+ req = NewRequestWithBody(t, "PUT", url+"/symbolpackage", createSymbolPackage(packageName, "DummyPackage")).
AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusBadRequest)
- req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "SymbolsPackage")).
+ req = NewRequestWithBody(t, "PUT", url+"/symbolpackage", createSymbolPackage(packageName, "SymbolsPackage")).
AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusCreated)
@@ -400,7 +400,7 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`)
pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID)
assert.NoError(t, err)
assert.Equal(t, int64(616), pb.Size)
- case fmt.Sprintf("%s.nuspec", packageName):
+ case packageName + ".nuspec":
assert.False(t, pf.IsLead)
pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID)
@@ -423,7 +423,7 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`)
}
}
- req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "SymbolsPackage")).
+ req = NewRequestWithBody(t, "PUT", url+"/symbolpackage", createSymbolPackage(packageName, "SymbolsPackage")).
AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusConflict)
})
@@ -631,7 +631,7 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`)
})
t.Run("Next", func(t *testing.T) {
- req := NewRequest(t, "GET", fmt.Sprintf("%s/Search()?searchTerm='test'&$skip=0&$top=1", url)).
+ req := NewRequest(t, "GET", url+"/Search()?searchTerm='test'&$skip=0&$top=1").
AddBasicAuth(user.Name)
resp := MakeRequest(t, req, http.StatusOK)
diff --git a/tests/integration/api_packages_pub_test.go b/tests/integration/api_packages_pub_test.go
index 11da894ddf..3c1bca908e 100644
--- a/tests/integration/api_packages_pub_test.go
+++ b/tests/integration/api_packages_pub_test.go
@@ -37,7 +37,7 @@ func TestPackagePub(t *testing.T) {
packageVersion := "1.0.1"
packageDescription := "Test Description"
- filename := fmt.Sprintf("%s.tar.gz", packageVersion)
+ filename := packageVersion + ".tar.gz"
pubspecContent := `name: ` + packageName + `
version: ` + packageVersion + `
diff --git a/tests/integration/api_packages_pypi_test.go b/tests/integration/api_packages_pypi_test.go
index 2dabb5005b..54db45f1ac 100644
--- a/tests/integration/api_packages_pypi_test.go
+++ b/tests/integration/api_packages_pypi_test.go
@@ -67,7 +67,7 @@ func TestPackagePyPI(t *testing.T) {
body, writer, closeFunc := createBasicMultipartFile(filename, packageName, content)
writer.WriteField("project_urls", "DOCUMENTATION , https://readthedocs.org")
- writer.WriteField("project_urls", fmt.Sprintf("Home-page, %s", projectURL))
+ writer.WriteField("project_urls", "Home-page, "+projectURL)
_ = closeFunc()
diff --git a/tests/integration/api_packages_rubygems_test.go b/tests/integration/api_packages_rubygems_test.go
index fe9283df4d..ab76c52440 100644
--- a/tests/integration/api_packages_rubygems_test.go
+++ b/tests/integration/api_packages_rubygems_test.go
@@ -185,7 +185,7 @@ func TestPackageRubyGems(t *testing.T) {
root := fmt.Sprintf("/api/packages/%s/rubygems", user.Name)
uploadFile := func(t *testing.T, content []byte, expectedStatus int) {
- req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/api/v1/gems", root), bytes.NewReader(content)).
+ req := NewRequestWithBody(t, "POST", root+"/api/v1/gems", bytes.NewReader(content)).
AddBasicAuth(user.Name)
MakeRequest(t, req, expectedStatus)
}
@@ -293,7 +293,7 @@ gAAAAP//MS06Gw==`)
t.Run("Versions", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%s/versions", root)).AddBasicAuth(user.Name)
+ req := NewRequest(t, "GET", root+"/versions").AddBasicAuth(user.Name)
resp := MakeRequest(t, req, http.StatusOK)
assert.Equal(t, `---
gitea 1.0.5 08843c2dd0ea19910e6b056b98e38f1c
@@ -307,7 +307,7 @@ gitea-another 0.99 8b639e4048d282941485368ec42609be
_ = writer.WriteField("gem_name", packageName)
_ = writer.WriteField("version", packageVersion)
_ = writer.Close()
- req := NewRequestWithBody(t, "DELETE", fmt.Sprintf("%s/api/v1/gems/yank", root), &body).
+ req := NewRequestWithBody(t, "DELETE", root+"/api/v1/gems/yank", &body).
SetHeader("Content-Type", writer.FormDataContentType()).
AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusOK)
@@ -330,7 +330,7 @@ gitea-another 0.99 8b639e4048d282941485368ec42609be
t.Run("VersionsAfterDelete", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("%s/versions", root)).AddBasicAuth(user.Name)
+ req := NewRequest(t, "GET", root+"/versions").AddBasicAuth(user.Name)
resp := MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "---\n", resp.Body.String())
})
diff --git a/tests/integration/api_packages_test.go b/tests/integration/api_packages_test.go
index b1abb1478a..8a9565f087 100644
--- a/tests/integration/api_packages_test.go
+++ b/tests/integration/api_packages_test.go
@@ -49,7 +49,7 @@ func TestPackageAPI(t *testing.T) {
t.Run("ListPackages", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s", user.Name)).
+ req := NewRequest(t, "GET", "/api/v1/packages/"+user.Name).
AddTokenAuth(tokenReadPackage)
resp := MakeRequest(t, req, http.StatusOK)
@@ -408,7 +408,7 @@ func TestPackageAccess(t *testing.T) {
{limitedOrgNoMember, http.StatusOK},
{publicOrgNoMember, http.StatusOK},
} {
- req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s", target.Owner.Name)).
+ req := NewRequest(t, "GET", "/api/v1/packages/"+target.Owner.Name).
AddTokenAuth(tokenReadPackage)
MakeRequest(t, req, target.ExpectedStatus)
}
diff --git a/tests/integration/api_packages_vagrant_test.go b/tests/integration/api_packages_vagrant_test.go
index a5e954f3a2..1743e37222 100644
--- a/tests/integration/api_packages_vagrant_test.go
+++ b/tests/integration/api_packages_vagrant_test.go
@@ -35,7 +35,7 @@ func TestPackageVagrant(t *testing.T) {
packageDescription := "Test Description"
packageProvider := "virtualbox"
- filename := fmt.Sprintf("%s.box", packageProvider)
+ filename := packageProvider + ".box"
infoContent, _ := json.Marshal(map[string]string{
"description": packageDescription,
@@ -59,7 +59,7 @@ func TestPackageVagrant(t *testing.T) {
t.Run("Authenticate", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- authenticateURL := fmt.Sprintf("%s/authenticate", root)
+ authenticateURL := root + "/authenticate"
req := NewRequest(t, "GET", authenticateURL)
MakeRequest(t, req, http.StatusUnauthorized)
diff --git a/tests/integration/api_pull_test.go b/tests/integration/api_pull_test.go
index 831129c6df..f3165c6fc5 100644
--- a/tests/integration/api_pull_test.go
+++ b/tests/integration/api_pull_test.go
@@ -193,7 +193,7 @@ func TestAPICreatePullSuccess(t *testing.T) {
session := loginUser(t, owner11.Name)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), &api.CreatePullRequestOption{
- Head: fmt.Sprintf("%s:master", owner11.Name),
+ Head: owner11.Name + ":master",
Base: "master",
Title: "create a failure pr",
}).AddTokenAuth(token)
@@ -213,7 +213,7 @@ func TestAPICreatePullBasePermission(t *testing.T) {
session := loginUser(t, user4.Name)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
opts := &api.CreatePullRequestOption{
- Head: fmt.Sprintf("%s:master", repo11.OwnerName),
+ Head: repo11.OwnerName + ":master",
Base: "master",
Title: "create a failure pr",
}
@@ -241,7 +241,7 @@ func TestAPICreatePullHeadPermission(t *testing.T) {
session := loginUser(t, user4.Name)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
opts := &api.CreatePullRequestOption{
- Head: fmt.Sprintf("%s:master", repo11.OwnerName),
+ Head: repo11.OwnerName + ":master",
Base: "master",
Title: "create a failure pr",
}
@@ -269,7 +269,7 @@ func TestAPICreatePullSameRepoSuccess(t *testing.T) {
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner.Name, repo.Name), &api.CreatePullRequestOption{
- Head: fmt.Sprintf("%s:pr-to-update", owner.Name),
+ Head: owner.Name + ":pr-to-update",
Base: "master",
Title: "successfully create a PR between branches of the same repository",
}).AddTokenAuth(token)
@@ -290,7 +290,7 @@ func TestAPICreatePullWithFieldsSuccess(t *testing.T) {
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
opts := &api.CreatePullRequestOption{
- Head: fmt.Sprintf("%s:master", owner11.Name),
+ Head: owner11.Name + ":master",
Base: "master",
Title: "create a failure pr",
Body: "foobaaar",
@@ -328,7 +328,7 @@ func TestAPICreatePullWithFieldsFailure(t *testing.T) {
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
opts := &api.CreatePullRequestOption{
- Head: fmt.Sprintf("%s:master", owner11.Name),
+ Head: owner11.Name + ":master",
Base: "master",
}
diff --git a/tests/integration/api_repo_branch_test.go b/tests/integration/api_repo_branch_test.go
index d897151a29..066eb366b1 100644
--- a/tests/integration/api_repo_branch_test.go
+++ b/tests/integration/api_repo_branch_test.go
@@ -4,11 +4,11 @@
package integration
import (
- "bytes"
"fmt"
"io"
"net/http"
"net/url"
+ "strings"
"testing"
auth_model "code.gitea.io/gitea/models/auth"
@@ -59,7 +59,7 @@ func TestAPIRepoBranchesPlain(t *testing.T) {
req := NewRequest(t, "POST", link.String()).AddTokenAuth(token)
req.Header.Add("Content-Type", "application/json")
- req.Body = io.NopCloser(bytes.NewBufferString(`{"new_branch_name":"test_branch2", "old_branch_name": "test_branch", "old_ref_name":"refs/heads/test_branch"}`))
+ req.Body = io.NopCloser(strings.NewReader(`{"new_branch_name":"test_branch2", "old_branch_name": "test_branch", "old_ref_name":"refs/heads/test_branch"}`))
resp = MakeRequest(t, req, http.StatusCreated)
bs, err = io.ReadAll(resp.Body)
assert.NoError(t, err)
@@ -117,7 +117,7 @@ func TestAPIRepoBranchesMirror(t *testing.T) {
req := NewRequest(t, "POST", link.String()).AddTokenAuth(token)
req.Header.Add("Content-Type", "application/json")
- req.Body = io.NopCloser(bytes.NewBufferString(`{"new_branch_name":"test_branch2", "old_branch_name": "test_branch", "old_ref_name":"refs/heads/test_branch"}`))
+ req.Body = io.NopCloser(strings.NewReader(`{"new_branch_name":"test_branch2", "old_branch_name": "test_branch", "old_ref_name":"refs/heads/test_branch"}`))
resp = MakeRequest(t, req, http.StatusForbidden)
bs, err = io.ReadAll(resp.Body)
assert.NoError(t, err)
diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go
index 6273ffa6e3..672c2a2c8b 100644
--- a/tests/integration/api_repo_test.go
+++ b/tests/integration/api_repo_test.go
@@ -45,7 +45,7 @@ func TestAPIUserReposNotLogin(t *testing.T) {
func TestAPIUserReposWithWrongToken(t *testing.T) {
defer tests.PrepareTestEnv(t)()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
- wrongToken := fmt.Sprintf("Bearer %s", "wrong_token")
+ wrongToken := "Bearer " + "wrong_token"
req := NewRequestf(t, "GET", "/api/v1/users/%s/repos", user.Name).
AddTokenAuth(wrongToken)
resp := MakeRequest(t, req, http.StatusUnauthorized)
diff --git a/tests/integration/api_user_block_test.go b/tests/integration/api_user_block_test.go
index ae6b9eb849..6f73b089df 100644
--- a/tests/integration/api_user_block_test.go
+++ b/tests/integration/api_user_block_test.go
@@ -76,7 +76,7 @@ func TestBlockUser(t *testing.T) {
blockeeName := "user10"
t.Run("Block", func(t *testing.T) {
- req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/blocks/%s", blockeeName))
+ req := NewRequest(t, "PUT", "/api/v1/user/blocks/"+blockeeName)
MakeRequest(t, req, http.StatusUnauthorized)
assert.EqualValues(t, 1, countStars(t, blockerID, blockeeID))
@@ -84,7 +84,7 @@ func TestBlockUser(t *testing.T) {
assert.EqualValues(t, 1, countRepositoryTransfers(t, blockerID, blockeeID))
assert.EqualValues(t, 1, countCollaborations(t, blockerID, blockeeID))
- req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/blocks/%s", blockeeName)).
+ req = NewRequest(t, "GET", "/api/v1/user/blocks/"+blockeeName).
AddTokenAuth(blockerToken)
MakeRequest(t, req, http.StatusNotFound)
@@ -97,15 +97,15 @@ func TestBlockUser(t *testing.T) {
assert.EqualValues(t, 0, countRepositoryTransfers(t, blockerID, blockeeID))
assert.EqualValues(t, 0, countCollaborations(t, blockerID, blockeeID))
- req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/blocks/%s", blockeeName)).
+ req = NewRequest(t, "GET", "/api/v1/user/blocks/"+blockeeName).
AddTokenAuth(blockerToken)
MakeRequest(t, req, http.StatusNoContent)
- req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/blocks/%s", blockeeName)).
+ req = NewRequest(t, "PUT", "/api/v1/user/blocks/"+blockeeName).
AddTokenAuth(blockerToken)
MakeRequest(t, req, http.StatusBadRequest) // can't block blocked user
- req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/blocks/%s", "org3")).
+ req = NewRequest(t, "PUT", "/api/v1/user/blocks/"+"org3").
AddTokenAuth(blockerToken)
MakeRequest(t, req, http.StatusBadRequest) // can't block organization
@@ -124,18 +124,18 @@ func TestBlockUser(t *testing.T) {
})
t.Run("Unblock", func(t *testing.T) {
- req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/blocks/%s", blockeeName))
+ req := NewRequest(t, "DELETE", "/api/v1/user/blocks/"+blockeeName)
MakeRequest(t, req, http.StatusUnauthorized)
- req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/blocks/%s", blockeeName)).
+ req = NewRequest(t, "DELETE", "/api/v1/user/blocks/"+blockeeName).
AddTokenAuth(blockerToken)
MakeRequest(t, req, http.StatusNoContent)
- req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/blocks/%s", blockeeName)).
+ req = NewRequest(t, "DELETE", "/api/v1/user/blocks/"+blockeeName).
AddTokenAuth(blockerToken)
MakeRequest(t, req, http.StatusBadRequest)
- req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/blocks/%s", "org3")).
+ req = NewRequest(t, "DELETE", "/api/v1/user/blocks/"+"org3").
AddTokenAuth(blockerToken)
MakeRequest(t, req, http.StatusBadRequest)
diff --git a/tests/integration/api_user_follow_test.go b/tests/integration/api_user_follow_test.go
index fe20af6769..6cb31a6802 100644
--- a/tests/integration/api_user_follow_test.go
+++ b/tests/integration/api_user_follow_test.go
@@ -32,7 +32,7 @@ func TestAPIFollow(t *testing.T) {
t.Run("Follow", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/following/%s", user1)).
+ req := NewRequest(t, "PUT", "/api/v1/user/following/"+user1).
AddTokenAuth(token2)
MakeRequest(t, req, http.StatusNoContent)
@@ -110,11 +110,11 @@ func TestAPIFollow(t *testing.T) {
t.Run("CheckMyFollowing", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following/%s", user1)).
+ req := NewRequest(t, "GET", "/api/v1/user/following/"+user1).
AddTokenAuth(token2)
MakeRequest(t, req, http.StatusNoContent)
- req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following/%s", user2)).
+ req = NewRequest(t, "GET", "/api/v1/user/following/"+user2).
AddTokenAuth(token1)
MakeRequest(t, req, http.StatusNotFound)
})
@@ -122,7 +122,7 @@ func TestAPIFollow(t *testing.T) {
t.Run("Unfollow", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/following/%s", user1)).
+ req := NewRequest(t, "DELETE", "/api/v1/user/following/"+user1).
AddTokenAuth(token2)
MakeRequest(t, req, http.StatusNoContent)
})
diff --git a/tests/integration/api_user_info_test.go b/tests/integration/api_user_info_test.go
index 89f7266859..06353eabe0 100644
--- a/tests/integration/api_user_info_test.go
+++ b/tests/integration/api_user_info_test.go
@@ -4,7 +4,6 @@
package integration
import (
- "fmt"
"net/http"
"testing"
@@ -31,7 +30,7 @@ func TestAPIUserInfo(t *testing.T) {
t.Run("GetInfo", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s", user2)).
+ req := NewRequest(t, "GET", "/api/v1/users/"+user2).
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
@@ -39,17 +38,17 @@ func TestAPIUserInfo(t *testing.T) {
DecodeJSON(t, resp, &u)
assert.Equal(t, user2, u.UserName)
- req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s", user2))
+ req = NewRequest(t, "GET", "/api/v1/users/"+user2)
MakeRequest(t, req, http.StatusNotFound)
// test if the placaholder Mail is returned if a User is not logged in
- req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s", org3.Name))
+ req = NewRequest(t, "GET", "/api/v1/users/"+org3.Name)
resp = MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &u)
assert.Equal(t, org3.GetPlaceholderEmail(), u.Email)
// Test if the correct Mail is returned if a User is logged in
- req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s", org3.Name)).
+ req = NewRequest(t, "GET", "/api/v1/users/"+org3.Name).
AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &u)
diff --git a/tests/integration/api_user_secrets_test.go b/tests/integration/api_user_secrets_test.go
index 56bf30e804..10024ac090 100644
--- a/tests/integration/api_user_secrets_test.go
+++ b/tests/integration/api_user_secrets_test.go
@@ -4,7 +4,6 @@
package integration
import (
- "fmt"
"net/http"
"testing"
@@ -55,7 +54,7 @@ func TestAPIUserSecrets(t *testing.T) {
}
for _, c := range cases {
- req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/user/actions/secrets/%s", c.Name), api.CreateOrUpdateSecretOption{
+ req := NewRequestWithJSON(t, "PUT", "/api/v1/user/actions/secrets/"+c.Name, api.CreateOrUpdateSecretOption{
Data: "data",
}).AddTokenAuth(token)
MakeRequest(t, req, c.ExpectedStatus)
@@ -64,7 +63,7 @@ func TestAPIUserSecrets(t *testing.T) {
t.Run("Update", func(t *testing.T) {
name := "update_secret"
- url := fmt.Sprintf("/api/v1/user/actions/secrets/%s", name)
+ url := "/api/v1/user/actions/secrets/" + name
req := NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{
Data: "initial",
@@ -79,7 +78,7 @@ func TestAPIUserSecrets(t *testing.T) {
t.Run("Delete", func(t *testing.T) {
name := "delete_secret"
- url := fmt.Sprintf("/api/v1/user/actions/secrets/%s", name)
+ url := "/api/v1/user/actions/secrets/" + name
req := NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{
Data: "initial",
diff --git a/tests/integration/api_user_star_test.go b/tests/integration/api_user_star_test.go
index 368756528a..989e7ab1d1 100644
--- a/tests/integration/api_user_star_test.go
+++ b/tests/integration/api_user_star_test.go
@@ -32,13 +32,13 @@ func TestAPIStar(t *testing.T) {
t.Run("Star", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/starred/%s", repo)).
+ req := NewRequest(t, "PUT", "/api/v1/user/starred/"+repo).
AddTokenAuth(tokenWithUserScope)
MakeRequest(t, req, http.StatusNoContent)
// blocked user can't star a repo
user34 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 34})
- req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/starred/%s", repo)).
+ req = NewRequest(t, "PUT", "/api/v1/user/starred/"+repo).
AddTokenAuth(getUserToken(t, user34.Name, auth_model.AccessTokenScopeWriteRepository))
MakeRequest(t, req, http.StatusForbidden)
})
@@ -76,11 +76,11 @@ func TestAPIStar(t *testing.T) {
t.Run("IsStarring", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s", repo)).
+ req := NewRequest(t, "GET", "/api/v1/user/starred/"+repo).
AddTokenAuth(tokenWithUserScope)
MakeRequest(t, req, http.StatusNoContent)
- req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s", repo+"notexisting")).
+ req = NewRequest(t, "GET", "/api/v1/user/starred/"+repo+"notexisting").
AddTokenAuth(tokenWithUserScope)
MakeRequest(t, req, http.StatusNotFound)
})
@@ -88,7 +88,7 @@ func TestAPIStar(t *testing.T) {
t.Run("Unstar", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/starred/%s", repo)).
+ req := NewRequest(t, "DELETE", "/api/v1/user/starred/"+repo).
AddTokenAuth(tokenWithUserScope)
MakeRequest(t, req, http.StatusNoContent)
})
@@ -109,12 +109,12 @@ func TestAPIStarDisabled(t *testing.T) {
t.Run("Star", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/starred/%s", repo)).
+ req := NewRequest(t, "PUT", "/api/v1/user/starred/"+repo).
AddTokenAuth(tokenWithUserScope)
MakeRequest(t, req, http.StatusForbidden)
user34 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 34})
- req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/starred/%s", repo)).
+ req = NewRequest(t, "PUT", "/api/v1/user/starred/"+repo).
AddTokenAuth(getUserToken(t, user34.Name, auth_model.AccessTokenScopeWriteRepository))
MakeRequest(t, req, http.StatusForbidden)
})
@@ -138,11 +138,11 @@ func TestAPIStarDisabled(t *testing.T) {
t.Run("IsStarring", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s", repo)).
+ req := NewRequest(t, "GET", "/api/v1/user/starred/"+repo).
AddTokenAuth(tokenWithUserScope)
MakeRequest(t, req, http.StatusForbidden)
- req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s", repo+"notexisting")).
+ req = NewRequest(t, "GET", "/api/v1/user/starred/"+repo+"notexisting").
AddTokenAuth(tokenWithUserScope)
MakeRequest(t, req, http.StatusForbidden)
})
@@ -150,7 +150,7 @@ func TestAPIStarDisabled(t *testing.T) {
t.Run("Unstar", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
- req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/starred/%s", repo)).
+ req := NewRequest(t, "DELETE", "/api/v1/user/starred/"+repo).
AddTokenAuth(tokenWithUserScope)
MakeRequest(t, req, http.StatusForbidden)
})
diff --git a/tests/integration/api_user_variables_test.go b/tests/integration/api_user_variables_test.go
index 9fd84ddf81..367b83e7d4 100644
--- a/tests/integration/api_user_variables_test.go
+++ b/tests/integration/api_user_variables_test.go
@@ -4,7 +4,6 @@
package integration
import (
- "fmt"
"net/http"
"testing"
@@ -63,7 +62,7 @@ func TestAPIUserVariables(t *testing.T) {
}
for _, c := range cases {
- req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/actions/variables/%s", c.Name), api.CreateVariableOption{
+ req := NewRequestWithJSON(t, "POST", "/api/v1/user/actions/variables/"+c.Name, api.CreateVariableOption{
Value: "value",
}).AddTokenAuth(token)
MakeRequest(t, req, c.ExpectedStatus)
@@ -72,7 +71,7 @@ func TestAPIUserVariables(t *testing.T) {
t.Run("UpdateUserVariable", func(t *testing.T) {
variableName := "test_update_var"
- url := fmt.Sprintf("/api/v1/user/actions/variables/%s", variableName)
+ url := "/api/v1/user/actions/variables/" + variableName
req := NewRequestWithJSON(t, "POST", url, api.CreateVariableOption{
Value: "initial_val",
}).AddTokenAuth(token)
@@ -118,7 +117,7 @@ func TestAPIUserVariables(t *testing.T) {
}
for _, c := range cases {
- req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/user/actions/variables/%s", c.Name), api.UpdateVariableOption{
+ req := NewRequestWithJSON(t, "PUT", "/api/v1/user/actions/variables/"+c.Name, api.UpdateVariableOption{
Name: c.UpdateName,
Value: "updated_val",
}).AddTokenAuth(token)
@@ -128,7 +127,7 @@ func TestAPIUserVariables(t *testing.T) {
t.Run("DeleteRepoVariable", func(t *testing.T) {
variableName := "test_delete_var"
- url := fmt.Sprintf("/api/v1/user/actions/variables/%s", variableName)
+ url := "/api/v1/user/actions/variables/" + variableName
req := NewRequestWithJSON(t, "POST", url, api.CreateVariableOption{
Value: "initial_val",
diff --git a/tests/integration/delete_user_test.go b/tests/integration/delete_user_test.go
index ad3c882882..4b02c4725a 100644
--- a/tests/integration/delete_user_test.go
+++ b/tests/integration/delete_user_test.go
@@ -4,7 +4,6 @@
package integration
import (
- "fmt"
"net/http"
"testing"
@@ -34,7 +33,7 @@ func TestUserDeleteAccount(t *testing.T) {
session := loginUser(t, "user8")
csrf := GetUserCSRFToken(t, session)
- urlStr := fmt.Sprintf("/user/settings/account/delete?password=%s", userPassword)
+ urlStr := "/user/settings/account/delete?password=" + userPassword
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": csrf,
})
@@ -49,7 +48,7 @@ func TestUserDeleteAccountStillOwnRepos(t *testing.T) {
session := loginUser(t, "user2")
csrf := GetUserCSRFToken(t, session)
- urlStr := fmt.Sprintf("/user/settings/account/delete?password=%s", userPassword)
+ urlStr := "/user/settings/account/delete?password=" + userPassword
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": csrf,
})
diff --git a/tests/integration/editor_test.go b/tests/integration/editor_test.go
index c7cec722af..a5936d86de 100644
--- a/tests/integration/editor_test.go
+++ b/tests/integration/editor_test.go
@@ -12,6 +12,7 @@ import (
"net/http/httptest"
"net/url"
"path"
+ "strings"
"testing"
repo_model "code.gitea.io/gitea/models/repo"
@@ -227,7 +228,7 @@ func TestWebGitCommitEmail(t *testing.T) {
body := &bytes.Buffer{}
uploadForm := multipart.NewWriter(body)
file, _ := uploadForm.CreateFormFile("file", name)
- _, _ = io.Copy(file, bytes.NewBufferString(content))
+ _, _ = io.Copy(file, strings.NewReader(content))
_ = uploadForm.WriteField("_csrf", GetUserCSRFToken(t, session))
_ = uploadForm.Close()
diff --git a/tests/integration/empty_repo_test.go b/tests/integration/empty_repo_test.go
index de4f010043..f85d883cc7 100644
--- a/tests/integration/empty_repo_test.go
+++ b/tests/integration/empty_repo_test.go
@@ -11,6 +11,7 @@ import (
"mime/multipart"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
auth_model "code.gitea.io/gitea/models/auth"
@@ -130,7 +131,7 @@ func TestEmptyRepoUploadFile(t *testing.T) {
mpForm := multipart.NewWriter(body)
_ = mpForm.WriteField("_csrf", GetUserCSRFToken(t, session))
file, _ := mpForm.CreateFormFile("file", "uploaded-file.txt")
- _, _ = io.Copy(file, bytes.NewBufferString("newly-uploaded-test-file"))
+ _, _ = io.Copy(file, strings.NewReader("newly-uploaded-test-file"))
_ = mpForm.Close()
req = NewRequestWithBody(t, "POST", "/user30/empty/upload-file", body)
diff --git a/tests/integration/git_general_test.go b/tests/integration/git_general_test.go
index 2e9dd4f435..34fe212d50 100644
--- a/tests/integration/git_general_test.go
+++ b/tests/integration/git_general_test.go
@@ -592,7 +592,7 @@ func doPushCreate(ctx APITestContext, u *url.URL) func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
// create a context for a currently non-existent repository
- ctx.Reponame = fmt.Sprintf("repo-tmp-push-create-%s", u.Scheme)
+ ctx.Reponame = "repo-tmp-push-create-" + u.Scheme
u.Path = ctx.GitPath()
// Create a temporary directory
@@ -623,7 +623,7 @@ func doPushCreate(ctx APITestContext, u *url.URL) func(t *testing.T) {
// Now add a remote that is invalid to "Push To Create"
invalidCtx := ctx
- invalidCtx.Reponame = fmt.Sprintf("invalid/repo-tmp-push-create-%s", u.Scheme)
+ invalidCtx.Reponame = "invalid/repo-tmp-push-create-" + u.Scheme
u.Path = invalidCtx.GitPath()
t.Run("AddInvalidRemote", doGitAddRemote(tmpDir, "invalid", u))
diff --git a/tests/integration/git_helper_for_declarative_test.go b/tests/integration/git_helper_for_declarative_test.go
index fce9b8f247..7d42508bfe 100644
--- a/tests/integration/git_helper_for_declarative_test.go
+++ b/tests/integration/git_helper_for_declarative_test.go
@@ -123,7 +123,7 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) {
// forcibly set default branch to master
_, _, err := git.NewCommand("symbolic-ref", "HEAD", git.BranchPrefix+"master").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
- assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0o644))
+ assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte("# Testing Repository\n\nOriginally created in: "+dstPath), 0o644))
assert.NoError(t, git.AddChanges(dstPath, true))
signature := git.Signature{
Email: "test@example.com",
@@ -163,7 +163,7 @@ func doGitAddSomeCommits(dstPath, branch string) func(*testing.T) {
return func(t *testing.T) {
doGitCheckoutBranch(dstPath, branch)(t)
- assert.NoError(t, os.WriteFile(filepath.Join(dstPath, fmt.Sprintf("file-%s.txt", branch)), []byte(fmt.Sprintf("file %s", branch)), 0o644))
+ assert.NoError(t, os.WriteFile(filepath.Join(dstPath, fmt.Sprintf("file-%s.txt", branch)), []byte("file "+branch), 0o644))
assert.NoError(t, git.AddChanges(dstPath, true))
signature := git.Signature{
Email: "test@test.test",
@@ -172,7 +172,7 @@ func doGitAddSomeCommits(dstPath, branch string) func(*testing.T) {
assert.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{
Committer: &signature,
Author: &signature,
- Message: fmt.Sprintf("update %s", branch),
+ Message: "update " + branch,
}))
}
}
diff --git a/tests/integration/gpg_git_test.go b/tests/integration/gpg_git_test.go
index c661e54280..32de200f63 100644
--- a/tests/integration/gpg_git_test.go
+++ b/tests/integration/gpg_git_test.go
@@ -238,7 +238,7 @@ func crudActionCreateFile(_ *testing.T, ctx APITestContext, user *user_model.Use
Email: user.Email,
},
},
- ContentBase64: base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("This is new text for %s", path))),
+ ContentBase64: base64.StdEncoding.EncodeToString([]byte("This is new text for " + path)),
}, callback...)
}
diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go
index 57b70adbf6..d5b7bb7a3e 100644
--- a/tests/integration/integration_test.go
+++ b/tests/integration/integration_test.go
@@ -310,7 +310,7 @@ func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string
func NewRequestWithURLValues(t testing.TB, method, urlStr string, urlValues url.Values) *RequestWrapper {
t.Helper()
- return NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode())).
+ return NewRequestWithBody(t, method, urlStr, strings.NewReader(urlValues.Encode())).
SetHeader("Content-Type", "application/x-www-form-urlencoded")
}
diff --git a/tests/integration/issue_test.go b/tests/integration/issue_test.go
index d9746fcda9..f0a5e4f519 100644
--- a/tests/integration/issue_test.go
+++ b/tests/integration/issue_test.go
@@ -195,21 +195,21 @@ func TestEditIssue(t *testing.T) {
session := loginUser(t, "user2")
issueURL := testNewIssue(t, session, "user2", "repo1", "Title", "Description")
- req := NewRequestWithValues(t, "POST", fmt.Sprintf("%s/content", issueURL), map[string]string{
+ req := NewRequestWithValues(t, "POST", issueURL+"/content", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": "modified content",
"context": fmt.Sprintf("/%s/%s", "user2", "repo1"),
})
session.MakeRequest(t, req, http.StatusOK)
- req = NewRequestWithValues(t, "POST", fmt.Sprintf("%s/content", issueURL), map[string]string{
+ req = NewRequestWithValues(t, "POST", issueURL+"/content", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": "modified content",
"context": fmt.Sprintf("/%s/%s", "user2", "repo1"),
})
session.MakeRequest(t, req, http.StatusBadRequest)
- req = NewRequestWithValues(t, "POST", fmt.Sprintf("%s/content", issueURL), map[string]string{
+ req = NewRequestWithValues(t, "POST", issueURL+"/content", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": "modified content",
"content_version": "1",
diff --git a/tests/integration/lfs_local_endpoint_test.go b/tests/integration/lfs_local_endpoint_test.go
index d42888bbe1..e67f0712a3 100644
--- a/tests/integration/lfs_local_endpoint_test.go
+++ b/tests/integration/lfs_local_endpoint_test.go
@@ -4,7 +4,6 @@
package integration
import (
- "fmt"
"net/url"
"os"
"path/filepath"
@@ -41,55 +40,55 @@ func TestDetermineLocalEndpoint(t *testing.T) {
{
cloneurl: root,
lfsurl: "",
- expected: str2url(fmt.Sprintf("file://%s", root)),
+ expected: str2url("file://" + root),
},
// case 1
{
cloneurl: root,
lfsurl: lfsroot,
- expected: str2url(fmt.Sprintf("file://%s", lfsroot)),
+ expected: str2url("file://" + lfsroot),
},
// case 2
{
cloneurl: "https://git.com/repo.git",
lfsurl: lfsroot,
- expected: str2url(fmt.Sprintf("file://%s", lfsroot)),
+ expected: str2url("file://" + lfsroot),
},
// case 3
{
cloneurl: rootdotgit,
lfsurl: "",
- expected: str2url(fmt.Sprintf("file://%s", filepath.Join(rootdotgit, ".git"))),
+ expected: str2url("file://" + filepath.Join(rootdotgit, ".git")),
},
// case 4
{
cloneurl: "",
lfsurl: rootdotgit,
- expected: str2url(fmt.Sprintf("file://%s", filepath.Join(rootdotgit, ".git"))),
+ expected: str2url("file://" + filepath.Join(rootdotgit, ".git")),
},
// case 5
{
cloneurl: rootdotgit,
lfsurl: rootdotgit,
- expected: str2url(fmt.Sprintf("file://%s", filepath.Join(rootdotgit, ".git"))),
+ expected: str2url("file://" + filepath.Join(rootdotgit, ".git")),
},
// case 6
{
- cloneurl: fmt.Sprintf("file://%s", root),
+ cloneurl: "file://" + root,
lfsurl: "",
- expected: str2url(fmt.Sprintf("file://%s", root)),
+ expected: str2url("file://" + root),
},
// case 7
{
- cloneurl: fmt.Sprintf("file://%s", root),
- lfsurl: fmt.Sprintf("file://%s", lfsroot),
- expected: str2url(fmt.Sprintf("file://%s", lfsroot)),
+ cloneurl: "file://" + root,
+ lfsurl: "file://" + lfsroot,
+ expected: str2url("file://" + lfsroot),
},
// case 8
{
cloneurl: root,
- lfsurl: fmt.Sprintf("file://%s", lfsroot),
- expected: str2url(fmt.Sprintf("file://%s", lfsroot)),
+ lfsurl: "file://" + lfsroot,
+ expected: str2url("file://" + lfsroot),
},
// case 9
{
diff --git a/tests/integration/migrate_test.go b/tests/integration/migrate_test.go
index 8de472ae70..a89dc8b85c 100644
--- a/tests/integration/migrate_test.go
+++ b/tests/integration/migrate_test.go
@@ -9,6 +9,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "strconv"
"testing"
auth_model "code.gitea.io/gitea/models/auth"
@@ -95,7 +96,7 @@ func TestMigrateGiteaForm(t *testing.T) {
"issues": "on",
"repo_name": migratedRepoName,
"description": "",
- "uid": fmt.Sprintf("%d", repoOwner.ID),
+ "uid": strconv.FormatInt(repoOwner.ID, 10),
})
resp = session.MakeRequest(t, req, http.StatusSeeOther)
// Step 5: a redirection displays the migrated repository
diff --git a/tests/integration/migration-test/migration_test.go b/tests/integration/migration-test/migration_test.go
index c319fd20a7..ffb8afa9c5 100644
--- a/tests/integration/migration-test/migration_test.go
+++ b/tests/integration/migration-test/migration_test.go
@@ -140,10 +140,10 @@ func restoreOldDB(t *testing.T, version string) {
assert.NoError(t, err)
defer db.Close()
- _, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", setting.Database.Name))
+ _, err = db.Exec("DROP DATABASE IF EXISTS " + setting.Database.Name)
assert.NoError(t, err)
- _, err = db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", setting.Database.Name))
+ _, err = db.Exec("CREATE DATABASE IF NOT EXISTS " + setting.Database.Name)
assert.NoError(t, err)
db.Close()
@@ -170,10 +170,10 @@ func restoreOldDB(t *testing.T, version string) {
}
defer db.Close()
- _, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", setting.Database.Name))
+ _, err = db.Exec("DROP DATABASE IF EXISTS " + setting.Database.Name)
assert.NoError(t, err)
- _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", setting.Database.Name))
+ _, err = db.Exec("CREATE DATABASE " + setting.Database.Name)
assert.NoError(t, err)
db.Close()
@@ -195,7 +195,7 @@ func restoreOldDB(t *testing.T, version string) {
if !schrows.Next() {
// Create and setup a DB schema
- _, err = db.Exec(fmt.Sprintf("CREATE SCHEMA %s", setting.Database.Schema))
+ _, err = db.Exec("CREATE SCHEMA " + setting.Database.Schema)
assert.NoError(t, err)
}
schrows.Close()
diff --git a/tests/integration/org_team_invite_test.go b/tests/integration/org_team_invite_test.go
index 4c1053702e..7444980ea8 100644
--- a/tests/integration/org_team_invite_test.go
+++ b/tests/integration/org_team_invite_test.go
@@ -58,7 +58,7 @@ func TestOrgTeamEmailInvite(t *testing.T) {
session = loginUser(t, user.Name)
// join the team
- inviteURL := fmt.Sprintf("/org/invite/%s", invites[0].Token)
+ inviteURL := "/org/invite/" + invites[0].Token
csrf = GetUserCSRFToken(t, session)
req = NewRequestWithValues(t, "POST", inviteURL, map[string]string{
"_csrf": csrf,
@@ -108,8 +108,8 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) {
assert.Len(t, invites, 1)
// accept the invite
- inviteURL := fmt.Sprintf("/org/invite/%s", invites[0].Token)
- req = NewRequest(t, "GET", fmt.Sprintf("/user/login?redirect_to=%s", url.QueryEscape(inviteURL)))
+ inviteURL := "/org/invite/" + invites[0].Token
+ req = NewRequest(t, "GET", "/user/login?redirect_to="+url.QueryEscape(inviteURL))
resp = MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
@@ -179,8 +179,8 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) {
assert.Len(t, invites, 1)
// accept the invite
- inviteURL := fmt.Sprintf("/org/invite/%s", invites[0].Token)
- req = NewRequest(t, "GET", fmt.Sprintf("/user/sign_up?redirect_to=%s", url.QueryEscape(inviteURL)))
+ inviteURL := "/org/invite/" + invites[0].Token
+ req = NewRequest(t, "GET", "/user/sign_up?redirect_to="+url.QueryEscape(inviteURL))
resp = MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
@@ -260,8 +260,8 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) {
// new user: accept the invite
session = emptyTestSession(t)
- inviteURL := fmt.Sprintf("/org/invite/%s", invites[0].Token)
- req = NewRequest(t, "GET", fmt.Sprintf("/user/sign_up?redirect_to=%s", url.QueryEscape(inviteURL)))
+ inviteURL := "/org/invite/" + invites[0].Token
+ req = NewRequest(t, "GET", "/user/sign_up?redirect_to="+url.QueryEscape(inviteURL))
session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", "/user/sign_up", map[string]string{
"user_name": "doesnotexist",
@@ -275,7 +275,7 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) {
assert.NoError(t, err)
activationCode := user_model.GenerateUserTimeLimitCode(&user_model.TimeLimitCodeOptions{Purpose: user_model.TimeLimitCodeActivateAccount}, user)
- activateURL := fmt.Sprintf("/user/activate?code=%s", activationCode)
+ activateURL := "/user/activate?code=" + activationCode
req = NewRequestWithValues(t, "POST", activateURL, map[string]string{
"password": "examplePassword!1",
})
@@ -337,8 +337,8 @@ func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) {
session = loginUser(t, "user5")
// accept the invite (note: this uses the sign_up url)
- inviteURL := fmt.Sprintf("/org/invite/%s", invites[0].Token)
- req = NewRequest(t, "GET", fmt.Sprintf("/user/sign_up?redirect_to=%s", url.QueryEscape(inviteURL)))
+ inviteURL := "/org/invite/" + invites[0].Token
+ req = NewRequest(t, "GET", "/user/sign_up?redirect_to="+url.QueryEscape(inviteURL))
resp = session.MakeRequest(t, req, http.StatusSeeOther)
assert.Equal(t, inviteURL, test.RedirectURL(resp))
diff --git a/tests/integration/org_test.go b/tests/integration/org_test.go
index 7f450afae7..b1376fe1bf 100644
--- a/tests/integration/org_test.go
+++ b/tests/integration/org_test.go
@@ -151,7 +151,7 @@ func TestOrgRestrictedUser(t *testing.T) {
// assert restrictedUser cannot see the org or the public repo
restrictedSession := loginUser(t, restrictedUser)
- req := NewRequest(t, "GET", fmt.Sprintf("/%s", orgName))
+ req := NewRequest(t, "GET", "/"+orgName)
restrictedSession.MakeRequest(t, req, http.StatusNotFound)
req = NewRequest(t, "GET", fmt.Sprintf("/%s/%s", orgName, repoName))
@@ -188,7 +188,7 @@ func TestOrgRestrictedUser(t *testing.T) {
_ = adminSession.MakeRequest(t, req, http.StatusNoContent)
// Now we need to check if the restrictedUser can access the repo
- req = NewRequest(t, "GET", fmt.Sprintf("/%s", orgName))
+ req = NewRequest(t, "GET", "/"+orgName)
restrictedSession.MakeRequest(t, req, http.StatusOK)
req = NewRequest(t, "GET", fmt.Sprintf("/%s/%s", orgName, repoName))
diff --git a/tests/integration/pull_compare_test.go b/tests/integration/pull_compare_test.go
index 9284672a9e..86bdd1b9e3 100644
--- a/tests/integration/pull_compare_test.go
+++ b/tests/integration/pull_compare_test.go
@@ -110,7 +110,7 @@ func TestPullCompare_EnableAllowEditsFromMaintainer(t *testing.T) {
// user2 (admin of repo3) goes to the PR files page
user2Session := loginUser(t, "user2")
- resp = user2Session.MakeRequest(t, NewRequest(t, "GET", fmt.Sprintf("%s/files", prURL)), http.StatusOK)
+ resp = user2Session.MakeRequest(t, NewRequest(t, "GET", prURL+"/files"), http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
nodes := htmlDoc.doc.Find(".diff-file-box[data-new-filename=\"README.md\"] .diff-file-header-actions .tippy-target a")
if assert.Equal(t, 1, nodes.Length()) {
@@ -127,14 +127,14 @@ func TestPullCompare_EnableAllowEditsFromMaintainer(t *testing.T) {
htmlDoc = NewHTMLParser(t, resp.Body)
dataURL, exists := htmlDoc.doc.Find("#allow-edits-from-maintainers").Attr("data-url")
assert.True(t, exists)
- req := NewRequestWithValues(t, "POST", fmt.Sprintf("%s/set_allow_maintainer_edit", dataURL), map[string]string{
+ req := NewRequestWithValues(t, "POST", dataURL+"/set_allow_maintainer_edit", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"allow_maintainer_edit": "true",
})
user4Session.MakeRequest(t, req, http.StatusOK)
// user2 (admin of repo3) goes to the PR files page again
- resp = user2Session.MakeRequest(t, NewRequest(t, "GET", fmt.Sprintf("%s/files", prURL)), http.StatusOK)
+ resp = user2Session.MakeRequest(t, NewRequest(t, "GET", prURL+"/files"), http.StatusOK)
htmlDoc = NewHTMLParser(t, resp.Body)
nodes = htmlDoc.doc.Find(".diff-file-box[data-new-filename=\"README.md\"] .diff-file-header-actions .tippy-target a")
if assert.Equal(t, 2, nodes.Length()) {
diff --git a/tests/integration/pull_create_test.go b/tests/integration/pull_create_test.go
index 461a1400f7..179c84e673 100644
--- a/tests/integration/pull_create_test.go
+++ b/tests/integration/pull_create_test.go
@@ -293,10 +293,10 @@ func TestCreatePullWhenBlocked(t *testing.T) {
// sessionBase := loginUser(t, "user2")
token := getUserToken(t, RepoOwner, auth_model.AccessTokenScopeWriteUser)
- req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/blocks/%s", ForkOwner)).
+ req := NewRequest(t, "GET", "/api/v1/user/blocks/"+ForkOwner).
AddTokenAuth(token)
MakeRequest(t, req, http.StatusNotFound)
- req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/blocks/%s", ForkOwner)).
+ req = NewRequest(t, "PUT", "/api/v1/user/blocks/"+ForkOwner).
AddTokenAuth(token)
MakeRequest(t, req, http.StatusNoContent)
@@ -308,7 +308,7 @@ func TestCreatePullWhenBlocked(t *testing.T) {
// Teardown
// Unblock user
- req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/blocks/%s", ForkOwner)).
+ req = NewRequest(t, "DELETE", "/api/v1/user/blocks/"+ForkOwner).
AddTokenAuth(token)
MakeRequest(t, req, http.StatusNoContent)
})
diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go
index 6090da4cb5..cf50d5e639 100644
--- a/tests/integration/pull_merge_test.go
+++ b/tests/integration/pull_merge_test.go
@@ -296,7 +296,7 @@ func TestCantMergeUnrelated(t *testing.T) {
err := git.NewCommand("read-tree", "--empty").Run(git.DefaultContext, &git.RunOpts{Dir: path})
assert.NoError(t, err)
- stdin := bytes.NewBufferString("Unrelated File")
+ stdin := strings.NewReader("Unrelated File")
var stdout strings.Builder
err = git.NewCommand("hash-object", "-w", "--stdin").Run(git.DefaultContext, &git.RunOpts{
Dir: path,
diff --git a/tests/integration/repo_branch_test.go b/tests/integration/repo_branch_test.go
index f9cf13112a..50ceb65330 100644
--- a/tests/integration/repo_branch_test.go
+++ b/tests/integration/repo_branch_test.go
@@ -138,7 +138,7 @@ func TestCreateBranchInvalidCSRF(t *testing.T) {
}
func prepareRecentlyPushedBranchTest(t *testing.T, headSession *TestSession, baseRepo, headRepo *repo_model.Repository) {
- refSubURL := fmt.Sprintf("branch/%s", headRepo.DefaultBranch)
+ refSubURL := "branch/" + headRepo.DefaultBranch
baseRepoPath := baseRepo.OwnerName + "/" + baseRepo.Name
headRepoPath := headRepo.OwnerName + "/" + headRepo.Name
// Case 1: Normal branch changeset to display pushed message
@@ -168,7 +168,7 @@ func prepareRecentlyPushedBranchTest(t *testing.T, headSession *TestSession, bas
}
func prepareRecentlyPushedBranchSpecialTest(t *testing.T, session *TestSession, baseRepo, headRepo *repo_model.Repository) {
- refSubURL := fmt.Sprintf("branch/%s", headRepo.DefaultBranch)
+ refSubURL := "branch/" + headRepo.DefaultBranch
baseRepoPath := baseRepo.OwnerName + "/" + baseRepo.Name
headRepoPath := headRepo.OwnerName + "/" + headRepo.Name
// create branch with no new commit
@@ -196,7 +196,7 @@ func testCreatePullToDefaultBranch(t *testing.T, session *TestSession, baseRepo,
}
func prepareRepoPR(t *testing.T, baseSession, headSession *TestSession, baseRepo, headRepo *repo_model.Repository) {
- refSubURL := fmt.Sprintf("branch/%s", headRepo.DefaultBranch)
+ refSubURL := "branch/" + headRepo.DefaultBranch
testCreateBranch(t, headSession, headRepo.OwnerName, headRepo.Name, refSubURL, "new-commit", http.StatusSeeOther)
// create opening PR
diff --git a/tests/integration/repo_fork_test.go b/tests/integration/repo_fork_test.go
index c309c46632..a7010af14a 100644
--- a/tests/integration/repo_fork_test.go
+++ b/tests/integration/repo_fork_test.go
@@ -7,6 +7,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
+ "strconv"
"testing"
"code.gitea.io/gitea/models/db"
@@ -46,7 +47,7 @@ func testRepoFork(t *testing.T, session *TestSession, ownerName, repoName, forkO
assert.True(t, exists, "Fork owner '%s' is not present in select box", forkOwnerName)
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
- "uid": fmt.Sprintf("%d", forkOwner.ID),
+ "uid": strconv.FormatInt(forkOwner.ID, 10),
"repo_name": forkRepoName,
"fork_single_branch": forkBranch,
})
diff --git a/tests/integration/repo_generate_test.go b/tests/integration/repo_generate_test.go
index f5645d62bc..fca4e92982 100644
--- a/tests/integration/repo_generate_test.go
+++ b/tests/integration/repo_generate_test.go
@@ -7,6 +7,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
+ "strconv"
"strings"
"testing"
@@ -44,7 +45,7 @@ func testRepoGenerate(t *testing.T, session *TestSession, templateID, templateOw
assert.True(t, exists, "Generate owner '%s' is not present in select box", generateOwnerName)
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
- "uid": fmt.Sprintf("%d", generateOwner.ID),
+ "uid": strconv.FormatInt(generateOwner.ID, 10),
"repo_name": generateRepoName,
"repo_template": templateID,
"git_content": "true",
diff --git a/tests/integration/repo_webhook_test.go b/tests/integration/repo_webhook_test.go
index 4d2751d8e2..89df15b8de 100644
--- a/tests/integration/repo_webhook_test.go
+++ b/tests/integration/repo_webhook_test.go
@@ -660,7 +660,7 @@ jobs:
- run: echo 'cmd 1'
- run: echo 'cmd 2'
`
- opts := getWorkflowCreateFileOptions(user2, repo1.DefaultBranch, fmt.Sprintf("create %s", wfTreePath), wfFileContent)
+ opts := getWorkflowCreateFileOptions(user2, repo1.DefaultBranch, "create "+wfTreePath, wfFileContent)
createWorkflowFile(t, token, "user2", "repo1", wfTreePath, opts)
commitID, err := gitRepo1.GetBranchCommitID(repo1.DefaultBranch)
diff --git a/tests/integration/ssh_key_test.go b/tests/integration/ssh_key_test.go
index eb3a3e926a..fbdda9b3af 100644
--- a/tests/integration/ssh_key_test.go
+++ b/tests/integration/ssh_key_test.go
@@ -51,7 +51,7 @@ func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) {
ctx := NewAPITestContext(t, "user2", "deploy-key-empty-repo-1", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
ctxWithDeleteRepo := NewAPITestContext(t, "user2", "deploy-key-empty-repo-1", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
- keyname := fmt.Sprintf("%s-push", ctx.Reponame)
+ keyname := ctx.Reponame + "-push"
u.Path = ctx.GitPath()
t.Run("CreateEmptyRepository", doAPICreateRepository(ctx, true))
@@ -89,7 +89,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) {
reponame := "ssh-key-test-repo"
username := "user2"
u.Path = fmt.Sprintf("%s/%s.git", username, reponame)
- keyname := fmt.Sprintf("%s-push", reponame)
+ keyname := reponame + "-push"
// OK login
ctx := NewAPITestContext(t, username, reponame, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
diff --git a/tests/integration/user_avatar_test.go b/tests/integration/user_avatar_test.go
index 298818a967..14ea012ac8 100644
--- a/tests/integration/user_avatar_test.go
+++ b/tests/integration/user_avatar_test.go
@@ -5,7 +5,6 @@ package integration
import (
"bytes"
- "fmt"
"image/png"
"io"
"mime/multipart"
@@ -84,9 +83,9 @@ func TestUserAvatar(t *testing.T) {
}
func testGetAvatarRedirect(t *testing.T, user *user_model.User) {
- t.Run(fmt.Sprintf("getAvatarRedirect_%s", user.Name), func(t *testing.T) {
+ t.Run("getAvatarRedirect_"+user.Name, func(t *testing.T) {
req := NewRequestf(t, "GET", "/%s.png", user.Name)
resp := MakeRequest(t, req, http.StatusSeeOther)
- assert.Equal(t, fmt.Sprintf("/avatars/%s", user.Avatar), resp.Header().Get("location"))
+ assert.Equal(t, "/avatars/"+user.Avatar, resp.Header().Get("location"))
})
}
diff --git a/tests/integration/webfinger_test.go b/tests/integration/webfinger_test.go
index a1abc8d32b..2afaed4a45 100644
--- a/tests/integration/webfinger_test.go
+++ b/tests/integration/webfinger_test.go
@@ -7,6 +7,7 @@ import (
"fmt"
"net/http"
"net/url"
+ "strconv"
"testing"
"code.gitea.io/gitea/models/unittest"
@@ -52,7 +53,7 @@ func TestWebfinger(t *testing.T) {
var jrd webfingerJRD
DecodeJSON(t, resp, &jrd)
assert.Equal(t, "acct:user2@"+appURL.Host, jrd.Subject)
- assert.ElementsMatch(t, []string{user.HTMLURL(), appURL.String() + "api/v1/activitypub/user-id/" + fmt.Sprint(user.ID)}, jrd.Aliases)
+ assert.ElementsMatch(t, []string{user.HTMLURL(), appURL.String() + "api/v1/activitypub/user-id/" + strconv.FormatInt(user.ID, 10)}, jrd.Aliases)
req = NewRequest(t, "GET", fmt.Sprintf("/.well-known/webfinger?resource=acct:%s@%s", user.LowerName, "unknown.host"))
MakeRequest(t, req, http.StatusBadRequest)
@@ -63,6 +64,6 @@ func TestWebfinger(t *testing.T) {
req = NewRequest(t, "GET", fmt.Sprintf("/.well-known/webfinger?resource=acct:%s@%s", "user31", appURL.Host))
session.MakeRequest(t, req, http.StatusOK)
- req = NewRequest(t, "GET", fmt.Sprintf("/.well-known/webfinger?resource=mailto:%s", user.Email))
+ req = NewRequest(t, "GET", "/.well-known/webfinger?resource=mailto:"+user.Email)
MakeRequest(t, req, http.StatusNotFound)
}
diff --git a/tests/integration/wiki_test.go b/tests/integration/wiki_test.go
index db4da46669..ac458af378 100644
--- a/tests/integration/wiki_test.go
+++ b/tests/integration/wiki_test.go
@@ -4,7 +4,6 @@
package integration
import (
- "fmt"
"net/http"
"net/url"
"os"
@@ -38,7 +37,7 @@ func TestRepoCloneWiki(t *testing.T) {
dstPath := t.TempDir()
- r := fmt.Sprintf("%suser2/repo1.wiki.git", u.String())
+ r := u.String() + "user2/repo1.wiki.git"
u, _ = url.Parse(r)
u.User = url.UserPassword("user2", userPassword)
t.Run("Clone", func(t *testing.T) {
diff --git a/tests/test_utils.go b/tests/test_utils.go
index 96eb5731b4..6c95716e67 100644
--- a/tests/test_utils.go
+++ b/tests/test_utils.go
@@ -93,7 +93,7 @@ func InitTest(requireGitea bool) {
if err != nil {
log.Fatal("sql.Open: %v", err)
}
- if _, err = db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", setting.Database.Name)); err != nil {
+ if _, err = db.Exec("CREATE DATABASE IF NOT EXISTS " + setting.Database.Name); err != nil {
log.Fatal("db.Exec: %v", err)
}
case setting.Database.Type.IsPostgreSQL():
@@ -118,7 +118,7 @@ func InitTest(requireGitea bool) {
defer dbrows.Close()
if !dbrows.Next() {
- if _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", setting.Database.Name)); err != nil {
+ if _, err = db.Exec("CREATE DATABASE " + setting.Database.Name); err != nil {
log.Fatal("db.Exec: CREATE DATABASE: %v", err)
}
}
@@ -148,7 +148,7 @@ func InitTest(requireGitea bool) {
if !schrows.Next() {
// Create and setup a DB schema
- if _, err = db.Exec(fmt.Sprintf("CREATE SCHEMA %s", setting.Database.Schema)); err != nil {
+ if _, err = db.Exec("CREATE SCHEMA " + setting.Database.Schema); err != nil {
log.Fatal("db.Exec: CREATE SCHEMA: %v", err)
}
}