Skip to content

Commit

Permalink
Update to golangci-lint 1.60.1 to support go 1.23 (#3900)
Browse files Browse the repository at this point in the history
Once again a new release of go makes golangci-lint use all available
memory.

This also fixes some new linter issues, mostly:
- staticheck dropping a bunch of checks
- min/max overriding. They are now build-in in 1.21+, but I didn't want
  to replace them and bump to 1.21 in this commit already, given the
  whole toolchain thing.
- printf not being error checked or not being used with format +
  arguments.

Co-authored-by: Oleg Bespalov <[email protected]>
  • Loading branch information
mstoykov and olegbespalov authored Aug 16, 2024
1 parent f0685a6 commit fd03ba6
Show file tree
Hide file tree
Showing 22 changed files with 61 additions and 57 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# v1.57.2
# v1.60.1
# Please don't remove the first line. It uses in CI to determine the golangci version
run:
timeout: 5m
Expand Down
2 changes: 1 addition & 1 deletion cloudapi/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ func shouldRetry(resp *http.Response, err error, attempt, maxAttempts int) bool
return true
}

if resp.StatusCode >= 500 || resp.StatusCode == 429 {
if resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests {
return true
}

Expand Down
6 changes: 3 additions & 3 deletions cloudapi/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ func (sfn sleeperFunc) Sleep(d time.Duration) {
// between the latest iteration and the next retry.
// Interval is used as the base to compute an exponential backoff,
// if the computed interval overtakes the max interval then max will be used.
func retry(s sleeper, attempts uint, interval, max time.Duration, do func() error) (err error) {
func retry(s sleeper, attempts uint, interval, maxDuration time.Duration, do func() error) (err error) {
baseInterval := math.Abs(interval.Truncate(time.Second).Seconds())
r := rand.New(rand.NewSource(time.Now().UnixNano())) //nolint:gosec

Expand All @@ -236,8 +236,8 @@ func retry(s sleeper, attempts uint, interval, max time.Duration, do func() erro
wait := time.Duration(math.Pow(baseInterval, float64(i))) * time.Second
wait += time.Duration(r.Int63n(1000)) * time.Millisecond

if wait > max {
wait = max
if wait > maxDuration {
wait = maxDuration
}
s.Sleep(wait)
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/scale.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,16 @@ func getCmdScale(gs *state.GlobalState) *cobra.Command {
Use the global --address flag to specify the URL to the API server.`,
RunE: func(cmd *cobra.Command, _ []string) error {
vus := getNullInt64(cmd.Flags(), "vus")
max := getNullInt64(cmd.Flags(), "max")
if !vus.Valid && !max.Valid {
maxVUs := getNullInt64(cmd.Flags(), "max")
if !vus.Valid && !maxVUs.Valid {
return errors.New("Specify either -u/--vus or -m/--max") //nolint:golint,stylecheck
}

c, err := client.New(gs.Flags.Address)
if err != nil {
return err
}
status, err := c.SetStatus(gs.Ctx, v1.Status{VUs: vus, VUsMax: max})
status, err := c.SetStatus(gs.Ctx, v1.Status{VUs: vus, VUsMax: maxVUs})
if err != nil {
return err
}
Expand Down
14 changes: 7 additions & 7 deletions cmd/tests/cmd_run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1434,14 +1434,14 @@ func sum(vals []float64) (sum float64) {
return sum
}

func max(vals []float64) float64 {
max := vals[0]
func maxFloat64(vals []float64) float64 {
result := vals[0]
for _, val := range vals {
if max < val {
max = val
if result < val {
result = val
}
}
return max
return result
}

func TestActiveVUsCount(t *testing.T) {
Expand Down Expand Up @@ -1499,8 +1499,8 @@ func TestActiveVUsCount(t *testing.T) {
jsonResults, err := fsext.ReadFile(ts.FS, "results.json")
require.NoError(t, err)
// t.Log(string(jsonResults))
assert.Equal(t, float64(10), max(getSampleValues(t, jsonResults, "vus_max", nil)))
assert.Equal(t, float64(10), max(getSampleValues(t, jsonResults, "vus", nil)))
assert.Equal(t, float64(10), maxFloat64(getSampleValues(t, jsonResults, "vus_max", nil)))
assert.Equal(t, float64(10), maxFloat64(getSampleValues(t, jsonResults, "vus", nil)))
assert.Equal(t, float64(0), sum(getSampleValues(t, jsonResults, "iterations", nil)))

logEntries := ts.LoggerHook.Drain()
Expand Down
2 changes: 1 addition & 1 deletion js/modules/k6/crypto/x509/x509.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
package x509

import (
"crypto/dsa" //nolint:staticcheck // #nosec G505 // DSA is weak, but we need it for compatibility
"crypto/dsa" // #nosec G505 // DSA is weak, but we need it for compatibility
"crypto/ecdsa"
"crypto/rsa"
"crypto/sha1" // #nosec G505
Expand Down
2 changes: 1 addition & 1 deletion js/modules/k6/grpc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func decryptPrivateKey(key, password []byte) ([]byte, error) {
being used here because it is deprecated due to it not supporting *good* cryptography
ultimately though we want to support something so we will be using it for now.
*/
decryptedKey, err := x509.DecryptPEMBlock(block, password) //nolint:staticcheck
decryptedKey, err := x509.DecryptPEMBlock(block, password)
if err != nil {
return nil, err
}
Expand Down
10 changes: 5 additions & 5 deletions js/modules/k6/http/response_callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,16 @@ func (mi *ModuleInstance) expectedStatuses(args ...sobek.Value) *expectedStatuse
if isInt(arg) {
result.exact = append(result.exact, int(o.ToInteger()))
} else {
min := o.Get("min")
max := o.Get("max")
if min == nil || max == nil {
minValue := o.Get("min")
maxValue := o.Get("max")
if minValue == nil || maxValue == nil {
common.Throw(rt, fmt.Errorf(errMsg, i+1))
}
if !(isInt(min) && isInt(max)) {
if !(isInt(minValue) && isInt(maxValue)) {
common.Throw(rt, fmt.Errorf("both min and max need to be integers for argument number %d", i+1))
}

result.minmax = append(result.minmax, [2]int{int(min.ToInteger()), int(max.ToInteger())})
result.minmax = append(result.minmax, [2]int{int(minValue.ToInteger()), int(maxValue.ToInteger())})
}
}
return &result
Expand Down
7 changes: 4 additions & 3 deletions js/modules/k6/http/tls_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"net/http"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/guregu/null.v3"

"go.k6.io/k6/lib"
Expand All @@ -19,7 +19,8 @@ func TestTLS13Support(t *testing.T) {

ts.tb.Mux.HandleFunc("/tls-version", http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
ver := req.TLS.Version
fmt.Fprint(resp, lib.SupportedTLSVersionsToString[lib.TLSVersion(ver)])
_, err := fmt.Fprint(resp, lib.SupportedTLSVersionsToString[lib.TLSVersion(ver)])
require.NoError(t, err)
}))

// We don't expect any failed requests
Expand All @@ -32,5 +33,5 @@ func TestTLS13Support(t *testing.T) {
throw new Error("unexpected tls version: " + resp.body);
}
`))
assert.NoError(t, err)
require.NoError(t, err)
}
1 change: 0 additions & 1 deletion js/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,6 @@ func (r *Runner) newVU(
"deprecation - https://pkg.go.dev/crypto/[email protected]#Config.",
)
})
//nolint:staticcheck // ignore SA1019 we can deprecate it but we have to continue to support the previous code.
tlsConfig.NameToCertificate = nameToCert
}
transport := &http.Transport{
Expand Down
2 changes: 1 addition & 1 deletion js/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1294,7 +1294,7 @@ func TestVUIntegrationTLSConfig(t *testing.T) {
"",
},
"UnsupportedVersion": {
lib.Options{TLSVersion: &lib.TLSVersions{Min: tls.VersionSSL30, Max: tls.VersionSSL30}}, //nolint:staticcheck
lib.Options{TLSVersion: &lib.TLSVersions{Min: tls.VersionSSL30, Max: tls.VersionSSL30}},
unsupportedVersionErrorMsg,
},
}
Expand Down
2 changes: 1 addition & 1 deletion lib/archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func ReadArchive(in io.Reader) (*Archive, error) {
}
return nil, err
}
if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA { //nolint:staticcheck
if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA {
continue
}

Expand Down
17 changes: 9 additions & 8 deletions lib/executor/base_config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package executor

import (
"errors"
"fmt"
"regexp"
"strings"
Expand Down Expand Up @@ -46,29 +47,29 @@ func NewBaseConfig(name, configType string) BaseConfig {
}

// Validate checks some basic things like present name, type, and a positive start time
func (bc BaseConfig) Validate() (errors []error) {
func (bc BaseConfig) Validate() (result []error) {
// Some just-in-case checks, since those things are likely checked in other places or
// even assigned by us:
if bc.Name == "" {
errors = append(errors, fmt.Errorf("scenario name can't be empty"))
result = append(result, errors.New("scenario name can't be empty"))
}
if !scenarioNameWhitelist.MatchString(bc.Name) {
errors = append(errors, fmt.Errorf(scenarioNameErr))
result = append(result, errors.New(scenarioNameErr))
}
if bc.Exec.Valid && bc.Exec.String == "" {
errors = append(errors, fmt.Errorf("exec value cannot be empty"))
result = append(result, errors.New("exec value cannot be empty"))
}
if bc.Type == "" {
errors = append(errors, fmt.Errorf("missing or empty type field"))
result = append(result, errors.New("missing or empty type field"))
}
// The actually reasonable checks:
if bc.StartTime.Duration < 0 {
errors = append(errors, fmt.Errorf("the startTime can't be negative"))
result = append(result, errors.New("the startTime can't be negative"))
}
if bc.GracefulStop.Duration < 0 {
errors = append(errors, fmt.Errorf("the gracefulStop timeout can't be negative"))
result = append(result, errors.New("the gracefulStop timeout can't be negative"))
}
return errors
return result
}

// GetName returns the name of the scenario.
Expand Down
2 changes: 1 addition & 1 deletion lib/executor/executors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ func TestConfigMapParsingAndValidation(t *testing.T) {
tc := tc
t.Run(fmt.Sprintf("TestCase#%d", i), func(t *testing.T) {
t.Parallel()
t.Logf(tc.rawJSON)
t.Log(tc.rawJSON)
var result lib.ScenarioConfigs
err := json.Unmarshal([]byte(tc.rawJSON), &result)
if tc.expected.parseError {
Expand Down
8 changes: 4 additions & 4 deletions lib/executor/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ func sumStagesDuration(stages []Stage) (result time.Duration) {
}

func getStagesUnscaledMaxTarget(unscaledStartValue int64, stages []Stage) int64 {
max := unscaledStartValue
result := unscaledStartValue
for _, s := range stages {
if s.Target.Int64 > max {
max = s.Target.Int64
if s.Target.Int64 > result {
result = s.Target.Int64
}
}
return max
return result
}

// validateTargetShifts validates the VU Target shifts.
Expand Down
2 changes: 1 addition & 1 deletion lib/netext/grpcext/conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ func methodFromProto(method string) protoreflect.MethodDescriptor {
// otherwise the parser will try to parse "google/protobuf/descriptor.proto"
// with exactly the same name as the one we are trying to parse for testing
if filename != path {
return nil, nil
return nil, nil //nolint:nilnil
}

b := `
Expand Down
2 changes: 1 addition & 1 deletion lib/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func decryptPrivateKey(privKey, password string) ([]byte, error) {
being used here because it is deprecated due to it not supporting *good* crypography
ultimately though we want to support something so we will be using it for now.
*/
decryptedKey, err := x509.DecryptPEMBlock(block, []byte(password)) //nolint:staticcheck
decryptedKey, err := x509.DecryptPEMBlock(block, []byte(password))
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions lib/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,11 +160,11 @@ func TestOptions(t *testing.T) {
})
t.Run("TLSVersion", func(t *testing.T) {
t.Parallel()
versions := TLSVersions{Min: tls.VersionSSL30, Max: tls.VersionTLS12} //nolint:staticcheck
versions := TLSVersions{Min: tls.VersionSSL30, Max: tls.VersionTLS12}
opts := Options{}.Apply(Options{TLSVersion: &versions})

assert.NotNil(t, opts.TLSVersion)
assert.Equal(t, opts.TLSVersion.Min, TLSVersion(tls.VersionSSL30)) //nolint:staticcheck
assert.Equal(t, opts.TLSVersion.Min, TLSVersion(tls.VersionSSL30))
assert.Equal(t, opts.TLSVersion.Max, TLSVersion(tls.VersionTLS12))

t.Run("JSON", func(t *testing.T) {
Expand Down
4 changes: 2 additions & 2 deletions output/cloud/expv2/flush.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,15 @@ func (f *metricsFlusher) flush() error {

func (f *metricsFlusher) flushBatches(batches []*pbcloud.MetricSet) error {
// TODO remove after go 1.21 becomes the minimum supported version - it has `min` in it
min := func(a, b int) int {
minInt := func(a, b int) int {
if a < b {
return a
}
return b
}

var (
workers = min(len(batches), f.batchPushConcurrency)
workers = minInt(len(batches), f.batchPushConcurrency)
errs = make(chan error, workers)
feed = make(chan *pbcloud.MetricSet)
finalErr error
Expand Down
3 changes: 2 additions & 1 deletion output/cloud/output_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,14 @@ func TestOutputCreateTestWithConfigOverwrite(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/tests":
fmt.Fprintf(w, `{
_, err := fmt.Fprintf(w, `{
"reference_id": "12345",
"config": {
"metricPushInterval": "10ms",
"aggregationPeriod": "40s"
}
}`)
require.NoError(t, err)
case "/v1/tests/12345":
w.WriteHeader(http.StatusOK)
default:
Expand Down
7 changes: 5 additions & 2 deletions ui/form.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,18 @@ func (f Form) Run(r io.Reader, w io.Writer) (map[string]string, error) {
if extra := field.GetLabelExtra(); extra != "" {
displayLabel += " " + color.New(color.Faint, color.FgCyan).Sprint("["+extra+"]")
}
if _, err := fmt.Fprintf(w, " "+displayLabel+": "); err != nil {
if _, err := fmt.Fprint(w, " "+displayLabel+": "); err != nil {
return nil, err
}

color.Set(color.FgCyan)
s, err := field.GetContents(r)

if _, ok := field.(PasswordField); ok {
fmt.Fprint(w, "\n")
_, err := fmt.Fprint(w, "\n")
if err != nil {
return nil, err
}
}

color.Unset()
Expand Down
13 changes: 6 additions & 7 deletions ui/pb/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,14 +110,13 @@ func GetFixedLengthDuration(d, maxDuration time.Duration) (result string) {
return string(buf[i:])
}

// Clampf returns the given value, "clamped" to the range [min, max].
// This is copied from lib/util.go to avoid circular imports.
func Clampf(val, min, max float64) float64 {
// Clampf returns the given value, "clamped" to the range [floor, ceiling].
func Clampf(val, floor, ceiling float64) float64 {
switch {
case val < min:
return min
case val > max:
return max
case val < floor:
return floor
case val > ceiling:
return ceiling
default:
return val
}
Expand Down

0 comments on commit fd03ba6

Please sign in to comment.