[#148] linter: Add funlen linter

Long functions are hard to understand and source of errors

Signed-off-by: Dmitrii Stepanov <d.stepanov@yadro.com>
pull/148/head
Dmitrii Stepanov 2023-03-20 10:01:27 +03:00
parent cc8ff015b4
commit 97c36ed3ec
52 changed files with 76 additions and 0 deletions

View File

@ -26,6 +26,9 @@ linters-settings:
check-shadowing: false
staticcheck:
checks: ["all", "-SA1019"] # TODO Enable SA1019 after deprecated warning are fixed.
funlen:
lines: 80
statements: 60
linters:
enable:
@ -54,5 +57,6 @@ linters:
- reassign
- whitespace
- containedctx
- funlen
disable-all: true
fast: false

View File

@ -44,6 +44,7 @@ const (
notaryEnabled = true
)
// nolint: funlen
func dumpBalances(cmd *cobra.Command, _ []string) error {
var (
dumpStorage, _ = cmd.Flags().GetBool(dumpBalancesStorageFlag)

View File

@ -152,6 +152,7 @@ func listContainers(cmd *cobra.Command, _ []string) error {
return nil
}
// nolint: funlen
func restoreContainers(cmd *cobra.Command, _ []string) error {
filename, err := cmd.Flags().GetString(containerDumpFlag)
if err != nil {

View File

@ -57,6 +57,7 @@ func init() {
ff.String(customZoneFlag, "frostfs", "Custom zone for NNS")
}
// nolint: funlen
func deployContractCmd(cmd *cobra.Command, args []string) error {
v := viper.GetViper()
c, err := newInitializeContext(cmd, v)

View File

@ -108,6 +108,7 @@ func (c *initializeContext) close() {
}
}
// nolint: funlen
func newInitializeContext(cmd *cobra.Command, v *viper.Viper) (*initializeContext, error) {
walletDir := config.ResolveHomePath(viper.GetString(alphabetWalletsFlag))
wallets, err := openAlphabetWallets(v, walletDir)

View File

@ -156,6 +156,7 @@ func (c *initializeContext) deployNNS(method string) error {
return c.awaitTx()
}
// nolint: funlen
func (c *initializeContext) updateContracts() error {
alphaCs := c.getContract(alphabetContract)

View File

@ -22,6 +22,7 @@ import (
// https://github.com/nspcc-dev/neo-go/blob/master/pkg/core/native/notary.go#L48
const defaultNotaryDepositLifetime = 5760
// nolint: funlen
func depositNotary(cmd *cobra.Command, _ []string) error {
p, err := cmd.Flags().GetString(storageWalletFlag)
if err != nil {

View File

@ -238,6 +238,7 @@ var (
}
)
// nolint: funlen
func init() {
RootCmd.AddCommand(generateAlphabetCmd)
generateAlphabetCmd.Flags().String(alphabetWalletsFlag, "", "Path to alphabet wallets dir")

View File

@ -307,6 +307,8 @@ const (
)
// common executor cmdSubnetAdminAdd and cmdSubnetAdminRemove commands.
//
// nolint: funlen
func manageSubnetAdmins(cmd *cobra.Command, rm bool) error {
// read private key
var key keys.PrivateKey
@ -651,6 +653,8 @@ func addCommandInheritPreRun(par *cobra.Command, subs ...*cobra.Command) {
}
// registers flags and binds sub-commands for subnet commands.
//
// nolint: funlen
func init() {
cmdSubnetCreate.Flags().StringP(flagSubnetWallet, "w", "", "Path to file with wallet")
_ = cmdSubnetCreate.MarkFlagRequired(flagSubnetWallet)
@ -868,6 +872,7 @@ func invokeNonNotary(c Client, key keys.PrivateKey, method string, args ...any)
return nil
}
// nolint: funlen
func invokeNotary(c Client, key keys.PrivateKey, method string, notaryHash util.Uint160, args ...any) error {
nnsCs, err := c.GetContractStateByID(1)
if err != nil {

View File

@ -79,6 +79,7 @@ type config struct {
MetabasePath string
}
// nolint: funlen
func storageConfig(cmd *cobra.Command, args []string) {
var outPath string
if len(args) != 0 {

View File

@ -42,6 +42,7 @@ func initObjectGetCmd() {
flags.Bool(binaryFlag, false, "Serialize whole object structure into given file(id + signature + header + payload).")
}
// nolint: funlen
func getObject(cmd *cobra.Command, _ []string) {
var cnr cid.ID
var obj oid.ID

View File

@ -58,6 +58,7 @@ func initObjectPutCmd() {
flags.Bool(binaryFlag, false, "Deserialize object structure from given file.")
}
// nolint: funlen
func putObject(cmd *cobra.Command, _ []string) {
binary, _ := cmd.Flags().GetBool(binaryFlag)
cidVal, _ := cmd.Flags().GetString(commonflags.CIDFlag)

View File

@ -339,6 +339,8 @@ func initFlagSession(cmd *cobra.Command, verb string) {
// container.
//
// The object itself is not included in the result.
//
// nolint: funlen
func collectObjectRelatives(cmd *cobra.Command, cli *client.Client, cnr cid.ID, obj oid.ID) []oid.ID {
common.PrintVerbose(cmd, "Fetching raw object header...")

View File

@ -41,6 +41,7 @@ func newConfig(path, directory string) (*viper.Viper, error) {
return v, err
}
// nolint: funlen
func defaultConfiguration(cfg *viper.Viper) {
cfg.SetDefault("logger.level", "info")

View File

@ -171,6 +171,8 @@ type subStorageCfg struct {
// readConfig fills applicationConfiguration with raw configuration values
// not modifying them.
//
// nolint: funlen
func (a *applicationConfiguration) readConfig(c *config.Config) error {
if a._read {
err := c.Reload()
@ -522,6 +524,7 @@ type cfgReputation struct {
var persistateSideChainLastBlockKey = []byte("side_chain_last_processed_block")
// nolint: funlen
func initCfg(appCfg *config.Config) *cfg {
c := &cfg{}
@ -654,6 +657,7 @@ type shardOptsWithID struct {
shOpts []shard.Option
}
// nolint: funlen
func (c *cfg) shardOpts() []shardOptsWithID {
shards := make([]shardOptsWithID, 0, len(c.EngineCfg.shards))

View File

@ -39,6 +39,7 @@ const (
stopEstimationNotifyEvent = "StopEstimation"
)
// nolint: funlen
func initContainerService(c *cfg) {
// container wrapper that tries to invoke notary
// requests if chain is configured so

View File

@ -135,6 +135,7 @@ func (c *cfg) addressNum() int {
return 0
}
// nolint: funlen
func initNetmapService(c *cfg) {
network.WriteToNodeInfo(c.localAddr, &c.cfgNodeInfo.localInfo)
c.cfgNodeInfo.localInfo.SetPublicKey(c.key.PublicKey().Bytes())

View File

@ -163,6 +163,7 @@ func (x *coreClientConstructor) Get(info coreclient.NodeInfo) (coreclient.MultiA
return c.(coreclient.MultiAddressClient), nil
}
// nolint: funlen
func initObjectService(c *cfg) {
ls := c.cfgObject.cfgLocalStorage.localStorage
keyStorage := util.NewKeyStorage(&c.key.PrivateKey, c.privateTokenStore, c.cfgNetmap.state)

View File

@ -33,6 +33,7 @@ import (
"go.uber.org/zap"
)
// nolint: funlen
func initReputationService(c *cfg) {
wrap, err := repClient.NewFromMorph(c.cfgMorph.client, c.cfgReputation.scriptHash, 0, repClient.TryNotary())
fatalOnErr(err)

View File

@ -202,6 +202,8 @@ func (i ContentMeta) Objects() []oid.ID {
}
// ValidateContent validates payload content according to the object type.
//
// nolint: funlen
func (v *FormatValidator) ValidateContent(o *object.Object) (ContentMeta, error) {
meta := ContentMeta{
typ: o.Type(),

View File

@ -53,6 +53,8 @@ const (
)
// String returns l in config-compatible format.
//
// nolint: funlen
func (l GlagoliticLetter) String() string {
switch l {
default:

View File

@ -158,6 +158,8 @@ var (
)
// Start runs all event providers.
//
// nolint: funlen
func (s *Server) Start(ctx context.Context, intError chan<- error) (err error) {
s.setHealthStatus(control.HealthStatus_STARTING)
defer func() {
@ -319,6 +321,8 @@ func (s *Server) registerStarter(f func() error) {
}
// New creates instance of inner ring sever structure.
//
// nolint: funlen
func New(ctx context.Context, log *logger.Logger, cfg *viper.Viper, errChan chan<- error) (*Server, error) {
var err error
server := &Server{log: log}

View File

@ -10,6 +10,7 @@ import (
const emitMethod = "emit"
// nolint: funlen
func (ap *Processor) processEmit() {
index := ap.irList.AlphabetIndex()
if index < 0 {

View File

@ -17,6 +17,7 @@ import (
"go.uber.org/zap"
)
// nolint: funlen
func (ap *Processor) processStartAudit(epoch uint64) {
log := ap.log.With(zap.Uint64("epoch", epoch))

View File

@ -46,6 +46,8 @@ type signatureVerificationData struct {
// - v.binPublicKey is a public session key
// - session context corresponds to the container and verb in v
// - session is "alive"
//
// nolint: funlen
func (cp *Processor) verifySignature(v signatureVerificationData) error {
var err error
var key frostfsecdsa.PublicKeyRFC6979

View File

@ -18,6 +18,7 @@ const (
alphabetUpdateIDPrefix = "AlphabetUpdate"
)
// nolint: funlen
func (gp *Processor) processAlphabetSync(txHash util.Uint256) {
if !gp.alphabetState.IsAlphabet() {
gp.log.Info("non alphabet mode, ignore alphabet sync")

View File

@ -13,6 +13,8 @@ import (
// Put saves object in the maximum weight blobobnicza.
//
// returns error if could not save object in any blobovnicza.
//
// nolint: funlen
func (b *Blobovniczas) Put(prm common.PutPrm) (common.PutRes, error) {
if b.readOnly {
return common.PutRes{}, common.ErrReadOnly

View File

@ -9,6 +9,7 @@ import (
"github.com/stretchr/testify/require"
)
// nolint: funlen
func TestIterate(t *testing.T, cons Constructor, min, max uint64) {
s := cons(t)
require.NoError(t, s.Open(false))

View File

@ -57,6 +57,8 @@ var errMustHaveTwoShards = errors.New("must have at least 1 spare shard")
// Evacuate moves data from one shard to the others.
// The shard being moved must be in read-only mode.
//
// nolint: funlen
func (e *StorageEngine) Evacuate(prm EvacuateShardPrm) (EvacuateShardRes, error) {
sidList := make([]string, len(prm.shardID))
for i := range prm.shardID {

View File

@ -52,6 +52,7 @@ func (e *StorageEngine) Get(prm GetPrm) (res GetRes, err error) {
return
}
// nolint: funlen
func (e *StorageEngine) get(prm GetPrm) (GetRes, error) {
if e.metrics != nil {
defer elapsed(e.metrics.AddGetDuration)()

View File

@ -65,6 +65,7 @@ func (e *StorageEngine) GetRange(prm RngPrm) (res RngRes, err error) {
return
}
// nolint: funlen
func (e *StorageEngine) getRange(prm RngPrm) (RngRes, error) {
if e.metrics != nil {
defer elapsed(e.metrics.AddRangeDuration)()

View File

@ -118,6 +118,8 @@ var ErrLockObjectRemoval = logicerr.New("lock object removal")
//
// NOTE: Marks any object with GC mark (despite any prohibitions on operations
// with that object) if WithForceGCMark option has been provided.
//
// nolint: funlen
func (db *DB) Inhume(prm InhumePrm) (res InhumeRes, err error) {
db.modeMtx.RLock()
defer db.modeMtx.RUnlock()

View File

@ -76,6 +76,7 @@ func (db *DB) Put(prm PutPrm) (res PutRes, err error) {
return
}
// nolint: funlen
func (db *DB) put(
tx *bbolt.Tx, obj *objectSDK.Object, id []byte,
si *objectSDK.SplitInfo, currEpoch uint64) error {

View File

@ -156,6 +156,7 @@ func (s *Shard) Init() error {
return nil
}
// nolint: funlen
func (s *Shard) refillMetabase() error {
err := s.metaBase.Reset()
if err != nil {

View File

@ -26,6 +26,7 @@ type (
const engineSubsystem = "engine"
// nolint: funlen
func newEngineMetrics() engineMetrics {
var (
listContainersDuration = prometheus.NewCounter(prometheus.CounterOpts{

View File

@ -75,6 +75,7 @@ func (m methodCount) Inc(success bool) {
}
}
// nolint: funlen
func newObjectServiceMetrics() objectServiceMetrics {
var ( // Request counter metrics.
getCounter = newMethodCallCounter("get")

View File

@ -445,6 +445,7 @@ func (c *Client) notaryInvokeAsCommittee(method string, nonce, vub uint32, args
return c.notaryInvoke(true, true, designate, nonce, &vub, method, args...)
}
// nolint: funlen
func (c *Client) notaryInvoke(committee, invokedByAlpha bool, contract util.Uint160, nonce uint32, vub *uint32, method string, args ...any) error {
alphabetList, err := c.notary.alphabetSource() // prepare arguments for test invocation
if err != nil {

View File

@ -191,6 +191,7 @@ func (l *listener) listen(ctx context.Context, intError chan<- error) error {
return nil
}
// nolint: funlen
func (l *listener) listenLoop(ctx context.Context, chEvent <-chan *state.ContainedNotificationEvent, intErr chan<- error) {
var (
blockChan <-chan *block.Block

View File

@ -103,6 +103,8 @@ func notaryPreparator(prm PreparatorPrm) NotaryPreparator {
// transaction is expected to be received one more time
// from the Notary service but already signed. This happens
// since every notary call is a new notary request in fact.
//
// nolint: funlen
func (p Preparator) Prepare(nr *payload.P2PNotaryRequest) (NotaryEvent, error) {
// notary request's main tx is expected to have
// three or four witnesses: one for proxy contract,

View File

@ -35,6 +35,7 @@ func (c *Context) executePoR() {
c.report.SetPoRCounters(c.porRequests.Load(), c.porRetries.Load())
}
// nolint: funlen
func (c *Context) checkStorageGroupPoR(sgID oid.ID, sg storagegroupSDK.StorageGroup) {
members := sg.Members()
c.updateSGInfo(sgID, members)

View File

@ -118,6 +118,8 @@ func (c *Checker) StickyBitCheck(info v2.RequestInfo, owner user.ID) bool {
}
// CheckEACL is a main check function for extended ACL.
//
// nolint: funlen
func (c *Checker) CheckEACL(msg any, reqInfo v2.RequestInfo) error {
basicACL := reqInfo.BasicACL()
if !basicACL.Extendable() {

View File

@ -101,6 +101,7 @@ func requestHeaders(msg xHeaderSource) []eaclSDK.Header {
var errMissingOID = errors.New("object ID is missing")
// nolint: funlen
func (h *cfg) readObjectHeaders(dst *headerSource) error {
switch m := h.msg.(type) {
default:

View File

@ -443,6 +443,7 @@ func (b Service) GetRangeHash(
return b.next.GetRangeHash(ctx, request)
}
// nolint: funlen
func (p putStreamBasicChecker) Send(request *objectV2.PutRequest) error {
body := request.GetBody()
if body == nil {

View File

@ -87,6 +87,7 @@ func (c *clientCacheWrapper) get(info coreclient.NodeInfo) (getClient, error) {
}, nil
}
// nolint: funlen
func (c *clientWrapper) getObject(exec *execCtx, info coreclient.NodeInfo) (*object.Object, error) {
if exec.isForwardingEnabled() {
return exec.prm.forwarder(info, c.client)

View File

@ -33,6 +33,7 @@ import (
var errWrongMessageSeq = errors.New("incorrect message sequence")
// nolint: funlen
func (s *Service) toPrm(req *objectV2.GetRequest, stream objectSvc.GetObjectStream) (*getsvc.Prm, error) {
body := req.GetBody()
@ -199,6 +200,7 @@ func (s *Service) toPrm(req *objectV2.GetRequest, stream objectSvc.GetObjectStre
return p, nil
}
// nolint: funlen
func (s *Service) toRangePrm(req *objectV2.GetRangeRequest, stream objectSvc.GetObjectRangeStream) (*getsvc.RangePrm, error) {
body := req.GetBody()
@ -424,6 +426,7 @@ func (w *headResponseWriter) WriteHeader(_ context.Context, hdr *object.Object)
return nil
}
// nolint: funlen
func (s *Service) toHeadPrm(ctx context.Context, req *objectV2.HeadRequest, resp *objectV2.HeadResponse) (*getsvc.HeadPrm, error) {
body := req.GetBody()

View File

@ -164,6 +164,7 @@ func (t *distributedTarget) sendObject(node nodeDesc) error {
return nil
}
// nolint: funlen
func (t *distributedTarget) iteratePlacement(f func(nodeDesc) error) (*transformer.AccessIdentifiers, error) {
id, _ := t.obj.ID()

View File

@ -54,6 +54,7 @@ func (p *Streamer) MaxObjectSize() uint64 {
return p.maxPayloadSz
}
// nolint: funlen
func (p *Streamer) initTarget(prm *PutInitPrm) error {
// prevent re-calling
if p.target != nil {

View File

@ -22,6 +22,7 @@ import (
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
)
// nolint: funlen
func (s *Service) toPrm(req *objectV2.SearchRequest, stream objectSvc.SearchStream) (*searchsvc.Prm, error) {
body := req.GetBody()

View File

@ -72,6 +72,7 @@ func TraverseSplitChain(r HeadReceiver, addr oid.Address, h SplitMemberHandler)
return err
}
// nolint: funlen
func traverseSplitChain(r HeadReceiver, addr oid.Address, h SplitMemberHandler) (bool, error) {
v, err := r.Head(addr)
if err != nil {

View File

@ -147,6 +147,7 @@ type processPlacementContext struct {
removeLocalCopy bool
}
// nolint: funlen
func (p *Policer) processNodes(ctx *processPlacementContext, addrWithType objectcore.AddressWithType,
nodes []netmap.NodeInfo, shortage uint32, checkedNodes *nodeCache) {
addr := addrWithType.Address

View File

@ -104,6 +104,7 @@ type iterDaughterPrm struct {
consumersIter TrustIterator
}
// nolint: funlen
func (c *Calculator) iterateDaughter(p iterDaughterPrm) {
initTrust, err := c.prm.InitialTrustSource.InitialTrust(p.id)
if err != nil {

View File

@ -255,6 +255,7 @@ func (s *Service) SynchronizeAll() error {
}
}
// nolint: funlen
func (s *Service) syncLoop(ctx context.Context) {
for {
select {