Skip to content

Commit

Permalink
lib: lint fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
mstoykov committed Jan 31, 2024
1 parent 70c151f commit 4839e8d
Show file tree
Hide file tree
Showing 26 changed files with 106 additions and 84 deletions.
25 changes: 15 additions & 10 deletions lib/archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"archive/tar"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
Expand All @@ -20,18 +21,20 @@ import (
)

var (
volumeRE = regexp.MustCompile(`^[/\\]?([a-zA-Z]):(.*)`)
sharedRE = regexp.MustCompile(`^\\\\([^\\]+)`) // matches a shared folder in Windows before backslack replacement. i.e \\VMBOXSVR\k6\script.js
volumeRE = regexp.MustCompile(`^[/\\]?([a-zA-Z]):(.*)`)
// matches a shared folder in Windows before backslack replacement. i.e \\VMBOXSVR\k6\script.js
sharedRE = regexp.MustCompile(`^\\\\([^\\]+)`)
homeDirRE = regexp.MustCompile(`(?i)^(/[a-zA-Z])?/(Users|home|Documents and Settings)/(?:[^/]+)`)
)

// NormalizeAndAnonymizePath Normalizes (to use a / path separator) and anonymizes a file path, by scrubbing usernames from home directories.
// NormalizeAndAnonymizePath Normalizes (to use a / path separator) and anonymizes a file path,
// by scrubbing usernames from home directories.
func NormalizeAndAnonymizePath(path string) string {
path = filepath.Clean(path)

p := volumeRE.ReplaceAllString(path, `/$1$2`)
p = sharedRE.ReplaceAllString(p, `/nobody`)
p = strings.Replace(p, "\\", "/", -1)
p = strings.ReplaceAll(p, "\\", "/")
return homeDirRE.ReplaceAllString(p, `$1/$2/nobody`)
}

Expand Down Expand Up @@ -106,6 +109,8 @@ func (arc *Archive) loadMetadataJSON(data []byte) (err error) {
}

