Skip to content

Commit

Permalink
fix go lint
Browse files Browse the repository at this point in the history
  • Loading branch information
yihuang committed Feb 21, 2024
1 parent ef5c2cf commit fb2d974
Show file tree
Hide file tree
Showing 42 changed files with 155 additions and 210 deletions.
52 changes: 34 additions & 18 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,21 +1,39 @@
run:
tests: true
timeout: 10m
sort-results: true
allow-parallel-runners: true
exclude-dir: testutil/testdata_pulsar
concurrency: 4

linters:
disable-all: true
enable:
- bodyclose
- depguard
- dogsled
- dupl
- exportloopref
- goconst
- gocritic
- gofmt
- gofumpt
- goimports
- gosec
- gosimple
- govet
- ineffassign
- misspell
- nakedret
- prealloc
- revive
- nolintlint
- staticcheck
- stylecheck
- typecheck
- unconvert
- unused

issues:
exclude-rules:
# fixed in go 1.22
- text: "G601:"
linters:
- gosec

linters-settings:
exclude: ./pystarport/*
Expand All @@ -25,15 +43,13 @@ linters-settings:
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
# default is false: such cases aren't reported by default.
check-blank: true
revive:
# minimal confidence for issues, default is 0.8
min-confidence: 0
prealloc:
# XXX: we don't recommend using this linter before doing performance profiling.
# For most programs usage of prealloc will be a premature optimization.

# Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
# True by default.
simple: false
range-loops: true # Report preallocation suggestions on range loops, true by default
for-loops: true # Report preallocation suggestions on for loops, false by default
dogsled:
max-blank-identifiers: 3
maligned:
# print struct with more effective memory layout or not, false by default
suggest-new: true
nolintlint:
allow-unused: false
allow-leading-space: true
require-explanation: false
require-specific: false
4 changes: 0 additions & 4 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,6 @@ var (
// They are exported for convenience in creating helper functions, as object
// capabilities aren't needed for testing.
// (Amino is still needed for Ledger at the moment)
// nolint: staticcheck
type ChainApp struct {
*baseapp.BaseApp
legacyAmino *codec.LegacyAmino
Expand Down Expand Up @@ -299,7 +298,6 @@ func New(
appOpts servertypes.AppOptions,
baseAppOptions ...func(*baseapp.BaseApp),
) *ChainApp {

// TODO: Remove cdc in favor of appCodec once all modules are migrated.
appCodec := encodingConfig.Marshaler
legacyAmino := encodingConfig.Amino
Expand Down Expand Up @@ -792,7 +790,6 @@ func (app *ChainApp) ModuleAccountAddrs() map[string]bool {
// NOTE: This is solely to be used for testing purposes as it may be desirable
// for modules to register their own custom testing types.
// (Amino is still needed for Ledger at the moment)
// nolint: staticcheck
func (app *ChainApp) LegacyAmino() *codec.LegacyAmino {
return app.legacyAmino
}
Expand Down Expand Up @@ -901,7 +898,6 @@ func GetMaccPerms() map[string][]string {

// initParamsKeeper init params keeper and its subspaces
// (Amino is still needed for Ledger at the moment)
// nolint: staticcheck
func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey) paramskeeper.Keeper {
paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey)

Expand Down
6 changes: 2 additions & 4 deletions app/docs/statik/statik.go

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion app/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
func (app *ChainApp) ExportAppStateAndValidators(
forZeroHeight bool, jailAllowedAddrs []string,
) (servertypes.ExportedApp, error) {

// as if they could withdraw from the start of the next block
ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()})

Expand Down
1 change: 0 additions & 1 deletion app/params/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
// EncodingConfig specifies the concrete encoding types to use for a given app.
// This is provided for compatibility between protobuf and amino implementations.
// (Amino is still needed for Ledger at the moment)
// nolint: staticcheck
type EncodingConfig struct {
InterfaceRegistry types.InterfaceRegistry
Marshaler codec.Codec
Expand Down
4 changes: 1 addition & 3 deletions app/sim_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ func TestAppImportExport(t *testing.T) {

fmt.Printf("importing genesis...\n")

// nolint: dogsled
_, newDB, newDir, _, _, err := simapp.SetupSimulation("leveldb-app-sim-2", "Simulation-2")
require.NoError(t, err, "simulation setup failed")

Expand Down Expand Up @@ -268,7 +267,6 @@ func TestAppSimulationAfterImport(t *testing.T) {

fmt.Printf("importing genesis...\n")

// nolint: dogsled
_, newDB, newDir, _, _, err := simapp.SetupSimulation("leveldb-app-sim-2", "Simulation-2")
require.NoError(t, err, "simulation setup failed")

Expand Down Expand Up @@ -319,7 +317,7 @@ func TestAppStateDeterminism(t *testing.T) {
appHashList := make([]json.RawMessage, numTimesToRunPerSeed)

for i := 0; i < numSeeds; i++ {
// nolint: gosec
//nolint: gosec
config.Seed = rand.Int63()

for j := 0; j < numTimesToRunPerSeed; j++ {
Expand Down
1 change: 0 additions & 1 deletion app/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
// AppStateFn returns the initial application state using a genesis or the simulation parameters.
// It panics if the user provides files for both of them.
// If a file is not given for the genesis or the sim params, it creates a randomized one.
// nolint:revive
func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simtypes.AppStateFn {
return simapp.AppStateFnWithExtendedCb(cdc, simManager, NewDefaultGenesisState(cdc), nil)
}
15 changes: 7 additions & 8 deletions app/test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,9 @@ func createRandomAccounts(accNum int) []sdk.AccAddress {

// createIncrementalAccounts is a strategy used by addTestAddrs() in order to generated addresses in ascending order.
func createIncrementalAccounts(accNum int) []sdk.AccAddress {
// nolint: prealloc
//nolint: prealloc

Check warning on line 220 in app/test_helpers.go

View check run for this annotation

Codecov / codecov/patch

app/test_helpers.go#L220

Added line #L220 was not covered by tests
var addresses []sdk.AccAddress
// nolint: prealloc
//nolint: prealloc

Check warning on line 222 in app/test_helpers.go

View check run for this annotation

Codecov / codecov/patch

app/test_helpers.go#L222

Added line #L222 was not covered by tests
var buffer bytes.Buffer

// start at 100 so we can make up to 999 test addresses with valid test addresses
Expand All @@ -228,10 +228,10 @@ func createIncrementalAccounts(accNum int) []sdk.AccAddress {
buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") // base address string

buffer.WriteString(numString) // adding on final two digits to make addresses unique
// nolint: errcheck
//nolint: errcheck

Check warning on line 231 in app/test_helpers.go

View check run for this annotation

Codecov / codecov/patch

app/test_helpers.go#L231

Added line #L231 was not covered by tests
res, _ := sdk.AccAddressFromHexUnsafe(buffer.String())
bech := res.String()
// nolint: errcheck
//nolint: errcheck

Check warning on line 234 in app/test_helpers.go

View check run for this annotation

Codecov / codecov/patch

app/test_helpers.go#L234

Added line #L234 was not covered by tests
addr, _ := TestAddr(buffer.String(), bech)

addresses = append(addresses, addr)
Expand Down Expand Up @@ -332,9 +332,8 @@ func SignCheckDeliver(
t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg,
chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey,
) (sdk.GasInfo, *sdk.Result, error) {

tx, err := helpers.GenSignedMockTx(
// nolint: gosec
//nolint: gosec

Check warning on line 336 in app/test_helpers.go

View check run for this annotation

Codecov / codecov/patch

app/test_helpers.go#L336

Added line #L336 was not covered by tests
rand.New(rand.NewSource(time.Now().UnixNano())),
txCfg,
msgs,
Expand Down Expand Up @@ -386,7 +385,7 @@ func GenSequenceOfTxs(txGen client.TxConfig, msgs []sdk.Msg, accNums []uint64, i
var err error
for i := 0; i < numToGenerate; i++ {
txs[i], err = helpers.GenSignedMockTx(
// nolint: gosec
//nolint: gosec

Check warning on line 388 in app/test_helpers.go

View check run for this annotation

Codecov / codecov/patch

app/test_helpers.go#L388

Added line #L388 was not covered by tests
rand.New(rand.NewSource(time.Now().UnixNano())),
txGen,
msgs,
Expand Down Expand Up @@ -414,7 +413,7 @@ func incrementAllSequenceNumbers(initSeqNums []uint64) {

// CreateTestPubKeys returns a total of numPubKeys public keys in ascending order.
func CreateTestPubKeys(numPubKeys int) []cryptotypes.PubKey {
// nolint: prealloc
//nolint: prealloc

Check warning on line 416 in app/test_helpers.go

View check run for this annotation

Codecov / codecov/patch

app/test_helpers.go#L416

Added line #L416 was not covered by tests
var publicKeys []cryptotypes.PubKey
var buffer bytes.Buffer

Expand Down
1 change: 0 additions & 1 deletion app/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
// App implements the common methods for a Cosmos SDK-based application
// specific blockchain.
// (Amino is still needed for Ledger at the moment)
// nolint: staticcheck
type App interface {
// The assigned name of the app.
Name() string
Expand Down
12 changes: 5 additions & 7 deletions cmd/chain-maind/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,11 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) {
cmd.SetOut(cmd.OutOrStdout())
cmd.SetErr(cmd.ErrOrStderr())

// nolint: govet
//nolint: govet
initClientCtx, err := client.ReadPersistentCommandFlags(initClientCtx, cmd.Flags())
if err != nil {
return err
}
// nolint: govet
initClientCtx, err = conf.ReadFromClientConfig(initClientCtx)
if err != nil {
return err
Expand Down Expand Up @@ -187,8 +186,7 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) {
path := config.GenesisFile()

cleanedPath := filepath.Clean(path)
// nolint: gosec
file, err := os.OpenFile(cleanedPath, os.O_RDWR, 0600)
file, err := os.OpenFile(cleanedPath, os.O_RDWR, 0o600)
if err != nil {
return err
}
Expand All @@ -211,7 +209,7 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) {
return err
}

return WriteFile(cleanedPath, bz, 0600)
return WriteFile(cleanedPath, bz, 0o600)
}

rootCmd.AddCommand(
Expand Down Expand Up @@ -326,8 +324,8 @@ func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts serverty
// and exports state.
func exportAppStateAndTMValidators(
logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string,
appOpts servertypes.AppOptions) (servertypes.ExportedApp, error) {

appOpts servertypes.AppOptions,
) (servertypes.ExportedApp, error) {

Check warning on line 328 in cmd/chain-maind/app/app.go

View check run for this annotation

Codecov / codecov/patch

cmd/chain-maind/app/app.go#L328

Added line #L328 was not covered by tests
encCfg := app.MakeEncodingConfig() // Ideally, we would reuse the one created by NewRootCmd.
encCfg.Marshaler = codec.NewProtoCodec(encCfg.InterfaceRegistry)

Expand Down
13 changes: 8 additions & 5 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,15 @@ func TestConversion(t *testing.T) {
{sdk.NewCoin(config.HumanCoinUnit, sdk.ZeroInt()), "foo", sdk.Coin{}, true},
{sdk.NewCoin(config.HumanCoinUnit, sdk.ZeroInt()), "FOO", sdk.Coin{}, true},

{sdk.NewCoin(config.HumanCoinUnit, sdk.NewInt(5)),
config.BaseCoinUnit, sdk.NewCoin(config.BaseCoinUnit, sdk.NewInt(500000000)), false}, // cro => carson
{
sdk.NewCoin(config.HumanCoinUnit, sdk.NewInt(5)),
config.BaseCoinUnit, sdk.NewCoin(config.BaseCoinUnit, sdk.NewInt(500000000)), false,
}, // cro => carson

{sdk.NewCoin(config.BaseCoinUnit, sdk.NewInt(500000000)),
config.HumanCoinUnit, sdk.NewCoin(config.HumanCoinUnit, sdk.NewInt(5)), false}, // carson => cro
{
sdk.NewCoin(config.BaseCoinUnit, sdk.NewInt(500000000)),
config.HumanCoinUnit, sdk.NewCoin(config.HumanCoinUnit, sdk.NewInt(5)), false,
}, // carson => cro

}

Expand All @@ -72,5 +76,4 @@ func TestConversion(t *testing.T) {
"invalid result; tc: #%d, input: %s, denom: %s", i+1, tc.input, tc.denom,
)
}

}
8 changes: 2 additions & 6 deletions x/chainmain/client/cli/genaccounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
}

// attempt to lookup address from Keybase if no address was provided
// nolint: govet
//nolint: govet
kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, clientCtx.HomeDir, inBuf, clientCtx.Codec)
if err != nil {
return err
Expand Down Expand Up @@ -147,7 +147,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
genAccount = baseAccount
}

// nolint: govet
//nolint: govet
if err := genAccount.Validate(); err != nil {
return fmt.Errorf("failed to validate new genesis account: %w", err)
}
Expand All @@ -160,7 +160,6 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa

authGenState := authtypes.GetGenesisStateFromAppState(cdc, appState)

// nolint: govet
accs, err := authtypes.UnpackAccounts(authGenState.Accounts)
if err != nil {
return fmt.Errorf("failed to get accounts from any: %w", err)
Expand All @@ -175,7 +174,6 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
accs = append(accs, genAccount)
accs = authtypes.SanitizeGenesisAccounts(accs)

// nolint: govet
genAccs, err := authtypes.PackAccounts(accs)
if err != nil {
return fmt.Errorf("failed to convert accounts into any's: %w", err)
Expand All @@ -193,15 +191,13 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
bankGenState.Balances = append(bankGenState.Balances, balances)
bankGenState.Balances = banktypes.SanitizeGenesisBalances(bankGenState.Balances)

// nolint: govet
bankGenStateBz, err := cdc.MarshalJSON(bankGenState)
if err != nil {
return fmt.Errorf("failed to marshal bank genesis state: %w", err)
}

appState[banktypes.ModuleName] = bankGenStateBz

// nolint: govet
appStateJSON, err := json.Marshal(appState)
if err != nil {
return fmt.Errorf("failed to marshal application genesis state: %w", err)
Expand Down
11 changes: 5 additions & 6 deletions x/chainmain/client/cli/testnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,10 @@ Example:
cmd.Flags().String(flagNodeDaemonHome, ".chain-maind", "Home directory of the node's daemon configuration")
cmd.Flags().String(flagStartingIPAddress,
"192.168.0.1",
"Starting IP address (192.168.0.1 results in persistent peers list [email protected]:46656, [email protected]:46656, ...)") //nolint
"Starting IP address (192.168.0.1 results in persistent peers list [email protected]:46656, [email protected]:46656, ...)")
cmd.Flags().String(flags.FlagChainID, "cro-test", "genesis file chain-id")
cmd.Flags().String(server.FlagMinGasPrices, "",
"Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.00000001cro,1basecro)") //nolint
"Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.00000001cro,1basecro)")
cmd.Flags().String(flags.FlagKeyringBackend, keyring.BackendTest, "Select keyring's backend (os|file|test)")
cmd.Flags().String(flags.FlagKeyAlgorithm, string(hd.Secp256k1Type), "Key signing algorithm to generate keys for")
cmd.Flags().String(flagAmount, "20000000000000000basecro", "amount of coins for accounts")
Expand All @@ -146,7 +146,7 @@ Example:
return cmd
}

const nodeDirPerm = 0755
const nodeDirPerm = 0o755

var (
genAccounts []authtypes.GenesisAccount
Expand Down Expand Up @@ -459,7 +459,6 @@ func collectGenFiles(
nodeIDs []string, valPubKeys []crypto.PubKey, numValidators int,
outputDir, nodeDirPrefix, nodeDaemonHome string, genBalIterator banktypes.GenesisBalancesIterator,
) error {

var appState json.RawMessage
genTime := tmtime.Now()

Expand Down Expand Up @@ -529,12 +528,12 @@ func calculateIP(ip string, i int) (string, error) {
func writeFile(name string, dir string, contents []byte) error {
file := filepath.Join(dir, name)

err := tmos.EnsureDir(dir, 0755)
err := tmos.EnsureDir(dir, 0o755)

Check warning on line 531 in x/chainmain/client/cli/testnet.go

View check run for this annotation

Codecov / codecov/patch

x/chainmain/client/cli/testnet.go#L531

Added line #L531 was not covered by tests
if err != nil {
return err
}

err = tmos.WriteFile(file, contents, 0600)
err = tmos.WriteFile(file, contents, 0o600)

Check warning on line 536 in x/chainmain/client/cli/testnet.go

View check run for this annotation

Codecov / codecov/patch

x/chainmain/client/cli/testnet.go#L536

Added line #L536 was not covered by tests
if err != nil {
return err
}
Expand Down
Loading

0 comments on commit fb2d974

Please sign in to comment.