1
1
mirror of https://github.com/go-gitea/gitea synced 2025-07-23 02:38:35 +00:00

Enable addtional linters (#34085)

enable mirror, usestdlibbars and perfsprint 
part of: https://github.com/go-gitea/gitea/issues/34083

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
TheFox0x7
2025-04-01 12:14:01 +02:00
committed by GitHub
parent 56e42be36d
commit ee3c82f874
294 changed files with 848 additions and 805 deletions

View File

@@ -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 {

View File

@@ -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

View File

@@ -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)

View File

@@ -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")

View File

@@ -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
}

View File

@@ -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)

View File

@@ -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 {

View File

@@ -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{

View File

@@ -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
}

View File

@@ -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())
}
}

View File

@@ -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()

View File

@@ -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")
}

View File

@@ -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
}

View File

@@ -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)

View File

@@ -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() {}

View File

@@ -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 {

View File

@@ -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)),
)
}

View File

@@ -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")
}

View File

@@ -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

View File

@@ -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 {

View File

@@ -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"

View File

@@ -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",

View File

@@ -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 {

View File

@@ -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

View File

@@ -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(),
}
}

View File

@@ -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)
}

View File

@@ -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)

View File

@@ -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)

View File

@@ -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
}

View File

@@ -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,

View File

@@ -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")

View File

@@ -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

View File

@@ -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",
)

View File

@@ -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 {

View File

@@ -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)

View File

@@ -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),
}
}

View File

@@ -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)

View File

@@ -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)
}

View File

@@ -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"
},
// -----------------------------------------------------------------

View File

@@ -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)

View File

@@ -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"

View File

@@ -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(`<relative-time %s datetime="%s">%s</relative-time>`, strings.Join(attrs, " "), datetimeEscaped, textEscaped))
default:
panic(fmt.Sprintf("Unsupported format %s", format))
panic("Unsupported format " + format)
}
}

View File

@@ -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 {

View File

@@ -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)

View File

@@ -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

View File

@@ -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{})

View File

@@ -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

View File

@@ -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
}

View File

@@ -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")

View File

@@ -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)
}

View File

@@ -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)

View File

@@ -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], ":")

View File

@@ -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)