// ReadArchive reads an archive created by Archive.Write from a reader.
//
//nolint:gocognit
func ReadArchive(in io.Reader) (*Archive, error) {
r := tar.NewReader(in)
arc := &Archive{Filesystems: make(map[string]fsext.Fs, 2)}
Expand All @@ -115,12 +120,12 @@ func ReadArchive(in io.Reader) (*Archive, error) {
for {
hdr, err := r.Next()
if err != nil {
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
return nil, err
}
if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA {
if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA { //nolint:staticcheck
continue
}

Expand Down Expand Up @@ -161,12 +166,10 @@ func ReadArchive(in io.Reader) (*Archive, error) {
case "https", "file":
fileSystem := arc.getFs(pfx)
name = filepath.FromSlash(name)
err = fsext.WriteFile(fileSystem, name, data, fs.FileMode(hdr.Mode))
if err != nil {
if err = fsext.WriteFile(fileSystem, name, data, fs.FileMode(hdr.Mode)); err != nil {
return nil, err
}
err = fileSystem.Chtimes(name, hdr.AccessTime, hdr.ModTime)
if err != nil {
if err = fileSystem.Chtimes(name, hdr.AccessTime, hdr.ModTime); err != nil {
return nil, err
}
default:
Expand Down Expand Up @@ -218,6 +221,8 @@ func getURLtoString(u *url.URL) string {
// The format should be treated as opaque; currently it is simply a TAR rollup, but this may
// change. If it does change, ReadArchive must be able to handle all previous formats as well as
// the current one.
//
//nolint:funlen,gocognit
func (arc *Archive) Write(out io.Writer) error {
w := tar.NewWriter(out)

Expand Down
1 change: 1 addition & 0 deletions lib/consts/consts.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package consts houses some constants needed across k6
package consts

import (
Expand Down
5 changes: 3 additions & 2 deletions lib/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ func GetExecutionState(ctx context.Context) *ExecutionState {
if v == nil {
return nil
}
return v.(*ExecutionState)

return v.(*ExecutionState) //nolint:forcetypeassert
}

// WithScenarioState embeds a ScenarioState in ctx.
Expand All @@ -36,5 +37,5 @@ func GetScenarioState(ctx context.Context) *ScenarioState {
if v == nil {
return nil
}
return v.(*ScenarioState)
return v.(*ScenarioState) //nolint:forcetypeassert
}
4 changes: 2 additions & 2 deletions lib/execution_segment.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func stringToRat(s string) (*big.Rat, error) {
}
return new(big.Rat).SetFrac(num, big.NewInt(100)), nil
}
rat, ok := new(big.Rat).SetString(s)
rat, ok := new(big.Rat).SetString(s) //nolint:gosec // the vulnerability was patched in 1.16
if !ok {
return nil, fmt.Errorf("'%s' is not a valid percentage, decimal, fraction or interval value", s)
}
Expand Down Expand Up @@ -417,7 +417,7 @@ func gcd(a, b int64) int64 {
// IsFull returns whether the sequences is full, that is, whether it starts at 0
// and ends at 1. Use GetFilledExecutionSegmentSequence() to get a full sequence.
func (ess ExecutionSegmentSequence) IsFull() bool {
return ess != nil && len(ess) != 0 && ess[0].from.Cmp(zeroRat) == 0 && ess[len(ess)-1].to.Cmp(oneRat) == 0
return len(ess) != 0 && ess[0].from.Cmp(zeroRat) == 0 && ess[len(ess)-1].to.Cmp(oneRat) == 0
}

// FindSegmentPosition returns the index of the supplied execution segment in
Expand Down
31 changes: 16 additions & 15 deletions lib/execution_segment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func TestExecutionSegmentEquals(t *testing.T) {
t.Run("To it's self", func(t *testing.T) {
t.Parallel()
es := stringToES(t, "1/2:2/3")
require.True(t, es.Equal(es))
require.True(t, es.Equal(es)) //nolint:gocritic
})
}

Expand Down Expand Up @@ -422,6 +422,14 @@ func TestExecutionSegmentStringSequences(t *testing.T) {
}
}

func getTestRand(t testing.TB) *rand.Rand {
t.Helper()
seed := time.Now().UnixNano()
r := rand.New(rand.NewSource(seed)) //nolint:gosec
t.Logf("Random source seeded with %d\n", seed)
return r
}

// Return a randomly distributed sequence of n amount of
// execution segments whose length totals 1.
func generateRandomSequence(t testing.TB, n, m int64, r *rand.Rand) ExecutionSegmentSequence {
Expand Down Expand Up @@ -449,13 +457,11 @@ func generateRandomSequence(t testing.TB, n, m int64, r *rand.Rand) ExecutionSeg
func TestExecutionSegmentScaleConsistency(t *testing.T) {
t.Parallel()

seed := time.Now().UnixNano()
r := rand.New(rand.NewSource(seed))
t.Logf("Random source seeded with %d\n", seed)
r := getTestRand(t)

const numTests = 10
for i := 0; i < numTests; i++ {
scale := rand.Int31n(99) + 2
scale := r.Int31n(99) + 2
seq := generateRandomSequence(t, r.Int63n(9)+2, 100, r)

t.Run(fmt.Sprintf("%d_%s", scale, seq), func(t *testing.T) {
Expand All @@ -474,13 +480,10 @@ func TestExecutionSegmentScaleConsistency(t *testing.T) {
func TestExecutionTupleScaleConsistency(t *testing.T) {
t.Parallel()

seed := time.Now().UnixNano()
r := rand.New(rand.NewSource(seed))
t.Logf("Random source seeded with %d\n", seed)

r := getTestRand(t)
const numTests = 10
for i := 0; i < numTests; i++ {
scale := rand.Int31n(99) + 2
scale := r.Int31n(99) + 2
seq := generateRandomSequence(t, r.Int63n(9)+2, 200, r)

et, err := NewExecutionTuple(seq[0], &seq)
Expand Down Expand Up @@ -517,16 +520,14 @@ func TestExecutionSegmentScaleNoWobble(t *testing.T) {
requireSegmentScaleGreater(t, et)
})

seed := time.Now().UnixNano()
r := rand.New(rand.NewSource(seed))
t.Logf("Random source seeded with %d\n", seed)
r := getTestRand(t)

// Random segments
const numTests = 10
for i := 0; i < numTests; i++ {
seq := generateRandomSequence(t, r.Int63n(9)+2, 100, r)

es := seq[rand.Intn(len(seq))]
es := seq[r.Intn(len(seq))]

et, err := NewExecutionTuple(seq[0], &seq)
require.NoError(t, err)
Expand Down Expand Up @@ -623,7 +624,7 @@ func TestSequenceLCD(t *testing.T) {
func BenchmarkGetStripedOffsets(b *testing.B) {
lengths := [...]int64{10, 100}
const seed = 777
r := rand.New(rand.NewSource(seed))
r := rand.New(rand.NewSource(seed)) //nolint:gosec

for _, length := range lengths {
length := length
Expand Down
1 change: 1 addition & 0 deletions lib/executor/base_executor.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package executor defines the executors k6 can use.
package executor

import (
Expand Down
1 change: 1 addition & 0 deletions lib/executor/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ type executorTest struct {
logHook *testutils.SimpleLogrusHook
}

//nolint:unparam
func setupExecutorTest(
t testing.TB, segmentStr, sequenceStr string, extraOptions lib.Options,
runner lib.Runner, config lib.ExecutorConfig,
Expand Down
2 changes: 1 addition & 1 deletion lib/executor/constant_arrival_rate.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ type ConstantArrivalRate struct {
var _ lib.Executor = &ConstantArrivalRate{}

// Init values needed for the execution
func (car *ConstantArrivalRate) Init(ctx context.Context) error {
func (car *ConstantArrivalRate) Init(_ context.Context) error {
// err should always be nil, because Init() won't be called for executors
// with no work, as determined by their config's HasWork() method.
et, err := car.BaseExecutor.executionState.ExecutionTuple.GetNewExecutionTupleFromValue(car.config.MaxVUs.Int64)
Expand Down
8 changes: 3 additions & 5 deletions lib/executor/constant_vus.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ var _ lib.Executor = &ConstantVUs{}

// Run constantly loops through as many iterations as possible on a fixed number
// of VUs for the specified duration.
func (clv ConstantVUs) Run(parentCtx context.Context, out chan<- metrics.SampleContainer) (err error) {
func (clv ConstantVUs) Run(parentCtx context.Context, _ chan<- metrics.SampleContainer) (err error) {
numVUs := clv.config.GetVUs(clv.executionState.ExecutionTuple)
duration := clv.config.Duration.TimeDuration()
gracefulStop := clv.config.GetGracefulStop()
Expand Down Expand Up @@ -180,15 +180,13 @@ func (clv ConstantVUs) Run(parentCtx context.Context, out chan<- metrics.SampleC
defer cancel()

activeVU := initVU.Activate(
getVUActivationParams(ctx, clv.config.BaseConfig, returnVU,
clv.nextIterationCounters))
getVUActivationParams(ctx, clv.config.BaseConfig, returnVU, clv.nextIterationCounters))

for {
select {
case <-regDurationDone:
return // don't make more iterations
default:
// continue looping
default: // continue looping
}
runIteration(maxDurationCtx, activeVU)
}
Expand Down
2 changes: 1 addition & 1 deletion lib/executor/constant_vus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func TestConstantVUsRun(t *testing.T) {

var totalIters uint64
result.Range(func(key, value interface{}) bool {
vuIters := value.(uint64)
vuIters := value.(uint64) //nolint:forcetypeassert
assert.Equal(t, uint64(5), vuIters)
totalIters += vuIters
return true
Expand Down
4 changes: 2 additions & 2 deletions lib/executor/executors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ var configMapTestCases = []configMapTestCase{
`{"carrival": {"executor": "constant-arrival-rate", "rate": 10, "duration": "10m", "preAllocatedVUs": 20}}`,
exp{custom: func(t *testing.T, cm lib.ScenarioConfigs) {
assert.Empty(t, cm["carrival"].Validate())
require.EqualValues(t, 20, cm["carrival"].(*ConstantArrivalRateConfig).MaxVUs.Int64)
require.EqualValues(t, 20, cm["carrival"].(*ConstantArrivalRateConfig).MaxVUs.Int64) //nolint:forcetypeassert
}},
},
{`{"carrival": {"executor": "constant-arrival-rate", "rate": 10, "duration": "10m", "maxVUs": 30}}`, exp{validationError: true}},
Expand Down Expand Up @@ -396,7 +396,7 @@ var configMapTestCases = []configMapTestCase{
`{"varrival": {"executor": "ramping-arrival-rate", "preAllocatedVUs": 20, "stages": [{"duration": "5m", "target": 10}]}}`,
exp{custom: func(t *testing.T, cm lib.ScenarioConfigs) {
assert.Empty(t, cm["varrival"].Validate())
require.EqualValues(t, 20, cm["varrival"].(*RampingArrivalRateConfig).MaxVUs.Int64)
require.EqualValues(t, 20, cm["varrival"].(*RampingArrivalRateConfig).MaxVUs.Int64) //nolint:forcetypeassert
}},
},
{`{"varrival": {"executor": "ramping-arrival-rate", "maxVUs": 50, "stages": [{"duration": "5m", "target": 10}]}}`, exp{validationError: true}},
Expand Down
12 changes: 6 additions & 6 deletions lib/executor/externally_controlled.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ func (mex ExternallyControlled) GetLogger() *logrus.Entry {
}

// Init doesn't do anything...
func (mex ExternallyControlled) Init(ctx context.Context) error {
func (mex ExternallyControlled) Init(_ context.Context) error {
return nil
}

Expand Down Expand Up @@ -480,7 +480,7 @@ func (rs *externallyControlledRunState) handleConfigChange(oldCfg, newCfg Extern
// until the test is manually stopped.
//
//nolint:funlen,gocognit
func (mex *ExternallyControlled) Run(parentCtx context.Context, out chan<- metrics.SampleContainer) (err error) {
func (mex *ExternallyControlled) Run(parentCtx context.Context, _ chan<- metrics.SampleContainer) (err error) {
mex.configLock.RLock()
// Safely get the current config - it's important that the close of the
// hasStarted channel is inside of the lock, so that there are no data races
Expand Down Expand Up @@ -528,7 +528,7 @@ func (mex *ExternallyControlled) Run(parentCtx context.Context, out chan<- metri
ss.ProgressFn = runState.progressFn

*runState.maxVUs = startMaxVUs
if err = runState.retrieveStartMaxVUs(); err != nil {
if err = runState.retrieveStartMaxVUs(); err != nil { //nolint:contextcheck
return err
}

Expand All @@ -537,7 +537,7 @@ func (mex *ExternallyControlled) Run(parentCtx context.Context, out chan<- metri
trackProgress(parentCtx, ctx, ctx, mex, runState.progressFn)
close(waitOnProgressChannel)
}()

//nolint:contextcheck
err = runState.handleConfigChange( // Start by setting MaxVUs to the starting MaxVUs
ExternallyControlledConfigParams{MaxVUs: mex.config.MaxVUs}, currentControlConfig,
)
Expand All @@ -553,10 +553,10 @@ func (mex *ExternallyControlled) Run(parentCtx context.Context, out chan<- metri
case <-ctx.Done():
return nil
case updateConfigEvent := <-mex.newControlConfigs:
err := runState.handleConfigChange(currentControlConfig, updateConfigEvent.newConfig)
err := runState.handleConfigChange(currentControlConfig, updateConfigEvent.newConfig) //nolint:contextcheck
if err != nil {
updateConfigEvent.err <- err
if ctx.Err() == err {
if errors.Is(ctx.Err(), err) {
return nil // we've already returned an error to the API client, but k6 should stop normally
}
return err
Expand Down
4 changes: 2 additions & 2 deletions lib/executor/per_vu_iterations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func TestPerVUIterationsRun(t *testing.T) {

var totalIters uint64
result.Range(func(key, value interface{}) bool {
vuIters := value.(uint64)
vuIters := value.(uint64) //nolint:forcetypeassert
assert.Equal(t, uint64(100), vuIters)
totalIters += vuIters
return true
Expand Down Expand Up @@ -81,7 +81,7 @@ func TestPerVUIterationsRunVariableVU(t *testing.T) {

var totalIters uint64
result.Range(func(key, value interface{}) bool {
vuIters := value.(uint64)
vuIters := value.(uint64) //nolint:forcetypeassert
if key != slowVUID {
assert.Equal(t, uint64(100), vuIters)
}
Expand Down
2 changes: 1 addition & 1 deletion lib/executor/ramping_arrival_rate.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ type RampingArrivalRate struct {
var _ lib.Executor = &RampingArrivalRate{}

// Init values needed for the execution
func (varr *RampingArrivalRate) Init(ctx context.Context) error {
func (varr *RampingArrivalRate) Init(_ context.Context) error {
// err should always be nil, because Init() won't be called for executors
// with no work, as determined by their config's HasWork() method.
et, err := varr.BaseExecutor.executionState.ExecutionTuple.GetNewExecutionTupleFromValue(varr.config.MaxVUs.Int64)
Expand Down
3 changes: 1 addition & 2 deletions lib/executor/ramping_arrival_rate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,7 @@ func BenchmarkRampingArrivalRateRun(b *testing.B) {
engineOut := make(chan metrics.SampleContainer, 1000)
defer close(engineOut)
go func() {
for range engineOut {
// discard
for range engineOut { //nolint:revive // we want to discard samples
}
}()

Expand Down
2 changes: 1 addition & 1 deletion lib/executor/ramping_vus.go
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,7 @@ func (rs *rampingVUsRunState) runLoopsIfPossible(ctx context.Context, cancel fun
rs.vuHandles[i] = newStoppedVUHandle(
ctx, getVU, returnVU, rs.executor.nextIterationCounters,
&rs.executor.config.BaseConfig, rs.executor.logger.WithField("vuNum", i))
go rs.vuHandles[i].runLoopsIfPossible(rs.runIteration)
go rs.vuHandles[i].runLoopsIfPossible(rs.runIteration) //nolint:contextcheck
}
}

Expand Down
2 changes: 1 addition & 1 deletion lib/executor/shared_iterations.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ func (sic SharedIterationsConfig) HasWork(et *lib.ExecutionTuple) bool {
}

// Init values needed for the execution
func (si *SharedIterations) Init(ctx context.Context) error {
func (si *SharedIterations) Init(_ context.Context) error {
// err should always be nil, because Init() won't be called for executors
// with no work, as determined by their config's HasWork() method.
et, err := si.BaseExecutor.executionState.ExecutionTuple.GetNewExecutionTupleFromValue(si.config.VUs.Int64)
Expand Down
2 changes: 1 addition & 1 deletion lib/executor/shared_iterations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func TestSharedIterationsRunVariableVU(t *testing.T) {

var totalIters uint64
result.Range(func(key, value interface{}) bool {
totalIters += value.(uint64)
totalIters += value.(uint64) //nolint:forcetypeassert
return true
})

Expand Down
Loading

0 comments on commit 4839e8d

Please sign in to comment.