Skip to content

Commit

Permalink
golangci-lint: add intrange & update code
Browse files Browse the repository at this point in the history
Add the 'intrange' linter, which enforces usage of the hip new-ish
"range over int" feature in Go.

Signed-off-by: Carlo Teubner <carlo@cteubner.net>
  • Loading branch information
c4rlo committed Dec 20, 2024
1 parent 6928ff1 commit 3013d14
Show file tree
Hide file tree
Showing 32 changed files with 74 additions and 73 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ linters:
- nakedret
- unconvert
- unparam
- intrange
- whitespace
- gocritic
- nolintlint
Expand Down
2 changes: 1 addition & 1 deletion cmd/spire-server/cli/entry/show_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ func getEntries(count int) []*types.Entry {
}

e := []*types.Entry{}
for i := 0; i < count; i++ {
for i := range count {
e = append(e, entries[i])
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/agent/attestor/workload/workload.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func (wla *attestor) Attest(ctx context.Context, pid int) ([]*common.Selector, e

// Collect the results
selectors := []*common.Selector{}
for i := 0; i < len(plugins); i++ {
for range plugins {
select {
case s := <-sChan:
selectors = append(selectors, s...)
Expand Down
4 changes: 2 additions & 2 deletions pkg/agent/client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -660,7 +660,7 @@ func TestFetchReleaseWaitsForFetchUpdatesToFinish(t *testing.T) {
func TestNewNodeClientRelease(t *testing.T) {
client, _ := createClient(t)

for i := 0; i < 3; i++ {
for range 3 {
// Create agent client and release
_, r, err := client.newAgentClient(ctx)
require.NoError(t, err)
Expand Down Expand Up @@ -697,7 +697,7 @@ func TestNewNodeClientRelease(t *testing.T) {
func TestNewNodeInternalClientRelease(t *testing.T) {
client, _ := createClient(t)

for i := 0; i < 3; i++ {
for range 3 {
// Create agent client
_, conn, err := client.newAgentClient(ctx)
require.NoError(t, err)
Expand Down
4 changes: 2 additions & 2 deletions pkg/agent/client/nodeconn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func TestNewNodeMany(t *testing.T) {
firstRelease := false

go func() {
for i := 0; i < 100; i++ {
for range 100 {
nodeConn.AddRef()
if !firstRelease {
nodeConn.Release()
Expand All @@ -75,7 +75,7 @@ func TestNewNodeMany(t *testing.T) {
}()

go func() {
for i := 0; i < 100; i++ {
for range 100 {
nodeConn.Release()
}
close(waitForReleases)
Expand Down
12 changes: 6 additions & 6 deletions pkg/agent/manager/cache/lru_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1251,7 +1251,7 @@ func BenchmarkLRUCacheGlobalNotification(b *testing.B) {
Bundles: bundlesV1,
RegistrationEntries: make(map[string]*common.RegistrationEntry, numEntries),
}
for i := 0; i < numEntries; i++ {
for i := range numEntries {
entryID := fmt.Sprintf("00000000-0000-0000-0000-%012d", i)
updateEntries.RegistrationEntries[entryID] = &common.RegistrationEntry{
EntryId: entryID,
Expand All @@ -1262,7 +1262,7 @@ func BenchmarkLRUCacheGlobalNotification(b *testing.B) {
}

cache.UpdateEntries(updateEntries, nil)
for i := 0; i < numWorkloads; i++ {
for i := range numWorkloads {
selectors := distinctSelectors(i, selectorsPerWorkload)
cache.NewSubscriber(selectors)
}
Expand All @@ -1271,7 +1271,7 @@ func BenchmarkLRUCacheGlobalNotification(b *testing.B) {

b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for i := range b.N {
if i%2 == 0 {
updateEntries.Bundles = bundlesV2
} else {
Expand Down Expand Up @@ -1299,7 +1299,7 @@ func createUpdateEntries(numEntries int, bundles map[spiffeid.TrustDomain]*spiff
RegistrationEntries: make(map[string]*common.RegistrationEntry, numEntries),
}

for i := 0; i < numEntries; i++ {
for i := range numEntries {
entryID := fmt.Sprintf("00000000-0000-0000-0000-%012d", i)
updateEntries.RegistrationEntries[entryID] = &common.RegistrationEntry{
EntryId: entryID,
Expand Down Expand Up @@ -1335,7 +1335,7 @@ func subscribeToWorkloadUpdates(t *testing.T, cache *LRUCache, selectors []*comm

func distinctSelectors(id, n int) []*common.Selector {
out := make([]*common.Selector, 0, n)
for i := 0; i < n; i++ {
for i := range n {
out = append(out, &common.Selector{
Type: "test",
Value: fmt.Sprintf("id:%d:n:%d", id, i),
Expand Down Expand Up @@ -1436,7 +1436,7 @@ func makeFederatesWith(bundles ...*Bundle) []string {

func createTestEntries(count int) []*common.RegistrationEntry {
var entries []*common.RegistrationEntry
for i := 0; i < count; i++ {
for i := range count {
entry := makeRegistrationEntry(fmt.Sprintf("e%d", i), fmt.Sprintf("s%d", i))
entries = append(entries, entry)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/agent/manager/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ func TestSVIDRotation(t *testing.T) {
defer closer()

// Loop, we should not detect SVID rotations
for i := 0; i < 10; i++ {
for range 10 {
s := m.GetCurrentCredentials()
svid = s.SVID
require.True(t, svidsEqual(svid, baseSVID))
Expand Down
2 changes: 1 addition & 1 deletion pkg/common/catalog/catalog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ func testPlugin(t *testing.T, pluginPath string) {
t.Run("no maximum", func(t *testing.T) {
testLoad(t, pluginPath, loadTest{
mutateConfig: func(config *catalog.Config) {
for i := 0; i < 10; i++ {
for range 10 {
config.PluginConfigs = append(config.PluginConfigs, config.PluginConfigs[0])
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func printStruct(msg any, stdout, stderr io.Writer) error {
}

builder := new(strings.Builder)
for i := 0; i < msgType.NumField(); i++ {
for i := range msgType.NumField() {
fieldType := msgType.Field(i)
fieldValue := msgValue.Field(i)

Expand Down
8 changes: 4 additions & 4 deletions pkg/common/diskcertmanager/cert_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ func TestTLSConfig(t *testing.T) {
t.Run("update cert file with an invalid cert start error log loop", func(t *testing.T) {
writeFile(t, certFilePath, []byte("invalid-cert"))

for i := 0; i < 5; i++ {
for range 5 {
clk.Add(10 * time.Millisecond)
}

Expand Down Expand Up @@ -254,7 +254,7 @@ func TestTLSConfig(t *testing.T) {

writeFile(t, keyFilePath, []byte("invalid-key"))

for i := 0; i < 5; i++ {
for range 5 {
clk.Add(10 * time.Millisecond)
}

Expand Down Expand Up @@ -302,7 +302,7 @@ func TestTLSConfig(t *testing.T) {
t.Run("delete cert files start error log loop", func(t *testing.T) {
removeFile(t, keyFilePath)

for i := 0; i < 5; i++ {
for range 5 {
clk.Add(10 * time.Millisecond)
}

Expand All @@ -319,7 +319,7 @@ func TestTLSConfig(t *testing.T) {

removeFile(t, certFilePath)

for i := 0; i < 5; i++ {
for range 5 {
clk.Add(10 * time.Millisecond)
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/common/plugin/sshpop/handshake_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ func marshalAttestationData(t *testing.T, cert []byte) []byte {
func TestIssueChallengeUniqueness(t *testing.T) {
_, s := newTestHandshake(t)
challenges := make(map[string]struct{})
for i := 0; i < 10000; i++ {
for range 10000 {
s.state = stateAttestationDataVerified
challenge, err := s.IssueChallenge()
require.NoError(t, err)
Expand Down
2 changes: 1 addition & 1 deletion pkg/common/protoutil/masks.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ var (
func MakeAllTrueMask(m proto.Message) proto.Message {
v := reflect.ValueOf(proto.Clone(m)).Elem()
t := v.Type()
for i := 0; i < v.NumField(); i++ {
for i := range v.NumField() {
ft := t.Field(i)
fv := v.Field(i)
// Skip the protobuf internal fields or those that aren't bools
Expand Down
4 changes: 2 additions & 2 deletions pkg/common/selector/set_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ func powerSet(s *set, c chan Set) {

// Walk through the binary, and append
// "enabled" elements to the working set
for position := 0; position < len(binary); position++ {
for position := range binary {
// Read the binary right to left
negPosition := (len(binary) - position - 1)
negPosition := len(binary) - position - 1
if binary[negPosition] == "1" {
set.Add(sarr[position])
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/common/telemetry/server/datastore/wrapper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func TestWithMetrics(t *testing.T) {
methodNames := make(map[string]struct{})
wv := reflect.ValueOf(w)
wt := reflect.TypeOf(w)
for i := 0; i < wt.NumMethod(); i++ {
for i := range wt.NumMethod() {
methodNames[wt.Method(i).Name] = struct{}{}
}

Expand Down Expand Up @@ -270,7 +270,7 @@ func TestWithMetrics(t *testing.T) {
}
out := methodValue.Call(args)
require.Len(t, out, numOut)
for i := 0; i < numOut-1; i++ {
for i := range numOut - 1 {
mv := methodValue.Type().Out(i)
switch v := reflect.ValueOf(mv); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/api/agent/v1/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ func TestCountAgents(t *testing.T) {
test := setupServiceTest(t, 0)
defer test.Cleanup()

for i := 0; i < int(tt.count); i++ {
for i := range int(tt.count) {
now := time.Now()
_, err := test.ds.CreateAttestedNode(ctx, &common.AttestedNode{
SpiffeId: ids[i].String(),
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/api/bundle/v1/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1698,7 +1698,7 @@ func TestCountBundles(t *testing.T) {
test := setupServiceTest(t)
defer test.Cleanup()

for i := 0; i < int(tt.count); i++ {
for i := range int(tt.count) {
createBundle(t, test, tds[i].IDString())
}

Expand Down
8 changes: 4 additions & 4 deletions pkg/server/api/entry/v1/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ func TestCountEntries(t *testing.T) {
test := setupServiceTest(t, ds)
defer test.Cleanup()

for i := 0; i < int(tt.count); i++ {
for i := range int(tt.count) {
_, err := test.ds.CreateRegistrationEntry(ctx, &common.RegistrationEntry{
ParentId: spiffeid.RequireFromSegments(td, fmt.Sprintf("parent%d", i)).String(),
SpiffeId: spiffeid.RequireFromSegments(td, fmt.Sprintf("child%d", i)).String(),
Expand Down Expand Up @@ -3322,7 +3322,7 @@ func FuzzSyncAuthorizedStreams(f *testing.F) {

const maxEntries = 40
var entries []*types.Entry
for i := 0; i < maxEntries; i++ {
for i := range maxEntries {
entries = append(entries, &types.Entry{Id: strconv.Itoa(i), RevisionNumber: 1})
}

Expand Down Expand Up @@ -3374,7 +3374,7 @@ func FuzzSyncAuthorizedStreams(f *testing.F) {
// The number of entries exceeded the page size. Expect one or more
// pages of entry revisions.
var actualIDs []string
for page := 0; page < calculatePageCount(totalEntries)-1; page++ {
for range calculatePageCount(totalEntries) - 1 {
resp := recvNoError(t, stream)
require.Equal(t, len(resp.EntryRevisions), entryPageSize)
require.Zero(t, resp.Entries)
Expand All @@ -3397,7 +3397,7 @@ func FuzzSyncAuthorizedStreams(f *testing.F) {
require.NoError(t, stream.Send(&entryv1.SyncAuthorizedEntriesRequest{Ids: staleIDs}))

actualIDs = actualIDs[:0]
for page := 0; page < calculatePageCount(len(staleIDs))-1; page++ {
for range calculatePageCount(len(staleIDs)) - 1 {
resp = recvNoError(t, stream)
require.Equal(t, len(resp.Entries), entryPageSize)
require.Zero(t, resp.EntryRevisions)
Expand Down
8 changes: 4 additions & 4 deletions pkg/server/authorizedentries/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ func BenchmarkGetAuthorizedEntriesInMemory(b *testing.B) {
staticSelector2 := &types.Selector{Type: "static", Value: "static-2"}

const numAgents = 50000
for i := 0; i < numAgents; i++ {
for i := range numAgents {
test.withAgent(spiffeid.RequireFromPathf(td, "/agent-%d", i), staticSelector1)
}

Expand All @@ -382,7 +382,7 @@ func BenchmarkGetAuthorizedEntriesInMemory(b *testing.B) {
},
)

for i := 0; i < 300; i++ {
for i := range 300 {
test.withEntries(&types.Entry{
Id: fmt.Sprintf("alias1-workload-%d", i),
SpiffeId: &types.SPIFFEID{
Expand All @@ -396,7 +396,7 @@ func BenchmarkGetAuthorizedEntriesInMemory(b *testing.B) {
})
}

for i := 0; i < 300; i++ {
for i := range 300 {
test.withEntries(&types.Entry{
Id: fmt.Sprintf("alias2-workload-%d", i),
SpiffeId: &types.SPIFFEID{
Expand All @@ -412,7 +412,7 @@ func BenchmarkGetAuthorizedEntriesInMemory(b *testing.B) {

cache := test.hydrate(b)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for range b.N {
cache.GetAuthorizedEntries(test.pickAgent())
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/bundle/pubmanager/pubmanager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ type managerTest struct {
}

func (test *managerTest) waitForPublishResult(ctx context.Context, t *testing.T, expectedResults publishResults) {
for i := 0; i < len(expectedResults); i++ {
for range expectedResults {
select {
case bpe := <-test.m.hooks.publishResultCh:
expectedBPEvent, ok := expectedResults[bpe.pluginName]
Expand Down
4 changes: 2 additions & 2 deletions pkg/server/ca/manager/journal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ func TestX509CAOverflow(t *testing.T) {

journal := test.loadJournal(t)

for i := 0; i < (journalCap + 1); i++ {
for range journalCap + 1 {
now = now.Add(time.Minute)
err := journal.AppendX509CA(ctx, "A", now, &ca.X509CA{
Signer: kmKeys["X509-CA-A"],
Expand Down Expand Up @@ -313,7 +313,7 @@ func TestJWTKeyOverflow(t *testing.T) {

journal := test.loadJournal(t)

for i := 0; i < (journalCap + 1); i++ {
for range journalCap + 1 {
now = now.Add(time.Minute)
err := journal.AppendJWTKey(ctx, "B", now, &ca.JWTKey{
Signer: kmKeys["JWT-Signer-B"],
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/ca/manager/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -736,7 +736,7 @@ func (m *Manager) notify(ctx context.Context, event string, advise bool, pre fun
}

var allErrs errs.Group
for i := 0; i < len(notifiers); i++ {
for range notifiers {
// don't select on the ctx here as we can rely on the plugins to
// respond to context cancellation and return an error.
if err := <-errsCh; err != nil {
Expand Down
10 changes: 5 additions & 5 deletions pkg/server/cache/entrycache/fullcache_ds_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func TestEntryIteratorDS(t *testing.T) {
{Type: "doesn't", Value: "matter"},
}
entriesToCreate := make([]*common.RegistrationEntry, numEntries)
for i := 0; i < numEntries; i++ {
for i := range numEntries {
entriesToCreate[i] = &common.RegistrationEntry{
ParentId: parentID,
SpiffeId: spiffeIDPrefix + strconv.Itoa(i),
Expand All @@ -57,7 +57,7 @@ func TestEntryIteratorDS(t *testing.T) {
it := makeEntryIteratorDS(ds)
var entries []*types.Entry

for i := 0; i < numEntries; i++ {
for range numEntries {
assert.True(t, it.Next(ctx))
require.NoError(t, it.Err())

Expand All @@ -73,7 +73,7 @@ func TestEntryIteratorDS(t *testing.T) {

t.Run("datastore error", func(t *testing.T) {
it := makeEntryIteratorDS(ds)
for i := 0; i < int(listEntriesRequestPageSize); i++ {
for range listEntriesRequestPageSize {
assert.True(t, it.Next(ctx))
require.NoError(t, it.Err())
}
Expand Down Expand Up @@ -105,7 +105,7 @@ func TestAgentIteratorDS(t *testing.T) {

expectedSelectors := api.ProtoFromSelectors(selectors)
expectedAgents := make([]Agent, numAgents)
for i := 0; i < numAgents; i++ {
for i := range numAgents {
iterStr := strconv.Itoa(i)
agentID, err := spiffeid.FromString("spiffe://example.org/spire/agent/agent" + iterStr)
require.NoError(t, err)
Expand All @@ -129,7 +129,7 @@ func TestAgentIteratorDS(t *testing.T) {
t.Run("multiple pages", func(t *testing.T) {
it := makeAgentIteratorDS(ds)
agents := make([]Agent, numAgents)
for i := 0; i < numAgents; i++ {
for i := range numAgents {
assert.True(t, it.Next(ctx))
assert.NoError(t, it.Err())
agents[i] = it.Agent()
Expand Down
Loading

0 comments on commit 3013d14

Please sign in to comment.