refactor: use errors.New to replace fmt.Errorf with no parameters (#20943)

Co-authored-by: Marko <marko@baricevic.me>
This commit is contained in:
Qt 2024-07-18 18:01:45 +08:00 committed by GitHub
parent 9376db5508
commit 3304d0803d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
22 changed files with 75 additions and 61 deletions

View File

@ -177,7 +177,7 @@ func validateExtendedCommitAgainstLastCommit(ec abci.ExtendedCommitInfo, lc come
}
return -int(vote1.Validator.Power - vote2.Validator.Power) // vp sorted in descending order
}) {
return fmt.Errorf("extended commit votes are not sorted by voting power")
return errors.New("extended commit votes are not sorted by voting power")
}
addressCache := make(map[string]struct{}, len(ec.Votes))

View File

@ -2,6 +2,7 @@ package config
import (
"crypto/tls"
"errors"
"fmt"
"os"
"path/filepath"
@ -68,7 +69,7 @@ func CreateClientConfig(ctx client.Context, customClientTemplate string, customC
}
if (customClientTemplate != "" && customConfig == nil) || (customClientTemplate == "" && customConfig != nil) {
return ctx, fmt.Errorf("customClientTemplate and customConfig should be both nil or not nil")
return ctx, errors.New("customClientTemplate and customConfig should be both nil or not nil")
}
if customClientTemplate != "" {

View File

@ -1,6 +1,7 @@
package client
import (
"errors"
"fmt"
"net/url"
"unicode"
@ -11,7 +12,7 @@ import (
// ValidatePromptNotEmpty validates that the input is not empty.
func ValidatePromptNotEmpty(input string) error {
if input == "" {
return fmt.Errorf("input cannot be empty")
return errors.New("input cannot be empty")
}
return nil

View File

@ -1,6 +1,7 @@
package pruning
import (
"errors"
"fmt"
"path/filepath"
@ -76,7 +77,7 @@ Supported app-db-backend types include 'goleveldb', 'rocksdb', 'pebbledb'.`,
rootMultiStore, ok := cms.(*rootmulti.Store)
if !ok {
return fmt.Errorf("currently only support the pruning of rootmulti.Store type")
return errors.New("currently only support the pruning of rootmulti.Store type")
}
latestHeight := rootmulti.GetLatestVersion(db)
// valid heights should be greater than 0.

View File

@ -4,6 +4,7 @@ import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
@ -17,7 +18,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/version"
)
@ -187,7 +188,7 @@ $ %[1]s tx [flags] | %[1]s q wait-tx
return clientCtx.PrintProto(newResponseFormatBroadcastTxCommit(res))
}
case <-ctx.Done():
return errors.ErrLogic.Wrapf("timed out waiting for transaction %X to be included in a block", hash)
return sdkerrors.ErrLogic.Wrapf("timed out waiting for transaction %X to be included in a block", hash)
}
return nil
},
@ -222,5 +223,5 @@ func parseHashFromInput(in []byte) ([]byte, error) {
return hex.DecodeString(hash)
}
}
return nil, fmt.Errorf("txhash not found")
return nil, errors.New("txhash not found")
}

View File

@ -2,6 +2,7 @@ package flag
import (
"context"
"errors"
"fmt"
"google.golang.org/protobuf/reflect/protoreflect"
@ -47,7 +48,7 @@ func (a *pubkeyValue) Set(s string) error {
any, err := types.NewAnyWithValue(pk)
if err != nil {
return fmt.Errorf("error converting to any type")
return errors.New("error converting to any type")
}
a.value = any

View File

@ -2,6 +2,7 @@ package autocli
import (
"context"
"errors"
"fmt"
"io"
"strings"
@ -176,14 +177,14 @@ func encoder(encoder aminojson.Encoder) aminojson.Encoder {
fields := msg.Descriptor().Fields()
secondsField := fields.ByName(secondsName)
if secondsField == nil {
return fmt.Errorf("expected seconds field")
return errors.New("expected seconds field")
}
seconds := msg.Get(secondsField).Int()
nanosField := fields.ByName(nanosName)
if nanosField == nil {
return fmt.Errorf("expected nanos field")
return errors.New("expected nanos field")
}
nanos := msg.Get(nanosField).Int()
@ -199,14 +200,14 @@ func encoder(encoder aminojson.Encoder) aminojson.Encoder {
fields := msg.Descriptor().Fields()
denomField := fields.ByName(denomName)
if denomField == nil {
return fmt.Errorf("expected denom field")
return errors.New("expected denom field")
}
denom := msg.Get(denomField).String()
amountField := fields.ByName(amountName)
if amountField == nil {
return fmt.Errorf("expected amount field")
return errors.New("expected amount field")
}
amount := msg.Get(amountField).String()

View File

@ -2,6 +2,7 @@ package runtime
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
@ -31,7 +32,7 @@ type msgRouterService struct {
// CanInvoke returns an error if the given message cannot be invoked.
func (m *msgRouterService) CanInvoke(ctx context.Context, typeURL string) error {
if typeURL == "" {
return fmt.Errorf("missing type url")
return errors.New("missing type url")
}
typeURL = strings.TrimPrefix(typeURL, "/")
@ -94,7 +95,7 @@ type queryRouterService struct {
// CanInvoke returns an error if the given request cannot be invoked.
func (m *queryRouterService) CanInvoke(ctx context.Context, typeURL string) error {
if typeURL == "" {
return fmt.Errorf("missing type url")
return errors.New("missing type url")
}
typeURL = strings.TrimPrefix(typeURL, "/")

View File

@ -1,7 +1,7 @@
package decoding
import (
"fmt"
"errors"
"testing"
"cosmossdk.io/schema"
@ -106,7 +106,7 @@ func TestModuleSetDecoderResolver_LookupDecoder(t *testing.T) {
type modD struct{}
func (m modD) ModuleCodec() (schema.ModuleCodec, error) {
return schema.ModuleCodec{}, fmt.Errorf("an error")
return schema.ModuleCodec{}, errors.New("an error")
}
func TestModuleSetDecoderResolver_IterateAll_Error(t *testing.T) {

View File

@ -1,6 +1,9 @@
package schema
import "fmt"
import (
"errors"
"fmt"
)
// EnumDefinition represents the definition of an enum type.
type EnumDefinition struct {
@ -22,7 +25,7 @@ func (e EnumDefinition) Validate() error {
}
if len(e.Values) == 0 {
return fmt.Errorf("enum definition values cannot be empty")
return errors.New("enum definition values cannot be empty")
}
seen := make(map[string]bool, len(e.Values))
for i, v := range e.Values {

View File

@ -292,7 +292,7 @@ func interceptConfigs(rootViper *viper.Viper, customAppTemplate string, customCo
appCfgFilePath := filepath.Join(configPath, "app.toml")
if _, err := os.Stat(appCfgFilePath); os.IsNotExist(err) {
if (customAppTemplate != "" && customConfig == nil) || (customAppTemplate == "" && customConfig != nil) {
return nil, fmt.Errorf("customAppTemplate and customConfig should be both nil or not nil")
return nil, errors.New("customAppTemplate and customConfig should be both nil or not nil")
}
if customAppTemplate != "" {

View File

@ -1,6 +1,7 @@
package root
import (
"errors"
"fmt"
"os"
@ -76,7 +77,7 @@ func CreateRootStore(opts *FactoryOptions) (store.RootStore, error) {
ssDb, err = pebbledb.New(dir)
case SSTypeRocks:
// TODO: rocksdb requires build tags so is not supported here by default
return nil, fmt.Errorf("rocksdb not supported")
return nil, errors.New("rocksdb not supported")
}
if err != nil {
return nil, err
@ -110,7 +111,7 @@ func CreateRootStore(opts *FactoryOptions) (store.RootStore, error) {
case SCTypeIavl:
trees[key] = iavl.NewIavlTree(db.NewPrefixDB(opts.SCRawDB, []byte(key)), opts.Logger, opts.IavlConfig)
case SCTypeIavlV2:
return nil, fmt.Errorf("iavl v2 not supported")
return nil, errors.New("iavl v2 not supported")
}
}
}

View File

@ -3,6 +3,7 @@ package telemetry
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
@ -192,7 +193,7 @@ func (m *Metrics) Gather(format string) (GatherResponse, error) {
// If Prometheus metrics are not enabled, it returns an error.
func (m *Metrics) gatherPrometheus() (GatherResponse, error) {
if !m.prometheusEnabled {
return GatherResponse{}, fmt.Errorf("prometheus metrics are not enabled")
return GatherResponse{}, errors.New("prometheus metrics are not enabled")
}
metricsFamilies, err := prometheus.DefaultGatherer.Gather()
@ -218,7 +219,7 @@ func (m *Metrics) gatherPrometheus() (GatherResponse, error) {
func (m *Metrics) gatherGeneric() (GatherResponse, error) {
gm, ok := m.sink.(DisplayableSink)
if !ok {
return GatherResponse{}, fmt.Errorf("non in-memory metrics sink does not support generic format")
return GatherResponse{}, errors.New("non in-memory metrics sink does not support generic format")
}
summary, err := gm.DisplayMetrics(nil, nil)

View File

@ -1,7 +1,7 @@
package testutil
import (
"fmt"
"errors"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
@ -47,12 +47,12 @@ func GenerateSaveCoinKey(
// ensure no overwrite
if !overwrite && exists {
return sdk.AccAddress{}, "", fmt.Errorf("key already exists, overwrite is disabled")
return sdk.AccAddress{}, "", errors.New("key already exists, overwrite is disabled")
}
if exists {
if err := keybase.Delete(keyName); err != nil {
return sdk.AccAddress{}, "", fmt.Errorf("failed to overwrite key")
return sdk.AccAddress{}, "", errors.New("failed to overwrite key")
}
}

View File

@ -176,7 +176,7 @@ func (l Launcher) doBackup() error {
}
if uInfo.Name == "" {
return fmt.Errorf("upgrade-info.json is empty")
return errors.New("upgrade-info.json is empty")
}
// a destination directory, Format YYYY-MM-DD
@ -241,7 +241,7 @@ func (l Launcher) doCustomPreUpgrade() error {
if oldMode != newMode {
if err := os.Chmod(preupgradeFile, newMode); err != nil {
l.logger.Info("COSMOVISOR_CUSTOM_PREUPGRADE could not add execute permission")
return fmt.Errorf("COSMOVISOR_CUSTOM_PREUPGRADE could not add execute permission")
return errors.New("COSMOVISOR_CUSTOM_PREUPGRADE could not add execute permission")
}
}

View File

@ -1,7 +1,7 @@
package tx
import (
"fmt"
"errors"
"google.golang.org/protobuf/reflect/protoreflect"
@ -40,22 +40,22 @@ func (t *Tx) GetMsgs() []sdk.Msg {
// ValidateBasic implements the ValidateBasic method on sdk.Tx.
func (t *Tx) ValidateBasic() error {
if t == nil {
return fmt.Errorf("bad Tx")
return errors.New("bad Tx")
}
body := t.Body
if body == nil {
return fmt.Errorf("missing TxBody")
return errors.New("missing TxBody")
}
authInfo := t.AuthInfo
if authInfo == nil {
return fmt.Errorf("missing AuthInfo")
return errors.New("missing AuthInfo")
}
fee := authInfo.Fee
if fee == nil {
return fmt.Errorf("missing fee")
return errors.New("missing fee")
}
if fee.GasLimit > MaxGasWanted {

View File

@ -1,6 +1,7 @@
package cli
import (
"errors"
"fmt"
"strings"
@ -11,7 +12,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
querytypes "github.com/cosmos/cosmos-sdk/types/query"
"github.com/cosmos/cosmos-sdk/version"
)
@ -101,7 +102,7 @@ $ %s query tx --%s=%s <sig1_base64>,<sig2_base64...>
switch typ {
case TypeHash:
if args[0] == "" {
return fmt.Errorf("argument should be a tx hash")
return errors.New("argument should be a tx hash")
}
// if hash is given, then query the tx by hash
@ -135,19 +136,19 @@ $ %s query tx --%s=%s <sig1_base64>,<sig2_base64...>
}
if len(txs.Txs) == 0 {
return fmt.Errorf("found no txs matching given signatures")
return errors.New("found no txs matching given signatures")
}
if len(txs.Txs) > 1 {
// This case means there's a bug somewhere else in the code as this
// should not happen.
return errors.ErrLogic.Wrapf("found %d txs matching given signatures", len(txs.Txs))
return sdkerrors.ErrLogic.Wrapf("found %d txs matching given signatures", len(txs.Txs))
}
return clientCtx.PrintProto(txs.Txs[0])
case TypeAccSeq:
if args[0] == "" {
return fmt.Errorf("`acc_seq` type takes an argument '<addr>/<seq>'")
return errors.New("`acc_seq` type takes an argument '<addr>/<seq>'")
}
query := fmt.Sprintf("%s.%s='%s'", sdk.EventTypeTx, sdk.AttributeKeyAccountSequence, args[0])
@ -158,7 +159,7 @@ $ %s query tx --%s=%s <sig1_base64>,<sig2_base64...>
}
if len(txs.Txs) == 0 {
return fmt.Errorf("found no txs matching given address and sequence combination")
return errors.New("found no txs matching given address and sequence combination")
}
if len(txs.Txs) > 1 {
// This case means there's a bug somewhere else in the code as this
@ -183,7 +184,7 @@ $ %s query tx --%s=%s <sig1_base64>,<sig2_base64...>
// ParseSigArgs parses comma-separated signatures from the CLI arguments.
func ParseSigArgs(args []string) ([]string, error) {
if len(args) != 1 || args[0] == "" {
return nil, fmt.Errorf("argument should be comma-separated signatures")
return nil, errors.New("argument should be comma-separated signatures")
}
return strings.Split(args[0], ","), nil

View File

@ -1,6 +1,7 @@
package cli
import (
"errors"
"fmt"
"os"
@ -257,7 +258,7 @@ func multisigSign(clientCtx client.Context, txBuilder client.TxBuilder, txFactor
}
if !isSigner {
return fmt.Errorf("signing key is not a part of multisig key")
return errors.New("signing key is not a part of multisig key")
}
if err = authclient.SignTxWithSignerAddress(
@ -449,7 +450,7 @@ func signTx(cmd *cobra.Command, clientCtx client.Context, txFactory tx.Factory,
return err
}
if !isSigner {
return fmt.Errorf("signing key is not a part of multisig key")
return errors.New("signing key is not a part of multisig key")
}
err = authclient.SignTxWithSignerAddress(

View File

@ -137,7 +137,7 @@ Examples:
}
if !spendLimit.IsAllPositive() {
return fmt.Errorf("spend-limit should be greater than zero")
return errors.New("spend-limit should be greater than zero")
}
allowList, err := cmd.Flags().GetStringSlice(FlagAllowList)
@ -202,7 +202,7 @@ Examples:
}
if !spendLimit.IsPositive() {
return fmt.Errorf("spend-limit should be greater than zero")
return errors.New("spend-limit should be greater than zero")
}
delegateLimit = &spendLimit
}

View File

@ -209,7 +209,7 @@ func (cs *ConsensusGenesis) UnmarshalJSON(b []byte) error {
func (cs *ConsensusGenesis) ValidateAndComplete() error {
if cs == nil {
return fmt.Errorf("consensus genesis cannot be nil")
return errors.New("consensus genesis cannot be nil")
}
if cs.Params == nil {

View File

@ -196,7 +196,7 @@ func (k Keeper) SetToDistribute(ctx context.Context, amount sdk.Coins, addr stri
totalStreamFundsPercentage = totalStreamFundsPercentage.Add(cf.Percentage)
if totalStreamFundsPercentage.GT(math.LegacyOneDec()) {
return true, fmt.Errorf("total funds percentage cannot exceed 100")
return true, errors.New("total funds percentage cannot exceed 100")
}
return false, nil
@ -272,7 +272,7 @@ func (k Keeper) IterateAndUpdateFundsDistribution(ctx context.Context) error {
// sanity check for max percentage
totalPercentageToBeDistributed = totalPercentageToBeDistributed.Add(cf.Percentage)
if totalPercentageToBeDistributed.GT(math.LegacyOneDec()) {
return true, fmt.Errorf("total funds percentage cannot exceed 100")
return true, errors.New("total funds percentage cannot exceed 100")
}
// Calculate the funds to be distributed based on the percentage
@ -356,7 +356,7 @@ func (k Keeper) getClaimableFunds(ctx context.Context, recipientAddr string) (am
// Check if the distribution time has not reached
if budget.LastClaimedAt != nil {
if currentTime.Before(*budget.LastClaimedAt) {
return sdk.Coin{}, fmt.Errorf("distribution has not started yet")
return sdk.Coin{}, errors.New("distribution has not started yet")
}
}
@ -374,7 +374,7 @@ func (k Keeper) calculateClaimableFunds(ctx context.Context, recipient sdk.AccAd
// Check the time elapsed has passed period length
if timeElapsed < *budget.Period {
return sdk.Coin{}, fmt.Errorf("budget period has not passed yet")
return sdk.Coin{}, errors.New("budget period has not passed yet")
}
// Calculate how many periods have passed
@ -415,7 +415,7 @@ func (k Keeper) calculateClaimableFunds(ctx context.Context, recipient sdk.AccAd
func (k Keeper) validateAndUpdateBudgetProposal(ctx context.Context, bp types.MsgSubmitBudgetProposal) (*types.Budget, error) {
if bp.BudgetPerTranche.IsZero() {
return nil, fmt.Errorf("invalid budget proposal: budget per tranche cannot be zero")
return nil, errors.New("invalid budget proposal: budget per tranche cannot be zero")
}
if err := validateAmount(sdk.NewCoins(*bp.BudgetPerTranche)); err != nil {
@ -428,15 +428,15 @@ func (k Keeper) validateAndUpdateBudgetProposal(ctx context.Context, bp types.Ms
}
if currentTime.After(*bp.StartTime) {
return nil, fmt.Errorf("invalid budget proposal: start time cannot be less than the current block time")
return nil, errors.New("invalid budget proposal: start time cannot be less than the current block time")
}
if bp.Tranches == 0 {
return nil, fmt.Errorf("invalid budget proposal: tranches must be greater than zero")
return nil, errors.New("invalid budget proposal: tranches must be greater than zero")
}
if bp.Period == nil || *bp.Period == 0 {
return nil, fmt.Errorf("invalid budget proposal: period length should be greater than zero")
return nil, errors.New("invalid budget proposal: period length should be greater than zero")
}
// Create and return an updated budget proposal
@ -455,19 +455,19 @@ func (k Keeper) validateAndUpdateBudgetProposal(ctx context.Context, bp types.Ms
func (k Keeper) validateContinuousFund(ctx context.Context, msg types.MsgCreateContinuousFund) error {
// Validate percentage
if msg.Percentage.IsZero() || msg.Percentage.IsNil() {
return fmt.Errorf("percentage cannot be zero or empty")
return errors.New("percentage cannot be zero or empty")
}
if msg.Percentage.IsNegative() {
return fmt.Errorf("percentage cannot be negative")
return errors.New("percentage cannot be negative")
}
if msg.Percentage.GTE(math.LegacyOneDec()) {
return fmt.Errorf("percentage cannot be greater than or equal to one")
return errors.New("percentage cannot be greater than or equal to one")
}
// Validate expiry
currentTime := k.HeaderService.HeaderInfo(ctx).Time
if msg.Expiry != nil && msg.Expiry.Compare(currentTime) == -1 {
return fmt.Errorf("expiry time cannot be less than the current block time")
return errors.New("expiry time cannot be less than the current block time")
}
return nil

View File

@ -2,7 +2,7 @@ package types
import (
"context"
"fmt"
"errors"
"cosmossdk.io/core/address"
"cosmossdk.io/core/appmodule"
@ -64,12 +64,12 @@ func (a StakeAuthorization) MsgTypeURL() string {
// is unspecified.
func (a StakeAuthorization) ValidateBasic() error {
if a.MaxTokens != nil && a.MaxTokens.IsNegative() {
return errorsmod.Wrapf(fmt.Errorf("max tokens should be positive"),
return errorsmod.Wrapf(errors.New("max tokens should be positive"),
"negative coin amount: %v", a.MaxTokens)
}
if a.AuthorizationType == AuthorizationType_AUTHORIZATION_TYPE_UNSPECIFIED {
return fmt.Errorf("unknown authorization type")
return errors.New("unknown authorization type")
}
return nil
@ -220,7 +220,7 @@ func normalizeAuthzType(authzType AuthorizationType) (string, error) {
case AuthorizationType_AUTHORIZATION_TYPE_CANCEL_UNBONDING_DELEGATION:
return sdk.MsgTypeURL(&MsgCancelUnbondingDelegation{}), nil
default:
return "", errorsmod.Wrapf(fmt.Errorf("unknown authorization type"),
return "", errorsmod.Wrapf(errors.New("unknown authorization type"),
"cannot normalize authz type with %T", authzType)
}
}