chore(cleanup): replaces unnecessary calls to formatting functions by non-formatting equivalents (#7994)

This PR replaces unnecessary calls to formatting functions (`fmt.Printf`, `fmt.Errorf`, ...) by non-formatting equivalents.
Resolves #7967

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/7994
Reviewed-by: Gusted <gusted@noreply.codeberg.org>
Co-authored-by: chavacava <chavacava@noreply.codeberg.org>
Co-committed-by: chavacava <chavacava@noreply.codeberg.org>
This commit is contained in:
chavacava 2025-05-29 17:34:29 +02:00 committed by Gusted
parent 25f3f8e1d2
commit 99d697263f
126 changed files with 340 additions and 281 deletions

View file

@ -81,7 +81,7 @@ func runListAuth(c *cli.Context) error {
// loop through each source and print
w := tabwriter.NewWriter(os.Stdout, c.Int("min-width"), c.Int("tab-width"), c.Int("padding"), padChar, flags)
fmt.Fprintf(w, "ID\tName\tType\tEnabled\n")
fmt.Fprint(w, "ID\tName\tType\tEnabled\n")
for _, source := range authSources {
fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", source.ID, source.Name, source.Type.String(), source.IsActive)
}

View file

@ -108,7 +108,7 @@ func runCreateUser(c *cli.Context) error {
username = c.String("username")
} else {
username = c.String("name")
_, _ = fmt.Fprintf(c.App.ErrWriter, "--name flag is deprecated. Use --username instead.\n")
_, _ = fmt.Fprint(c.App.ErrWriter, "--name flag is deprecated. Use --username instead.\n")
}
ctx, cancel := installSignals()

View file

@ -41,7 +41,7 @@ func runListUsers(c *cli.Context) error {
w := tabwriter.NewWriter(os.Stdout, 5, 0, 1, ' ', 0)
if c.IsSet("admin") {
fmt.Fprintf(w, "ID\tUsername\tEmail\tIsActive\n")
fmt.Fprint(w, "ID\tUsername\tEmail\tIsActive\n")
for _, u := range users {
if u.IsAdmin {
fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", u.ID, u.Name, u.Email, u.IsActive)
@ -49,7 +49,7 @@ func runListUsers(c *cli.Context) error {
}
} else {
twofa := user_model.UserList(users).GetTwoFaStatus(ctx)
fmt.Fprintf(w, "ID\tUsername\tEmail\tIsActive\tIsAdmin\t2FA\n")
fmt.Fprint(w, "ID\tUsername\tEmail\tIsActive\tIsAdmin\t2FA\n")
for _, u := range users {
fmt.Fprintf(w, "%d\t%s\t%s\t%t\t%t\t%t\n", u.ID, u.Name, u.Email, u.IsActive, u.IsAdmin, twofa[u.ID])
}

View file

@ -5,6 +5,7 @@
package cmd
import (
"errors"
"fmt"
"io"
"os"
@ -212,13 +213,13 @@ func runDump(ctx *cli.Context) error {
if !setting.InstallLock {
log.Error("Is '%s' really the right config path?\n", setting.CustomConf)
return fmt.Errorf("forgejo is not initialized")
return errors.New("forgejo is not initialized")
}
setting.LoadSettings() // cannot access session settings otherwise
verbose := ctx.Bool("verbose")
if verbose && ctx.Bool("quiet") {
return fmt.Errorf("--quiet and --verbose cannot both be set")
return errors.New("--quiet and --verbose cannot both be set")
}
stdCtx, cancel := installSignals()

View file

@ -6,6 +6,7 @@ package forgejo
import (
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
@ -124,7 +125,7 @@ func readSecret(ctx context.Context, cliCtx *cli.Context) (string, error) {
}
return string(buf), nil
}
return "", fmt.Errorf("at least one of the --secret, --secret-stdin, --secret-file options is required")
return "", errors.New("at least one of the --secret, --secret-stdin, --secret-file options is required")
}
func validateSecret(secret string) error {
@ -144,7 +145,7 @@ func getLabels(cliCtx *cli.Context) (*[]string, error) {
return &lblValue, nil
}
if cliCtx.String("labels") != "" {
return nil, fmt.Errorf("--labels and --keep-labels should not be used together")
return nil, errors.New("--labels and --keep-labels should not be used together")
}
return nil, nil
}

View file

@ -63,7 +63,7 @@ func runGenerateInternalToken(c *cli.Context) error {
fmt.Printf("%s", internalToken)
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Printf("\n")
fmt.Println()
}
return nil
@ -75,7 +75,7 @@ func runGenerateLfsJwtSecret(c *cli.Context) error {
fmt.Printf("%s", jwtSecretBase64)
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Printf("\n")
fmt.Print("\n")
}
return nil
@ -90,7 +90,7 @@ func runGenerateSecretKey(c *cli.Context) error {
fmt.Printf("%s", secretKey)
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Printf("\n")
fmt.Print("\n")
}
return nil

View file

@ -247,7 +247,7 @@ Forgejo or set your environment appropriately.`, "")
newCommitIDs[count] = newCommitID
refFullNames[count] = refFullName
count++
fmt.Fprintf(out, "*")
fmt.Fprint(out, "*")
if count >= hookBatchSize {
fmt.Fprintf(out, " Checking %d references\n", count)
@ -263,10 +263,10 @@ Forgejo or set your environment appropriately.`, "")
lastline = 0
}
} else {
fmt.Fprintf(out, ".")
fmt.Fprint(out, ".")
}
if lastline >= hookBatchSize {
fmt.Fprintf(out, "\n")
fmt.Fprint(out, "\n")
lastline = 0
}
}
@ -283,7 +283,7 @@ Forgejo or set your environment appropriately.`, "")
return fail(ctx, extra.UserMsg, "HookPreReceive(last) failed: %v", extra.Error)
}
} else if lastline > 0 {
fmt.Fprintf(out, "\n")
fmt.Fprint(out, "\n")
}
fmt.Fprintf(out, "Checked %d references in total\n", total)
@ -399,7 +399,7 @@ Forgejo or set your environment appropriately.`, "")
continue
}
fmt.Fprintf(out, ".")
fmt.Fprint(out, ".")
oldCommitIDs[count] = string(fields[0])
newCommitIDs[count] = string(fields[1])
refFullNames[count] = git.RefName(fields[2])

View file

@ -4,6 +4,7 @@
package cmd
import (
"errors"
"fmt"
"io"
"path/filepath"
@ -128,7 +129,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")
require.Error(t, err)
assert.Equal(t, 1, r.ExitCode)

View file

@ -5,6 +5,7 @@ package actions
import (
"context"
"errors"
"fmt"
"slices"
"strings"
@ -355,7 +356,7 @@ func UpdateRunWithoutNotification(ctx context.Context, run *ActionRun, cols ...s
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.
}

View file

@ -7,6 +7,7 @@ package activities
import (
"context"
"errors"
"fmt"
"net/url"
"path"
@ -458,7 +459,7 @@ type GetFeedsOptions struct {
// 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")
}
cond, err := activityQueryCondition(ctx, opts)

View file

@ -5,6 +5,7 @@ package asymkey
import (
"context"
"errors"
"fmt"
"strings"
"time"
@ -209,7 +210,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))

View file

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

View file

@ -6,6 +6,7 @@ package asymkey
import (
"context"
"errors"
"fmt"
"hash"
"strings"
@ -316,7 +317,7 @@ func verifyWithGPGSettings(ctx context.Context, gpgSettings *git.GPGSettings, si
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)

View file

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

View file

@ -35,7 +35,7 @@ func Test_FederationHostValidation(t *testing.T) {
HostSchema: "https",
}
if res, _ := validation.IsValid(sut); res {
t.Errorf("sut should be invalid: HostFqdn empty")
t.Error("sut should be invalid: HostFqdn empty")
}
sut = FederationHost{
@ -48,7 +48,7 @@ func Test_FederationHostValidation(t *testing.T) {
HostSchema: "https",
}
if res, _ := validation.IsValid(sut); res {
t.Errorf("sut should be invalid: HostFqdn too long (len=256)")
t.Error("sut should be invalid: HostFqdn too long (len=256)")
}
sut = FederationHost{
@ -59,7 +59,7 @@ func Test_FederationHostValidation(t *testing.T) {
HostSchema: "https",
}
if res, _ := validation.IsValid(sut); res {
t.Errorf("sut should be invalid: NodeInfo invalid")
t.Error("sut should be invalid: NodeInfo invalid")
}
sut = FederationHost{
@ -72,7 +72,7 @@ func Test_FederationHostValidation(t *testing.T) {
HostSchema: "https",
}
if res, _ := validation.IsValid(sut); res {
t.Errorf("sut should be invalid: Future timestamp")
t.Error("sut should be invalid: Future timestamp")
}
sut = FederationHost{
@ -85,6 +85,6 @@ func Test_FederationHostValidation(t *testing.T) {
HostSchema: "https",
}
if res, _ := validation.IsValid(sut); res {
t.Errorf("sut should be invalid: HostFqdn lower case")
t.Error("sut should be invalid: HostFqdn lower case")
}
}

View file

@ -4,7 +4,7 @@
package forgefed
import (
"fmt"
"errors"
"reflect"
"strings"
"testing"
@ -28,7 +28,7 @@ func Test_NodeInfoWellKnownUnmarshalJSON(t *testing.T) {
},
"empty": {
item: []byte(``),
wantErr: fmt.Errorf("cannot parse JSON: cannot parse empty string; unparsed tail: \"\""),
wantErr: errors.New("cannot parse JSON: cannot parse empty string; unparsed tail: \"\""),
},
}
@ -74,7 +74,7 @@ func Test_NewNodeInfoWellKnown(t *testing.T) {
_, err := NewNodeInfoWellKnown([]byte(`invalid`))
if err == nil {
t.Errorf("error was expected here")
t.Error("error was expected here")
}
}
@ -87,6 +87,6 @@ func Test_NewNodeInfo(t *testing.T) {
_, err := NewNodeInfo([]byte(`invalid`))
if err == nil {
t.Errorf("error was expected here")
t.Error("error was expected here")
}
}

View file

@ -5,6 +5,7 @@ package forgejo_migrations //nolint:revive
import (
"context"
"errors"
"fmt"
"os"
@ -130,7 +131,7 @@ func EnsureUpToDate(x *xorm.Engine) error {
}
if currentDB < 0 {
return fmt.Errorf("database has not been initialized")
return errors.New("database has not been initialized")
}
expected := ExpectedVersion()

View file

@ -6,6 +6,7 @@ package issues
import (
"context"
"errors"
"fmt"
"html/template"
"regexp"
@ -804,7 +805,7 @@ func (issue *Issue) MovePin(ctx context.Context, newPosition int) error {
}
if newPosition < 1 {
return fmt.Errorf("The Position can't be lower than 1")
return errors.New("The Position can't be lower than 1")
}
dbctx, committer, err := db.TxContext(ctx)

View file

@ -6,6 +6,7 @@ package issues
import (
"context"
"errors"
"fmt"
"strings"
@ -338,10 +339,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")
}
opts.Issue.Created = timeutil.TimeStampNanoNow()

View file

@ -6,6 +6,7 @@ package issues
import (
"context"
"errors"
"fmt"
"io"
"regexp"
@ -795,7 +796,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

View file

@ -5,6 +5,7 @@ package issues
import (
"context"
"errors"
"fmt"
"slices"
"strings"
@ -349,7 +350,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 {
@ -908,7 +909,7 @@ func MarkConversation(ctx context.Context, comment *Comment, doer *user_model.Us
// the PR writer , offfcial 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 doer.ID != issue.PosterID {
@ -945,11 +946,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{

View file

@ -74,7 +74,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 {

View file

@ -6,6 +6,7 @@ package migrations
import (
"context"
"errors"
"fmt"
"forgejo.org/models/db"
@ -412,7 +413,7 @@ func EnsureUpToDate(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 {

View file

@ -5,6 +5,7 @@ package v1_13 //nolint
import (
"context"
"errors"
"fmt"
"strings"
@ -83,7 +84,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 {

View file

@ -4,7 +4,7 @@
package v1_14 //nolint
import (
"fmt"
"errors"
"strconv"
"forgejo.org/modules/log"
@ -72,7 +72,7 @@ func UpdateCodeCommentReplies(x *xorm.Engine) error {
case setting.Database.Type.IsSQLite3():
sqlCmd = sqlSelect + sqlTail + " LIMIT " + strconv.Itoa(batchSize) + " OFFSET " + strconv.Itoa(start)
default:
return fmt.Errorf("Unsupported database type")
return errors.New("Unsupported database type")
}
if err := sess.SQL(sqlCmd).Find(&comments); err != nil {

View file

@ -73,12 +73,12 @@ func Test_DeleteOrphanedIssueLabels(t *testing.T) {
// Now test what is left
if _, ok := postMigration[2]; ok {
t.Errorf("Orphaned Label[2] survived the migration")
t.Error("Orphaned Label[2] survived the migration")
return
}
if _, ok := postMigration[5]; ok {
t.Errorf("Orphaned Label[5] survived the migration")
t.Error("Orphaned Label[5] survived the migration")
return
}

View file

@ -5,6 +5,7 @@ package v1_17 //nolint
import (
"context"
"errors"
"fmt"
"forgejo.org/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

View file

@ -5,7 +5,7 @@ package v1_21 //nolint
import (
"context"
"fmt"
"errors"
"forgejo.org/models/db"
"forgejo.org/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)

View file

@ -145,7 +145,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)
@ -170,7 +170,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

View file

@ -5,7 +5,7 @@ package project
import (
"context"
"fmt"
"errors"
"forgejo.org/models/db"
"forgejo.org/modules/log"
@ -73,7 +73,7 @@ func MoveIssuesOnProjectColumn(ctx context.Context, column *Column, sortedIssueI
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")
}
for sorting, issueID := range sortedIssueIDs {
@ -88,7 +88,7 @@ func MoveIssuesOnProjectColumn(ctx context.Context, column *Column, sortedIssueI
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 {

View file

@ -5,6 +5,7 @@ package repo
import (
"context"
"errors"
"fmt"
"net/url"
"path"
@ -232,7 +233,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")
}
if attach.ExternalURL != "" && !validation.IsValidExternalURL(attach.ExternalURL) {
return ErrInvalidExternalURL{ExternalURL: attach.ExternalURL}

View file

@ -26,6 +26,6 @@ func Test_FollowingRepoValidation(t *testing.T) {
URI: "http://localhost:3000/api/v1/activitypub/repo-id/1",
}
if res, _ := validation.IsValid(sut); res {
t.Errorf("sut should be invalid")
t.Error("sut should be invalid")
}
}

View file

@ -6,6 +6,7 @@ package repo
import (
"context"
"errors"
"fmt"
"html/template"
"net"
@ -820,7 +821,7 @@ func GetRepositoryByURL(ctx context.Context, repoURL string) (*Repository, error
pathSegments := getRepositoryURLPathSegments(repoURL)
if len(pathSegments) != 2 {
return nil, fmt.Errorf("unknown or malformed repository URL")
return nil, errors.New("unknown or malformed repository URL")
}
ownerName := pathSegments[0]

View file

@ -24,6 +24,6 @@ func Test_FederatedUserValidation(t *testing.T) {
FederationHostID: 1,
}
if res, _ := validation.IsValid(sut); res {
t.Errorf("sut should be invalid")
t.Error("sut should be invalid")
}
}

View file

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

View file

@ -30,7 +30,7 @@ func TestTimedDiscoveryCache(t *testing.T) {
// Make sure we can retrieve them
if di := dc.Get("foo"); di == nil {
t.Errorf("Expected a result, got nil")
t.Error("Expected a result, got nil")
} else if di.OpEndpoint() != "opEndpoint" || di.OpLocalID() != "opLocalID" || di.ClaimedID() != "claimedID" {
t.Errorf("Expected opEndpoint opLocalID claimedID, got %v %v %v", di.OpEndpoint(), di.OpLocalID(), di.ClaimedID())
}
@ -44,6 +44,6 @@ func TestTimedDiscoveryCache(t *testing.T) {
time.Sleep(100 * time.Millisecond)
if di := dc.Get("foo"); di != nil {
t.Errorf("Expected a nil, got a result")
t.Error("Expected a nil, got a result")
}
}

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,7 @@
package cache
import (
"errors"
"fmt"
"strconv"
"time"
@ -48,7 +49,7 @@ const (
func Test() (time.Duration, error) {
if conn == nil {
return 0, fmt.Errorf("default cache not initialized")
return 0, errors.New("default cache not initialized")
}
testData := fmt.Sprintf("%x", make([]byte, 500))
@ -63,10 +64,10 @@ func Test() (time.Duration, error) {
}
testVal := conn.Get(testCacheKey)
if testVal == nil {
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"
@ -45,7 +45,7 @@ func TestGetString(t *testing.T) {
createTestCache()
data, err := GetString("key", func() (string, error) {
return "", fmt.Errorf("some error")
return "", errors.New("some error")
})
require.Error(t, err)
assert.Empty(t, data)
@ -70,7 +70,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")
})
require.NoError(t, err)
assert.Equal(t, "some data", data)
@ -81,7 +81,7 @@ func TestGetInt(t *testing.T) {
createTestCache()
data, err := GetInt("key", func() (int, error) {
return 0, fmt.Errorf("some error")
return 0, errors.New("some error")
})
require.Error(t, err)
assert.Equal(t, 0, data)
@ -106,7 +106,7 @@ func TestGetInt(t *testing.T) {
assert.Equal(t, 100, data)
data, err = GetInt("key", func() (int, error) {
return 0, fmt.Errorf("some error")
return 0, errors.New("some error")
})
require.NoError(t, err)
assert.Equal(t, 100, data)
@ -117,7 +117,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")
})
require.Error(t, err)
assert.EqualValues(t, 0, data)
@ -142,7 +142,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")
})
require.NoError(t, err)
assert.EqualValues(t, 100, data)

View file

@ -23,16 +23,16 @@ func TestLookup(t *testing.T) {
d := FromAlias("beer")
if !reflect.DeepEqual(a, b) {
t.Errorf("a and b should equal")
t.Error("a and b should equal")
}
if !reflect.DeepEqual(b, c) {
t.Errorf("b and c should equal")
t.Error("b and c should equal")
}
if !reflect.DeepEqual(c, d) {
t.Errorf("c and d should equal")
t.Error("c and d should equal")
}
if !reflect.DeepEqual(a, d) {
t.Errorf("a and d should equal")
t.Error("a and d should equal")
}
m := FromCode("\U0001f44d")
@ -40,13 +40,13 @@ func TestLookup(t *testing.T) {
o := FromAlias("+1")
if !reflect.DeepEqual(m, n) {
t.Errorf("m and n should equal")
t.Error("m and n should equal")
}
if !reflect.DeepEqual(n, o) {
t.Errorf("n and o should equal")
t.Error("n and o should equal")
}
if !reflect.DeepEqual(m, o) {
t.Errorf("m and o should equal")
t.Error("m and o should equal")
}
}

View file

@ -4,7 +4,7 @@
package forgefed
import (
"fmt"
"errors"
"reflect"
"strings"
"testing"
@ -99,7 +99,7 @@ func Test_LikeUnmarshalJSON(t *testing.T) {
"invalid": {
item: []byte(`{"type":"Invalid","actor":"https://repo.prod.meissa.de/api/activitypub/user-id/1","object":"https://codeberg.org/api/activitypub/repository-id/1"`),
want: &ForgeLike{},
wantErr: fmt.Errorf("cannot parse JSON"),
wantErr: errors.New("cannot parse JSON"),
},
}

View file

@ -4,7 +4,7 @@
package forgefed
import (
"fmt"
"errors"
"reflect"
"strings"
"testing"
@ -125,7 +125,7 @@ func Test_UndoLikeUnmarshalJSON(t *testing.T) {
"invalid": {
item: []byte(`invalid JSON`),
want: nil,
wantErr: fmt.Errorf("cannot parse JSON"),
wantErr: errors.New("cannot parse JSON"),
},
}

View file

@ -166,31 +166,31 @@ func TestShouldThrowErrorOnInvalidInput(t *testing.T) {
var err any
_, err = NewPersonID("", "forgejo")
if err == nil {
t.Errorf("empty input should be invalid.")
t.Error("empty input should be invalid.")
}
_, err = NewPersonID("http://localhost:3000/api/v1/something", "forgejo")
if err == nil {
t.Errorf("localhost uris are not external")
t.Error("localhost uris are not external")
}
_, err = NewPersonID("./api/v1/something", "forgejo")
if err == nil {
t.Errorf("relative uris are not allowed")
t.Error("relative uris are not allowed")
}
_, err = NewPersonID("http://1.2.3.4/api/v1/something", "forgejo")
if err == nil {
t.Errorf("uri may not be ip-4 based")
t.Error("uri may not be ip-4 based")
}
_, err = NewPersonID("http:///[fe80::1ff:fe23:4567:890a%25eth0]/api/v1/something", "forgejo")
if err == nil {
t.Errorf("uri may not be ip-6 based")
t.Error("uri may not be ip-6 based")
}
_, err = NewPersonID("https://codeberg.org/api/v1/activitypub/../activitypub/user-id/12345", "forgejo")
if err == nil {
t.Errorf("uri may not contain relative path elements")
t.Error("uri may not contain relative path elements")
}
_, err = NewPersonID("https://myuser@an.other.host/api/v1/activitypub/user-id/1", "forgejo")
if err == nil {
t.Errorf("uri may not contain unparsed elements")
t.Error("uri may not contain unparsed elements")
}
_, err = NewPersonID("https://an.other.host/api/v1/activitypub/user-id/1", "forgejo")
if err != nil {

View file

@ -9,7 +9,6 @@ import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os/exec"
"strconv"
@ -386,7 +385,7 @@ func parseSubmoduleContent(bs []byte) (*ObjectCache, error) {
}
submoduleCache := newObjectCache()
if len(cfg.Submodules) == 0 {
return nil, fmt.Errorf("no submodules found")
return nil, errors.New("no submodules found")
}
for _, subModule := range cfg.Submodules {
submoduleCache.Set(subModule.Path, subModule.URL)

View file

@ -7,6 +7,7 @@ import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
@ -116,7 +117,7 @@ func (ca GitAttribute) Bool() optional.Option[bool] {
// instantiation.
func (repo *Repository) gitCheckAttrCommand(treeish string, attributes ...string) (*Command, *RunOpts, context.CancelFunc, error) {
if len(attributes) == 0 {
return nil, nil, nil, fmt.Errorf("no provided attributes to check-attr")
return nil, nil, nil, errors.New("no provided attributes to check-attr")
}
env := os.Environ()

View file

@ -41,7 +41,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(repo.Ctx, "symbolic-ref", "HEAD").RunStdString(&RunOpts{Dir: repo.Path})
if err != nil {

View file

@ -5,7 +5,7 @@ package internal
import (
"context"
"fmt"
"errors"
"forgejo.org/models/db"
repo_model "forgejo.org/models/repo"
@ -57,13 +57,13 @@ type dummyIndexer struct {
}
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"
"forgejo.org/modules/indexer/internal"
"forgejo.org/modules/log"
@ -38,11 +38,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)
@ -82,10 +82,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"
"forgejo.org/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))
@ -63,10 +64,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,7 @@ package internal
import (
"context"
"fmt"
"errors"
"forgejo.org/modules/indexer/internal"
)
@ -30,13 +30,13 @@ type dummyIndexer struct {
}
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 "forgejo.org/models/repo"
"forgejo.org/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 {

View file

@ -5,7 +5,7 @@
package markdown
import (
"fmt"
"errors"
"html/template"
"io"
"strings"
@ -54,7 +54,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

@ -262,7 +262,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"
@ -68,7 +69,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

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

@ -38,7 +38,7 @@ func Test_IsValid(t *testing.T) {
func Test_ValidateNotEmpty_ForString(t *testing.T) {
sut := ""
if len(ValidateNotEmpty(sut, "dummyField")) == 0 {
t.Errorf("sut should be invalid")
t.Error("sut should be invalid")
}
sut = "not empty"
if res := ValidateNotEmpty(sut, "dummyField"); len(res) > 0 {
@ -49,7 +49,7 @@ func Test_ValidateNotEmpty_ForString(t *testing.T) {
func Test_ValidateNotEmpty_ForTimestamp(t *testing.T) {
sut := timeutil.TimeStamp(0)
if res := ValidateNotEmpty(sut, "dummyField"); len(res) == 0 {
t.Errorf("sut should be invalid")
t.Error("sut should be invalid")
}
sut = timeutil.TimeStampNow()
if res := ValidateNotEmpty(sut, "dummyField"); len(res) > 0 {
@ -60,7 +60,7 @@ func Test_ValidateNotEmpty_ForTimestamp(t *testing.T) {
func Test_ValidateMaxLen(t *testing.T) {
sut := "0123456789"
if len(ValidateMaxLen(sut, 9, "dummyField")) == 0 {
t.Errorf("sut should be invalid")
t.Error("sut should be invalid")
}
sut = "0123456789"
if res := ValidateMaxLen(sut, 11, "dummyField"); len(res) > 0 {

View file

@ -51,11 +51,11 @@ 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 {
checkErr = errors.Join(checkErr, fmt.Errorf("contentSize not match body size"))
checkErr = errors.Join(checkErr, errors.New("contentSize not match body size"))
}
if checkErr != nil {
if err := st.Delete(storagePath); err != nil {
@ -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() {

View file

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

View file

@ -8,6 +8,7 @@ import (
"crypto/x509"
"database/sql"
"encoding/pem"
"errors"
"fmt"
"net/http"
"net/url"
@ -29,7 +30,7 @@ import (
func decodePublicKeyPem(pubKeyPem string) ([]byte, error) {
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")
}
return block.Bytes, nil

View file

@ -4,7 +4,7 @@
package admin
import (
"fmt"
"errors"
"net/http"
quota_model "forgejo.org/models/quota"
@ -83,7 +83,7 @@ func CreateQuotaRule(ctx *context.APIContext) {
form := web.GetForm(ctx).(*api.CreateQuotaRuleOptions)
if form.Limit == nil {
ctx.Error(http.StatusUnprocessableEntity, "quota_model.ParseLimitSubject", fmt.Errorf("[Limit]: Required"))
ctx.Error(http.StatusUnprocessableEntity, "quota_model.ParseLimitSubject", errors.New("[Limit]: Required"))
return
}

View file

@ -196,7 +196,7 @@ func EditUser(ctx *context.APIContext) {
// If either LoginSource or LoginName is given, the other must be present too.
if form.SourceID != nil || form.LoginName != nil {
if form.SourceID == nil || form.LoginName == nil {
ctx.Error(http.StatusUnprocessableEntity, "LoginSourceAndLoginName", fmt.Errorf("source_id and login_name must be specified together"))
ctx.Error(http.StatusUnprocessableEntity, "LoginSourceAndLoginName", errors.New("source_id and login_name must be specified together"))
return
}
}
@ -304,7 +304,7 @@ func DeleteUser(ctx *context.APIContext) {
// admin should not delete themself
if ctx.ContextUser.ID == ctx.Doer.ID {
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("you cannot delete yourself"))
ctx.Error(http.StatusUnprocessableEntity, "", errors.New("you cannot delete yourself"))
return
}

View file

@ -6,7 +6,6 @@ package repo
import (
"errors"
"fmt"
"net/http"
"forgejo.org/models"
@ -151,7 +150,7 @@ func DeleteBranch(ctx *context.APIContext) {
}
if ctx.Repo.Repository.IsMirror {
ctx.Error(http.StatusForbidden, "IsMirrored", fmt.Errorf("can not delete branch of an mirror repository"))
ctx.Error(http.StatusForbidden, "IsMirrored", errors.New("can not delete branch of an mirror repository"))
return
}
@ -160,9 +159,9 @@ func DeleteBranch(ctx *context.APIContext) {
case git.IsErrBranchNotExist(err):
ctx.NotFound(err)
case errors.Is(err, repo_service.ErrBranchIsDefault):
ctx.Error(http.StatusForbidden, "DefaultBranch", fmt.Errorf("can not delete default branch"))
ctx.Error(http.StatusForbidden, "DefaultBranch", errors.New("can not delete default branch"))
case errors.Is(err, git_model.ErrBranchIsProtected):
ctx.Error(http.StatusForbidden, "IsProtectedBranch", fmt.Errorf("branch protected"))
ctx.Error(http.StatusForbidden, "IsProtectedBranch", errors.New("branch protected"))
default:
ctx.Error(http.StatusInternalServerError, "DeleteBranch", err)
}

View file

@ -692,7 +692,7 @@ func UpdateFile(ctx *context.APIContext) {
// "$ref": "#/responses/repoArchivedError"
apiOpts := web.GetForm(ctx).(*api.UpdateFileOptions)
if ctx.Repo.Repository.IsEmpty {
ctx.Error(http.StatusUnprocessableEntity, "RepoIsEmpty", fmt.Errorf("repo is empty"))
ctx.Error(http.StatusUnprocessableEntity, "RepoIsEmpty", errors.New("repo is empty"))
return
}

View file

@ -5,7 +5,7 @@
package repo
import (
"fmt"
"errors"
"net/http"
"reflect"
@ -352,12 +352,12 @@ func prepareForReplaceOrAdd(ctx *context.APIContext, form api.IssueLabelsOption)
labelNames = append(labelNames, rv.String())
default:
ctx.Error(http.StatusBadRequest, "InvalidLabel", "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.Error(http.StatusBadRequest, "InvalidLabels", "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)

View file

@ -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.Error(http.StatusForbidden, "", fmt.Errorf("query by user not allowed; not enough rights"))
ctx.Error(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.Error(http.StatusForbidden, "", fmt.Errorf("query by user not allowed; not enough rights"))
ctx.Error(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.Error(http.StatusForbidden, "", fmt.Errorf("query by user not allowed; not enough rights"))
ctx.Error(http.StatusForbidden, "", errors.New("query by user not allowed; not enough rights"))
return
}
}

View file

@ -123,12 +123,12 @@ func Migrate(ctx *context.APIContext) {
gitServiceType := convert.ToGitServiceType(form.Service)
if form.Mirror && setting.Mirror.DisableNewPull {
ctx.Error(http.StatusForbidden, "MirrorsGlobalDisabled", fmt.Errorf("the site administrator has disabled the creation of new pull mirrors"))
ctx.Error(http.StatusForbidden, "MirrorsGlobalDisabled", errors.New("the site administrator has disabled the creation of new pull mirrors"))
return
}
if setting.Repository.DisableMigrations {
ctx.Error(http.StatusForbidden, "MigrationsGlobalDisabled", fmt.Errorf("the site administrator has disabled migrations"))
ctx.Error(http.StatusForbidden, "MigrationsGlobalDisabled", errors.New("the site administrator has disabled migrations"))
return
}

View file

@ -4,6 +4,7 @@
package repo
import (
"errors"
"fmt"
"net/http"
@ -63,7 +64,7 @@ func GetNote(ctx *context.APIContext) {
func getNote(ctx *context.APIContext, identifier string) {
if ctx.Repo.GitRepo == nil {
ctx.InternalServerError(fmt.Errorf("no open git repo"))
ctx.InternalServerError(errors.New("no open git repo"))
return
}

View file

@ -1050,11 +1050,11 @@ func MergePullRequest(ctx *context.APIContext) {
if err := repo_service.DeleteBranchAfterMerge(ctx, ctx.Doer, pr, headRepo); err != nil {
switch {
case errors.Is(err, repo_service.ErrBranchIsDefault):
ctx.Error(http.StatusForbidden, "DefaultBranch", fmt.Errorf("the head branch is the default branch"))
ctx.Error(http.StatusForbidden, "DefaultBranch", errors.New("the head branch is the default branch"))
case errors.Is(err, git_model.ErrBranchIsProtected):
ctx.Error(http.StatusForbidden, "IsProtectedBranch", fmt.Errorf("the head branch is protected"))
ctx.Error(http.StatusForbidden, "IsProtectedBranch", errors.New("the head branch is protected"))
case errors.Is(err, util.ErrPermissionDenied):
ctx.Error(http.StatusForbidden, "HeadBranch", fmt.Errorf("insufficient permission to delete head branch"))
ctx.Error(http.StatusForbidden, "HeadBranch", errors.New("insufficient permission to delete head branch"))
default:
ctx.Error(http.StatusInternalServerError, "DeleteBranchAfterMerge", err)
}

View file

@ -4,6 +4,7 @@
package repo
import (
"errors"
"fmt"
"net/http"
"strings"
@ -581,7 +582,7 @@ func SubmitPullReview(ctx *context.APIContext) {
}
if review.Type != issues_model.ReviewTypePending {
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("only a pending review can be submitted"))
ctx.Error(http.StatusUnprocessableEntity, "", errors.New("only a pending review can be submitted"))
return
}
@ -593,7 +594,7 @@ func SubmitPullReview(ctx *context.APIContext) {
// if review stay pending return
if reviewType == issues_model.ReviewTypePending {
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("review stay pending"))
ctx.Error(http.StatusUnprocessableEntity, "", errors.New("review stay pending"))
return
}
@ -634,7 +635,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.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("approve your own pull is not allowed"))
ctx.Error(http.StatusUnprocessableEntity, "", errors.New("approve your own pull is not allowed"))
return -1, true
}
reviewType = issues_model.ReviewTypeApprove
@ -643,7 +644,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.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("reject your own pull is not allowed"))
ctx.Error(http.StatusUnprocessableEntity, "", errors.New("reject your own pull is not allowed"))
return -1, true
}
reviewType = issues_model.ReviewTypeReject

View file

@ -4,6 +4,7 @@
package repo
import (
"errors"
"fmt"
"net/http"
@ -226,7 +227,7 @@ func CreateRelease(ctx *context.APIContext) {
form := web.GetForm(ctx).(*api.CreateReleaseOption)
if ctx.Repo.Repository.IsEmpty {
ctx.Error(http.StatusUnprocessableEntity, "RepoIsEmpty", fmt.Errorf("repo is empty"))
ctx.Error(http.StatusUnprocessableEntity, "RepoIsEmpty", errors.New("repo is empty"))
return
}
rel, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, form.TagName)

View file

@ -5,6 +5,7 @@
package repo
import (
"errors"
"fmt"
"net/http"
"slices"
@ -723,7 +724,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.Error(http.StatusUnprocessableEntity, "Force Private enabled", err)
return err
}
@ -794,12 +795,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.Error(http.StatusUnprocessableEntity, "Invalid external tracker URL", 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.Error(http.StatusUnprocessableEntity, "Invalid external tracker URL format", err)
return err
}
@ -870,7 +871,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.Error(http.StatusUnprocessableEntity, "", "Invalid external wiki URL")
return err
}
@ -1054,7 +1055,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.Error(http.StatusUnprocessableEntity, err.Error(), err)
return err
}

View file

@ -238,7 +238,7 @@ func acceptOrRejectRepoTransfer(ctx *context.APIContext, accept bool) error {
if !repoTransfer.CanUserAcceptTransfer(ctx, ctx.Doer) {
ctx.Error(http.StatusForbidden, "CanUserAcceptTransfer", nil)
return fmt.Errorf("user does not have permissions to do this")
return errors.New("user does not have permissions to do this")
}
if accept {

View file

@ -4,6 +4,7 @@
package user
import (
"errors"
"fmt"
"net/http"
"strings"
@ -143,7 +144,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.NotFound("Not Found", fmt.Errorf("gpg keys setting is not allowed to be visited"))
ctx.NotFound("Not Found", errors.New("gpg keys setting is not allowed to be visited"))
return
}
@ -298,7 +299,7 @@ func DeleteGPGKey(ctx *context.APIContext) {
// "$ref": "#/responses/notFound"
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageGPGKeys) {
ctx.NotFound("Not Found", fmt.Errorf("gpg keys setting is not allowed to be visited"))
ctx.NotFound("Not Found", errors.New("gpg keys setting is not allowed to be visited"))
return
}

View file

@ -5,7 +5,7 @@ package user
import (
std_ctx "context"
"fmt"
"errors"
"net/http"
asymkey_model "forgejo.org/models/asymkey"
@ -209,7 +209,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.NotFound("Not Found", fmt.Errorf("ssh keys setting is not allowed to be visited"))
ctx.NotFound("Not Found", errors.New("ssh keys setting is not allowed to be visited"))
return
}
@ -285,7 +285,7 @@ func DeletePublicKey(ctx *context.APIContext) {
// "$ref": "#/responses/notFound"
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys) {
ctx.NotFound("Not Found", fmt.Errorf("ssh keys setting is not allowed to be visited"))
ctx.NotFound("Not Found", errors.New("ssh keys setting is not allowed to be visited"))
return
}

View file

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

View file

@ -5,7 +5,7 @@ package common
import (
"context"
"fmt"
"errors"
"time"
"forgejo.org/models/db"
@ -24,7 +24,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)

View file

@ -122,7 +122,7 @@ func writeProcess(out io.Writer, process *process_module.Process, indent string,
if stack.Count > 1 {
_, _ = fmt.Fprintf(sb, "* %d", stack.Count)
}
_, _ = fmt.Fprintf(sb, "\n")
_, _ = fmt.Fprintln(sb)
indent += "| "
if len(stack.Labels) > 0 {
_, _ = fmt.Fprintf(sb, "%sLabels: %q:%q", indent, stack.Labels[0].Name, stack.Labels[0].Value)
@ -132,7 +132,7 @@ func writeProcess(out io.Writer, process *process_module.Process, indent string,
_, _ = fmt.Fprintf(sb, ", %q:%q", label.Name, label.Value)
}
}
_, _ = fmt.Fprintf(sb, "\n")
_, _ = fmt.Fprintln(sb)
}
_, _ = fmt.Fprintf(sb, "%sStack:\n", indent)
indent += " "

View file

@ -4,6 +4,7 @@
package auth
import (
"errors"
"fmt"
"net/http"
"net/url"
@ -55,13 +56,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")
}
}

View file

@ -179,7 +179,7 @@ func (kase *testCase) doTest(t *testing.T) {
if len(after) != len(issue.Comments) {
t.Logf("Expected %v comments, got %v", len(after), len(issue.Comments))
t.Logf("Comments got after combination:")
t.Log("Comments got after combination:")
for c := 0; c < len(issue.Comments); c++ {
cmt := issue.Comments[c]
t.Logf("%v %v %v\n", cmt.Type, cmt.CreatedUnix, cmt.Content)

View file

@ -517,7 +517,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")
}
continue
}

View file

@ -5,7 +5,7 @@
package setting
import (
"fmt"
"errors"
"net/http"
asymkey_model "forgejo.org/models/asymkey"
@ -80,7 +80,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("Not Found", fmt.Errorf("gpg keys setting is not allowed to be visited"))
ctx.NotFound("Not Found", errors.New("gpg keys setting is not allowed to be visited"))
return
}
@ -161,7 +161,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("Not Found", fmt.Errorf("ssh keys setting is not allowed to be visited"))
ctx.NotFound("Not Found", errors.New("ssh keys setting is not allowed to be visited"))
return
}
@ -205,7 +205,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("Not Found", fmt.Errorf("ssh keys setting is not allowed to be visited"))
ctx.NotFound("Not Found", errors.New("ssh keys setting is not allowed to be visited"))
return
}
@ -242,7 +242,7 @@ func DeleteKey(ctx *context.Context) {
switch ctx.FormString("type") {
case "gpg":
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageGPGKeys) {
ctx.NotFound("Not Found", fmt.Errorf("gpg keys setting is not allowed to be visited"))
ctx.NotFound("Not Found", 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 {
@ -252,7 +252,7 @@ func DeleteKey(ctx *context.Context) {
}
case "ssh":
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys) {
ctx.NotFound("Not Found", fmt.Errorf("ssh keys setting is not allowed to be visited"))
ctx.NotFound("Not Found", errors.New("ssh keys setting is not allowed to be visited"))
return
}

View file

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

View file

@ -5,6 +5,7 @@ package actions
import (
"context"
"errors"
"fmt"
"path"
@ -50,7 +51,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 webhook_module.HookEventPullRequest, webhook_module.HookEventPullRequestSync, webhook_module.HookEventPullRequestLabel, webhook_module.HookEventPullRequestAssign, webhook_module.HookEventPullRequestMilestone:
@ -64,9 +65,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:

View file

@ -5,6 +5,7 @@ package actions
import (
"context"
"errors"
"fmt"
"time"
@ -205,7 +206,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 fmt.Errorf("job has changed, try again")
return errors.New("job has changed, try again")
}
// Continue with the next job.

View file

@ -5,6 +5,7 @@ package actions
import (
"context"
"errors"
"fmt"
actions_model "forgejo.org/models/actions"
@ -183,7 +184,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() {

View file

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

View file

@ -4,6 +4,7 @@
package oauth2
import (
"errors"
"fmt"
"time"
@ -51,12 +52,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
}

View file

@ -32,7 +32,7 @@ func Init() error {
shared_automerge.PRAutoMergeQueue = queue.CreateUniqueQueue(graceful.GetManager().ShutdownContext(), "pr_auto_merge", handler)
if shared_automerge.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(shared_automerge.PRAutoMergeQueue)
return nil

View file

@ -6,6 +6,7 @@ package context
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
@ -365,12 +366,12 @@ func RepoRefForAPI(next http.Handler) http.Handler {
ctx := GetAPIContext(req)
if ctx.Repo.Repository.IsEmpty {
ctx.NotFound(fmt.Errorf("repository is empty"))
ctx.NotFound(errors.New("repository is empty"))
return
}
if ctx.Repo.GitRepo == nil {
ctx.InternalServerError(fmt.Errorf("no open git repo"))
ctx.InternalServerError(errors.New("no open git repo"))
return
}

View file

@ -7,6 +7,7 @@ import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"os"
"path/filepath"
@ -77,7 +78,7 @@ func checkAuthorizedKeys(ctx context.Context, logger log.Logger, autofix bool) e
fPath,
"forgejo admin regenerate keys",
"forgejo doctor check --run authorized-keys --fix")
return fmt.Errorf(`authorized_keys is out of date and should be regenerated with "forgejo admin regenerate keys" or "forgejo doctor check --run authorized-keys --fix"`)
return errors.New(`authorized_keys is out of date and should be regenerated with "forgejo admin regenerate keys" or "forgejo doctor check --run authorized-keys --fix"`)
}
logger.Warn("authorized_keys is out of date. Attempting rewrite...")
err = asymkey_model.RewriteAllPublicKeys(ctx)

View file

@ -5,7 +5,7 @@ package doctor
import (
"context"
"fmt"
"errors"
"time"
"forgejo.org/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{

View file

@ -5,7 +5,7 @@ package externalaccount
import (
"context"
"fmt"
"errors"
user_model "forgejo.org/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))

View file

@ -5,6 +5,7 @@ package federation
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
@ -46,7 +47,7 @@ func ProcessLikeActivity(ctx context.Context, form any, repositoryID int64) (int
return http.StatusInternalServerError, "Wrong FederationHost", err
}
if !activity.IsNewer(federationHost.LatestActivity) {
return http.StatusNotAcceptable, "Activity out of order.", fmt.Errorf("Activity already processed")
return http.StatusNotAcceptable, "Activity out of order.", errors.New("Activity already processed")
}
actorID, err := fm.NewPersonID(actorURI, string(federationHost.NodeInfo.SoftwareName))
if err != nil {

View file

@ -5,6 +5,7 @@ package issue
import (
"context"
"errors"
"fmt"
"forgejo.org/models/db"
@ -18,7 +19,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")
}
// Check if same reference from same commit has already existed.

View file

@ -6,6 +6,7 @@ package issue
import (
"context"
"errors"
"fmt"
"time"
@ -345,13 +346,13 @@ func SetIssueUpdateDate(ctx context.Context, issue *issues_model.Issue, updated
return err
}
if !perm.IsAdmin() && !perm.IsOwner() {
return fmt.Errorf("user needs to have admin or owner right")
return errors.New("user needs to have admin or owner right")
}
// A simple guard against potential inconsistent calls
updatedUnix := timeutil.TimeStamp(updated.Unix())
if updatedUnix < issue.CreatedUnix || updatedUnix > timeutil.TimeStampNow() {
return fmt.Errorf("unallowed update date")
return errors.New("unallowed update date")
}
issue.UpdatedUnix = updatedUnix

View file

@ -5,6 +5,7 @@ package issue
import (
"context"
"errors"
"fmt"
"forgejo.org/models/db"
@ -47,7 +48,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")
}
}

View file

@ -595,15 +595,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.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)
@ -616,12 +616,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.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]) {
@ -630,7 +630,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) {

Some files were not shown because too many files have changed in this diff Show more