From fcb8197f3f0773d70ad202c195c6ce88fcb01c2d Mon Sep 17 00:00:00 2001 From: Jarek Kowalski Date: Wed, 29 May 2024 20:31:57 -0700 Subject: [PATCH] chore(ci): upgraded linter to 1.59.0 (#3883) --- .golangci.yml | 18 +++------- cli/app.go | 4 +-- cli/command_acl_add.go | 4 +-- cli/command_benchmark_crypto.go | 4 +-- cli/command_benchmark_ecc.go | 10 +----- cli/command_benchmark_encryption.go | 4 +-- cli/command_benchmark_hashing.go | 2 +- cli/command_blob_shards_modify.go | 2 +- cli/command_index_epoch_list.go | 10 +++--- cli/command_logs_cleanup.go | 2 +- cli/command_logs_session.go | 2 +- cli/command_maintenance_set.go | 2 +- cli/command_policy_edit.go | 2 +- cli/command_policy_set.go | 2 +- cli/command_repository_connect.go | 10 +++--- cli/command_repository_set_parameters.go | 8 ++--- cli/command_restore.go | 6 ++-- cli/command_server_start.go | 6 ++-- cli/command_server_tls.go | 12 +++---- cli/command_snapshot_create.go | 2 +- cli/command_snapshot_estimate.go | 2 +- cli/config.go | 2 +- cli/json_output.go | 10 +++--- cli/password.go | 8 ++--- cli/storage_filesystem.go | 4 +-- fs/cachefs/cache.go | 4 +-- internal/acl/acl.go | 2 +- internal/acl/acl_manager.go | 2 +- internal/auth/authz_acl.go | 2 +- internal/bigmap/bigmap_internal.go | 4 +-- internal/blobcrypto/blob_crypto.go | 2 +- internal/blobtesting/verify.go | 2 +- internal/crypto/aesgcm.go | 4 +-- internal/crypto/pb_key_deriver_scrypt.go | 4 +-- internal/diff/diff.go | 16 ++++----- internal/editor/editor.go | 2 +- internal/epoch/epoch_advance.go | 14 ++++---- internal/epoch/epoch_manager.go | 14 ++++---- internal/epoch/epoch_manager_test.go | 4 +-- internal/epoch/epoch_range.go | 4 +-- internal/epoch/epoch_range_test.go | 4 +-- internal/epoch/epoch_utils.go | 6 ++-- internal/gather/gather_write_buffer_chunk.go | 8 ++--- internal/metricid/id_mapping.go | 8 ++--- internal/metricid/metricid.go | 4 +-- internal/mockfs/mockfs.go | 2 +- internal/mount/mount_net_use.go | 2 +- internal/mount/mount_webdav.go | 2 +- .../providervalidation/providervalidation.go | 6 ++-- internal/retry/retry.go | 6 ++-- internal/server/grpc_session.go | 4 +-- internal/server/server.go | 4 +-- internal/testutil/tmpdir.go | 6 ++-- internal/tlsutil/tlsutil.go | 2 +- internal/uitask/uitask_manager.go | 2 +- internal/units/units.go | 8 ++--- internal/zaplogutil/zaplogutil.go | 2 +- repo/blob/gdrive/gdrive_storage.go | 2 +- repo/blob/rclone/rclone_storage.go | 4 +-- repo/blob/rclone/rclone_storage_test.go | 2 +- repo/blob/sharded/sharded.go | 2 +- repo/blob/storage.go | 16 ++++----- .../throttling/throttling_semaphore_test.go | 2 +- repo/content/committed_read_manager.go | 2 +- repo/content/content_index_recovery.go | 4 +-- repo/content/index/index_builder.go | 8 ++--- repo/content/index/index_encode_util.go | 4 +-- repo/content/index/index_v1.go | 6 ++-- repo/content/index/index_v2.go | 8 ----- repo/content/index/merged.go | 14 ++++---- .../indexblob/index_blob_manager_v0_test.go | 4 +-- repo/ecc/ecc_rs_crc.go | 18 +++++----- repo/ecc/ecc_utils.go | 14 ++++---- repo/format/format_blob.go | 4 +-- repo/format/format_provider.go | 2 +- repo/grpc_repository_client_test.go | 4 +-- repo/hashing/blake3_hashes.go | 4 +-- repo/hashing/blake_hashes.go | 8 ++--- repo/hashing/sha_hashes.go | 10 +++--- repo/initialize.go | 14 ++++---- repo/logging/logging_buf.go | 8 ++--- repo/maintenance/cleanup_logs.go | 2 +- repo/maintenance/content_rewrite.go | 4 +-- repo/maintenance/maintenance_params.go | 2 +- repo/maintenance/maintenance_safety.go | 10 +++--- repo/object/object_reader.go | 2 +- repo/splitter/splitter_buzhash32.go | 4 +-- repo/splitter/splitter_rabinkarp64.go | 2 +- snapshot/policy/policy_tree.go | 2 +- snapshot/policy/retention_policy.go | 12 +++---- snapshot/policy/scheduling_policy.go | 2 +- snapshot/restore/local_fs_output.go | 2 +- snapshot/snapshotfs/all_sources.go | 2 +- snapshot/snapshotfs/repofs.go | 4 +-- snapshot/snapshotfs/source_directories.go | 2 +- snapshot/snapshotfs/source_snapshots.go | 4 +-- snapshot/snapshotfs/upload.go | 8 ++--- snapshot/snapshotfs/upload_actions.go | 2 +- .../snapshotfs/upload_os_snapshot_windows.go | 2 +- snapshot/snapshotfs/upload_test.go | 8 ++--- .../multiclient_test/framework/client.go | 2 +- tests/tools/fio/options.go | 8 ++--- tests/tools/kopiarunner/kopia_snapshotter.go | 2 +- tools/cli2md/cli2md.go | 34 +++++++++++-------- tools/gettool/checksums.txt | 12 +++---- tools/gettool/gettool.go | 4 +-- tools/tools.mk | 2 +- 107 files changed, 290 insertions(+), 308 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 3b94eeb05..1937ff3fa 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -65,34 +65,26 @@ linters-settings: linters: enable-all: true disable: - - deadcode - depguard - - exhaustivestruct + - execinquery - exhaustruct - gochecknoinits - - golint + - gomnd - gci - - ifshort - - interfacer - ireturn # this one may be interesting to control allocations - gosmopolitan - - maligned - musttag - nilnil - nlreturn - nonamedreturns - - nosnakecase - paralleltest - prealloc - rowserrcheck - - scopelint - sqlclosecheck - - structcheck - tagalign - tagliatelle - testpackage - tparallel - - varcheck - varnamelen # this one may be interesting, but too much churn - wastedassign - whitespace @@ -116,7 +108,7 @@ issues: - gochecknoglobals - gocognit - goconst - - gomnd + - mnd - gosec - musttag - nestif @@ -137,7 +129,7 @@ issues: - revive - text: "Magic number: 1e" linters: - - gomnd + - mnd - text: "unnecessaryDefer" linters: - gocritic @@ -164,7 +156,7 @@ issues: - gocritic - text: ".*Magic number\\: [01]," linters: - - gomnd + - mnd - text: "Errors unhandled" linters: - gosec diff --git a/cli/app.go b/cli/app.go index 8010e04fc..755c34a31 100644 --- a/cli/app.go +++ b/cli/app.go @@ -64,11 +64,11 @@ func (o *textOutput) stderr() io.Writer { } func (o *textOutput) printStdout(msg string, args ...interface{}) { - fmt.Fprintf(o.stdout(), msg, args...) + fmt.Fprintf(o.stdout(), msg, args...) //nolint:errcheck } func (o *textOutput) printStderr(msg string, args ...interface{}) { - fmt.Fprintf(o.stderr(), msg, args...) + fmt.Fprintf(o.stderr(), msg, args...) //nolint:errcheck } // appServices are the methods of *App that command handles are allowed to call. diff --git a/cli/command_acl_add.go b/cli/command_acl_add.go index 63471024b..df34ed7b4 100644 --- a/cli/command_acl_add.go +++ b/cli/command_acl_add.go @@ -30,8 +30,8 @@ func (c *commandACLAdd) run(ctx context.Context, rep repo.RepositoryWriter) erro r := acl.TargetRule{} for _, v := range strings.Split(c.target, ",") { - parts := strings.SplitN(v, "=", 2) //nolint:gomnd - if len(parts) != 2 { //nolint:gomnd + parts := strings.SplitN(v, "=", 2) //nolint:mnd + if len(parts) != 2 { //nolint:mnd return errors.Errorf("invalid target labels %q, must be key=value", v) } diff --git a/cli/command_benchmark_crypto.go b/cli/command_benchmark_crypto.go index 468f412c1..97ca475ab 100644 --- a/cli/command_benchmark_crypto.go +++ b/cli/command_benchmark_crypto.go @@ -70,8 +70,8 @@ func (c *commandBenchmarkCrypto) runBenchmark(ctx context.Context) []cryptoBench fo := &format.ContentFormat{ Encryption: ea, Hash: ha, - MasterKey: make([]byte, 32), //nolint:gomnd - HMACSecret: make([]byte, 32), //nolint:gomnd + MasterKey: make([]byte, 32), //nolint:mnd + HMACSecret: make([]byte, 32), //nolint:mnd } hf, err := hashing.CreateHashFunc(fo) diff --git a/cli/command_benchmark_ecc.go b/cli/command_benchmark_ecc.go index 473ddea63..ee5aeac10 100644 --- a/cli/command_benchmark_ecc.go +++ b/cli/command_benchmark_ecc.go @@ -49,7 +49,7 @@ func (c *commandBenchmarkEcc) run(ctx context.Context) error { c.out.printStdout("%3d. %-30v %12v/s %12v/s %6v%% [%v]", ndx, r.ecc, units.BytesString(int64(r.throughputEncoding)), units.BytesString(int64(r.throughputDecoding)), - int(math.Round(r.growth*100)), //nolint:gomnd + int(math.Round(r.growth*100)), //nolint:mnd units.BytesString(int64(r.size)), ) @@ -155,11 +155,3 @@ type eccBenchResult struct { size int growth float64 } - -func min(a, b float64) float64 { - if a <= b { - return a - } - - return b -} diff --git a/cli/command_benchmark_encryption.go b/cli/command_benchmark_encryption.go index 630100589..31cbe053b 100644 --- a/cli/command_benchmark_encryption.go +++ b/cli/command_benchmark_encryption.go @@ -69,8 +69,8 @@ func (c *commandBenchmarkEncryption) runBenchmark(ctx context.Context) []cryptoB enc, err := encryption.CreateEncryptor(&format.ContentFormat{ Encryption: ea, Hash: hashing.DefaultAlgorithm, - MasterKey: make([]byte, 32), //nolint:gomnd - HMACSecret: make([]byte, 32), //nolint:gomnd + MasterKey: make([]byte, 32), //nolint:mnd + HMACSecret: make([]byte, 32), //nolint:mnd }) if err != nil { continue diff --git a/cli/command_benchmark_hashing.go b/cli/command_benchmark_hashing.go index 5744d2c39..555f2b821 100644 --- a/cli/command_benchmark_hashing.go +++ b/cli/command_benchmark_hashing.go @@ -65,7 +65,7 @@ func (c *commandBenchmarkHashing) runBenchmark(ctx context.Context) []cryptoBenc for _, ha := range hashing.SupportedAlgorithms() { hf, err := hashing.CreateHashFunc(&format.ContentFormat{ Hash: ha, - HMACSecret: make([]byte, 32), //nolint:gomnd + HMACSecret: make([]byte, 32), //nolint:mnd }) if err != nil { continue diff --git a/cli/command_blob_shards_modify.go b/cli/command_blob_shards_modify.go index fe6fd5655..43b540972 100644 --- a/cli/command_blob_shards_modify.go +++ b/cli/command_blob_shards_modify.go @@ -253,7 +253,7 @@ func (c *commandBlobShardsModify) renameBlobs(ctx context.Context, dir, prefix s if !c.dryRun { err := os.Rename(srcFile, destFile) if os.IsNotExist(err) { - //nolint:gomnd + //nolint:mnd if err2 := os.MkdirAll(destDir, 0o700); err2 != nil { return errors.Wrap(err2, "error creating directory") } diff --git a/cli/command_index_epoch_list.go b/cli/command_index_epoch_list.go index 327f7ffe0..3ac5ac65a 100644 --- a/cli/command_index_epoch_list.go +++ b/cli/command_index_epoch_list.go @@ -50,16 +50,16 @@ func (c *commandIndexEpochList) run(ctx context.Context, rep repo.DirectReposito for e := snap.WriteEpoch; e >= firstNonRangeCompacted; e-- { if uces := snap.UncompactedEpochSets[e]; len(uces) > 0 { - min := blob.MinTimestamp(uces) - max := blob.MaxTimestamp(uces) + minTime := blob.MinTimestamp(uces) + maxTime := blob.MaxTimestamp(uces) c.out.printStdout("%v %v ... %v, %v blobs, %v, span %v\n", e, - formatTimestamp(min), - formatTimestamp(max), + formatTimestamp(minTime), + formatTimestamp(maxTime), len(uces), units.BytesString(blob.TotalLength(uces)), - max.Sub(min).Round(time.Second), + maxTime.Sub(minTime).Round(time.Second), ) } diff --git a/cli/command_logs_cleanup.go b/cli/command_logs_cleanup.go index 4ef9ef34c..9cd3c17b1 100644 --- a/cli/command_logs_cleanup.go +++ b/cli/command_logs_cleanup.go @@ -30,7 +30,7 @@ func (c *commandLogsCleanup) setup(svc appServices, parent commandParent) { func (c *commandLogsCleanup) run(ctx context.Context, rep repo.DirectRepositoryWriter) error { toDelete, err := maintenance.CleanupLogs(ctx, rep, maintenance.LogRetentionOptions{ - MaxTotalSize: c.maxTotalSizeMB << 20, //nolint:gomnd + MaxTotalSize: c.maxTotalSizeMB << 20, //nolint:mnd MaxCount: c.maxCount, MaxAge: c.maxAge, DryRun: c.dryRun, diff --git a/cli/command_logs_session.go b/cli/command_logs_session.go index 0cccecd6c..a66986ecd 100644 --- a/cli/command_logs_session.go +++ b/cli/command_logs_session.go @@ -73,7 +73,7 @@ func getLogSessions(ctx context.Context, st blob.Reader) ([]*logSessionInfo, err if err := st.ListBlobs(ctx, repodiag.LogBlobPrefix, func(bm blob.Metadata) error { parts := strings.Split(string(bm.BlobID), "_") - //nolint:gomnd + //nolint:mnd if len(parts) < 8 { log(ctx).Errorf("invalid part count: %v skipping unrecognized log: %v", len(parts), bm.BlobID) return nil diff --git a/cli/command_maintenance_set.go b/cli/command_maintenance_set.go index 93b3ddf92..15366b0d9 100644 --- a/cli/command_maintenance_set.go +++ b/cli/command_maintenance_set.go @@ -79,7 +79,7 @@ func (c *commandMaintenanceSet) setLogCleanupParametersFromFlags(ctx context.Con if v := c.maxTotalRetainedLogSizeMB; v != -1 { cl := p.LogRetention.OrDefault() - cl.MaxTotalSize = v << 20 //nolint:gomnd + cl.MaxTotalSize = v << 20 //nolint:mnd p.LogRetention = cl *changed = true diff --git a/cli/command_policy_edit.go b/cli/command_policy_edit.go index c8f27ed39..f47d3cc52 100644 --- a/cli/command_policy_edit.go +++ b/cli/command_policy_edit.go @@ -105,7 +105,7 @@ func (c *commandPolicyEdit) run(ctx context.Context, rep repo.RepositoryWriter) var shouldSave string - fmt.Scanf("%v", &shouldSave) + fmt.Scanf("%v", &shouldSave) //nolint:errcheck if strings.HasPrefix(strings.ToLower(shouldSave), "y") { if err := policy.SetPolicy(ctx, rep, target, updated); err != nil { diff --git a/cli/command_policy_set.go b/cli/command_policy_set.go index be822798e..d6ef91516 100644 --- a/cli/command_policy_set.go +++ b/cli/command_policy_set.go @@ -229,7 +229,7 @@ func applyOptionalInt64MiB(ctx context.Context, desc string, val **policy.Option } // convert MiB to bytes - v *= 1 << 20 //nolint:gomnd + v *= 1 << 20 //nolint:mnd i := policy.OptionalInt64(v) *changeCount++ diff --git a/cli/command_repository_connect.go b/cli/command_repository_connect.go index ca95669ed..7df71b8ff 100644 --- a/cli/command_repository_connect.go +++ b/cli/command_repository_connect.go @@ -65,7 +65,7 @@ func (c *connectOptions) setup(svc appServices, cmd *kingpin.CmdClause) { // we must use *Var() methods, otherwise one of the commands would always get default flag values. cmd.Flag("cache-directory", "Cache directory").PlaceHolder("PATH").Envar(svc.EnvName("KOPIA_CACHE_DIRECTORY")).StringVar(&c.connectCacheDirectory) - c.maxListCacheDuration = 30 * time.Second //nolint:gomnd + c.maxListCacheDuration = 30 * time.Second //nolint:mnd c.contentCacheSizeMB = 5000 c.metadataCacheSizeMB = 5000 c.cacheSizeFlags.setup(cmd) @@ -93,10 +93,10 @@ func (c *connectOptions) toRepoConnectOptions() *repo.ConnectOptions { return &repo.ConnectOptions{ CachingOptions: content.CachingOptions{ CacheDirectory: c.connectCacheDirectory, - ContentCacheSizeBytes: c.contentCacheSizeMB << 20, //nolint:gomnd - ContentCacheSizeLimitBytes: c.contentCacheSizeLimitMB << 20, //nolint:gomnd - MetadataCacheSizeBytes: c.metadataCacheSizeMB << 20, //nolint:gomnd - MetadataCacheSizeLimitBytes: c.metadataCacheSizeLimitMB << 20, //nolint:gomnd + ContentCacheSizeBytes: c.contentCacheSizeMB << 20, //nolint:mnd + ContentCacheSizeLimitBytes: c.contentCacheSizeLimitMB << 20, //nolint:mnd + MetadataCacheSizeBytes: c.metadataCacheSizeMB << 20, //nolint:mnd + MetadataCacheSizeLimitBytes: c.metadataCacheSizeLimitMB << 20, //nolint:mnd MaxListCacheDuration: content.DurationSeconds(c.maxListCacheDuration.Seconds()), MinContentSweepAge: content.DurationSeconds(c.contentMinSweepAge.Seconds()), MinMetadataSweepAge: content.DurationSeconds(c.metadataMinSweepAge.Seconds()), diff --git a/cli/command_repository_set_parameters.go b/cli/command_repository_set_parameters.go index 5930ce995..350a191be 100644 --- a/cli/command_repository_set_parameters.go +++ b/cli/command_repository_set_parameters.go @@ -72,10 +72,10 @@ func (c *commandRepositorySetParameters) setSizeMBParameter(ctx context.Context, return } - *dst = v << 20 //nolint:gomnd + *dst = v << 20 //nolint:mnd *anyChange = true - log(ctx).Infof(" - setting %v to %v.\n", desc, units.BytesString(int64(v)<<20)) //nolint:gomnd + log(ctx).Infof(" - setting %v to %v.\n", desc, units.BytesString(int64(v)<<20)) //nolint:mnd } func (c *commandRepositorySetParameters) setInt64SizeMBParameter(ctx context.Context, v int64, desc string, dst *int64, anyChange *bool) { @@ -83,10 +83,10 @@ func (c *commandRepositorySetParameters) setInt64SizeMBParameter(ctx context.Con return } - *dst = v << 20 //nolint:gomnd + *dst = v << 20 //nolint:mnd *anyChange = true - log(ctx).Infof(" - setting %v to %v.\n", desc, units.BytesString(v<<20)) //nolint:gomnd + log(ctx).Infof(" - setting %v to %v.\n", desc, units.BytesString(v<<20)) //nolint:mnd } func (c *commandRepositorySetParameters) setIntParameter(ctx context.Context, v int, desc string, dst *int, anyChange *bool) { diff --git a/cli/command_restore.go b/cli/command_restore.go index 945348348..198f2ea43 100644 --- a/cli/command_restore.go +++ b/cli/command_restore.go @@ -546,9 +546,9 @@ func computeMaxTime(timespec string) (time.Time, error) { } // Just used as markers, the value does not really matter - day := 24 * time.Hour //nolint:gomnd - month := 30 * day //nolint:gomnd - year := 12 * month //nolint:gomnd + day := 24 * time.Hour //nolint:mnd + month := 30 * day //nolint:mnd + year := 12 * month //nolint:mnd formats := []struct { format string diff --git a/cli/command_server_start.go b/cli/command_server_start.go index 923a0d8b3..185af2304 100644 --- a/cli/command_server_start.go +++ b/cli/command_server_start.go @@ -194,7 +194,7 @@ func (c *commandServerStart) run(ctx context.Context) error { } httpServer := &http.Server{ - ReadHeaderTimeout: 15 * time.Second, //nolint:gomnd + ReadHeaderTimeout: 15 * time.Second, //nolint:mnd Addr: stripProtocol(c.sf.serverAddress), BaseContext: func(_ net.Listener) context.Context { return ctx @@ -330,7 +330,7 @@ func (c *commandServerStart) getAuthenticator(ctx context.Context) (auth.Authent randomPassword := hex.EncodeToString(b) // print it to the stderr bypassing any log file so that the user or calling process can connect - fmt.Fprintln(c.out.stderr(), "SERVER PASSWORD:", randomPassword) + fmt.Fprintln(c.out.stderr(), "SERVER PASSWORD:", randomPassword) //nolint:errcheck authenticators = append(authenticators, auth.AuthenticateSingleUser(c.sf.serverUsername, randomPassword)) } @@ -348,7 +348,7 @@ func (c *commandServerStart) getAuthenticator(ctx context.Context) (auth.Authent randomPassword := hex.EncodeToString(b) // print it to the stderr bypassing any log file so that the user or calling process can connect - fmt.Fprintln(c.out.stderr(), "SERVER CONTROL PASSWORD:", randomPassword) + fmt.Fprintln(c.out.stderr(), "SERVER CONTROL PASSWORD:", randomPassword) //nolint:errcheck authenticators = append(authenticators, auth.AuthenticateSingleUser(c.serverControlUsername, randomPassword)) } diff --git a/cli/command_server_tls.go b/cli/command_server_tls.go index e49e7e422..e30bfca8c 100644 --- a/cli/command_server_tls.go +++ b/cli/command_server_tls.go @@ -89,7 +89,7 @@ func (c *commandServerStart) maybeGenerateTLS(ctx context.Context) error { } fingerprint := sha256.Sum256(cert.Raw) - fmt.Fprintf(c.out.stderr(), "SERVER CERT SHA256: %v\n", hex.EncodeToString(fingerprint[:])) + fmt.Fprintf(c.out.stderr(), "SERVER CERT SHA256: %v\n", hex.EncodeToString(fingerprint[:])) //nolint:errcheck log(ctx).Infof("writing TLS certificate to %v", c.serverStartTLSCertFile) @@ -119,7 +119,7 @@ func (c *commandServerStart) startServerWithOptionalTLSAndListener(ctx context.C switch { case c.serverStartTLSCertFile != "" && c.serverStartTLSKeyFile != "": // PEM files provided - fmt.Fprintf(c.out.stderr(), "SERVER ADDRESS: %shttps://%v\n", udsPfx, httpServer.Addr) + fmt.Fprintf(c.out.stderr(), "SERVER ADDRESS: %shttps://%v\n", udsPfx, httpServer.Addr) //nolint:errcheck c.showServerUIPrompt(ctx) return errors.Wrap(httpServer.ServeTLS(listener, c.serverStartTLSCertFile, c.serverStartTLSKeyFile), "error starting TLS server") @@ -142,7 +142,7 @@ func (c *commandServerStart) startServerWithOptionalTLSAndListener(ctx context.C } fingerprint := sha256.Sum256(cert.Raw) - fmt.Fprintf(c.out.stderr(), "SERVER CERT SHA256: %v\n", hex.EncodeToString(fingerprint[:])) + fmt.Fprintf(c.out.stderr(), "SERVER CERT SHA256: %v\n", hex.EncodeToString(fingerprint[:])) //nolint:errcheck if c.serverStartTLSPrintFullServerCert { // dump PEM-encoded server cert, only used by KopiaUI to securely connect. @@ -152,10 +152,10 @@ func (c *commandServerStart) startServerWithOptionalTLSAndListener(ctx context.C return errors.Wrap(err, "Failed to write data") } - fmt.Fprintf(c.out.stderr(), "SERVER CERTIFICATE: %v\n", base64.StdEncoding.EncodeToString(b.Bytes())) + fmt.Fprintf(c.out.stderr(), "SERVER CERTIFICATE: %v\n", base64.StdEncoding.EncodeToString(b.Bytes())) //nolint:errcheck } - fmt.Fprintf(c.out.stderr(), "SERVER ADDRESS: %shttps://%v\n", udsPfx, httpServer.Addr) + fmt.Fprintf(c.out.stderr(), "SERVER ADDRESS: %shttps://%v\n", udsPfx, httpServer.Addr) //nolint:errcheck c.showServerUIPrompt(ctx) return errors.Wrap(httpServer.ServeTLS(listener, "", ""), "error starting TLS server") @@ -165,7 +165,7 @@ func (c *commandServerStart) startServerWithOptionalTLSAndListener(ctx context.C return errors.Errorf("TLS not configured. To start server without encryption pass --insecure") } - fmt.Fprintf(c.out.stderr(), "SERVER ADDRESS: %shttp://%v\n", udsPfx, httpServer.Addr) + fmt.Fprintf(c.out.stderr(), "SERVER ADDRESS: %shttp://%v\n", udsPfx, httpServer.Addr) //nolint:errcheck c.showServerUIPrompt(ctx) return errors.Wrap(httpServer.Serve(listener), "error starting server") diff --git a/cli/command_snapshot_create.go b/cli/command_snapshot_create.go index 613490597..49ae30ba4 100644 --- a/cli/command_snapshot_create.go +++ b/cli/command_snapshot_create.go @@ -207,7 +207,7 @@ func validateStartEndTime(st, et string) error { func (c *commandSnapshotCreate) setupUploader(rep repo.RepositoryWriter) *snapshotfs.Uploader { u := snapshotfs.NewUploader(rep) - u.MaxUploadBytes = c.snapshotCreateCheckpointUploadLimitMB << 20 //nolint:gomnd + u.MaxUploadBytes = c.snapshotCreateCheckpointUploadLimitMB << 20 //nolint:mnd if c.snapshotCreateForceEnableActions { u.EnableActions = true diff --git a/cli/command_snapshot_estimate.go b/cli/command_snapshot_estimate.go index 96b47fdbf..7c0b4f794 100644 --- a/cli/command_snapshot_estimate.go +++ b/cli/command_snapshot_estimate.go @@ -128,7 +128,7 @@ func (c *commandSnapshotEstimate) run(ctx context.Context, rep repo.Repository) c.out.printStdout("Encountered %v error(s).\n", ep.stats.ErrorCount) } - megabits := float64(ep.stats.TotalFileSize) * 8 / 1000000 //nolint:gomnd + megabits := float64(ep.stats.TotalFileSize) * 8 / 1000000 //nolint:mnd seconds := megabits / c.snapshotEstimateUploadSpeed c.out.printStdout("\n") diff --git a/cli/config.go b/cli/config.go index 3daac638a..40ad3105c 100644 --- a/cli/config.go +++ b/cli/config.go @@ -21,7 +21,7 @@ func deprecatedFlag(w io.Writer, help string) func(_ *kingpin.ParseContext) error { return func(_ *kingpin.ParseContext) error { - fmt.Fprintf(w, "DEPRECATED: %v\n", help) + fmt.Fprintf(w, "DEPRECATED: %v\n", help) //nolint:errcheck return nil } } diff --git a/cli/json_output.go b/cli/json_output.go index 4649959d0..2a46f555a 100644 --- a/cli/json_output.go +++ b/cli/json_output.go @@ -96,7 +96,7 @@ func (l *jsonList) begin(o *jsonOutput) { l.o = o if o.jsonOutput { - fmt.Fprintf(l.o.out, "[") + fmt.Fprintf(l.o.out, "[") //nolint:errcheck if !o.jsonIndent { l.separator = "\n " @@ -107,16 +107,16 @@ func (l *jsonList) begin(o *jsonOutput) { func (l *jsonList) end() { if l.o.jsonOutput { if !l.o.jsonIndent { - fmt.Fprintf(l.o.out, "\n") + fmt.Fprintf(l.o.out, "\n") //nolint:errcheck } - fmt.Fprintf(l.o.out, "]") + fmt.Fprintf(l.o.out, "]") //nolint:errcheck } } func (l *jsonList) emit(v interface{}) { - fmt.Fprintf(l.o.out, l.separator) - fmt.Fprintf(l.o.out, "%s", l.o.jsonBytes(v)) + fmt.Fprintf(l.o.out, l.separator) //nolint:errcheck + fmt.Fprintf(l.o.out, "%s", l.o.jsonBytes(v)) //nolint:errcheck if l.o.jsonIndent { l.separator = "," diff --git a/cli/password.go b/cli/password.go index fab110f17..be8a89942 100644 --- a/cli/password.go +++ b/cli/password.go @@ -26,7 +26,7 @@ func askForNewRepositoryPassword(out io.Writer) (string, error) { } if p1 != p2 { - fmt.Fprintln(out, "Passwords don't match!") + fmt.Fprintln(out, "Passwords don't match!") //nolint:errcheck } else { return p1, nil } @@ -59,7 +59,7 @@ func askForExistingRepositoryPassword(out io.Writer) (string, error) { return "", err } - fmt.Fprintln(out) + fmt.Fprintln(out) //nolint:errcheck return p1, nil } @@ -95,14 +95,14 @@ func (c *App) getPasswordFromFlags(ctx context.Context, isCreate, allowPersisten // askPass presents a given prompt and asks the user for password. func askPass(out io.Writer, prompt string) (string, error) { for range 5 { - fmt.Fprint(out, prompt) + fmt.Fprint(out, prompt) //nolint:errcheck passBytes, err := term.ReadPassword(int(os.Stdin.Fd())) if err != nil { return "", errors.Wrap(err, "password prompt error") } - fmt.Fprintln(out) + fmt.Fprintln(out) //nolint:errcheck if len(passBytes) == 0 { continue diff --git a/cli/storage_filesystem.go b/cli/storage_filesystem.go index 040c2b9fb..8a855b7c7 100644 --- a/cli/storage_filesystem.go +++ b/cli/storage_filesystem.go @@ -50,12 +50,12 @@ func (c *storageFilesystemFlags) Connect(ctx context.Context, isCreate bool, for } if v := c.connectOwnerUID; v != "" { - //nolint:gomnd + //nolint:mnd fso.FileUID = getIntPtrValue(v, 10) } if v := c.connectOwnerGID; v != "" { - //nolint:gomnd + //nolint:mnd fso.FileGID = getIntPtrValue(v, 10) } diff --git a/fs/cachefs/cache.go b/fs/cachefs/cache.go index 3cce38a1b..6988d6d5a 100644 --- a/fs/cachefs/cache.go +++ b/fs/cachefs/cache.go @@ -202,8 +202,8 @@ type Options struct { //nolint:gochecknoglobals var defaultOptions = &Options{ - MaxCachedDirectories: 1000, //nolint:gomnd - MaxCachedEntries: 100000, //nolint:gomnd + MaxCachedDirectories: 1000, //nolint:mnd + MaxCachedEntries: 100000, //nolint:mnd } // NewCache creates filesystem cache. diff --git a/internal/acl/acl.go b/internal/acl/acl.go index 97290bd02..382886259 100644 --- a/internal/acl/acl.go +++ b/internal/acl/acl.go @@ -123,7 +123,7 @@ func (e *Entry) Validate() error { } parts := strings.Split(e.User, "@") - if len(parts) != 2 { //nolint:gomnd + if len(parts) != 2 { //nolint:mnd return errors.Errorf("user must be 'username@hostname' possibly including wildcards") } diff --git a/internal/acl/acl_manager.go b/internal/acl/acl_manager.go index 3026f09e9..d08837555 100644 --- a/internal/acl/acl_manager.go +++ b/internal/acl/acl_manager.go @@ -26,7 +26,7 @@ func matchOrWildcard(rule, actual string) bool { func userMatches(rule, username, hostname string) bool { ruleParts := strings.Split(rule, "@") - if len(ruleParts) != 2 { //nolint:gomnd + if len(ruleParts) != 2 { //nolint:mnd return false } diff --git a/internal/auth/authz_acl.go b/internal/auth/authz_acl.go index cb708f217..2eca3e2c6 100644 --- a/internal/auth/authz_acl.go +++ b/internal/auth/authz_acl.go @@ -106,7 +106,7 @@ func (ac *aclCache) Authorize(ctx context.Context, rep repo.Repository, username defer ac.mu.Unlock() parts := strings.Split(usernameAtHostname, "@") - if len(parts) != 2 { //nolint:gomnd + if len(parts) != 2 { //nolint:mnd return NoAccess() } diff --git a/internal/bigmap/bigmap_internal.go b/internal/bigmap/bigmap_internal.go index 3800a4fe3..a81017d19 100644 --- a/internal/bigmap/bigmap_internal.go +++ b/internal/bigmap/bigmap_internal.go @@ -179,7 +179,7 @@ func (m *internalMap) Get(buf, key []byte) ([]byte, bool) { } func (m *internalMap) hashValue(key []byte) uint64 { - if len(key) < 8 { //nolint:gomnd + if len(key) < 8 { //nolint:mnd return uint64(binary.BigEndian.Uint32(key)) } @@ -188,7 +188,7 @@ func (m *internalMap) hashValue(key []byte) uint64 { // h2 returns the secondary hash value used for double hashing. func (m *internalMap) h2(key []byte) uint64 { - if len(key) < 16 { //nolint:gomnd + if len(key) < 16 { //nolint:mnd // use linear scan. return 1 } diff --git a/internal/blobcrypto/blob_crypto.go b/internal/blobcrypto/blob_crypto.go index 91901b00f..4f8684cc3 100644 --- a/internal/blobcrypto/blob_crypto.go +++ b/internal/blobcrypto/blob_crypto.go @@ -31,7 +31,7 @@ func getIndexBlobIV(s blob.ID) ([]byte, error) { return nil, errors.Errorf("blob id too short: %v", s) } - v, err := hex.DecodeString(string(s[len(s)-(aes.BlockSize*2):])) //nolint:gomnd + v, err := hex.DecodeString(string(s[len(s)-(aes.BlockSize*2):])) //nolint:mnd if err != nil { return nil, errors.Errorf("invalid blob ID: %v", s) } diff --git a/internal/blobtesting/verify.go b/internal/blobtesting/verify.go index 8c24bf6ff..62d9d633e 100644 --- a/internal/blobtesting/verify.go +++ b/internal/blobtesting/verify.go @@ -217,7 +217,7 @@ func AssertConnectionInfoRoundTrips(ctx context.Context, t *testing.T, s blob.St // TestValidationOptions is the set of options used when running providing validation from tests. // -//nolint:gomnd +//nolint:mnd var TestValidationOptions = providervalidation.Options{ MaxClockDrift: 3 * time.Minute, ConcurrencyTestDuration: 15 * time.Second, diff --git a/internal/crypto/aesgcm.go b/internal/crypto/aesgcm.go index 2ca291437..3d79d1b9a 100644 --- a/internal/crypto/aesgcm.go +++ b/internal/crypto/aesgcm.go @@ -17,8 +17,8 @@ ) func initCrypto(masterKey, salt []byte) (cipher.AEAD, []byte, error) { - aesKey := DeriveKeyFromMasterKey(masterKey, salt, purposeAESKey, 32) //nolint:gomnd - authData := DeriveKeyFromMasterKey(masterKey, salt, purposeAuthData, 32) //nolint:gomnd + aesKey := DeriveKeyFromMasterKey(masterKey, salt, purposeAESKey, 32) //nolint:mnd + authData := DeriveKeyFromMasterKey(masterKey, salt, purposeAuthData, 32) //nolint:mnd blk, err := aes.NewCipher(aesKey) if err != nil { diff --git a/internal/crypto/pb_key_deriver_scrypt.go b/internal/crypto/pb_key_deriver_scrypt.go index 765fddbfc..ed0e82bcb 100644 --- a/internal/crypto/pb_key_deriver_scrypt.go +++ b/internal/crypto/pb_key_deriver_scrypt.go @@ -22,8 +22,8 @@ func init() { registerPBKeyDeriver(ScryptAlgorithm, &scryptKeyDeriver{ - n: 65536, //nolint:gomnd - r: 8, //nolint:gomnd + n: 65536, //nolint:mnd + r: 8, //nolint:mnd p: 1, minSaltLength: scryptMinSaltLength, }) diff --git a/internal/diff/diff.go b/internal/diff/diff.go index 61ce09290..59245bc66 100644 --- a/internal/diff/diff.go +++ b/internal/diff/diff.go @@ -159,12 +159,12 @@ func compareEntry(e1, e2 fs.Entry, fullpath string, out io.Writer) bool { } if e1 == nil { - fmt.Fprintln(out, fullpath, "does not exist in source directory") + fmt.Fprintln(out, fullpath, "does not exist in source directory") //nolint:errcheck return false } if e2 == nil { - fmt.Fprintln(out, fullpath, "does not exist in destination directory") + fmt.Fprintln(out, fullpath, "does not exist in destination directory") //nolint:errcheck return false } @@ -173,32 +173,32 @@ func compareEntry(e1, e2 fs.Entry, fullpath string, out io.Writer) bool { if m1, m2 := e1.Mode(), e2.Mode(); m1 != m2 { equal = false - fmt.Fprintln(out, fullpath, "modes differ: ", m1, m2) + fmt.Fprintln(out, fullpath, "modes differ: ", m1, m2) //nolint:errcheck } if s1, s2 := e1.Size(), e2.Size(); s1 != s2 { equal = false - fmt.Fprintln(out, fullpath, "sizes differ: ", s1, s2) + fmt.Fprintln(out, fullpath, "sizes differ: ", s1, s2) //nolint:errcheck } if mt1, mt2 := e1.ModTime(), e2.ModTime(); !mt1.Equal(mt2) { equal = false - fmt.Fprintln(out, fullpath, "modification times differ: ", mt1, mt2) + fmt.Fprintln(out, fullpath, "modification times differ: ", mt1, mt2) //nolint:errcheck } o1, o2 := e1.Owner(), e2.Owner() if o1.UserID != o2.UserID { equal = false - fmt.Fprintln(out, fullpath, "owner users differ: ", o1.UserID, o2.UserID) + fmt.Fprintln(out, fullpath, "owner users differ: ", o1.UserID, o2.UserID) //nolint:errcheck } if o1.GroupID != o2.GroupID { equal = false - fmt.Fprintln(out, fullpath, "owner groups differ: ", o1.GroupID, o2.GroupID) + fmt.Fprintln(out, fullpath, "owner groups differ: ", o1.GroupID, o2.GroupID) //nolint:errcheck } // don't compare filesystem boundaries (e1.Device()), it's pretty useless and is not stored in backups @@ -298,7 +298,7 @@ func downloadFile(ctx context.Context, f fs.File, fname string) error { } func (c *Comparer) output(msg string, args ...interface{}) { - fmt.Fprintf(c.out, msg, args...) + fmt.Fprintf(c.out, msg, args...) //nolint:errcheck } // NewComparer creates a comparer for a given repository that will output the results to a given writer. diff --git a/internal/editor/editor.go b/internal/editor/editor.go index 0ff45b774..1e26e0ad1 100644 --- a/internal/editor/editor.go +++ b/internal/editor/editor.go @@ -30,7 +30,7 @@ func EditLoop(ctx context.Context, fname, initial string, parse func(updated str tmpFile := filepath.Join(tmpDir, fname) defer os.RemoveAll(tmpDir) //nolint:errcheck - //nolint:gomnd + //nolint:mnd if err := os.WriteFile(tmpFile, []byte(initial), 0o600); err != nil { return errors.Wrap(err, "unable to write file to edit") } diff --git a/internal/epoch/epoch_advance.go b/internal/epoch/epoch_advance.go index 07d86f1a2..07c01eb09 100644 --- a/internal/epoch/epoch_advance.go +++ b/internal/epoch/epoch_advance.go @@ -19,25 +19,25 @@ func shouldAdvance(bms []blob.Metadata, minEpochDuration time.Duration, countThr } var ( - min = bms[0].Timestamp - max = bms[0].Timestamp + minTime = bms[0].Timestamp + maxTime = bms[0].Timestamp totalSize = int64(0) ) for _, bm := range bms { - if bm.Timestamp.Before(min) { - min = bm.Timestamp + if bm.Timestamp.Before(minTime) { + minTime = bm.Timestamp } - if bm.Timestamp.After(max) { - max = bm.Timestamp + if bm.Timestamp.After(maxTime) { + maxTime = bm.Timestamp } totalSize += bm.Length } // not enough time between first and last write in an epoch. - if max.Sub(min) < minEpochDuration { + if maxTime.Sub(minTime) < minEpochDuration { return false } diff --git a/internal/epoch/epoch_manager.go b/internal/epoch/epoch_manager.go index 3ee0bb325..32bf7e6d9 100644 --- a/internal/epoch/epoch_manager.go +++ b/internal/epoch/epoch_manager.go @@ -109,7 +109,7 @@ func (p *Parameters) GetEpochDeleteParallelism() int { // Validate validates epoch parameters. // -//nolint:gomnd +//nolint:mnd func (p *Parameters) Validate() error { if !p.Enabled { return nil @@ -144,7 +144,7 @@ func (p *Parameters) Validate() error { // DefaultParameters contains default epoch manager parameters. // -//nolint:gomnd +//nolint:mnd func DefaultParameters() Parameters { return Parameters{ Enabled: true, @@ -419,8 +419,8 @@ func (e *Manager) CleanupSupersededIndexes(ctx context.Context) error { } func blobSetWrittenEarlyEnough(replacementSet []blob.Metadata, maxReplacementTime time.Time) bool { - max := blob.MaxTimestamp(replacementSet) - if max.IsZero() { + maxTime := blob.MaxTimestamp(replacementSet) + if maxTime.IsZero() { return false } @@ -604,14 +604,14 @@ func getRangeToCompact(cs CurrentSnapshot, p Parameters) (low, high int, compact return latestSettled, firstNonRangeCompacted, true } -func (e *Manager) loadUncompactedEpochs(ctx context.Context, min, max int) (map[int][]blob.Metadata, error) { +func (e *Manager) loadUncompactedEpochs(ctx context.Context, first, last int) (map[int][]blob.Metadata, error) { var mu sync.Mutex result := map[int][]blob.Metadata{} eg, ctx := errgroup.WithContext(ctx) - for n := min; n <= max; n++ { + for n := first; n <= last; n++ { if n < 0 { continue } @@ -791,7 +791,7 @@ func (e *Manager) WriteIndex(ctx context.Context, dataShards map[blob.ID]blob.By } // make sure we have at least 75% of remaining time - //nolint:gomnd + //nolint:mnd cs, err := e.committedState(ctx, 3*p.EpochRefreshFrequency/4) if err != nil { return nil, errors.Wrap(err, "error getting committed state") diff --git a/internal/epoch/epoch_manager_test.go b/internal/epoch/epoch_manager_test.go index fb1605601..178d326ca 100644 --- a/internal/epoch/epoch_manager_test.go +++ b/internal/epoch/epoch_manager_test.go @@ -1416,8 +1416,8 @@ func TestCleanupMarkers_CleanUpManyMarkers(t *testing.T) { require.Len(t, cs.EpochMarkerBlobs, 2) // at least 2 epoch markers are kept } -func randomTime(min, max time.Duration) time.Duration { - return time.Duration(float64(max-min)*rand.Float64() + float64(min)) +func randomTime(minTime, maxTime time.Duration) time.Duration { + return time.Duration(float64(maxTime-minTime)*rand.Float64() + float64(minTime)) } func (te *epochManagerTestEnv) verifyCompleteIndexSet(ctx context.Context, t *testing.T, maxEpoch int, want *fakeIndex, wantDeletionWatermark time.Time) { diff --git a/internal/epoch/epoch_range.go b/internal/epoch/epoch_range.go index 2fb5ba6d9..86863f403 100644 --- a/internal/epoch/epoch_range.go +++ b/internal/epoch/epoch_range.go @@ -35,8 +35,8 @@ func findLongestRangeCheckpointStartingAt(startEpoch int, byMin, memo map[int][] for _, cp := range byMin[startEpoch] { combined := append([]*RangeMetadata{cp}, findLongestRangeCheckpointStartingAt(cp.MaxEpoch+1, byMin, memo)...) - if max := combined[len(combined)-1].MaxEpoch; (max > longest) || (max == longest && len(combined) < len(longestMetadata)) { - longest = max + if m := combined[len(combined)-1].MaxEpoch; (m > longest) || (m == longest && len(combined) < len(longestMetadata)) { + longest = m longestMetadata = combined } } diff --git a/internal/epoch/epoch_range_test.go b/internal/epoch/epoch_range_test.go index aefc9f343..f552142f6 100644 --- a/internal/epoch/epoch_range_test.go +++ b/internal/epoch/epoch_range_test.go @@ -64,6 +64,6 @@ func TestLongestRangeCheckpoint(t *testing.T) { } } -func newEpochRangeMetadataForTesting(min, max int) *RangeMetadata { - return &RangeMetadata{MinEpoch: min, MaxEpoch: max} +func newEpochRangeMetadataForTesting(minEpoch, maxEpoch int) *RangeMetadata { + return &RangeMetadata{MinEpoch: minEpoch, MaxEpoch: maxEpoch} } diff --git a/internal/epoch/epoch_utils.go b/internal/epoch/epoch_utils.go index 43a3705a4..005e60aad 100644 --- a/internal/epoch/epoch_utils.go +++ b/internal/epoch/epoch_utils.go @@ -34,10 +34,10 @@ func epochNumberFromBlobID(blobID blob.ID) (int, bool) { // epochRangeFromBlobID extracts the range epoch numbers from a string formatted as // __. -func epochRangeFromBlobID(blobID blob.ID) (min, max int, ok bool) { +func epochRangeFromBlobID(blobID blob.ID) (minEpoch, maxEpoch int, ok bool) { parts := strings.Split(string(blobID), "_") - //nolint:gomnd + //nolint:mnd if len(parts) < 3 { return 0, 0, false } @@ -118,7 +118,7 @@ func (r closedIntRange) isEmpty() bool { // constants from the standard math package. const ( - //nolint:gomnd + //nolint:mnd intSize = 32 << (^uint(0) >> 63) // 32 or 64 maxInt = 1<<(intSize-1) - 1 diff --git a/internal/gather/gather_write_buffer_chunk.go b/internal/gather/gather_write_buffer_chunk.go index 666c2a8b7..9d81bdd5f 100644 --- a/internal/gather/gather_write_buffer_chunk.go +++ b/internal/gather/gather_write_buffer_chunk.go @@ -21,21 +21,21 @@ defaultAllocator = &chunkAllocator{ name: "default", - chunkSize: 1 << 16, //nolint:gomnd - maxFreeListSize: 2048, //nolint:gomnd + chunkSize: 1 << 16, //nolint:mnd + maxFreeListSize: 2048, //nolint:mnd } // typicalContiguousAllocator is used for short-term buffers for encryption. typicalContiguousAllocator = &chunkAllocator{ name: "mid-size contiguous", - chunkSize: 8<<20 + 128, //nolint:gomnd + chunkSize: 8<<20 + 128, //nolint:mnd maxFreeListSize: runtime.NumCPU(), } // maxContiguousAllocator is used for short-term buffers for encryption. maxContiguousAllocator = &chunkAllocator{ name: "contiguous", - chunkSize: 16<<20 + 128, //nolint:gomnd + chunkSize: 16<<20 + 128, //nolint:mnd maxFreeListSize: runtime.NumCPU(), } ) diff --git a/internal/metricid/id_mapping.go b/internal/metricid/id_mapping.go index 6818b2c1c..6d8f9f6f1 100644 --- a/internal/metricid/id_mapping.go +++ b/internal/metricid/id_mapping.go @@ -44,15 +44,15 @@ func NewMapping(fwd map[string]int) *Mapping { IndexToName: inverse(fwd), } - max := 0 + maxIndex := 0 for _, index := range fwd { - if index > max { - max = index + if index > maxIndex { + maxIndex = index } } - m.MaxIndex = max + m.MaxIndex = maxIndex return m } diff --git a/internal/metricid/metricid.go b/internal/metricid/metricid.go index 14acf326f..9e375317b 100644 --- a/internal/metricid/metricid.go +++ b/internal/metricid/metricid.go @@ -3,7 +3,7 @@ // Counters contains a mapping of counter names to ID. // -//nolint:gochecknoglobals,gomnd +//nolint:gochecknoglobals,mnd var Counters = NewMapping(map[string]int{ "blob_download_full_blob_bytes": 1, "blob_download_partial_blob_bytes": 2, @@ -45,7 +45,7 @@ // DurationDistributions contains a mapping of DurationDistribution names to ID. // -//nolint:gochecknoglobals,gomnd +//nolint:gochecknoglobals,mnd var DurationDistributions = NewMapping(map[string]int{ "blob_storage_latency[method:Close]": 1, "blob_storage_latency[method:DeleteBlob]": 2, diff --git a/internal/mockfs/mockfs.go b/internal/mockfs/mockfs.go index 7c55a7e83..0ef689190 100644 --- a/internal/mockfs/mockfs.go +++ b/internal/mockfs/mockfs.go @@ -369,7 +369,7 @@ func NewDirectory() *Directory { return &Directory{ entry: entry{ name: "", - mode: 0o777 | os.ModeDir, //nolint:gomnd + mode: 0o777 | os.ModeDir, //nolint:mnd modTime: DefaultModTime, }, } diff --git a/internal/mount/mount_net_use.go b/internal/mount/mount_net_use.go index f58ddd4d2..983cd78f2 100644 --- a/internal/mount/mount_net_use.go +++ b/internal/mount/mount_net_use.go @@ -78,7 +78,7 @@ func netUseUnmount(ctx context.Context, driveLetter string) error { } func isWindowsDrive(s string) bool { - if len(s) != 2 { //nolint:gomnd + if len(s) != 2 { //nolint:mnd return false } diff --git a/internal/mount/mount_webdav.go b/internal/mount/mount_webdav.go index cf85d8aa9..24c221984 100644 --- a/internal/mount/mount_webdav.go +++ b/internal/mount/mount_webdav.go @@ -52,7 +52,7 @@ func DirectoryWebDAV(ctx context.Context, entry fs.Directory) (Controller, error } srv := &http.Server{ - ReadHeaderTimeout: 15 * time.Second, //nolint:gomnd + ReadHeaderTimeout: 15 * time.Second, //nolint:mnd Handler: mux, } diff --git a/internal/providervalidation/providervalidation.go b/internal/providervalidation/providervalidation.go index 5db215d3e..1f28b4a10 100644 --- a/internal/providervalidation/providervalidation.go +++ b/internal/providervalidation/providervalidation.go @@ -40,7 +40,7 @@ type Options struct { // DefaultOptions is the default set of options. // -//nolint:gomnd,gochecknoglobals +//nolint:mnd,gochecknoglobals var DefaultOptions = Options{ MaxClockDrift: 3 * time.Minute, ConcurrencyTestDuration: 30 * time.Second, @@ -102,7 +102,7 @@ func openEquivalentStorageConnections(ctx context.Context, st blob.Storage, n in // ValidateProvider runs a series of tests against provided storage to validate that // it can be used with Kopia. // -//nolint:gomnd,funlen,gocyclo,cyclop +//nolint:mnd,funlen,gocyclo,cyclop func ValidateProvider(ctx context.Context, st0 blob.Storage, opt Options) error { if os.Getenv("KOPIA_SKIP_PROVIDER_VALIDATION") != "" { return nil @@ -350,7 +350,7 @@ func (c *concurrencyTest) putBlobWorker(ctx context.Context, worker int) func() } func (c *concurrencyTest) randomSleep() { - time.Sleep(time.Duration(rand.Intn(int(500 * time.Millisecond)))) //nolint:gosec,gomnd + time.Sleep(time.Duration(rand.Intn(int(500 * time.Millisecond)))) //nolint:gosec,mnd } func (c *concurrencyTest) pickBlob() (blob.ID, int64, bool) { diff --git a/internal/retry/retry.go b/internal/retry/retry.go index 893042af8..28a74bf5f 100644 --- a/internal/retry/retry.go +++ b/internal/retry/retry.go @@ -55,7 +55,7 @@ func PeriodicallyNoValue(ctx context.Context, interval time.Duration, count int, // internalRetry runs the provided attempt until it succeeds, retrying on all errors that are // deemed retriable by the provided function. The delay between retries grows exponentially up to // a certain limit. -func internalRetry[T any](ctx context.Context, desc string, attempt func() (T, error), isRetriableError IsRetriableFunc, initial, max time.Duration, count int, factor float64) (T, error) { +func internalRetry[T any](ctx context.Context, desc string, attempt func() (T, error), isRetriableError IsRetriableFunc, initial, maxSleep time.Duration, count int, factor float64) (T, error) { sleepAmount := initial var ( @@ -86,8 +86,8 @@ func internalRetry[T any](ctx context.Context, desc string, attempt func() (T, e time.Sleep(sleepAmount) sleepAmount = time.Duration(float64(sleepAmount) * factor) - if sleepAmount > max { - sleepAmount = max + if sleepAmount > maxSleep { + sleepAmount = maxSleep } } diff --git a/internal/server/grpc_session.go b/internal/server/grpc_session.go index 51d924f87..b10fb06a1 100644 --- a/internal/server/grpc_session.go +++ b/internal/server/grpc_session.go @@ -448,7 +448,7 @@ func handleApplyRetentionPolicyRequest(ctx context.Context, rep repo.RepositoryW defer span.End() parts := strings.Split(usernameAtHostname, "@") - if len(parts) != 2 { //nolint:gomnd + if len(parts) != 2 { //nolint:mnd return errorResponse(errors.Errorf("invalid username@hostname: %q", usernameAtHostname)) } @@ -578,7 +578,7 @@ func (s *Server) RegisterGRPCHandlers(r grpc.ServiceRegistrar) { func makeGRPCServerState(maxConcurrency int) grpcServerState { if maxConcurrency == 0 { - maxConcurrency = 2 * runtime.NumCPU() //nolint:gomnd + maxConcurrency = 2 * runtime.NumCPU() //nolint:mnd } return grpcServerState{ diff --git a/internal/server/server.go b/internal/server/server.go index 1280e995f..af9064ffa 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -491,11 +491,11 @@ func (s *Server) requestShutdown(ctx context.Context) { } } -func (s *Server) setMaxParallelSnapshotsLocked(max int) { +func (s *Server) setMaxParallelSnapshotsLocked(maxParallel int) { s.parallelSnapshotsMutex.Lock() defer s.parallelSnapshotsMutex.Unlock() - s.maxParallelSnapshots = max + s.maxParallelSnapshots = maxParallel s.parallelSnapshotsChanged.Broadcast() } diff --git a/internal/testutil/tmpdir.go b/internal/testutil/tmpdir.go index 24c26f1e2..2010dae82 100644 --- a/internal/testutil/tmpdir.go +++ b/internal/testutil/tmpdir.go @@ -38,7 +38,7 @@ func GetInterestingTempDirectoryName() (string, error) { td = filepath.Join(td, strings.Repeat("f", targetLen-n)) } - //nolint:gomnd + //nolint:mnd if err := os.MkdirAll(td, 0o700); err != nil { return "", errors.Wrap(err, "unable to create temp directory") } @@ -161,9 +161,9 @@ func trimOutput(s string) string { return s } - lines2 := append([]string(nil), lines[0:(maxOutputLinesToLog/2)]...) //nolint:gomnd + lines2 := append([]string(nil), lines[0:(maxOutputLinesToLog/2)]...) //nolint:mnd lines2 = append(lines2, fmt.Sprintf("/* %v lines removed */", len(lines)-maxOutputLinesToLog)) - lines2 = append(lines2, lines[len(lines)-(maxOutputLinesToLog/2):]...) //nolint:gomnd + lines2 = append(lines2, lines[len(lines)-(maxOutputLinesToLog/2):]...) //nolint:mnd return strings.Join(lines2, "\n") } diff --git a/internal/tlsutil/tlsutil.go b/internal/tlsutil/tlsutil.go index dba9c83d3..d0ddb8a53 100644 --- a/internal/tlsutil/tlsutil.go +++ b/internal/tlsutil/tlsutil.go @@ -43,7 +43,7 @@ func GenerateServerCertificate(ctx context.Context, keySize int, certValid time. notBefore := clock.Now() notAfter := notBefore.Add(certValid) - //nolint:gomnd + //nolint:mnd serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) if err != nil { return nil, nil, errors.Wrap(err, "unable to generate serial number") diff --git a/internal/uitask/uitask_manager.go b/internal/uitask/uitask_manager.go index 3a05ee4e6..3876959b6 100644 --- a/internal/uitask/uitask_manager.go +++ b/internal/uitask/uitask_manager.go @@ -106,7 +106,7 @@ func (m *Manager) WaitForTask(ctx context.Context, taskID string, maxWaitTime ti deadline := clock.Now().Add(maxWaitTime) - sleepInterval := maxWaitTime / 10 //nolint:gomnd + sleepInterval := maxWaitTime / 10 //nolint:mnd if sleepInterval > maxWaitInterval { sleepInterval = maxWaitInterval } diff --git a/internal/units/units.go b/internal/units/units.go index e2f9f8222..c3d28cc67 100644 --- a/internal/units/units.go +++ b/internal/units/units.go @@ -36,13 +36,13 @@ func toDecimalUnitString(f, thousand float64, prefixes []string, suffix string) // BytesStringBase10 formats the given value as bytes with the appropriate base-10 suffix (KB, MB, GB, ...) func BytesStringBase10(b int64) string { - //nolint:gomnd + //nolint:mnd return toDecimalUnitString(float64(b), 1000, base10UnitPrefixes, "B") } // BytesStringBase2 formats the given value as bytes with the appropriate base-2 suffix (KiB, MiB, GiB, ...) func BytesStringBase2(b int64) string { - //nolint:gomnd + //nolint:mnd return toDecimalUnitString(float64(b), 1024.0, base2UnitPrefixes, "B") } @@ -57,12 +57,12 @@ func BytesString(b int64) string { // BytesPerSecondsString formats the given value bytes per second with the appropriate base-10 suffix (KB/s, MB/s, GB/s, ...) func BytesPerSecondsString(bps float64) string { - //nolint:gomnd + //nolint:mnd return toDecimalUnitString(bps, 1000, base10UnitPrefixes, "B/s") } // Count returns the given number with the appropriate base-10 suffix (K, M, G, ...) func Count(v int64) string { - //nolint:gomnd + //nolint:mnd return toDecimalUnitString(float64(v), 1000, base10UnitPrefixes, "") } diff --git a/internal/zaplogutil/zaplogutil.go b/internal/zaplogutil/zaplogutil.go index 5b22f4166..78a40cf9b 100644 --- a/internal/zaplogutil/zaplogutil.go +++ b/internal/zaplogutil/zaplogutil.go @@ -128,7 +128,7 @@ func (c *stdConsoleEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Fiel line.AppendString(ent.Message) if line2, err := c.Encoder.EncodeEntry(ent, fields); err == nil { - if line2.Len() > 2 { //nolint:gomnd + if line2.Len() > 2 { //nolint:mnd line.AppendString("\t") line.AppendString(line2.String()) } diff --git a/repo/blob/gdrive/gdrive_storage.go b/repo/blob/gdrive/gdrive_storage.go index ac7e9b9ab..f4aa02356 100644 --- a/repo/blob/gdrive/gdrive_storage.go +++ b/repo/blob/gdrive/gdrive_storage.go @@ -384,7 +384,7 @@ func (gdrive *gdriveStorage) getFileByBlobID(ctx context.Context, blobID blob.ID IncludeItemsFromAllDrives(true). Q(fmt.Sprintf("'%s' in parents and name = '%s' and mimeType = '%s' and trashed = false", gdrive.folderID, toFileName(blobID), blobMimeType)). Fields(fields). - PageSize(2). //nolint:gomnd + PageSize(2). //nolint:mnd Context(ctx). Do() diff --git a/repo/blob/rclone/rclone_storage.go b/repo/blob/rclone/rclone_storage.go index 000229012..5dfef6d64 100644 --- a/repo/blob/rclone/rclone_storage.go +++ b/repo/blob/rclone/rclone_storage.go @@ -276,7 +276,7 @@ func New(ctx context.Context, opt *Options, isCreate bool) (blob.Storage, error) }() // write TLS files. - //nolint:gomnd + //nolint:mnd cert, key, err := tlsutil.GenerateServerCertificate(ctx, 2048, 365*24*time.Hour, []string{"127.0.0.1"}) if err != nil { return nil, errors.Wrap(err, "unable to generate server certificate") @@ -313,7 +313,7 @@ func New(ctx context.Context, opt *Options, isCreate bool) (blob.Storage, error) if opt.EmbeddedConfig != "" { tmpConfigFile := filepath.Join(r.temporaryDir, "rclone.conf") - //nolint:gomnd + //nolint:mnd if err = os.WriteFile(tmpConfigFile, []byte(opt.EmbeddedConfig), 0o600); err != nil { return nil, errors.Wrap(err, "unable to write config file") } diff --git a/repo/blob/rclone/rclone_storage_test.go b/repo/blob/rclone/rclone_storage_test.go index b226d2490..019678735 100644 --- a/repo/blob/rclone/rclone_storage_test.go +++ b/repo/blob/rclone/rclone_storage_test.go @@ -324,7 +324,7 @@ func cleanupOldData(t *testing.T, rcloneExe, remotePath string) { configFile = filepath.Join(tmpDir, "rclone.conf") - //nolint:gomnd + //nolint:mnd if err = os.WriteFile(configFile, b, 0o600); err != nil { t.Fatalf("unable to write config file: %v", err) } diff --git a/repo/blob/sharded/sharded.go b/repo/blob/sharded/sharded.go index ab46f6043..96a1331ae 100644 --- a/repo/blob/sharded/sharded.go +++ b/repo/blob/sharded/sharded.go @@ -72,7 +72,7 @@ func (s *Storage) ListBlobs(ctx context.Context, prefix blob.ID, callback func(b pw := parallelwork.NewQueue() // channel to which pw will write blob.Metadata, some buf - result := make(chan blob.Metadata, 128) //nolint:gomnd + result := make(chan blob.Metadata, 128) //nolint:mnd finished := make(chan struct{}) defer close(finished) diff --git a/repo/blob/storage.go b/repo/blob/storage.go index f4a4b105a..074da2e90 100644 --- a/repo/blob/storage.go +++ b/repo/blob/storage.go @@ -331,28 +331,28 @@ func TotalLength(mds []Metadata) int64 { // MinTimestamp returns minimum timestamp for blobs in Metadata slice. func MinTimestamp(mds []Metadata) time.Time { - min := time.Time{} + minTime := time.Time{} for _, md := range mds { - if min.IsZero() || md.Timestamp.Before(min) { - min = md.Timestamp + if minTime.IsZero() || md.Timestamp.Before(minTime) { + minTime = md.Timestamp } } - return min + return minTime } // MaxTimestamp returns maximum timestamp for blobs in Metadata slice. func MaxTimestamp(mds []Metadata) time.Time { - max := time.Time{} + maxTime := time.Time{} for _, md := range mds { - if md.Timestamp.After(max) { - max = md.Timestamp + if md.Timestamp.After(maxTime) { + maxTime = md.Timestamp } } - return max + return maxTime } // DeleteMultiple deletes multiple blobs in parallel. diff --git a/repo/blob/throttling/throttling_semaphore_test.go b/repo/blob/throttling/throttling_semaphore_test.go index a11f7579a..b255435b4 100644 --- a/repo/blob/throttling/throttling_semaphore_test.go +++ b/repo/blob/throttling/throttling_semaphore_test.go @@ -59,6 +59,6 @@ func TestThrottlingSemaphore(t *testing.T) { // Equal() would probably work here due to Sleep(), but not risking a flake. require.LessOrEqual(t, maxConcurrency, lim) - require.Greater(t, maxConcurrency, 0) + require.Positive(t, maxConcurrency) } } diff --git a/repo/content/committed_read_manager.go b/repo/content/committed_read_manager.go index bde08288b..de76e878c 100644 --- a/repo/content/committed_read_manager.go +++ b/repo/content/committed_read_manager.go @@ -201,7 +201,7 @@ func (sm *SharedManager) attemptReadPackFileLocalIndex(ctx context.Context, pack // +checklocks:sm.indexesLock func (sm *SharedManager) loadPackIndexesLocked(ctx context.Context) error { - nextSleepTime := 100 * time.Millisecond //nolint:gomnd + nextSleepTime := 100 * time.Millisecond //nolint:mnd for i := range indexLoadAttempts { ibm, err0 := sm.indexBlobManager(ctx) diff --git a/repo/content/content_index_recovery.go b/repo/content/content_index_recovery.go index 4ea6c80c1..31c08623e 100644 --- a/repo/content/content_index_recovery.go +++ b/repo/content/content_index_recovery.go @@ -70,7 +70,7 @@ func (p *packContentPostamble) toBytes() ([]byte, error) { binary.BigEndian.PutUint32(buf[n:], checksum) n += 4 - if n > 255 { //nolint:gomnd + if n > 255 { //nolint:mnd return nil, errors.Errorf("postamble too long: %v", n) } @@ -90,7 +90,7 @@ func findPostamble(b []byte) *packContentPostamble { // length of postamble is the last byte postambleLength := int(b[len(b)-1]) - if postambleLength < 5 { //nolint:gomnd + if postambleLength < 5 { //nolint:mnd // too short, must be at least 5 bytes (checksum + own length) return nil } diff --git a/repo/content/index/index_builder.go b/repo/content/index/index_builder.go index b6b25ea4b..d4f18164b 100644 --- a/repo/content/index/index_builder.go +++ b/repo/content/index/index_builder.go @@ -55,8 +55,8 @@ func init() { } for i := range 26 { - base36Value['a'+i] = byte(i + 10) //nolint:gomnd - base36Value['A'+i] = byte(i + 10) //nolint:gomnd + base36Value['a'+i] = byte(i + 10) //nolint:mnd + base36Value['A'+i] = byte(i + 10) //nolint:mnd } } @@ -70,10 +70,10 @@ func (b Builder) sortedContents() []Info { // by first [0-9a-z] and second character [0-9a-f]. for cid, v := range b { first := int(base36Value[cid.prefix]) - second := int(cid.data[0] >> 4) //nolint:gomnd + second := int(cid.data[0] >> 4) //nolint:mnd // first: 0..35, second: 0..15 - buck := first<<4 + second //nolint:gomnd + buck := first<<4 + second //nolint:mnd buckets[buck] = append(buckets[buck], v) } diff --git a/repo/content/index/index_encode_util.go b/repo/content/index/index_encode_util.go index 1c6073f08..a7c3cff31 100644 --- a/repo/content/index/index_encode_util.go +++ b/repo/content/index/index_encode_util.go @@ -22,7 +22,7 @@ func decodeBigEndianUint16(d []byte) uint16 { func encodeBigEndianUint24(b []byte, v uint32) { _ = b[2] // early bounds check - b[0] = byte(v >> 16) //nolint:gomnd - b[1] = byte(v >> 8) //nolint:gomnd + b[0] = byte(v >> 16) //nolint:mnd + b[1] = byte(v >> 8) //nolint:mnd b[2] = byte(v) } diff --git a/repo/content/index/index_v1.go b/repo/content/index/index_v1.go index 94ed49f61..45633e8ad 100644 --- a/repo/content/index/index_v1.go +++ b/repo/content/index/index_v1.go @@ -89,7 +89,7 @@ func (b *indexV1) entryToInfoStruct(contentID ID, data []byte, result *Info) err result.PackBlobID = b.packBlobIDForOffset(nameOffset, nameLength) // entry bytes 12..15 - deleted flag (MSBit), 31 lower bits encode pack offset. - result.Deleted = data[12]&0x80 != 0 //nolint:gomnd + result.Deleted = data[12]&0x80 != 0 //nolint:mnd const packOffsetMask = 1<<31 - 1 result.PackOffset = decodeBigEndianUint32(data[12:]) & packOffsetMask @@ -367,7 +367,7 @@ func (b *indexBuilderV1) formatEntry(entry []byte, it Info) error { entryPackFileOffset := entry[8:12] entryPackedOffset := entry[12:16] entryPackedLength := entry[16:20] - timestampAndFlags := uint64(it.TimestampSeconds) << 16 //nolint:gomnd + timestampAndFlags := uint64(it.TimestampSeconds) << 16 //nolint:mnd packBlobID := it.PackBlobID if len(packBlobID) == 0 { @@ -383,7 +383,7 @@ func (b *indexBuilderV1) formatEntry(entry []byte, it Info) error { } binary.BigEndian.PutUint32(entryPackedLength, it.PackedLength) - timestampAndFlags |= uint64(it.FormatVersion) << 8 //nolint:gomnd + timestampAndFlags |= uint64(it.FormatVersion) << 8 //nolint:mnd timestampAndFlags |= uint64(len(packBlobID)) binary.BigEndian.PutUint64(entryTimestampAndFlags, timestampAndFlags) diff --git a/repo/content/index/index_v2.go b/repo/content/index/index_v2.go index 245508e32..494f3f4ca 100644 --- a/repo/content/index/index_v2.go +++ b/repo/content/index/index_v2.go @@ -428,14 +428,6 @@ func maxContentLengths(sortedInfos []Info) (maxPackedLength, maxOriginalLength, return } -func max(a, b int) int { - if a > b { - return a - } - - return b -} - func newIndexBuilderV2(sortedInfos []Info) (*indexBuilderV2, error) { entrySize := v2EntryOffsetFormatID diff --git a/repo/content/index/merged.go b/repo/content/index/merged.go index 6bd5c4da9..1bd939de1 100644 --- a/repo/content/index/merged.go +++ b/repo/content/index/merged.go @@ -157,23 +157,23 @@ func (m Merged) Iterate(r IDRange, cb func(i Info) error) error { for len(minHeap) > 0 { //nolint:forcetypeassert - min := heap.Pop(&minHeap).(*nextInfo) - if !havePendingItem || pendingItem.ContentID != min.it.ContentID { + minNextInfo := heap.Pop(&minHeap).(*nextInfo) + if !havePendingItem || pendingItem.ContentID != minNextInfo.it.ContentID { if havePendingItem { if err := cb(pendingItem); err != nil { return err } } - pendingItem = min.it + pendingItem = minNextInfo.it havePendingItem = true - } else if contentInfoGreaterThanStruct(min.it, pendingItem) { - pendingItem = min.it + } else if contentInfoGreaterThanStruct(minNextInfo.it, pendingItem) { + pendingItem = minNextInfo.it } - it, ok := <-min.ch + it, ok := <-minNextInfo.ch if ok { - heap.Push(&minHeap, &nextInfo{it, min.ch}) + heap.Push(&minHeap, &nextInfo{it, minNextInfo.ch}) } } diff --git a/repo/content/indexblob/index_blob_manager_v0_test.go b/repo/content/indexblob/index_blob_manager_v0_test.go index 7c6a9d9e0..cba55d17a 100644 --- a/repo/content/indexblob/index_blob_manager_v0_test.go +++ b/repo/content/indexblob/index_blob_manager_v0_test.go @@ -345,8 +345,8 @@ func TestIndexBlobManagerPreventsResurrectOfDeletedContents_RandomizedTimings(t } } -func randomDuration(max time.Duration) time.Duration { - return time.Duration(float64(max) * rand.Float64()) +func randomDuration(maxDuration time.Duration) time.Duration { + return time.Duration(float64(maxDuration) * rand.Float64()) } func verifyIndexBlobManagerPreventsResurrectOfDeletedContents(t *testing.T, delay1, delay2, delay3, delay4, delay5 time.Duration) { diff --git a/repo/ecc/ecc_rs_crc.go b/repo/ecc/ecc_rs_crc.go index 919f1e625..80e46117e 100644 --- a/repo/ecc/ecc_rs_crc.go +++ b/repo/ecc/ecc_rs_crc.go @@ -44,13 +44,13 @@ func newReedSolomonCrcECC(opts *Options) (*ReedSolomonCrcECC, error) { case opts.OverheadPercent == 1: result.MaxShardSize = 1024 - case opts.OverheadPercent == 2: //nolint:gomnd + case opts.OverheadPercent == 2: //nolint:mnd result.MaxShardSize = 512 - case opts.OverheadPercent == 3: //nolint:gomnd + case opts.OverheadPercent == 3: //nolint:mnd result.MaxShardSize = 256 - case opts.OverheadPercent <= 6: //nolint:gomnd + case opts.OverheadPercent <= 6: //nolint:mnd result.MaxShardSize = 128 default: @@ -60,11 +60,11 @@ func newReedSolomonCrcECC(opts *Options) (*ReedSolomonCrcECC, error) { // Remove the space used for the crc from the allowed space overhead, if possible freeSpaceOverhead := float32(opts.OverheadPercent) - 100*crcSize/float32(result.MaxShardSize) - freeSpaceOverhead = maxFloat32(freeSpaceOverhead, 0.01) //nolint:gomnd + freeSpaceOverhead = maxFloat32(freeSpaceOverhead, 0.01) //nolint:mnd result.DataShards, result.ParityShards = computeShards(freeSpaceOverhead) // Bellow this threshold the data will be split in less shards - result.ThresholdParityInput = 2 * crcSize * (result.DataShards + result.ParityShards) //nolint:gomnd + result.ThresholdParityInput = 2 * crcSize * (result.DataShards + result.ParityShards) //nolint:mnd result.ThresholdParityOutput = computeFinalFileSizeWithPadding(smallFilesDataShards, smallFilesParityShards, ceilInt(result.ThresholdParityInput, smallFilesDataShards), 1) // Bellow this threshold the shard size will shrink to the smallest possible @@ -280,7 +280,7 @@ func (r *ReedSolomonCrcECC) Decrypt(input gather.Bytes, _ []byte, output *gather for b := range sizes.Blocks { for i := range sizes.DataShards { - initialDataPos := dataPos //nolint:copyloopvar + initialDataPos := dataPos crc := binary.BigEndian.Uint32(dataBytes[dataPos : dataPos+crcSize]) dataPos += crcSize @@ -355,21 +355,21 @@ func readLength(shards [][]byte, sizes *sizesInfo) (originalSize, startShard, st lengthBuffer[i] = shards[i][0] } - case 2: //nolint:gomnd + case 2: //nolint:mnd startShard = 2 startByte = 0 copy(lengthBuffer[0:2], shards[0]) copy(lengthBuffer[2:4], shards[1]) - case 3: //nolint:gomnd + case 3: //nolint:mnd startShard = 1 startByte = 1 copy(lengthBuffer[0:3], shards[0]) copy(lengthBuffer[3:4], shards[1]) - case 4: //nolint:gomnd + case 4: //nolint:mnd startShard = 1 startByte = 0 diff --git a/repo/ecc/ecc_utils.go b/repo/ecc/ecc_utils.go index f98f1765a..ba29319ec 100644 --- a/repo/ecc/ecc_utils.go +++ b/repo/ecc/ecc_utils.go @@ -9,22 +9,22 @@ func computeShards(spaceOverhead float32) (data, parity int) { // If it turns out it is only 1, we invert the logic and compute how many // data shards are needed for 2 parity shards. data = 128 - parity = between(applyPercent(data, spaceOverhead/100), 1, 128) //nolint:gomnd + parity = between(applyPercent(data, spaceOverhead/100), 1, 128) //nolint:mnd if parity == 1 { parity = 2 - data = between(applyPercent(parity, 100/spaceOverhead), 128, 254) //nolint:gomnd + data = between(applyPercent(parity, 100/spaceOverhead), 128, 254) //nolint:mnd } return } -func between(val, min, max int) int { +func between(val, minValue, maxValue int) int { switch { - case val < min: - return min - case val > max: - return max + case val < minValue: + return minValue + case val > maxValue: + return maxValue default: return val } diff --git a/repo/format/format_blob.go b/repo/format/format_blob.go index def049a6b..c17ed0ee8 100644 --- a/repo/format/format_blob.go +++ b/repo/format/format_blob.go @@ -224,9 +224,9 @@ func addFormatBlobChecksumAndLength(fb []byte) ([]byte, error) { } // return - result := append([]byte(nil), byte(l), byte(l>>8)) //nolint:gomnd + result := append([]byte(nil), byte(l), byte(l>>8)) //nolint:mnd result = append(result, checksummedFormatBytes...) - result = append(result, byte(l), byte(l>>8)) //nolint:gomnd + result = append(result, byte(l), byte(l>>8)) //nolint:mnd return result, nil } diff --git a/repo/format/format_provider.go b/repo/format/format_provider.go index 33e9d883d..f48baa5e2 100644 --- a/repo/format/format_provider.go +++ b/repo/format/format_provider.go @@ -100,7 +100,7 @@ func NewFormattingOptionsProvider(f0 *ContentFormat, formatBytes []byte) (Provid // apply default if f.MaxPackSize == 0 { // legacy only, apply default - f.MaxPackSize = 20 << 20 //nolint:gomnd + f.MaxPackSize = 20 << 20 //nolint:mnd } h, err := hashing.CreateHashFunc(f) diff --git a/repo/grpc_repository_client_test.go b/repo/grpc_repository_client_test.go index 8cbbf4146..684663660 100644 --- a/repo/grpc_repository_client_test.go +++ b/repo/grpc_repository_client_test.go @@ -15,8 +15,8 @@ func TestMaxGRPCMessageSize(t *testing.T) { var maxmax int for _, s := range splitter.SupportedAlgorithms() { - if max := splitter.GetFactory(s)().MaxSegmentSize(); max > maxmax { - maxmax = max + if m := splitter.GetFactory(s)().MaxSegmentSize(); m > maxmax { + maxmax = m } } diff --git a/repo/hashing/blake3_hashes.go b/repo/hashing/blake3_hashes.go index 8720b0719..4aced9f2a 100644 --- a/repo/hashing/blake3_hashes.go +++ b/repo/hashing/blake3_hashes.go @@ -22,6 +22,6 @@ func newBlake3(key []byte) (hash.Hash, error) { } func init() { - Register("BLAKE3-256", truncatedKeyedHashFuncFactory(newBlake3, 32)) //nolint:gomnd - Register("BLAKE3-256-128", truncatedKeyedHashFuncFactory(newBlake3, 16)) //nolint:gomnd + Register("BLAKE3-256", truncatedKeyedHashFuncFactory(newBlake3, 32)) //nolint:mnd + Register("BLAKE3-256-128", truncatedKeyedHashFuncFactory(newBlake3, 16)) //nolint:mnd } diff --git a/repo/hashing/blake_hashes.go b/repo/hashing/blake_hashes.go index 96063c401..fbabbe0b0 100644 --- a/repo/hashing/blake_hashes.go +++ b/repo/hashing/blake_hashes.go @@ -6,8 +6,8 @@ ) func init() { - Register("BLAKE2S-128", truncatedKeyedHashFuncFactory(blake2s.New128, 16)) //nolint:gomnd - Register("BLAKE2S-256", truncatedKeyedHashFuncFactory(blake2s.New256, 32)) //nolint:gomnd - Register("BLAKE2B-256-128", truncatedKeyedHashFuncFactory(blake2b.New256, 16)) //nolint:gomnd - Register("BLAKE2B-256", truncatedKeyedHashFuncFactory(blake2b.New256, 32)) //nolint:gomnd + Register("BLAKE2S-128", truncatedKeyedHashFuncFactory(blake2s.New128, 16)) //nolint:mnd + Register("BLAKE2S-256", truncatedKeyedHashFuncFactory(blake2s.New256, 32)) //nolint:mnd + Register("BLAKE2B-256-128", truncatedKeyedHashFuncFactory(blake2b.New256, 16)) //nolint:mnd + Register("BLAKE2B-256", truncatedKeyedHashFuncFactory(blake2b.New256, 32)) //nolint:mnd } diff --git a/repo/hashing/sha_hashes.go b/repo/hashing/sha_hashes.go index f5d23600f..9e547fd10 100644 --- a/repo/hashing/sha_hashes.go +++ b/repo/hashing/sha_hashes.go @@ -7,9 +7,9 @@ ) func init() { - Register("HMAC-SHA256", truncatedHMACHashFuncFactory(sha256.New, 32)) //nolint:gomnd - Register("HMAC-SHA256-128", truncatedHMACHashFuncFactory(sha256.New, 16)) //nolint:gomnd - Register("HMAC-SHA224", truncatedHMACHashFuncFactory(sha256.New224, 28)) //nolint:gomnd - Register("HMAC-SHA3-224", truncatedHMACHashFuncFactory(sha3.New224, 28)) //nolint:gomnd - Register("HMAC-SHA3-256", truncatedHMACHashFuncFactory(sha3.New256, 32)) //nolint:gomnd + Register("HMAC-SHA256", truncatedHMACHashFuncFactory(sha256.New, 32)) //nolint:mnd + Register("HMAC-SHA256-128", truncatedHMACHashFuncFactory(sha256.New, 16)) //nolint:mnd + Register("HMAC-SHA224", truncatedHMACHashFuncFactory(sha256.New224, 28)) //nolint:mnd + Register("HMAC-SHA3-224", truncatedHMACHashFuncFactory(sha3.New224, 28)) //nolint:mnd + Register("HMAC-SHA3-256", truncatedHMACHashFuncFactory(sha3.New256, 32)) //nolint:mnd } diff --git a/repo/initialize.go b/repo/initialize.go index 58a25f97a..7b9e7a774 100644 --- a/repo/initialize.go +++ b/repo/initialize.go @@ -100,12 +100,12 @@ func repositoryObjectFormatFromOptions(opt *NewRepositoryOptions) (*format.Repos Hash: applyDefaultString(opt.BlockFormat.Hash, hashing.DefaultAlgorithm), Encryption: applyDefaultString(opt.BlockFormat.Encryption, encryption.DefaultAlgorithm), ECC: applyDefaultString(opt.BlockFormat.ECC, ecc.DefaultAlgorithm), - ECCOverheadPercent: applyDefaultIntRange(opt.BlockFormat.ECCOverheadPercent, 0, 100), //nolint:gomnd + ECCOverheadPercent: applyDefaultIntRange(opt.BlockFormat.ECCOverheadPercent, 0, 100), //nolint:mnd HMACSecret: applyDefaultRandomBytes(opt.BlockFormat.HMACSecret, hmacSecretLength), MasterKey: applyDefaultRandomBytes(opt.BlockFormat.MasterKey, masterKeyLength), MutableParameters: format.MutableParameters{ Version: fv, - MaxPackSize: applyDefaultInt(opt.BlockFormat.MaxPackSize, 20<<20), //nolint:gomnd + MaxPackSize: applyDefaultInt(opt.BlockFormat.MaxPackSize, 20<<20), //nolint:mnd IndexVersion: applyDefaultInt(opt.BlockFormat.IndexVersion, content.DefaultIndexVersion), EpochParameters: opt.BlockFormat.EpochParameters, }, @@ -140,11 +140,11 @@ func applyDefaultInt(v, def int) int { return v } -func applyDefaultIntRange(v, min, max int) int { - if v < min { - return min - } else if v > max { - return max +func applyDefaultIntRange(v, minValue, maxValue int) int { + if v < minValue { + return minValue + } else if v > maxValue { + return maxValue } return v diff --git a/repo/logging/logging_buf.go b/repo/logging/logging_buf.go index 8829d0445..21d976e6b 100644 --- a/repo/logging/logging_buf.go +++ b/repo/logging/logging_buf.go @@ -99,12 +99,12 @@ func (b *Buffer) AppendBoolean(val bool) *Buffer { // AppendInt32 appends int32 value formatted as a decimal string. func (b *Buffer) AppendInt32(val int32) *Buffer { - return b.AppendInt(int64(val), 10) //nolint:gomnd + return b.AppendInt(int64(val), 10) //nolint:mnd } // AppendInt64 appends int64 value formatted as a decimal string. func (b *Buffer) AppendInt64(val int64) *Buffer { - return b.AppendInt(val, 10) //nolint:gomnd + return b.AppendInt(val, 10) //nolint:mnd } // AppendInt appends integer value formatted as a string in a given base. @@ -116,12 +116,12 @@ func (b *Buffer) AppendInt(val int64, base int) *Buffer { // AppendUint32 appends uint32 value formatted as a decimal string. func (b *Buffer) AppendUint32(val uint32) *Buffer { - return b.AppendUint(uint64(val), 10) //nolint:gomnd + return b.AppendUint(uint64(val), 10) //nolint:mnd } // AppendUint64 appends uint64 value formatted as a decimal string. func (b *Buffer) AppendUint64(val uint64) *Buffer { - return b.AppendUint(val, 10) //nolint:gomnd + return b.AppendUint(val, 10) //nolint:mnd } // AppendUint appends unsigned integer value formatted as a string in a given base. diff --git a/repo/maintenance/cleanup_logs.go b/repo/maintenance/cleanup_logs.go index b9d16479d..25a47f561 100644 --- a/repo/maintenance/cleanup_logs.go +++ b/repo/maintenance/cleanup_logs.go @@ -33,7 +33,7 @@ func (o LogRetentionOptions) OrDefault() LogRetentionOptions { // defaultLogRetention returns CleanupLogsOptions applied by default during maintenance. func defaultLogRetention() LogRetentionOptions { - //nolint:gomnd + //nolint:mnd return LogRetentionOptions{ MaxTotalSize: 1 << 30, // keep no more than 1 GiB logs MaxAge: 30 * 24 * time.Hour, // no more than 30 days of data diff --git a/repo/maintenance/content_rewrite.go b/repo/maintenance/content_rewrite.go index 313fd8a61..ac3987686 100644 --- a/repo/maintenance/content_rewrite.go +++ b/repo/maintenance/content_rewrite.go @@ -138,7 +138,7 @@ func getContentToRewrite(ctx context.Context, rep repo.DirectRepository, opt *Re if opt.ShortPacks { mp, mperr := rep.ContentReader().ContentFormat().GetMutableParameters(ctx) if mperr == nil { - threshold := int64(mp.MaxPackSize * shortPackThresholdPercent / 100) //nolint:gomnd + threshold := int64(mp.MaxPackSize * shortPackThresholdPercent / 100) //nolint:mnd findContentInShortPacks(ctx, rep, ch, threshold, opt) } } @@ -213,7 +213,7 @@ func(pi content.PackInfo) error { return nil } - //nolint:gomnd + //nolint:mnd if packNumberByPrefix[prefix] == 2 { // when we encounter the 2nd pack, emit contents from the first one too. for _, ci := range firstPackByPrefix[prefix].ContentInfos { diff --git a/repo/maintenance/maintenance_params.go b/repo/maintenance/maintenance_params.go index e28bdda24..7a4f77d21 100644 --- a/repo/maintenance/maintenance_params.go +++ b/repo/maintenance/maintenance_params.go @@ -37,7 +37,7 @@ func DefaultParams() Params { return Params{ FullCycle: CycleParams{ Enabled: true, - Interval: 24 * time.Hour, //nolint:gomnd + Interval: 24 * time.Hour, //nolint:mnd }, QuickCycle: CycleParams{ Enabled: true, diff --git a/repo/maintenance/maintenance_safety.go b/repo/maintenance/maintenance_safety.go index 38fd682aa..7cd5516b2 100644 --- a/repo/maintenance/maintenance_safety.go +++ b/repo/maintenance/maintenance_safety.go @@ -56,12 +56,12 @@ type SafetyParameters struct { // SafetyFull has default safety parameters which allow safe GC concurrent with snapshotting // by other Kopia clients. SafetyFull = SafetyParameters{ - BlobDeleteMinAge: 24 * time.Hour, //nolint:gomnd + BlobDeleteMinAge: 24 * time.Hour, //nolint:mnd DropContentFromIndexExtraMargin: time.Hour, - MarginBetweenSnapshotGC: 4 * time.Hour, //nolint:gomnd - MinContentAgeSubjectToGC: 24 * time.Hour, //nolint:gomnd - RewriteMinAge: 2 * time.Hour, //nolint:gomnd - SessionExpirationAge: 96 * time.Hour, //nolint:gomnd + MarginBetweenSnapshotGC: 4 * time.Hour, //nolint:mnd + MinContentAgeSubjectToGC: 24 * time.Hour, //nolint:mnd + RewriteMinAge: 2 * time.Hour, //nolint:mnd + SessionExpirationAge: 96 * time.Hour, //nolint:mnd RequireTwoGCCycles: true, MinRewriteToOrphanDeletionDelay: time.Hour, } diff --git a/repo/object/object_reader.go b/repo/object/object_reader.go index 5e4da900b..f3ce2cbbc 100644 --- a/repo/object/object_reader.go +++ b/repo/object/object_reader.go @@ -133,7 +133,7 @@ func (r *objectReader) findChunkIndexForOffset(offset int64) (int, error) { right := len(r.seekTable) - 1 for left <= right { - middle := (left + right) / 2 //nolint:gomnd + middle := (left + right) / 2 //nolint:mnd if offset < r.seekTable[middle].Start { right = middle - 1 diff --git a/repo/splitter/splitter_buzhash32.go b/repo/splitter/splitter_buzhash32.go index 09984c543..c4ed4b004 100644 --- a/repo/splitter/splitter_buzhash32.go +++ b/repo/splitter/splitter_buzhash32.go @@ -86,8 +86,8 @@ func newBuzHash32SplitterFactory(avgSize int) Factory { // avgSize must be a power of two, so 0b000001000...0000 // it just so happens that mask is avgSize-1 :) mask := uint32(avgSize - 1) - maxSize := avgSize * 2 //nolint:gomnd - minSize := avgSize / 2 //nolint:gomnd + maxSize := avgSize * 2 //nolint:mnd + minSize := avgSize / 2 //nolint:mnd return func() Splitter { s := buzhash32.New() diff --git a/repo/splitter/splitter_rabinkarp64.go b/repo/splitter/splitter_rabinkarp64.go index 9dcd9d8a5..7a9cb6ba4 100644 --- a/repo/splitter/splitter_rabinkarp64.go +++ b/repo/splitter/splitter_rabinkarp64.go @@ -84,7 +84,7 @@ func (rs *rabinKarp64Splitter) MaxSegmentSize() int { func newRabinKarp64SplitterFactory(avgSize int) Factory { mask := uint64(avgSize - 1) - minSize, maxSize := avgSize/2, avgSize*2 //nolint:gomnd + minSize, maxSize := avgSize/2, avgSize*2 //nolint:mnd return func() Splitter { s := rabinkarp64.New() diff --git a/snapshot/policy/policy_tree.go b/snapshot/policy/policy_tree.go index 33bd9731d..4f5c2a67e 100644 --- a/snapshot/policy/policy_tree.go +++ b/snapshot/policy/policy_tree.go @@ -64,7 +64,7 @@ MaxParallelFileReads: nil, // defaults to runtime.NumCPUs() // upload large files in chunks of 2 GiB - ParallelUploadAboveSize: newOptionalInt64(2 << 30), //nolint:gomnd + ParallelUploadAboveSize: newOptionalInt64(2 << 30), //nolint:mnd } // DefaultPolicy is a default policy returned by policy tree in absence of other policies. diff --git a/snapshot/policy/retention_policy.go b/snapshot/policy/retention_policy.go index 79b94be70..8b5b7635f 100644 --- a/snapshot/policy/retention_policy.go +++ b/snapshot/policy/retention_policy.go @@ -197,7 +197,7 @@ func daysAgo(base time.Time, n int) time.Time { } func weeksAgo(base time.Time, n int) time.Time { - return base.AddDate(0, 0, -n*7) //nolint:gomnd + return base.AddDate(0, 0, -n*7) //nolint:mnd } func hoursAgo(base time.Time, n int) time.Time { @@ -317,11 +317,11 @@ func CompactPins(pins []string) []string { func SortRetentionTags(tags []string) { retentionPrefixSortValue := map[string]int{ "latest": 1, - "hourly": 2, //nolint:gomnd - "daily": 3, //nolint:gomnd - "weekly": 4, //nolint:gomnd - "monthly": 5, //nolint:gomnd - "annual": 6, //nolint:gomnd + "hourly": 2, //nolint:mnd + "daily": 3, //nolint:mnd + "weekly": 4, //nolint:mnd + "monthly": 5, //nolint:mnd + "annual": 6, //nolint:mnd } sort.Slice(tags, func(i, j int) bool { diff --git a/snapshot/policy/scheduling_policy.go b/snapshot/policy/scheduling_policy.go index 4870cf714..d91d5a2a1 100644 --- a/snapshot/policy/scheduling_policy.go +++ b/snapshot/policy/scheduling_policy.go @@ -288,5 +288,5 @@ func ValidateSchedulingPolicy(p SchedulingPolicy) error { } func stripCronComment(s string) string { - return strings.TrimSpace(strings.SplitN(s, "#", 2)[0]) //nolint:gomnd + return strings.TrimSpace(strings.SplitN(s, "#", 2)[0]) //nolint:mnd } diff --git a/snapshot/restore/local_fs_output.go b/snapshot/restore/local_fs_output.go index d78e37c40..ac8f6a026 100644 --- a/snapshot/restore/local_fs_output.go +++ b/snapshot/restore/local_fs_output.go @@ -386,7 +386,7 @@ func (o *FilesystemOutput) createDirectory(ctx context.Context, path string) err } func write(targetPath string, r fs.Reader, size int64, c streamCopier) error { - f, err := os.OpenFile(targetPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) //nolint:gosec,gomnd + f, err := os.OpenFile(targetPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) //nolint:gosec,mnd if err != nil { return err //nolint:wrapcheck } diff --git a/snapshot/snapshotfs/all_sources.go b/snapshot/snapshotfs/all_sources.go index 9dab0d97e..fdaafbb35 100644 --- a/snapshot/snapshotfs/all_sources.go +++ b/snapshot/snapshotfs/all_sources.go @@ -30,7 +30,7 @@ func (s *repositoryAllSources) ModTime() time.Time { } func (s *repositoryAllSources) Mode() os.FileMode { - return 0o555 | os.ModeDir //nolint:gomnd + return 0o555 | os.ModeDir //nolint:mnd } func (s *repositoryAllSources) Size() int64 { diff --git a/snapshot/snapshotfs/repofs.go b/snapshot/snapshotfs/repofs.go index 4f2f1d307..a0baf002c 100644 --- a/snapshot/snapshotfs/repofs.go +++ b/snapshot/snapshotfs/repofs.go @@ -274,7 +274,7 @@ func withFileInfo(r object.Reader, e fs.Entry) fs.Reader { func DirectoryEntry(rep repo.Repository, objectID object.ID, dirSummary *fs.DirectorySummary) fs.Directory { d := EntryFromDirEntry(rep, &snapshot.DirEntry{ Name: "/", - Permissions: 0o555, //nolint:gomnd + Permissions: 0o555, //nolint:mnd Type: snapshot.EntryTypeDirectory, ObjectID: objectID, DirSummary: dirSummary, @@ -325,7 +325,7 @@ func AutoDetectEntryFromObjectID(ctx context.Context, rep repo.Repository, oid o f := EntryFromDirEntry(rep, &snapshot.DirEntry{ Name: maybeName, - Permissions: 0o644, //nolint:gomnd + Permissions: 0o644, //nolint:mnd Type: snapshot.EntryTypeFile, ObjectID: oid, FileSize: fileSize, diff --git a/snapshot/snapshotfs/source_directories.go b/snapshot/snapshotfs/source_directories.go index 605dcf24c..35e162306 100644 --- a/snapshot/snapshotfs/source_directories.go +++ b/snapshot/snapshotfs/source_directories.go @@ -30,7 +30,7 @@ func (s *sourceDirectories) Name() string { } func (s *sourceDirectories) Mode() os.FileMode { - return 0o555 | os.ModeDir //nolint:gomnd + return 0o555 | os.ModeDir //nolint:mnd } func (s *sourceDirectories) ModTime() time.Time { diff --git a/snapshot/snapshotfs/source_snapshots.go b/snapshot/snapshotfs/source_snapshots.go index 3e83de49a..abd9af16e 100644 --- a/snapshot/snapshotfs/source_snapshots.go +++ b/snapshot/snapshotfs/source_snapshots.go @@ -28,7 +28,7 @@ func (s *sourceSnapshots) Name() string { } func (s *sourceSnapshots) Mode() os.FileMode { - return 0o555 | os.ModeDir //nolint:gomnd + return 0o555 | os.ModeDir //nolint:mnd } func (s *sourceSnapshots) Size() int64 { @@ -83,7 +83,7 @@ func (s *sourceSnapshots) Iterate(ctx context.Context) (fs.DirectoryIterator, er de := &snapshot.DirEntry{ Name: name, - Permissions: 0o555, //nolint:gomnd + Permissions: 0o555, //nolint:mnd Type: snapshot.EntryTypeDirectory, ModTime: m.StartTime, ObjectID: m.RootObjectID(), diff --git a/snapshot/snapshotfs/upload.go b/snapshot/snapshotfs/upload.go index f55ec223c..3d5e29050 100644 --- a/snapshot/snapshotfs/upload.go +++ b/snapshot/snapshotfs/upload.go @@ -181,7 +181,7 @@ func (u *Uploader) uploadFileInternal(ctx context.Context, parentCheckpointRegis for i := range parts { offset := int64(i) * chunkSize - length := chunkSize //nolint:copyloopvar + length := chunkSize if i == len(parts)-1 { // last part has unknown length to accommodate the file that may be growing as we're snapshotting it length = -1 @@ -769,9 +769,9 @@ func (u *Uploader) effectiveParallelFileReads(pol *policy.Policy) int { } // use policy setting or number of CPUs. - max := pol.UploadPolicy.MaxParallelFileReads.OrDefault(runtime.NumCPU()) - if p < 1 || p > max { - return max + maxParallelism := pol.UploadPolicy.MaxParallelFileReads.OrDefault(runtime.NumCPU()) + if p < 1 || p > maxParallelism { + return maxParallelism } return p diff --git a/snapshot/snapshotfs/upload_actions.go b/snapshot/snapshotfs/upload_actions.go index 960684080..125820793 100644 --- a/snapshot/snapshotfs/upload_actions.go +++ b/snapshot/snapshotfs/upload_actions.go @@ -178,7 +178,7 @@ func runActionCommand( func parseCaptures(v []byte, captures map[string]string) error { s := bufio.NewScanner(bytes.NewReader(v)) for s.Scan() { - //nolint:gomnd + //nolint:mnd l := strings.SplitN(s.Text(), "=", 2) if len(l) <= 1 { continue diff --git a/snapshot/snapshotfs/upload_os_snapshot_windows.go b/snapshot/snapshotfs/upload_os_snapshot_windows.go index fe219dd32..d9f11f39a 100644 --- a/snapshot/snapshotfs/upload_os_snapshot_windows.go +++ b/snapshot/snapshotfs/upload_os_snapshot_windows.go @@ -48,7 +48,7 @@ func createOSSnapshot(ctx context.Context, root fs.Directory, _ *policy.OSSnapsh } // Retry "Another shadow copy operation is already in progress" in 5-10s - //nolint:gosec,gomnd + //nolint:gosec,mnd delay := 5*time.Second + time.Duration(rand.Int63n(int64(5*time.Second))) if !clock.SleepInterruptibly(ctx, delay) { return nil, nil, ctx.Err() diff --git a/snapshot/snapshotfs/upload_test.go b/snapshot/snapshotfs/upload_test.go index 99284d70b..934c0a9b4 100644 --- a/snapshot/snapshotfs/upload_test.go +++ b/snapshot/snapshotfs/upload_test.go @@ -700,9 +700,9 @@ func TestParallelUploadUploadsBlobsInParallel(t *testing.T) { // measure concurrency of PutBlob calls th.faulty.AddFault(blobtesting.MethodPutBlob).Repeat(10).Before(func() { v := currentParallelCalls.Add(1) - max := maxParallelCalls.Load() - if v > max { - maxParallelCalls.CompareAndSwap(max, v) + maxParallelism := maxParallelCalls.Load() + if v > maxParallelism { + maxParallelCalls.CompareAndSwap(maxParallelism, v) } time.Sleep(100 * time.Millisecond) @@ -1217,7 +1217,7 @@ func TestParallelUploadOfLargeFiles(t *testing.T) { }) // make sure we actually tested something - require.Greater(t, successCount, 0) + require.Positive(t, successCount) } func verifyFileContent(t *testing.T, f1Entry fs.File, f2Name string) { diff --git a/tests/robustness/multiclient_test/framework/client.go b/tests/robustness/multiclient_test/framework/client.go index 7cba44eab..5e040fd08 100644 --- a/tests/robustness/multiclient_test/framework/client.go +++ b/tests/robustness/multiclient_test/framework/client.go @@ -38,7 +38,7 @@ func NewClientContext(ctx context.Context) context.Context { func NewClientContexts(ctx context.Context, n int) []context.Context { ctxs := make([]context.Context, n) for i := range ctxs { - ctxs[i] = NewClientContext(ctx) + ctxs[i] = NewClientContext(ctx) //nolint:fatcontext } return ctxs diff --git a/tests/tools/fio/options.go b/tests/tools/fio/options.go index f6d5908b7..7e987c2e0 100644 --- a/tests/tools/fio/options.go +++ b/tests/tools/fio/options.go @@ -132,12 +132,12 @@ func boolOpt(key string, val bool) Options { return Options{key: strconv.Itoa(0)} } -func rangeOpt(key string, min, max int) Options { - if min > max { - min, max = max, min +func rangeOpt(key string, minValue, maxValue int) Options { + if minValue > maxValue { + minValue, maxValue = maxValue, minValue } return Options{ - key: fmt.Sprintf("%d%s%d", min, RangeDelimFio, max), + key: fmt.Sprintf("%d%s%d", minValue, RangeDelimFio, maxValue), } } diff --git a/tests/tools/kopiarunner/kopia_snapshotter.go b/tests/tools/kopiarunner/kopia_snapshotter.go index 121ece4b4..6ec3de2a9 100644 --- a/tests/tools/kopiarunner/kopia_snapshotter.go +++ b/tests/tools/kopiarunner/kopia_snapshotter.go @@ -323,7 +323,7 @@ func parseSnapshotListForSnapshotIDs(output string) []string { for _, f := range fields { spl := strings.Split(f, "manifest:") - if len(spl) == 2 { //nolint:gomnd + if len(spl) == 2 { //nolint:mnd ret = append(ret, spl[1]) } } diff --git a/tools/cli2md/cli2md.go b/tools/cli2md/cli2md.go index 61953775d..c10da7045 100644 --- a/tools/cli2md/cli2md.go +++ b/tools/cli2md/cli2md.go @@ -42,8 +42,8 @@ func emitFlags(w io.Writer, flags []*kingpin.FlagModel) { return } - fmt.Fprintf(w, "| Flag | Short | Default | Help |\n") - fmt.Fprintf(w, "| ---- | ----- | --- | --- |\n") + fmt.Fprintf(w, "| Flag | Short | Default | Help |\n") //nolint:errcheck + fmt.Fprintf(w, "| ---- | ----- | --- | --- |\n") //nolint:errcheck for _, f := range sortFlags(flags) { maybeAdvanced := "" @@ -75,13 +75,13 @@ func emitFlags(w io.Writer, flags []*kingpin.FlagModel) { defaultValue = "`false`" } - fmt.Fprintf(w, "| `--[no-]%v` | %v | %v | %v%v |\n", f.Name, shortFlag, defaultValue, maybeAdvanced, f.Help) + fmt.Fprintf(w, "| `--[no-]%v` | %v | %v | %v%v |\n", f.Name, shortFlag, defaultValue, maybeAdvanced, f.Help) //nolint:errcheck } else { - fmt.Fprintf(w, "| `--%v` | %v | %v | %v%v |\n", f.Name, shortFlag, defaultValue, maybeAdvanced, f.Help) + fmt.Fprintf(w, "| `--%v` | %v | %v | %v%v |\n", f.Name, shortFlag, defaultValue, maybeAdvanced, f.Help) //nolint:errcheck } } - fmt.Fprintf(w, "\n") + fmt.Fprintf(w, "\n") //nolint:errcheck } func combineFlags(lists ...[]*kingpin.FlagModel) []*kingpin.FlagModel { @@ -113,8 +113,8 @@ func emitArgs(w io.Writer, args []*kingpin.ArgModel) { return } - fmt.Fprintf(w, "| Argument | Help |\n") - fmt.Fprintf(w, "| -------- | --- |\n") + fmt.Fprintf(w, "| Argument | Help |\n") //nolint:errcheck + fmt.Fprintf(w, "| -------- | --- |\n") //nolint:errcheck args2 := append([]*kingpin.ArgModel(nil), args...) sort.Slice(args2, func(i, j int) bool { @@ -122,10 +122,10 @@ func emitArgs(w io.Writer, args []*kingpin.ArgModel) { }) for _, f := range args2 { - fmt.Fprintf(w, "| `%v` | %v |\n", f.Name, f.Help) + fmt.Fprintf(w, "| `%v` | %v |\n", f.Name, f.Help) //nolint:errcheck } - fmt.Fprintf(w, "\n") + fmt.Fprintf(w, "\n") //nolint:errcheck } func generateAppFlags(app *kingpin.ApplicationModel) error { @@ -136,6 +136,8 @@ func generateAppFlags(app *kingpin.ApplicationModel) error { defer f.Close() //nolint:errcheck title := "Flags" + + //nolint:errcheck fmt.Fprintf(f, `--- title: %q linkTitle: %q @@ -161,6 +163,8 @@ func generateCommands(app *kingpin.ApplicationModel, section string, weight int, defer f.Close() //nolint:errcheck title := section + " Commands" + + //nolint:errcheck fmt.Fprintf(f, `--- title: %q linkTitle: %q @@ -242,15 +246,15 @@ func generateSubcommands(w io.Writer, dir, sectionTitle string, cmds []*kingpin. } if first { - fmt.Fprintf(w, "\n### %v\n\n", strings.TrimSuffix(sectionTitle, ".")) + fmt.Fprintf(w, "\n### %v\n\n", strings.TrimSuffix(sectionTitle, ".")) //nolint:errcheck first = false } subcommandSlug := strings.Replace(c.FullCommand, " ", "-", -1) - helpSummary := strings.SplitN(c.Help, "\n", 2)[0] //nolint:gomnd + helpSummary := strings.SplitN(c.Help, "\n", 2)[0] //nolint:mnd helpSummary = strings.TrimSuffix(helpSummary, ".") - fmt.Fprintf(w, "* [`%v`](%v) - %v\n", c.FullCommand, subcommandSlug+"/", helpSummary) + fmt.Fprintf(w, "* [`%v`](%v) - %v\n", c.FullCommand, subcommandSlug+"/", helpSummary) //nolint:errcheck generateSubcommandPage(filepath.Join(dir, subcommandSlug+".md"), c) } } @@ -263,6 +267,8 @@ func generateSubcommandPage(fname string, cmd *kingpin.CmdModel) { defer f.Close() //nolint:errcheck title := cmd.FullCommand + + //nolint:errcheck fmt.Fprintf(f, `--- title: %q linkTitle: %q @@ -290,8 +296,8 @@ func generateSubcommandPage(fname string, cmd *kingpin.CmdModel) { } } - fmt.Fprintf(f, "```shell\n$ kopia %v%v%v\n```\n\n", cmd.FullCommand, flagSummary, argSummary) - fmt.Fprintf(f, "%v\n\n", cmd.Help) + fmt.Fprintf(f, "```shell\n$ kopia %v%v%v\n```\n\n", cmd.FullCommand, flagSummary, argSummary) //nolint:errcheck + fmt.Fprintf(f, "%v\n\n", cmd.Help) //nolint:errcheck emitFlags(f, cmd.Flags) emitArgs(f, cmd.Args) diff --git a/tools/gettool/checksums.txt b/tools/gettool/checksums.txt index f49e20c77..d6edaf81c 100644 --- a/tools/gettool/checksums.txt +++ b/tools/gettool/checksums.txt @@ -7,12 +7,12 @@ https://github.com/git-chglog/git-chglog/releases/download/v0.15.1/git-chglog_0. https://github.com/gohugoio/hugo/releases/download/v0.113.0/hugo_extended_0.113.0_darwin-universal.tar.gz: 1557f896f34743d241e1aecab588be273dde59692b362a9f4488231a2595b2ae https://github.com/gohugoio/hugo/releases/download/v0.113.0/hugo_extended_0.113.0_linux-amd64.tar.gz: e04bccfa81df6c727f1c03bc858eb21d6f95123d311cafe245f4485d289123f3 https://github.com/gohugoio/hugo/releases/download/v0.113.0/hugo_extended_0.113.0_windows-amd64.zip: 3eabfbfad1431939058e6f7e76573c6bac1fee92f3a7b1ac5739c555940f0e0e -https://github.com/golangci/golangci-lint/releases/download/v1.57.1/golangci-lint-1.57.1-darwin-amd64.tar.gz: 7b6ce262d6b318822ad6ad866da31a7e0e8f8042ec2b1a34018488532d9beb50 -https://github.com/golangci/golangci-lint/releases/download/v1.57.1/golangci-lint-1.57.1-darwin-arm64.tar.gz: 0099453f7f9edf7438c848d2f1cebfe8bd2fe8ef8817ba89c315127ccddddee4 -https://github.com/golangci/golangci-lint/releases/download/v1.57.1/golangci-lint-1.57.1-linux-amd64.tar.gz: 7e148df10de55dcbda283b43b9ea1c2f2a38b6e96ba91a71ec02eefcf336efbe -https://github.com/golangci/golangci-lint/releases/download/v1.57.1/golangci-lint-1.57.1-linux-arm64.tar.gz: 55708f17c659d1b4589fe2b2f6c1d5528f5e3d9376d6e26d4ae266346d035d06 -https://github.com/golangci/golangci-lint/releases/download/v1.57.1/golangci-lint-1.57.1-linux-armv6.tar.gz: 245bfa5e8c43bedb9fddfb0e32896f914d3e2b74db99e1c828192256e302d42c -https://github.com/golangci/golangci-lint/releases/download/v1.57.1/golangci-lint-1.57.1-windows-amd64.zip: 7383a7dc7498ad4d0500ff6e661e50236216089cf68460f665553b9484c41601 +https://github.com/golangci/golangci-lint/releases/download/v1.59.0/golangci-lint-1.59.0-darwin-amd64.tar.gz: 418acf7e255ddc0783e97129c9b03d9311b77826a5311d425a01c708a86417e7 +https://github.com/golangci/golangci-lint/releases/download/v1.59.0/golangci-lint-1.59.0-darwin-arm64.tar.gz: 5f6a1d95a6dd69f6e328eb56dd311a38e04cfab79a1305fbf4957f4e203f47b6 +https://github.com/golangci/golangci-lint/releases/download/v1.59.0/golangci-lint-1.59.0-linux-amd64.tar.gz: 3b14a439f33c4fff83dbe0349950d984042b9a1feb6c62f82787b598fc3ab5f4 +https://github.com/golangci/golangci-lint/releases/download/v1.59.0/golangci-lint-1.59.0-linux-arm64.tar.gz: c57e6c0b0fa03089a2611dceddd5bc5d206716cccdff8b149da8baac598719a1 +https://github.com/golangci/golangci-lint/releases/download/v1.59.0/golangci-lint-1.59.0-linux-armv6.tar.gz: 93149e2d3b25ac754df9a23172403d8aa6d021a7e0d9c090a12f51897f68c9a0 +https://github.com/golangci/golangci-lint/releases/download/v1.59.0/golangci-lint-1.59.0-windows-amd64.zip: 3317d8a87a99a49a0a1321d295c010790e6dbf43ee96b318f4b8bb23eae7a565 https://github.com/goreleaser/goreleaser/releases/download/v0.176.0/goreleaser_Darwin_arm64.tar.gz: 1f95e6561974f4766d8833438b646b06930563ca9867447ea03edb623d876c75 https://github.com/goreleaser/goreleaser/releases/download/v0.176.0/goreleaser_Darwin_x86_64.tar.gz: 17ecad881a50e32f033da5a200c8417d37cae70f09e925645452937998aca506 https://github.com/goreleaser/goreleaser/releases/download/v0.176.0/goreleaser_Linux_arm64.tar.gz: 8bf2a9b9e84498bfa239f2fe91b2d555642c87ab9d3f5d37f29e6e97116910a3 diff --git a/tools/gettool/gettool.go b/tools/gettool/gettool.go index 1fc1f997a..8e7f7635e 100644 --- a/tools/gettool/gettool.go +++ b/tools/gettool/gettool.go @@ -187,7 +187,7 @@ func main() { for _, toolNameVersion := range strings.Split(*tool, ",") { parts := strings.Split(toolNameVersion, ":") - //nolint:gomnd + //nolint:mnd if len(parts) != 2 { log.Fatalf("invalid tool spec, must be tool:version[,tool:version]") } @@ -238,7 +238,7 @@ func writeLinesToFile(lines []string) error { defer f.Close() //nolint:errcheck for _, l := range lines { - fmt.Fprintln(f, l) + fmt.Fprintln(f, l) //nolint:errcheck } return nil diff --git a/tools/tools.mk b/tools/tools.mk index f66f28433..cdadc6779 100644 --- a/tools/tools.mk +++ b/tools/tools.mk @@ -102,7 +102,7 @@ retry:= endif # tool versions -GOLANGCI_LINT_VERSION=1.57.1 +GOLANGCI_LINT_VERSION=1.59.0 CHECKLOCKS_VERSION=e8c1fff214d0ecf02cfe5aa9c62d11174130c339 NODE_VERSION=18.16.0 HUGO_VERSION=0.113.0