Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lint: Add intrange linter to reduce code complexity. #1811

Merged
merged 6 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ on:
# Required for aws-actions/configure-aws-credentials using OIDC, assume role
permissions:
id-token: write
contents: read
contents: read

jobs:
lint:
Expand Down
1 change: 1 addition & 0 deletions build/ci/golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ linters:
- govet
- importas
- ineffassign
- intrange
- makezero
- nakedret
- nilerr
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/filesystem/aferofs/filesystem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func (tc *testCases) runTests(t *testing.T) {
// Call all Test* methods
tp := reflect.TypeOf(tc)
prefix := `Test`
for i := 0; i < tp.NumMethod(); i++ {
for i := range tp.NumMethod() {
method := tp.Method(i)
if strings.HasPrefix(method.Name, prefix) {
fs, logger := tc.createFs()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ func TestLoader_LoadConfig_Race(t *testing.T) {
wg := sync.WaitGroup{}
counter := atomic.NewInt64(0)
// Load configuration 10x in parallel
for i := 0; i < 10; i++ {
for range 10 {
wg.Add(1)
go func() {
defer wg.Done()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func TestManager_Notify_Race(t *testing.T) {
wg := sync.WaitGroup{}
counter := atomic.NewInt64(0)
// Load configuration 10x in parallel
for i := 0; i < 10; i++ {
for range 10 {
wg.Add(1)
go func() {
defer wg.Done()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func TestManager_Wakeup_Race(t *testing.T) {
wg := sync.WaitGroup{}
counter := atomic.NewInt64(0)
// Load configuration 10x in parallel
for i := 0; i < 10; i++ {
for range 10 {
wg.Add(1)
go func() {
defer wg.Done()
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/appsproxy/proxy/proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1722,7 +1722,7 @@ func TestAppProxyRouter(t *testing.T) {

wg := sync.WaitGroup{}
counter := atomic.NewInt64(0)
for i := 0; i < 100; i++ {
for range 100 {
wg.Add(1)
go func() {
defer wg.Done()
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/appsproxy/syncmap/syncmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func TestSyncMap_GetOrInit_Race(t *testing.T) {

wg := sync.WaitGroup{}
accessCounter := atomic.NewInt64(0)
for i := 0; i < 10; i++ {
for range 10 {
wg.Add(1)
go func() {
defer wg.Done()
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/common/configmap/visit.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func doVisit(vc *VisitContext, cfg VisitConfig) error {
return err
}

for i := 0; i < typ.NumField(); i++ {
for i := range typ.NumField() {
// Fill context with field information
field := &VisitContext{}
field.StructField = typ.Field(i)
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/common/configpatch/bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ func BindKVs(patchStruct any, kvs PatchKVs, opts ...Option) error {
targetSlice.Set(reflect.Zero(expectedType))

// Convert items
for index := 0; index < value.Len(); index++ {
for index := range value.Len() {
item := value.Index(index)
for item.Kind() == reflect.Pointer || item.Kind() == reflect.Interface {
item = item.Elem()
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/common/dependencies/lazy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func TestLazy_InitAndGet_Parallel(t *testing.T) {

// Call in parallel
wg := &sync.WaitGroup{}
for i := 0; i < 100; i++ {
for range 100 {
wg.Add(1)
go func() {
defer wg.Done()
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/common/distribution/node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func TestNodesDiscovery(t *testing.T) {

// Create nodes
wg := &sync.WaitGroup{}
for i := 0; i < nodesCount; i++ {
for i := range nodesCount {
wg.Add(1)
go func() {
defer wg.Done()
Expand Down
8 changes: 4 additions & 4 deletions internal/pkg/service/common/etcdop/mutex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ func TestMutex_ParallelWork(t *testing.T) {

total := atomic.NewInt64(0) // count and verify that all operations have been invoked
var lockTesters []lockTester
for i := 0; i < tc.UniqueLocks; i++ {
for i := range tc.UniqueLocks {
active := atomic.NewInt64(0) // count of active CriticalWork calls per lock, should be always at most one
lockTesters = append(lockTesters, lockTester{
LockName: fmt.Sprintf("locks/my-lock-%02d", i+1),
Expand All @@ -177,7 +177,7 @@ func TestMutex_ParallelWork(t *testing.T) {

// Start N sessions
workWg := &sync.WaitGroup{}
for i := 0; i < tc.Sessions; i++ {
for range tc.Sessions {
workWg.Add(1)
readyWg.Add(1)
go func() {
Expand All @@ -194,7 +194,7 @@ func TestMutex_ParallelWork(t *testing.T) {
locksWg := &sync.WaitGroup{}
for _, lockTester := range lockTesters {
// Use each lock N times in parallel
for k := 0; k < tc.Parallel; k++ {
for range tc.Parallel {
workWg.Add(1)
locksWg.Add(1)
go func() {
Expand All @@ -210,7 +210,7 @@ func TestMutex_ParallelWork(t *testing.T) {
}

// Use each lock N time sequentially
for l := 0; l < tc.Serial; l++ {
for range tc.Serial {
lockTester.CriticalWork(session.NewMutex(lockTester.LockName))
}
}()
Expand Down
4 changes: 2 additions & 2 deletions internal/pkg/service/common/etcdop/prefix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ func BenchmarkPrefix_GetAll(b *testing.B) {
if err := Key("key0").Put(client, "foo").Do(ctx).Err(); err != nil {
b.Fatalf("cannot create etcd key: %s", err)
}
for i := 0; i < 100; i++ {
for i := range 100 {
key := fmt.Sprintf("key%04d", i)
if err := pfx.Key(key).Put(client, "bar").Do(ctx).Err(); err != nil {
b.Fatalf(`cannot create etcd key "%s": %s`, key, err)
Expand Down Expand Up @@ -377,7 +377,7 @@ func BenchmarkPrefixT_GetAll(b *testing.B) {
if err := Key("key0").Put(client, "foo").Do(ctx).Err(); err != nil {
b.Fatalf("cannot create etcd key: %s", err)
}
for i := 0; i < 100; i++ {
for i := range 100 {
key := fmt.Sprintf("key%04d", i)
if err := pfx.Key(key).Put(client, "bar").Do(ctx).Err(); err != nil {
b.Fatalf(`cannot create etcd key "%s": %s`, key, err)
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/common/etcdop/session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func TestSessionBackoff(t *testing.T) {

// Get all delays without sleep
var delays []time.Duration
for i := 0; i < 14; i++ {
for range 14 {
delay := b.NextBackOff()
if delay == backoff.Stop {
assert.Fail(t, "unexpected stop")
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/common/etcdop/watch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ func TestWatchBackoff(t *testing.T) {

// Get all delays without sleep
var delays []time.Duration
for i := 0; i < 14; i++ {
for range 14 {
delay := b.NextBackOff()
if delay == backoff.Stop {
assert.Fail(t, "unexpected stop")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func AssignSlices(all []model.SliceKey, nodes []string, nodeID string, minSlices
targetCount := min(slicesPerNode, slicesCount)
assigned = make([]model.SliceKey, targetCount)
start := index * slicesPerNode
for i := 0; i < targetCount; i++ {
for i := range targetCount {
assigned[i] = all[(start+i)%slicesCount]
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ func newBenchmark(configure func(wb *benchmark.WriterBenchmark)) *benchmark.Writ
// Pre-generate unique records
records := make([]recordctx.Context, benchmarkUniqueRecords)
now := utctime.MustParse("2000-01-01T01:00:00.000Z")
for i := 0; i < benchmarkUniqueRecords; i++ {
for i := range benchmarkUniqueRecords {
now = now.Add(time.Hour)
records[i] = recordctx.FromHTTP(
now.Time(),
Expand All @@ -227,7 +227,7 @@ func newBenchmark(configure func(wb *benchmark.WriterBenchmark)) *benchmark.Writ
// Send the pre-generated records to the channel over and over
go func() {
defer close(ch)
for i := 0; i < n; i++ {
for i := range n {
if ctx.Err() != nil {
break
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func NewWritersPool(out io.Writer, rowSizeLimit datasize.ByteSize, writers int)
}

p.sem = make(chan struct{}, writers)
for i := 0; i < writers; i++ {
for range writers {
p.sem <- struct{}{}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ func (h *writerSyncHelper) NewSyncer(ctx context.Context, logger log.Logger, clo
func (h *writerSyncHelper) ExpectWritesCount(tb testing.TB, n int) {
tb.Helper()
tb.Logf(`waiting for %d writes`, n)
for i := 0; i < n; i++ {
for i := range n {
select {
case <-h.writeDone:
tb.Logf(`write %d done`, i+1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func TestNotifier_Success(t *testing.T) {
}

// Call Wait 5x before done
for i := 0; i < 5; i++ {
for range 5 {
wait()
}

Expand All @@ -84,7 +84,7 @@ func TestNotifier_Success(t *testing.T) {
n.Done(nil)

// Call Wait 5x after done
for i := 0; i < 5; i++ {
for range 5 {
wait()
}

Expand Down Expand Up @@ -126,7 +126,7 @@ func TestNotifier_Error(t *testing.T) {
}

// Call Wait 5x before done
for i := 0; i < 5; i++ {
for range 5 {
wait()
}

Expand All @@ -136,7 +136,7 @@ func TestNotifier_Error(t *testing.T) {
n.Done(errors.New("some error"))

// Call Wait 5x after done
for i := 0; i < 5; i++ {
for range 5 {
wait()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -828,7 +828,7 @@ func TestSyncWriter_OnlyOneRunningSync(t *testing.T) {
// Trigger sync multiple times, but it should run only once
go func() {
tc.Chain.SyncLock.Lock() // block sync completion
for i := 0; i < 20; i++ {
for range 20 {
syncerWriter.TriggerSync(false)
}
tc.Chain.SyncLock.Unlock()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func TestOpenVolumes_DuplicatedVolumeID(t *testing.T) {
tc := newVolumesTestCase(t)

// Create some volumes directories
for i := 0; i < 5; i++ {
for i := range 5 {
require.NoError(t, os.MkdirAll(filepath.Join(tc.VolumesPath, "default", cast.ToString(i)), 0o750))
}

Expand All @@ -61,7 +61,7 @@ func TestOpenVolumes_OpenError(t *testing.T) {
}

// Create some volumes directories
for i := 0; i < 5; i++ {
for i := range 5 {
require.NoError(t, os.MkdirAll(filepath.Join(tc.VolumesPath, "default", cast.ToString(i)), 0o750))
}

Expand Down Expand Up @@ -140,7 +140,7 @@ func TestOpenVolumes_CloseError(t *testing.T) {
}

// Create some volumes directories
for i := 0; i < 5; i++ {
for i := range 5 {
require.NoError(t, os.MkdirAll(filepath.Join(tc.VolumesPath, "default", cast.ToString(i)), 0o750))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func TestRepository_Put(t *testing.T) {
nodeID3 := "test-node-3"
var records []statistics.PerSlice
start := utctime.MustParse("2000-01-21T00:00:00.000Z")
for i := 0; i < 150; i++ {
for i := range 150 {
openedAt := start.Add(time.Duration(i) * time.Second)
records = append(records, statistics.PerSlice{
SliceKey: test.NewSliceKeyOpenedAt(openedAt.String()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func (wb *WriterBenchmark) Run(b *testing.B) {
defer wg.Done()

// Start wb.Parallelism goroutines
for i := 0; i < wb.Parallelism; i++ {
for range wb.Parallelism {
wg.Add(1)
go func() {
defer wg.Done()
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/state/local/workers.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func (w *Workers) StartAndWait() error {

// Collect errors in the same order as workers were defined
workersCount := w.workerNum.Load()
for i := int64(0); i < workersCount; i++ {
for i := range workersCount {
if err, ok := w.errors[i]; ok {
errs.Append(err)
}
Expand Down
4 changes: 2 additions & 2 deletions internal/pkg/telemetry/fortest.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ func (v *forTest) AssertSpans(t *testing.T, expectedSpans tracetest.SpanStubs, o
spansCount := (int)(math.Max((float64)(len(expectedSpans)), (float64)(len(actualSpans))))
var actualSpan tracetest.SpanStub
var expectedSpan tracetest.SpanStub
for i := 0; i < spansCount; i++ {
for i := range spansCount {
if len(actualSpans) > i {
actualSpan = actualSpans[i]
} else {
Expand Down Expand Up @@ -246,7 +246,7 @@ func (v *forTest) AssertMetrics(t *testing.T, expectedMetrics []metricdata.Metri
metersCount := (int)(math.Max((float64)(len(expectedMetrics)), (float64)(len(actualMetrics))))
var actualMeter metricdata.Metrics
var expectedMeter metricdata.Metrics
for i := 0; i < metersCount; i++ {
for i := range metersCount {
if len(actualMetrics) > i {
actualMeter = actualMetrics[i]
} else {
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/template/input/find.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func Find(objectKey model.Key, component *keboola.Component, content *orderedmap
inputType = TypeStringArray
inputKind = KindMultiSelect
// Each element must be string
for i := 0; i < valRef.Len(); i++ {
for i := range valRef.Len() {
item := valRef.Index(i)
// Unwrap interface
if item.Type().Kind() == reflect.Interface {
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/template/input/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func (t Type) ValidateValue(value reflect.Value) error {
return errors.Errorf("should be array, got %s", kindStr)
} else {
// Each element must be string
for i := 0; i < value.Len(); i++ {
for i := range value.Len() {
item := value.Index(i)
// Unwrap interface
if item.Type().Kind() == reflect.Interface {
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/utils/reflecthelper/reflecthelper.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func GetFieldsWithTag(tag string, model any) []*StructField {

var fields []*StructField
numFields := modelType.NumField()
for i := 0; i < numFields; i++ {
for i := range numFields {
field := modelType.Field(i)
tag := field.Tag.Get(tagName)
if tag == tagValue {
Expand Down
4 changes: 2 additions & 2 deletions internal/pkg/utils/testassert/testassert.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func DeepEqualNotSame(t *testing.T, a, b any, path string) {
}
switch typeA.Kind() {
case reflect.Struct:
for i := 0; i < typeA.NumField(); i++ {
for i := range typeA.NumField() {
field := typeA.Field(i)
fieldA := valueA.Field(i)
fieldB := valueB.Field(i)
Expand All @@ -62,7 +62,7 @@ func DeepEqualNotSame(t *testing.T, a, b any, path string) {
)
}
case reflect.Slice:
for i := 0; i < valueA.Len(); i++ {
for i := range valueA.Len() {
DeepEqualNotSame(
t,
valueA.Index(i).Interface(),
Expand Down
2 changes: 1 addition & 1 deletion scripts/tools.sh
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ if ! command -v golangci-lint &> /dev/null
then
# Disabled due to issues with windows curl command not working
# Related to https://github.com/keboola/keboola-as-code/pull/1818/commits/df23a4e2855557a01460593f7d6ba59b5dc8825c
# curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b "$GOBIN" v1.58.0
# curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b "$GOBIN" v1.61.0
go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.61.0
fi

Expand Down