diff --git a/cmd/admin_auth.go b/cmd/admin_auth.go index b5e0212df7..13cae76705 100644 --- a/cmd/admin_auth.go +++ b/cmd/admin_auth.go @@ -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) } diff --git a/cmd/admin_user_create.go b/cmd/admin_user_create.go index f84254f39c..8434dc241d 100644 --- a/cmd/admin_user_create.go +++ b/cmd/admin_user_create.go @@ -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() diff --git a/cmd/admin_user_list.go b/cmd/admin_user_list.go index 6044ce7c3f..4ca81babbb 100644 --- a/cmd/admin_user_list.go +++ b/cmd/admin_user_list.go @@ -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]) } diff --git a/cmd/dump.go b/cmd/dump.go index bc0b269924..16ad412fda 100644 --- a/cmd/dump.go +++ b/cmd/dump.go @@ -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() diff --git a/cmd/forgejo/actions.go b/cmd/forgejo/actions.go index dbe7398bcf..ea6db91f6d 100644 --- a/cmd/forgejo/actions.go +++ b/cmd/forgejo/actions.go @@ -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 } diff --git a/cmd/generate.go b/cmd/generate.go index dcbdcd0353..fd8b50a0c1 100644 --- a/cmd/generate.go +++ b/cmd/generate.go @@ -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 diff --git a/cmd/hook.go b/cmd/hook.go index 935c1b08ea..1c8d4e499b 100644 --- a/cmd/hook.go +++ b/cmd/hook.go @@ -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]) diff --git a/cmd/main_test.go b/cmd/main_test.go index 1ff71005e3..f2d393313a 100644 --- a/cmd/main_test.go +++ b/cmd/main_test.go @@ -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) diff --git a/models/actions/run.go b/models/actions/run.go index 006f401053..48756b7a08 100644 --- a/models/actions/run.go +++ b/models/actions/run.go @@ -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. } diff --git a/models/activities/action.go b/models/activities/action.go index f4be7d23e2..a309637d04 100644 --- a/models/activities/action.go +++ b/models/activities/action.go @@ -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) diff --git a/models/asymkey/gpg_key.go b/models/asymkey/gpg_key.go index b7e10ce85c..64866da076 100644 --- a/models/asymkey/gpg_key.go +++ b/models/asymkey/gpg_key.go @@ -5,6 +5,7 @@ package asymkey import ( "context" + "errors" "fmt" "strings" "time" @@ -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)) diff --git a/models/asymkey/gpg_key_common.go b/models/asymkey/gpg_key_common.go index db1912c316..5b8a22fe63 100644 --- a/models/asymkey/gpg_key_common.go +++ b/models/asymkey/gpg_key_common.go @@ -7,6 +7,7 @@ import ( "bytes" "crypto" "encoding/base64" + "errors" "fmt" "hash" "io" @@ -75,7 +76,7 @@ func base64DecPubKey(content string) (*packet.PublicKey, error) { // Check type pkey, ok := p.(*packet.PublicKey) if !ok { - return nil, fmt.Errorf("key is not a public key") + return nil, errors.New("key is not a public key") } return pkey, nil } @@ -122,15 +123,15 @@ func readArmoredSign(r io.Reader) (body io.Reader, err error) { func extractSignature(s string) (*packet.Signature, error) { r, err := readArmoredSign(strings.NewReader(s)) if err != nil { - return nil, fmt.Errorf("Failed to read signature armor") + return nil, errors.New("Failed to read signature armor") } p, err := packet.Read(r) if err != nil { - return nil, fmt.Errorf("Failed to read signature packet") + return nil, errors.New("Failed to read signature packet") } sig, ok := p.(*packet.Signature) if !ok { - return nil, fmt.Errorf("Packet is not a signature") + return nil, errors.New("Packet is not a signature") } return sig, nil } diff --git a/models/asymkey/gpg_key_object_verification.go b/models/asymkey/gpg_key_object_verification.go index ccd31a38b1..745ed04869 100644 --- a/models/asymkey/gpg_key_object_verification.go +++ b/models/asymkey/gpg_key_object_verification.go @@ -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) diff --git a/models/asymkey/ssh_key_parse.go b/models/asymkey/ssh_key_parse.go index 305e464b4b..7321553eb2 100644 --- a/models/asymkey/ssh_key_parse.go +++ b/models/asymkey/ssh_key_parse.go @@ -10,6 +10,7 @@ import ( "encoding/base64" "encoding/binary" "encoding/pem" + "errors" "fmt" "math/big" "os" @@ -93,7 +94,7 @@ func parseKeyString(content string) (string, error) { block, _ := pem.Decode([]byte(content)) if block == nil { - return "", fmt.Errorf("failed to parse PEM block containing the public key") + return "", errors.New("failed to parse PEM block containing the public key") } if strings.Contains(block.Type, "PRIVATE") { return "", ErrKeyIsPrivate diff --git a/models/forgefed/federationhost_test.go b/models/forgefed/federationhost_test.go index 824495c9cb..d11affbae0 100644 --- a/models/forgefed/federationhost_test.go +++ b/models/forgefed/federationhost_test.go @@ -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") } } diff --git a/models/forgefed/nodeinfo_test.go b/models/forgefed/nodeinfo_test.go index 9e37e77100..a0c9781b90 100644 --- a/models/forgefed/nodeinfo_test.go +++ b/models/forgefed/nodeinfo_test.go @@ -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") } } diff --git a/models/forgejo_migrations/migrate.go b/models/forgejo_migrations/migrate.go index 73226c525f..d79bb1e455 100644 --- a/models/forgejo_migrations/migrate.go +++ b/models/forgejo_migrations/migrate.go @@ -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() diff --git a/models/issues/issue.go b/models/issues/issue.go index d6a0029638..5edebb4105 100644 --- a/models/issues/issue.go +++ b/models/issues/issue.go @@ -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) diff --git a/models/issues/issue_update.go b/models/issues/issue_update.go index d15533390e..aca9069205 100644 --- a/models/issues/issue_update.go +++ b/models/issues/issue_update.go @@ -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() diff --git a/models/issues/pull.go b/models/issues/pull.go index c46961447c..0781fd0a2d 100644 --- a/models/issues/pull.go +++ b/models/issues/pull.go @@ -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 diff --git a/models/issues/review.go b/models/issues/review.go index db5cd65e2e..584704d3e8 100644 --- a/models/issues/review.go +++ b/models/issues/review.go @@ -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{ diff --git a/models/migrations/base/db.go b/models/migrations/base/db.go index 897ad016ab..7f7edda53b 100644 --- a/models/migrations/base/db.go +++ b/models/migrations/base/db.go @@ -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 { diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index aea9b593bd..2a5b97f519 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -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 { diff --git a/models/migrations/v1_13/v151.go b/models/migrations/v1_13/v151.go index 60339962cb..ff584fff67 100644 --- a/models/migrations/v1_13/v151.go +++ b/models/migrations/v1_13/v151.go @@ -5,6 +5,7 @@ package v1_13 //nolint import ( "context" + "errors" "fmt" "strings" @@ -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 { diff --git a/models/migrations/v1_14/v158.go b/models/migrations/v1_14/v158.go index 9849d5a9ea..3fa27cfecd 100644 --- a/models/migrations/v1_14/v158.go +++ b/models/migrations/v1_14/v158.go @@ -4,7 +4,7 @@ package v1_14 //nolint import ( - "fmt" + "errors" "strconv" "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 { diff --git a/models/migrations/v1_14/v177_test.go b/models/migrations/v1_14/v177_test.go index 199a71186a..bffc6f92e3 100644 --- a/models/migrations/v1_14/v177_test.go +++ b/models/migrations/v1_14/v177_test.go @@ -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 } diff --git a/models/migrations/v1_17/v222.go b/models/migrations/v1_17/v222.go index c9a33f007d..ae910cbcb6 100644 --- a/models/migrations/v1_17/v222.go +++ b/models/migrations/v1_17/v222.go @@ -5,6 +5,7 @@ package v1_17 //nolint import ( "context" + "errors" "fmt" "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 diff --git a/models/migrations/v1_21/v264.go b/models/migrations/v1_21/v264.go index 88eaf0d918..5615600072 100644 --- a/models/migrations/v1_21/v264.go +++ b/models/migrations/v1_21/v264.go @@ -5,7 +5,7 @@ package v1_21 //nolint import ( "context" - "fmt" + "errors" "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) diff --git a/models/project/column.go b/models/project/column.go index 52917cb9fd..20de39357b 100644 --- a/models/project/column.go +++ b/models/project/column.go @@ -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 diff --git a/models/project/issue.go b/models/project/issue.go index 9e9db19004..d404033446 100644 --- a/models/project/issue.go +++ b/models/project/issue.go @@ -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 { diff --git a/models/repo/attachment.go b/models/repo/attachment.go index 3bf51e80ca..4a09ef14f2 100644 --- a/models/repo/attachment.go +++ b/models/repo/attachment.go @@ -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} diff --git a/models/repo/following_repo_test.go b/models/repo/following_repo_test.go index cff125dabe..4bac23e77a 100644 --- a/models/repo/following_repo_test.go +++ b/models/repo/following_repo_test.go @@ -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") } } diff --git a/models/repo/repo.go b/models/repo/repo.go index 9db1fd9039..6bf03d724c 100644 --- a/models/repo/repo.go +++ b/models/repo/repo.go @@ -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] diff --git a/models/user/federated_user_test.go b/models/user/federated_user_test.go index 374236f6d3..542798c9bc 100644 --- a/models/user/federated_user_test.go +++ b/models/user/federated_user_test.go @@ -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") } } diff --git a/models/user/setting.go b/models/user/setting.go index a915119ad2..e547d24e9f 100644 --- a/models/user/setting.go +++ b/models/user/setting.go @@ -5,6 +5,7 @@ package user import ( "context" + "errors" "fmt" "strings" @@ -114,10 +115,10 @@ func GetUserAllSettings(ctx context.Context, uid int64) (map[string]*Setting, er func validateUserSettingKey(key string) error { if len(key) == 0 { - return fmt.Errorf("setting key must be set") + return errors.New("setting key must be set") } if strings.ToLower(key) != key { - return fmt.Errorf("setting key should be lowercase") + return errors.New("setting key should be lowercase") } return nil } diff --git a/modules/auth/openid/discovery_cache_test.go b/modules/auth/openid/discovery_cache_test.go index 3c59bd5ba5..77ce46c4d5 100644 --- a/modules/auth/openid/discovery_cache_test.go +++ b/modules/auth/openid/discovery_cache_test.go @@ -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") } } diff --git a/modules/avatar/identicon/identicon.go b/modules/avatar/identicon/identicon.go index 40471565d6..13e8ec88e6 100644 --- a/modules/avatar/identicon/identicon.go +++ b/modules/avatar/identicon/identicon.go @@ -8,6 +8,7 @@ package identicon import ( "crypto/sha256" + "errors" "fmt" "image" "image/color" @@ -29,7 +30,7 @@ type Identicon struct { // fore all possible foreground colors. only one foreground color will be picked randomly for one image func New(size int, back color.Color, fore ...color.Color) (*Identicon, error) { if len(fore) == 0 { - return nil, fmt.Errorf("foreground is not set") + return nil, errors.New("foreground is not set") } if size < minImageSize { diff --git a/modules/cache/cache.go b/modules/cache/cache.go index 9ad4b5cd90..aa69a0d3a7 100644 --- a/modules/cache/cache.go +++ b/modules/cache/cache.go @@ -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 diff --git a/modules/cache/cache_test.go b/modules/cache/cache_test.go index f7bc400598..aa28c98452 100644 --- a/modules/cache/cache_test.go +++ b/modules/cache/cache_test.go @@ -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) diff --git a/modules/emoji/emoji_test.go b/modules/emoji/emoji_test.go index 2526cd121e..ad3db10fb4 100644 --- a/modules/emoji/emoji_test.go +++ b/modules/emoji/emoji_test.go @@ -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") } } diff --git a/modules/forgefed/activity_like_test.go b/modules/forgefed/activity_like_test.go index 815b0e02f3..f4cb7e4e00 100644 --- a/modules/forgefed/activity_like_test.go +++ b/modules/forgefed/activity_like_test.go @@ -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"), }, } diff --git a/modules/forgefed/activity_undo_like_test.go b/modules/forgefed/activity_undo_like_test.go index 1b77369b67..5867a84e7b 100644 --- a/modules/forgefed/activity_undo_like_test.go +++ b/modules/forgefed/activity_undo_like_test.go @@ -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"), }, } diff --git a/modules/forgefed/actor_test.go b/modules/forgefed/actor_test.go index 5315d0b4de..10b6578953 100644 --- a/modules/forgefed/actor_test.go +++ b/modules/forgefed/actor_test.go @@ -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 { diff --git a/modules/git/commit.go b/modules/git/commit.go index a8ebed4968..96831e3ae4 100644 --- a/modules/git/commit.go +++ b/modules/git/commit.go @@ -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) diff --git a/modules/git/repo_attribute.go b/modules/git/repo_attribute.go index 2154467332..2b07513162 100644 --- a/modules/git/repo_attribute.go +++ b/modules/git/repo_attribute.go @@ -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() diff --git a/modules/git/repo_branch.go b/modules/git/repo_branch.go index 1992060351..3a9aa3e4e6 100644 --- a/modules/git/repo_branch.go +++ b/modules/git/repo_branch.go @@ -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 { diff --git a/modules/indexer/code/internal/indexer.go b/modules/indexer/code/internal/indexer.go index cc2c2aaf06..73662b1dda 100644 --- a/modules/indexer/code/internal/indexer.go +++ b/modules/indexer/code/internal/indexer.go @@ -5,7 +5,7 @@ package internal import ( "context" - "fmt" + "errors" "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") } diff --git a/modules/indexer/internal/bleve/indexer.go b/modules/indexer/internal/bleve/indexer.go index 4a61a80765..669417bb4b 100644 --- a/modules/indexer/internal/bleve/indexer.go +++ b/modules/indexer/internal/bleve/indexer.go @@ -5,7 +5,7 @@ package bleve import ( "context" - "fmt" + "errors" "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 } diff --git a/modules/indexer/internal/elasticsearch/indexer.go b/modules/indexer/internal/elasticsearch/indexer.go index 9cd29f3e49..a7a710588c 100644 --- a/modules/indexer/internal/elasticsearch/indexer.go +++ b/modules/indexer/internal/elasticsearch/indexer.go @@ -5,6 +5,7 @@ package elasticsearch import ( "context" + "errors" "fmt" "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) diff --git a/modules/indexer/internal/indexer.go b/modules/indexer/internal/indexer.go index c7f356da1e..3442bbaff2 100644 --- a/modules/indexer/internal/indexer.go +++ b/modules/indexer/internal/indexer.go @@ -5,7 +5,7 @@ package internal import ( "context" - "fmt" + "errors" ) // Indexer defines an basic indexer interface @@ -27,11 +27,11 @@ func NewDummyIndexer() Indexer { type dummyIndexer struct{} func (d *dummyIndexer) Init(ctx context.Context) (bool, error) { - return false, fmt.Errorf("indexer is not ready") + return false, errors.New("indexer is not ready") } func (d *dummyIndexer) Ping(ctx context.Context) error { - return fmt.Errorf("indexer is not ready") + return errors.New("indexer is not ready") } func (d *dummyIndexer) Close() {} diff --git a/modules/indexer/internal/meilisearch/indexer.go b/modules/indexer/internal/meilisearch/indexer.go index feac1d052c..b21605772c 100644 --- a/modules/indexer/internal/meilisearch/indexer.go +++ b/modules/indexer/internal/meilisearch/indexer.go @@ -5,6 +5,7 @@ package meilisearch import ( "context" + "errors" "fmt" "github.com/meilisearch/meilisearch-go" @@ -33,11 +34,11 @@ func NewIndexer(url, apiKey, indexName string, version int, settings *meilisearc // Init initializes the indexer func (i *Indexer) Init(_ context.Context) (bool, error) { if i == nil { - return false, fmt.Errorf("cannot init nil indexer") + return false, errors.New("cannot init nil indexer") } if i.Client != nil { - return false, fmt.Errorf("indexer is already initialized") + return false, errors.New("indexer is already initialized") } i.Client = meilisearch.New(i.url, meilisearch.WithAPIKey(i.apiKey)) @@ -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 { diff --git a/modules/indexer/issues/internal/indexer.go b/modules/indexer/issues/internal/indexer.go index 2f3b4029dc..1b9428b889 100644 --- a/modules/indexer/issues/internal/indexer.go +++ b/modules/indexer/issues/internal/indexer.go @@ -5,7 +5,7 @@ package internal import ( "context" - "fmt" + "errors" "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") } diff --git a/modules/indexer/stats/queue.go b/modules/indexer/stats/queue.go index 2403eb8dca..e4eac70d95 100644 --- a/modules/indexer/stats/queue.go +++ b/modules/indexer/stats/queue.go @@ -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 diff --git a/modules/issue/template/template.go b/modules/issue/template/template.go index 859d27cda6..08c1b21c26 100644 --- a/modules/issue/template/template.go +++ b/modules/issue/template/template.go @@ -4,6 +4,7 @@ package template import ( + "errors" "fmt" "net/url" "regexp" @@ -31,17 +32,17 @@ func Validate(template *api.IssueTemplate) error { func validateMetadata(template *api.IssueTemplate) error { if strings.TrimSpace(template.Name) == "" { - return fmt.Errorf("'name' is required") + return errors.New("'name' is required") } if strings.TrimSpace(template.About) == "" { - return fmt.Errorf("'about' is required") + return errors.New("'about' is required") } return nil } func validateYaml(template *api.IssueTemplate) error { if len(template.Fields) == 0 { - return fmt.Errorf("'body' is required") + return errors.New("'body' is required") } ids := make(container.Set[string]) for idx, field := range template.Fields { diff --git a/modules/markup/markdown/markdown.go b/modules/markup/markdown/markdown.go index db92631acc..717da464b9 100644 --- a/modules/markup/markdown/markdown.go +++ b/modules/markup/markdown/markdown.go @@ -5,7 +5,7 @@ package markdown import ( - "fmt" + "errors" "html/template" "io" "strings" @@ -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) diff --git a/modules/setting/config_provider.go b/modules/setting/config_provider.go index e93b21abda..19f3b9008a 100644 --- a/modules/setting/config_provider.go +++ b/modules/setting/config_provider.go @@ -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 { diff --git a/modules/setting/incoming_email.go b/modules/setting/incoming_email.go index 502be159a1..e592220de6 100644 --- a/modules/setting/incoming_email.go +++ b/modules/setting/incoming_email.go @@ -4,6 +4,7 @@ package setting import ( + "errors" "fmt" "net/mail" "strings" @@ -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) diff --git a/modules/templates/util_dict.go b/modules/templates/util_dict.go index 9d9af77fad..16f722e61b 100644 --- a/modules/templates/util_dict.go +++ b/modules/templates/util_dict.go @@ -4,6 +4,7 @@ package templates import ( + "errors" "fmt" "html" "html/template" @@ -33,7 +34,7 @@ func dictMerge(base map[string]any, arg any) bool { // The dot syntax is highly discouraged because it might cause unclear key conflicts. It's always good to use explicit keys. func dict(args ...any) (map[string]any, error) { if len(args)%2 != 0 { - return nil, fmt.Errorf("invalid dict constructor syntax: must have key-value pairs") + return nil, errors.New("invalid dict constructor syntax: must have key-value pairs") } m := make(map[string]any, len(args)/2) for i := 0; i < len(args); i += 2 { diff --git a/modules/validation/validatable_test.go b/modules/validation/validatable_test.go index 0802d5cc92..c843afe702 100644 --- a/modules/validation/validatable_test.go +++ b/modules/validation/validatable_test.go @@ -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 { diff --git a/routers/api/actions/artifacts_chunks.go b/routers/api/actions/artifacts_chunks.go index a15fa4fd1e..c0af750d7b 100644 --- a/routers/api/actions/artifacts_chunks.go +++ b/routers/api/actions/artifacts_chunks.go @@ -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() { diff --git a/routers/api/packages/chef/auth.go b/routers/api/packages/chef/auth.go index bbd5ce860f..7263cf13bb 100644 --- a/routers/api/packages/chef/auth.go +++ b/routers/api/packages/chef/auth.go @@ -12,6 +12,7 @@ import ( "crypto/x509" "encoding/base64" "encoding/pem" + "errors" "fmt" "hash" "math/big" @@ -121,7 +122,7 @@ func verifyTimestamp(req *http.Request) error { } if diff > maxTimeDifference { - return fmt.Errorf("time difference") + return errors.New("time difference") } return nil @@ -190,7 +191,7 @@ func getAuthorizationData(req *http.Request) ([]byte, error) { tmp := make([]string, len(valueList)) for k, v := range valueList { if k > len(tmp) { - return nil, fmt.Errorf("invalid X-Ops-Authorization headers") + return nil, errors.New("invalid X-Ops-Authorization headers") } tmp[k-1] = v } @@ -267,7 +268,7 @@ func verifyDataOld(signature, data []byte, pub *rsa.PublicKey) error { } if !slices.Equal(out[skip:], data) { - return fmt.Errorf("could not verify signature") + return errors.New("could not verify signature") } return nil diff --git a/routers/api/v1/activitypub/reqsignature.go b/routers/api/v1/activitypub/reqsignature.go index 2d9cd3b1bb..b84fbe05fa 100644 --- a/routers/api/v1/activitypub/reqsignature.go +++ b/routers/api/v1/activitypub/reqsignature.go @@ -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 diff --git a/routers/api/v1/admin/quota_rule.go b/routers/api/v1/admin/quota_rule.go index ea188107fa..c2bc6843e4 100644 --- a/routers/api/v1/admin/quota_rule.go +++ b/routers/api/v1/admin/quota_rule.go @@ -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 } diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go index 3b0a4410ed..8aa67b3b0a 100644 --- a/routers/api/v1/admin/user.go +++ b/routers/api/v1/admin/user.go @@ -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 } diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index 7474df4fd9..7c9593d625 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -6,7 +6,6 @@ package repo import ( "errors" - "fmt" "net/http" "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) } diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index dd1d7b3a9a..3408f88dd1 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -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 } diff --git a/routers/api/v1/repo/issue_label.go b/routers/api/v1/repo/issue_label.go index 85af1149ff..3b2935305c 100644 --- a/routers/api/v1/repo/issue_label.go +++ b/routers/api/v1/repo/issue_label.go @@ -5,7 +5,7 @@ package repo import ( - "fmt" + "errors" "net/http" "reflect" @@ -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) diff --git a/routers/api/v1/repo/issue_tracked_time.go b/routers/api/v1/repo/issue_tracked_time.go index 7d88b1b2cd..61875b577c 100644 --- a/routers/api/v1/repo/issue_tracked_time.go +++ b/routers/api/v1/repo/issue_tracked_time.go @@ -4,6 +4,7 @@ package repo import ( + "errors" "fmt" "net/http" "time" @@ -116,7 +117,7 @@ func ListTrackedTimes(ctx *context.APIContext) { if opts.UserID == 0 { opts.UserID = ctx.Doer.ID } else { - ctx.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 } } diff --git a/routers/api/v1/repo/migrate.go b/routers/api/v1/repo/migrate.go index d0ab5e270e..4ee7aa58e4 100644 --- a/routers/api/v1/repo/migrate.go +++ b/routers/api/v1/repo/migrate.go @@ -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 } diff --git a/routers/api/v1/repo/notes.go b/routers/api/v1/repo/notes.go index 87903d9f36..f3ceeaeacf 100644 --- a/routers/api/v1/repo/notes.go +++ b/routers/api/v1/repo/notes.go @@ -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 } diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index b0bc7be90f..75b4870e51 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -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) } diff --git a/routers/api/v1/repo/pull_review.go b/routers/api/v1/repo/pull_review.go index aa4c7318a2..830a62bf54 100644 --- a/routers/api/v1/repo/pull_review.go +++ b/routers/api/v1/repo/pull_review.go @@ -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 diff --git a/routers/api/v1/repo/release.go b/routers/api/v1/repo/release.go index 336741b932..0bf958b523 100644 --- a/routers/api/v1/repo/release.go +++ b/routers/api/v1/repo/release.go @@ -4,6 +4,7 @@ package repo import ( + "errors" "fmt" "net/http" @@ -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) diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index 50f628e035..63100bca06 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -5,6 +5,7 @@ package repo import ( + "errors" "fmt" "net/http" "slices" @@ -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 } diff --git a/routers/api/v1/repo/transfer.go b/routers/api/v1/repo/transfer.go index 3b6cb4d3f2..72cfeaf902 100644 --- a/routers/api/v1/repo/transfer.go +++ b/routers/api/v1/repo/transfer.go @@ -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 { diff --git a/routers/api/v1/user/gpg_key.go b/routers/api/v1/user/gpg_key.go index 1581358b66..886e33b205 100644 --- a/routers/api/v1/user/gpg_key.go +++ b/routers/api/v1/user/gpg_key.go @@ -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 } diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go index 7119de9b2e..d8b5dfdfe9 100644 --- a/routers/api/v1/user/key.go +++ b/routers/api/v1/user/key.go @@ -5,7 +5,7 @@ package user import ( std_ctx "context" - "fmt" + "errors" "net/http" asymkey_model "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 } diff --git a/routers/api/v1/utils/git.go b/routers/api/v1/utils/git.go index 5359a54899..65a8994405 100644 --- a/routers/api/v1/utils/git.go +++ b/routers/api/v1/utils/git.go @@ -5,6 +5,7 @@ package utils import ( gocontext "context" + "errors" "fmt" "net/http" @@ -50,7 +51,7 @@ func ResolveRefOrSha(ctx *context.APIContext, ref string) string { // GetGitRefs return git references based on filter func GetGitRefs(ctx *context.APIContext, filter string) ([]*git.Reference, string, error) { if ctx.Repo.GitRepo == nil { - return nil, "", fmt.Errorf("no open git repo found in context") + return nil, "", errors.New("no open git repo found in context") } if len(filter) > 0 { filter = "refs/" + filter diff --git a/routers/common/db.go b/routers/common/db.go index 0f78d8debc..ec31ced1bf 100644 --- a/routers/common/db.go +++ b/routers/common/db.go @@ -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) diff --git a/routers/private/manager_process.go b/routers/private/manager_process.go index 87447da2be..e60ed04879 100644 --- a/routers/private/manager_process.go +++ b/routers/private/manager_process.go @@ -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 += " " diff --git a/routers/web/auth/openid.go b/routers/web/auth/openid.go index b12dea84ea..fcb2155953 100644 --- a/routers/web/auth/openid.go +++ b/routers/web/auth/openid.go @@ -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") } } diff --git a/routers/web/repo/action_aggregator_test.go b/routers/web/repo/action_aggregator_test.go index e1c6d37fd0..385cf5cbe5 100644 --- a/routers/web/repo/action_aggregator_test.go +++ b/routers/web/repo/action_aggregator_test.go @@ -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) diff --git a/routers/web/repo/actions/view.go b/routers/web/repo/actions/view.go index 364bbf34a8..260468f207 100644 --- a/routers/web/repo/actions/view.go +++ b/routers/web/repo/actions/view.go @@ -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 } diff --git a/routers/web/user/setting/keys.go b/routers/web/user/setting/keys.go index 94d32b730f..935efd7ba7 100644 --- a/routers/web/user/setting/keys.go +++ b/routers/web/user/setting/keys.go @@ -5,7 +5,7 @@ package setting import ( - "fmt" + "errors" "net/http" asymkey_model "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 } diff --git a/services/actions/auth.go b/services/actions/auth.go index 4dc86a35f3..98b618aeba 100644 --- a/services/actions/auth.go +++ b/services/actions/auth.go @@ -4,6 +4,7 @@ package actions import ( + "errors" "fmt" "net/http" "strings" @@ -80,7 +81,7 @@ func ParseAuthorizationToken(req *http.Request) (int64, error) { parts := strings.SplitN(h, " ", 2) if len(parts) != 2 { log.Error("split token failed: %s", h) - return 0, fmt.Errorf("split token failed") + return 0, errors.New("split token failed") } return TokenToTaskID(parts[1]) @@ -100,7 +101,7 @@ func TokenToTaskID(token string) (int64, error) { c, ok := parsedToken.Claims.(*actionsClaims) if !parsedToken.Valid || !ok { - return 0, fmt.Errorf("invalid token claim") + return 0, errors.New("invalid token claim") } return c.TaskID, nil diff --git a/services/actions/commit_status.go b/services/actions/commit_status.go index 1fffa6852f..755fa648dc 100644 --- a/services/actions/commit_status.go +++ b/services/actions/commit_status.go @@ -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: diff --git a/services/actions/schedule_tasks.go b/services/actions/schedule_tasks.go index 9bfa7d3e1d..3ec0807d5f 100644 --- a/services/actions/schedule_tasks.go +++ b/services/actions/schedule_tasks.go @@ -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. diff --git a/services/actions/task.go b/services/actions/task.go index 4e885f69cc..bb319c7d05 100644 --- a/services/actions/task.go +++ b/services/actions/task.go @@ -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() { diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index d3cbb8aa60..e776ccbbed 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -134,7 +134,7 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { // Check if it's really a ssh certificate cert, ok := pk.(*ssh.Certificate) if !ok { - return nil, fmt.Errorf("no certificate found") + return nil, errors.New("no certificate found") } c := &ssh.CertChecker{ @@ -153,7 +153,7 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { // check the CA of the cert if !c.IsUserAuthority(cert.SignatureKey) { - return nil, fmt.Errorf("CA check failed") + return nil, errors.New("CA check failed") } // Create a verifier @@ -191,7 +191,7 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { } // No public key matching a principal in the certificate is registered in gitea - return nil, fmt.Errorf("no valid principal found") + return nil, errors.New("no valid principal found") } // doVerify iterates across the provided public keys attempting the verify the current request against each key in turn diff --git a/services/auth/source/oauth2/token.go b/services/auth/source/oauth2/token.go index fba1fd8a01..b060b6b746 100644 --- a/services/auth/source/oauth2/token.go +++ b/services/auth/source/oauth2/token.go @@ -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 } diff --git a/services/automerge/automerge.go b/services/automerge/automerge.go index 51a14edd9a..f183136907 100644 --- a/services/automerge/automerge.go +++ b/services/automerge/automerge.go @@ -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 diff --git a/services/context/api.go b/services/context/api.go index 0a3cb04399..e9f67c720d 100644 --- a/services/context/api.go +++ b/services/context/api.go @@ -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 } diff --git a/services/doctor/authorizedkeys.go b/services/doctor/authorizedkeys.go index 04a3680ff5..465a3fc7c0 100644 --- a/services/doctor/authorizedkeys.go +++ b/services/doctor/authorizedkeys.go @@ -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) diff --git a/services/doctor/lfs.go b/services/doctor/lfs.go index fed127de5d..fe858605f4 100644 --- a/services/doctor/lfs.go +++ b/services/doctor/lfs.go @@ -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{ diff --git a/services/externalaccount/link.go b/services/externalaccount/link.go index f5d29b5ce5..5672313181 100644 --- a/services/externalaccount/link.go +++ b/services/externalaccount/link.go @@ -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)) diff --git a/services/federation/federation_service.go b/services/federation/federation_service.go index 3d6e219ffc..174c175f86 100644 --- a/services/federation/federation_service.go +++ b/services/federation/federation_service.go @@ -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 { diff --git a/services/issue/comments.go b/services/issue/comments.go index 2993d38003..2cac900d41 100644 --- a/services/issue/comments.go +++ b/services/issue/comments.go @@ -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. diff --git a/services/issue/issue.go b/services/issue/issue.go index 1ec41476b4..7071a912b0 100644 --- a/services/issue/issue.go +++ b/services/issue/issue.go @@ -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 diff --git a/services/issue/milestone.go b/services/issue/milestone.go index 3fa7083812..a561bf8eee 100644 --- a/services/issue/milestone.go +++ b/services/issue/milestone.go @@ -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") } } diff --git a/services/lfs/server.go b/services/lfs/server.go index 8b2d5e66e1..17e6d0eec7 100644 --- a/services/lfs/server.go +++ b/services/lfs/server.go @@ -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) { diff --git a/services/mailer/mail_team_invite.go b/services/mailer/mail_team_invite.go index a2a871d3c3..5375133415 100644 --- a/services/mailer/mail_team_invite.go +++ b/services/mailer/mail_team_invite.go @@ -6,6 +6,7 @@ package mailer import ( "bytes" "context" + "errors" "fmt" "net/url" @@ -39,7 +40,7 @@ func MailTeamInvite(ctx context.Context, inviter *user_model.User, team *org_mod if err != nil && !user_model.IsErrUserNotExist(err) { return err } else if user != nil && user.ProhibitLogin { - return fmt.Errorf("login is prohibited for the invited user") + return errors.New("login is prohibited for the invited user") } inviteRedirect := url.QueryEscape(fmt.Sprintf("/org/invite/%s", invite.Token)) diff --git a/services/mailer/mailer.go b/services/mailer/mailer.go index 4561240df5..ca5c645e0c 100644 --- a/services/mailer/mailer.go +++ b/services/mailer/mailer.go @@ -8,6 +8,7 @@ import ( "bytes" "context" "crypto/tls" + "errors" "fmt" "hash/fnv" "io" @@ -176,7 +177,7 @@ func (a *ntlmAuth) Start(server *smtp.ServerInfo) (string, []byte, error) { func (a *ntlmAuth) Next(fromServer []byte, more bool) ([]byte, error) { if more { if len(fromServer) == 0 { - return nil, fmt.Errorf("ntlm ChallengeMessage is empty") + return nil, errors.New("ntlm ChallengeMessage is empty") } authenticateMessage, err := ntlmssp.ProcessChallenge(fromServer, a.username, a.password, a.domainNeeded) return authenticateMessage, err @@ -264,7 +265,7 @@ func (s *smtpSender) Send(from string, to []string, msg io.WriterTo) error { canAuth, options := client.Extension("AUTH") if len(opts.User) > 0 { if !canAuth { - return fmt.Errorf("SMTP server does not support AUTH, but credentials provided") + return errors.New("SMTP server does not support AUTH, but credentials provided") } var auth smtp.Auth diff --git a/services/markup/processorhelper.go b/services/markup/processorhelper.go index b5fcd78cb7..2f1b1e738c 100644 --- a/services/markup/processorhelper.go +++ b/services/markup/processorhelper.go @@ -5,7 +5,7 @@ package markup import ( "context" - "fmt" + "errors" "forgejo.org/models/perm/access" "forgejo.org/models/repo" @@ -55,7 +55,7 @@ func ProcessorHelper() *markup.ProcessorHelper { return nil, err } if !perms.CanRead(unit.TypeCode) { - return nil, fmt.Errorf("cannot access repository code") + return nil, errors.New("cannot access repository code") } gitRepo, err := gitrepo.OpenRepository(ctx, repo) diff --git a/services/migrations/gogs_test.go b/services/migrations/gogs_test.go index 6780ad2923..bf0d063ca4 100644 --- a/services/migrations/gogs_test.go +++ b/services/migrations/gogs_test.go @@ -25,7 +25,7 @@ func TestGogsDownloadRepo(t *testing.T) { resp, err := http.Get("https://try.gogs.io/lunnytest/TESTREPO") if err != nil || resp.StatusCode/100 != 2 { // skip and don't run test - t.Skipf("visit test repo failed, ignored") + t.Skip("visit test repo failed, ignored") return } diff --git a/services/migrations/migrate.go b/services/migrations/migrate.go index 81d1c203fe..61630d9c6d 100644 --- a/services/migrations/migrate.go +++ b/services/migrations/migrate.go @@ -6,6 +6,7 @@ package migrations import ( "context" + "errors" "fmt" "net" "net/url" @@ -227,7 +228,7 @@ func migrateRepository(_ context.Context, doer *user_model.User, downloader base if cloneURL.Scheme == "file" || cloneURL.Scheme == "" { if cloneAddrURL.Scheme != "file" && cloneAddrURL.Scheme != "" { - return fmt.Errorf("repo info has changed from external to local filesystem") + return errors.New("repo info has changed from external to local filesystem") } } diff --git a/services/mirror/mirror.go b/services/mirror/mirror.go index 6d871ad5ff..514b7c3969 100644 --- a/services/mirror/mirror.go +++ b/services/mirror/mirror.go @@ -5,7 +5,7 @@ package mirror import ( "context" - "fmt" + "errors" quota_model "forgejo.org/models/quota" repo_model "forgejo.org/models/repo" @@ -31,7 +31,7 @@ func doMirrorSync(ctx context.Context, req *SyncRequest) { } } -var errLimit = fmt.Errorf("reached limit") +var errLimit = errors.New("reached limit") // Update checks and updates mirror repositories. func Update(ctx context.Context, pullLimit, pushLimit int) error { @@ -70,7 +70,7 @@ func Update(ctx context.Context, pullLimit, pushLimit int) error { // Check we've not been cancelled select { case <-ctx.Done(): - return fmt.Errorf("aborted") + return errors.New("aborted") default: } diff --git a/services/packages/alpine/repository.go b/services/packages/alpine/repository.go index 9435887a46..dd66c7d74e 100644 --- a/services/packages/alpine/repository.go +++ b/services/packages/alpine/repository.go @@ -258,7 +258,7 @@ func buildPackagesIndex(ctx context.Context, ownerID int64, repoVersion *package privPem, _ := pem.Decode([]byte(priv)) if privPem == nil { - return fmt.Errorf("failed to decode private key pem") + return errors.New("failed to decode private key pem") } privKey, err := x509.ParsePKCS1PrivateKey(privPem.Bytes) diff --git a/services/packages/auth.go b/services/packages/auth.go index ab2c347bc9..205125cf8b 100644 --- a/services/packages/auth.go +++ b/services/packages/auth.go @@ -4,6 +4,7 @@ package packages import ( + "errors" "fmt" "net/http" "strings" @@ -53,7 +54,7 @@ func ParseAuthorizationToken(req *http.Request) (int64, auth_model.AccessTokenSc 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") } token, err := jwt.ParseWithClaims(parts[1], &packageClaims{}, func(t *jwt.Token) (any, error) { @@ -68,7 +69,7 @@ func ParseAuthorizationToken(req *http.Request) (int64, auth_model.AccessTokenSc c, ok := token.Claims.(*packageClaims) if !token.Valid || !ok { - return 0, "", fmt.Errorf("invalid token claim") + return 0, "", errors.New("invalid token claim") } return c.UserID, c.Scope, nil diff --git a/services/pull/check.go b/services/pull/check.go index d038b3d829..afeb7e675e 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -395,7 +395,7 @@ func Init() error { prPatchCheckerQueue = queue.CreateUniqueQueue(graceful.GetManager().ShutdownContext(), "pr_patch_checker", handler) if prPatchCheckerQueue == nil { - return fmt.Errorf("unable to create pr_patch_checker queue") + return errors.New("unable to create pr_patch_checker queue") } go graceful.GetManager().RunWithCancel(prPatchCheckerQueue) diff --git a/services/pull/merge.go b/services/pull/merge.go index 9b0d632377..3f07c3df9b 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -6,6 +6,7 @@ package pull import ( "context" + "errors" "fmt" "net/url" "os" @@ -518,13 +519,13 @@ func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *use objectFormat := git.ObjectFormatFromName(pr.BaseRepo.ObjectFormatName) if len(commitID) != objectFormat.FullLength() { - return fmt.Errorf("Wrong commit ID") + return errors.New("Wrong commit ID") } commit, err := baseGitRepo.GetCommit(commitID) if err != nil { if git.IsErrNotExist(err) { - return fmt.Errorf("Wrong commit ID") + return errors.New("Wrong commit ID") } return err } @@ -535,7 +536,7 @@ func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *use return err } if !ok { - return fmt.Errorf("Wrong commit ID") + return errors.New("Wrong commit ID") } pr.MergedCommitID = commitID @@ -548,7 +549,7 @@ func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *use if merged, err = pr.SetMerged(ctx); err != nil { return err } else if !merged { - return fmt.Errorf("SetMerged failed") + return errors.New("SetMerged failed") } return nil }); err != nil { diff --git a/services/pull/review.go b/services/pull/review.go index 18c27de5a7..c740328e4c 100644 --- a/services/pull/review.go +++ b/services/pull/review.go @@ -6,6 +6,7 @@ package pull import ( "context" + "errors" "fmt" "io" "regexp" @@ -387,7 +388,7 @@ func DismissReview(ctx context.Context, reviewID, repoID int64, message string, } if review.Type != issues_model.ReviewTypeApprove && review.Type != issues_model.ReviewTypeReject { - return nil, fmt.Errorf("not need to dismiss this review because it's type is not Approve or change request") + return nil, errors.New("not need to dismiss this review because it's type is not Approve or change request") } // load data for notify @@ -397,7 +398,7 @@ func DismissReview(ctx context.Context, reviewID, repoID int64, message string, // Check if the review's repoID is the one we're currently expecting. if review.Issue.RepoID != repoID { - return nil, fmt.Errorf("reviews's repository is not the same as the one we expect") + return nil, errors.New("reviews's repository is not the same as the one we expect") } issue := review.Issue diff --git a/services/pull/update.go b/services/pull/update.go index 470abbd6dd..563c11fff3 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -5,6 +5,7 @@ package pull import ( "context" + "errors" "fmt" git_model "forgejo.org/models/git" @@ -22,7 +23,7 @@ import ( func Update(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, message string, rebase bool) error { if pr.Flow == issues_model.PullRequestFlowAGit { // TODO: update of agit flow pull request's head branch is unsupported - return fmt.Errorf("update of agit flow pull request's head branch is unsupported") + return errors.New("update of agit flow pull request's head branch is unsupported") } pullWorkingPool.CheckIn(fmt.Sprint(pr.ID)) diff --git a/services/release/release.go b/services/release/release.go index f0682c4dca..90eb1320ed 100644 --- a/services/release/release.go +++ b/services/release/release.go @@ -161,17 +161,17 @@ func CreateRelease(gitRepo *git.Repository, rel *repo_model.Release, msg string, for _, attachmentChange := range attachmentChanges { if attachmentChange.Action != "add" { - return fmt.Errorf("can only create new attachments when creating release") + return errors.New("can only create new attachments when creating release") } switch attachmentChange.Type { case "attachment": if attachmentChange.UUID == "" { - return fmt.Errorf("new attachment should have a uuid") + return errors.New("new attachment should have a uuid") } addAttachmentUUIDs.Add(attachmentChange.UUID) case "external": if attachmentChange.Name == "" || attachmentChange.ExternalURL == "" { - return fmt.Errorf("new external attachment should have a name and external url") + return errors.New("new external attachment should have a name and external url") } _, err = attachment.NewExternalAttachment(gitRepo.Ctx, &repo_model.Attachment{ @@ -186,7 +186,7 @@ func CreateRelease(gitRepo *git.Repository, rel *repo_model.Release, msg string, } default: if attachmentChange.Type == "" { - return fmt.Errorf("missing attachment type") + return errors.New("missing attachment type") } return fmt.Errorf("unknown attachment type: '%q'", attachmentChange.Type) } @@ -280,7 +280,7 @@ func UpdateRelease(ctx context.Context, doer *user_model.User, gitRepo *git.Repo addAttachmentUUIDs.Add(attachmentChange.UUID) case "external": if attachmentChange.Name == "" || attachmentChange.ExternalURL == "" { - return fmt.Errorf("new external attachment should have a name and external url") + return errors.New("new external attachment should have a name and external url") } _, err := attachment.NewExternalAttachment(ctx, &repo_model.Attachment{ Name: attachmentChange.Name, @@ -294,13 +294,13 @@ func UpdateRelease(ctx context.Context, doer *user_model.User, gitRepo *git.Repo } default: if attachmentChange.Type == "" { - return fmt.Errorf("missing attachment type") + return errors.New("missing attachment type") } return fmt.Errorf("unknown attachment type: %q", attachmentChange.Type) } case "delete": if attachmentChange.UUID == "" { - return fmt.Errorf("attachment deletion should have a uuid") + return errors.New("attachment deletion should have a uuid") } delAttachmentUUIDs.Add(attachmentChange.UUID) case "update": @@ -308,7 +308,7 @@ func UpdateRelease(ctx context.Context, doer *user_model.User, gitRepo *git.Repo updateAttachments.Add(attachmentChange) default: if attachmentChange.Action == "" { - return fmt.Errorf("missing attachment action") + return errors.New("missing attachment action") } return fmt.Errorf("unknown attachment action: %q", attachmentChange.Action) } diff --git a/services/repository/branch.go b/services/repository/branch.go index d5b68c1fa7..bc739825a5 100644 --- a/services/repository/branch.go +++ b/services/repository/branch.go @@ -251,7 +251,7 @@ func SyncBranchesToDB(ctx context.Context, repoID, pusherID int64, branchNames, // For other batches, it will hit optimization 4. if len(branchNames) != len(commitIDs) { - return fmt.Errorf("branchNames and commitIDs length not match") + return errors.New("branchNames and commitIDs length not match") } return db.WithTx(ctx, func(ctx context.Context) error { diff --git a/services/repository/contributors_graph.go b/services/repository/contributors_graph.go index ad4cc400cb..1805bd5960 100644 --- a/services/repository/contributors_graph.go +++ b/services/repository/contributors_graph.go @@ -111,7 +111,7 @@ func GetContributorStats(ctx context.Context, cache cache.Cache, repo *repo_mode var cachedStats map[string]*ContributorData return cachedStats, json.Unmarshal([]byte(v), &cachedStats) default: - return nil, fmt.Errorf("unexpected type in cache detected") + return nil, errors.New("unexpected type in cache detected") } } diff --git a/services/repository/files/cherry_pick.go b/services/repository/files/cherry_pick.go index 838891813e..0e88a29230 100644 --- a/services/repository/files/cherry_pick.go +++ b/services/repository/files/cherry_pick.go @@ -5,6 +5,7 @@ package files import ( "context" + "errors" "fmt" "strings" @@ -88,7 +89,7 @@ func CherryPick(ctx context.Context, repo *repo_model.Repository, doer *user_mod } if conflict { - return nil, fmt.Errorf("failed to merge due to conflicts") + return nil, errors.New("failed to merge due to conflicts") } } else { description := fmt.Sprintf("CherryPick %s onto %s", right, opts.OldBranch) @@ -98,7 +99,7 @@ func CherryPick(ctx context.Context, repo *repo_model.Repository, doer *user_mod } if conflict { - return nil, fmt.Errorf("failed to merge due to conflicts") + return nil, errors.New("failed to merge due to conflicts") } treeHash, err = t.WriteTree() diff --git a/services/repository/files/file.go b/services/repository/files/file.go index 810c60163d..ef9a87dbcf 100644 --- a/services/repository/files/file.go +++ b/services/repository/files/file.go @@ -5,7 +5,7 @@ package files import ( "context" - "fmt" + "errors" "net/url" "strings" "time" @@ -50,10 +50,10 @@ func GetFileResponseFromFilesResponse(filesResponse *api.FilesResponse, index in // GetFileCommitResponse Constructs a FileCommitResponse from a Commit object func GetFileCommitResponse(repo *repo_model.Repository, commit *git.Commit) (*api.FileCommitResponse, error) { if repo == nil { - return nil, fmt.Errorf("repo cannot be nil") + return nil, errors.New("repo cannot be nil") } if commit == nil { - return nil, fmt.Errorf("commit cannot be nil") + return nil, errors.New("commit cannot be nil") } commitURL, _ := url.Parse(repo.APIURL() + "/git/commits/" + url.PathEscape(commit.ID.String())) commitTreeURL, _ := url.Parse(repo.APIURL() + "/git/trees/" + url.PathEscape(commit.Tree.ID.String())) diff --git a/services/repository/files/temp_repo.go b/services/repository/files/temp_repo.go index b3aadbc6cb..64d3e5887d 100644 --- a/services/repository/files/temp_repo.go +++ b/services/repository/files/temp_repo.go @@ -6,6 +6,7 @@ package files import ( "bytes" "context" + "errors" "fmt" "io" "os" @@ -368,7 +369,7 @@ func (t *TemporaryUploadRepository) DiffIndex() (*gitdiff.Diff, error) { // GetBranchCommit Gets the commit object of the given branch func (t *TemporaryUploadRepository) GetBranchCommit(branch string) (*git.Commit, error) { if t.gitRepo == nil { - return nil, fmt.Errorf("repository has not been cloned") + return nil, errors.New("repository has not been cloned") } return t.gitRepo.GetBranchCommit(branch) } @@ -376,7 +377,7 @@ func (t *TemporaryUploadRepository) GetBranchCommit(branch string) (*git.Commit, // GetCommit Gets the commit object of the given commit ID func (t *TemporaryUploadRepository) GetCommit(commitID string) (*git.Commit, error) { if t.gitRepo == nil { - return nil, fmt.Errorf("repository has not been cloned") + return nil, errors.New("repository has not been cloned") } return t.gitRepo.GetCommit(commitID) } diff --git a/services/repository/push.go b/services/repository/push.go index 53574a7d93..eaedd80e1f 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -66,7 +66,7 @@ func PushUpdates(opts []*repo_module.PushUpdateOptions) error { for _, opt := range opts { if opt.IsNewRef() && opt.IsDelRef() { - return fmt.Errorf("Old and new revisions are both NULL") + return errors.New("Old and new revisions are both NULL") } } diff --git a/services/repository/repository.go b/services/repository/repository.go index a2620740b1..41f3a96dd1 100644 --- a/services/repository/repository.go +++ b/services/repository/repository.go @@ -6,6 +6,7 @@ package repository import ( "context" + "errors" "fmt" "forgejo.org/models/db" @@ -72,10 +73,10 @@ func PushCreateRepo(ctx context.Context, authUser, owner *user_model.User, repoN if ok, err := organization.CanCreateOrgRepo(ctx, owner.ID, authUser.ID); err != nil { return nil, err } else if !ok { - return nil, fmt.Errorf("cannot push-create repository for org") + return nil, errors.New("cannot push-create repository for org") } } else if authUser.ID != owner.ID { - return nil, fmt.Errorf("cannot push-create repository for another user") + return nil, errors.New("cannot push-create repository for another user") } } diff --git a/services/task/task.go b/services/task/task.go index 3181fc79d7..f030bdb38c 100644 --- a/services/task/task.go +++ b/services/task/task.go @@ -5,6 +5,7 @@ package task import ( "context" + "errors" "fmt" admin_model "forgejo.org/models/admin" @@ -41,7 +42,7 @@ func Run(ctx context.Context, t *admin_model.Task) error { func Init() error { taskQueue = queue.CreateSimpleQueue(graceful.GetManager().ShutdownContext(), "task", handler) if taskQueue == nil { - return fmt.Errorf("unable to create task queue") + return errors.New("unable to create task queue") } go graceful.GetManager().RunWithCancel(taskQueue) return nil diff --git a/services/webhook/deliver.go b/services/webhook/deliver.go index 0c7c039f10..23aca80345 100644 --- a/services/webhook/deliver.go +++ b/services/webhook/deliver.go @@ -6,6 +6,7 @@ package webhook import ( "context" "crypto/tls" + "errors" "fmt" "io" "net/http" @@ -218,7 +219,7 @@ func Init() error { hookQueue = queue.CreateUniqueQueue(graceful.GetManager().ShutdownContext(), "webhook_sender", handler) if hookQueue == nil { - return fmt.Errorf("unable to create webhook_sender queue") + return errors.New("unable to create webhook_sender queue") } go graceful.GetManager().RunWithCancel(hookQueue) diff --git a/services/wiki/wiki_test.go b/services/wiki/wiki_test.go index ff5141a1fd..cb984425af 100644 --- a/services/wiki/wiki_test.go +++ b/services/wiki/wiki_test.go @@ -284,9 +284,9 @@ func TestPrepareWikiFileName(t *testing.T) { } if existence != tt.existence { if existence { - t.Errorf("expect to find no escaped file but we detect one") + t.Error("expect to find no escaped file but we detect one") } else { - t.Errorf("expect to find an escaped file but we could not detect one") + t.Error("expect to find an escaped file but we could not detect one") } } assert.Equal(t, tt.wikiPath, newWikiPath) diff --git a/tests/integration/api_actions_artifact_test.go b/tests/integration/api_actions_artifact_test.go index dc2b86d28b..d6db22700a 100644 --- a/tests/integration/api_actions_artifact_test.go +++ b/tests/integration/api_actions_artifact_test.go @@ -56,7 +56,7 @@ func TestActionsArtifactUploadSingleFile(t *testing.T) { SetHeader("x-actions-results-md5", "XVlf820rMInUi64wmMi6EA==") // base64(md5(body)) MakeRequest(t, req, http.StatusOK) - t.Logf("Create artifact confirm") + t.Log("Create artifact confirm") // confirm artifact upload req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName=artifact-single"). @@ -206,7 +206,7 @@ func TestActionsArtifactUploadMultipleFile(t *testing.T) { MakeRequest(t, req, http.StatusOK) } - t.Logf("Create artifact confirm") + t.Log("Create artifact confirm") // confirm artifact upload req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName="+testArtifactName). @@ -297,7 +297,7 @@ func TestActionsArtifactUploadWithRetentionDays(t *testing.T) { SetHeader("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) MakeRequest(t, req, http.StatusOK) - t.Logf("Create artifact confirm") + t.Log("Create artifact confirm") // confirm artifact upload req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName=artifact-retention-days"). diff --git a/tests/integration/api_actions_artifact_v4_test.go b/tests/integration/api_actions_artifact_v4_test.go index 9fa7590620..af0dcb98a9 100644 --- a/tests/integration/api_actions_artifact_v4_test.go +++ b/tests/integration/api_actions_artifact_v4_test.go @@ -59,7 +59,7 @@ func uploadArtifact(t *testing.T, body string) string { req = NewRequestWithBody(t, "PUT", url, strings.NewReader(body)) MakeRequest(t, req, http.StatusCreated) - t.Logf("Create artifact confirm") + t.Log("Create artifact confirm") sha := sha256.Sum256([]byte(body)) @@ -113,7 +113,7 @@ func TestActionsArtifactV4UploadSingleFileWrongChecksum(t *testing.T) { req = NewRequestWithBody(t, "PUT", url, strings.NewReader(body)) MakeRequest(t, req, http.StatusCreated) - t.Logf("Create artifact confirm") + t.Log("Create artifact confirm") sha := sha256.Sum256([]byte(strings.Repeat("A", 1024))) @@ -158,7 +158,7 @@ func TestActionsArtifactV4UploadSingleFileWithRetentionDays(t *testing.T) { req = NewRequestWithBody(t, "PUT", url, strings.NewReader(body)) MakeRequest(t, req, http.StatusCreated) - t.Logf("Create artifact confirm") + t.Log("Create artifact confirm") sha := sha256.Sum256([]byte(body)) @@ -221,7 +221,7 @@ func TestActionsArtifactV4UploadSingleFileWithPotentialHarmfulBlockID(t *testing req = NewRequestWithBody(t, "PUT", blockListURL, bytes.NewReader(rawBlockList)) MakeRequest(t, req, http.StatusCreated) - t.Logf("Create artifact confirm") + t.Log("Create artifact confirm") sha := sha256.Sum256([]byte(body)) @@ -286,7 +286,7 @@ func TestActionsArtifactV4UploadSingleFileWithChunksOutOfOrder(t *testing.T) { req = NewRequestWithBody(t, "PUT", blockListURL, bytes.NewReader(rawBlockList)) MakeRequest(t, req, http.StatusCreated) - t.Logf("Create artifact confirm") + t.Log("Create artifact confirm") sha := sha256.Sum256([]byte(bodya + bodyb)) diff --git a/tests/integration/repo_settings_test.go b/tests/integration/repo_settings_test.go index 8814a44699..63cc5332bc 100644 --- a/tests/integration/repo_settings_test.go +++ b/tests/integration/repo_settings_test.go @@ -367,7 +367,7 @@ func TestRepoFollowing(t *testing.T) { isLikeType := activityType == "Like" isCorrectObject := strings.HasSuffix(object, "/api/v1/activitypub/repository-id/1") if !isLikeType || !isCorrectObject { - t.Errorf("Activity is not a like for this repo") + t.Error("Activity is not a like for this repo") } }) }