lint: enable intrange linter (#7331)

Enable intrange linter to enforce modern Go range syntax over
traditional for loops, by converting:

for i := 0; i < n; i++

to:

for i := range n

Adding type conversions where needed for compatibility
with existing uint64 parameters.

Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
This commit is contained in:
Ville Vesilehto 2025-05-29 03:50:55 +03:00 committed by GitHub
parent b3acbe5046
commit 19a6ae4983
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
47 changed files with 82 additions and 81 deletions

View File

@ -6,6 +6,7 @@ linters:
- copyloopvar
- govet
- ineffassign
- intrange
- staticcheck
- unconvert
- unused

View File

@ -116,7 +116,7 @@ func BenchmarkCoreServeDNS(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for range b.N {
s.ServeDNS(ctx, w, m)
}
}

View File

@ -73,7 +73,7 @@ func parse(c *caddy.Controller) (auth.EnvironmentSettings, map[string][]string,
for c.Next() {
args := c.RemainingArgs()
for i := 0; i < len(args); i++ {
for i := range args {
parts := strings.SplitN(args[i], ":", 2)
if len(parts) != 2 {
return env, resourceGroupMapping, accessMap, fall, c.Errf("invalid resource group/zone: %q", args[i])

View File

@ -603,7 +603,7 @@ func BenchmarkCacheResponse(b *testing.B) {
b.StartTimer()
j := 0
for i := 0; i < b.N; i++ {
for range b.N {
req := reqs[j]
c.ServeDNS(ctx, &test.ResponseWriter{}, req)
j = (j + 1) % 5

View File

@ -211,7 +211,7 @@ func (h *CloudDNS) updateZones(ctx context.Context) error {
// Collect errors (if any). This will also sync on all zones updates
// completion.
var errs []string
for i := 0; i < len(h.zones); i++ {
for range len(h.zones) {
err := <-errc
if err != nil {
errs = append(errs, err.Error())

View File

@ -43,7 +43,7 @@ func setup(c *caddy.Controller) error {
args := c.RemainingArgs()
for i := 0; i < len(args); i++ {
for i := range args {
parts := strings.SplitN(args[i], ":", 3)
if len(parts) != 3 {
return plugin.Error("clouddns", c.Errf("invalid zone %q", args[i]))

View File

@ -57,7 +57,7 @@ func hexdump(data []byte) []byte {
b := new(bytes.Buffer)
newline := ""
for i := 0; i < len(data); i++ {
for i := range data {
if i%16 == 0 {
fmt.Fprintf(b, "%s%s%06x", newline, prefix, i)
newline = "\n"

View File

@ -30,7 +30,7 @@ func accept(t *testing.T, l net.Listener, count int) {
t.Fatalf("Server decoder: %s", err)
}
for i := 0; i < count; i++ {
for range count {
if _, err := dec.Decode(); err != nil {
t.Errorf("Server decode: %s", err)
}
@ -96,7 +96,7 @@ func TestRace(t *testing.T) {
defer dio.close()
wg.Add(count)
for i := 0; i < count; i++ {
for range count {
go func() {
tmsg := tap.Dnstap_MESSAGE
dio.Dnstap(&tap.Dnstap{Type: &tmsg})
@ -147,7 +147,7 @@ func TestReconnect(t *testing.T) {
wg.Done()
}()
for i := 0; i < count; i++ {
for range count {
time.Sleep(100 * time.Millisecond)
dio.Dnstap(&tmsg)
}

View File

@ -57,7 +57,7 @@ func (e *Erratic) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg
rr.Header().Name = state.QName()
m.Answer = append(m.Answer, &rr)
if e.large {
for i := 0; i < 29; i++ {
for range 29 {
m.Answer = append(m.Answer, &rr)
}
}

View File

@ -18,7 +18,7 @@ func BenchmarkServeDNS(b *testing.B) {
w := &test.ResponseWriter{}
ctx := context.TODO()
for i := 0; i < b.N; i++ {
for range b.N {
_, err := h.ServeDNS(ctx, w, r)
if err != nil {
b.Errorf("ServeDNS returned error: %s", err)

View File

@ -164,7 +164,7 @@ func split255(s string) []string {
// targetStrip strips "targetstrip" labels from the left side of the fully qualified name.
func targetStrip(name string, targetStrip int) string {
offset, end := 0, false
for i := 0; i < targetStrip; i++ {
for range targetStrip {
offset, end = dns.NextLabel(name, offset)
}
if end {

View File

@ -8,7 +8,7 @@ func TestSplit255(t *testing.T) {
t.Errorf("Failure to split abc")
}
s := ""
for i := 0; i < 255; i++ {
for range 255 {
s += "a"
}
xs = split255(s)
@ -20,7 +20,7 @@ func TestSplit255(t *testing.T) {
if len(xs) != 2 || xs[1] != "b" {
t.Errorf("Failure to split 256 char long string: %d", len(xs))
}
for i := 0; i < 255; i++ {
for range 255 {
s += "a"
}
xs = split255(s)

View File

@ -169,7 +169,7 @@ func BenchmarkFileLookupDNSSEC(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
for range b.N {
fm.ServeDNS(ctx, rec, m)
}
}

View File

@ -6,7 +6,7 @@ import (
)
func BenchmarkFileParseInsert(b *testing.B) {
for i := 0; i < b.N; i++ {
for range b.N {
Parse(strings.NewReader(dbMiekENTNL), testzone, "stdin", 0)
}
}

View File

@ -318,7 +318,7 @@ func BenchmarkFileLookup(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
for range b.N {
fm.ServeDNS(ctx, rec, m)
}
}

View File

@ -63,7 +63,7 @@ Tests:
}
sort.Sort(set(test.in))
for i := 0; i < len(test.in); i++ {
for i := range len(test.in) {
if test.in[i] != test.out[i] {
t.Errorf("Test %d: expected %s, got %s", j, test.out[i], test.in[i])
n := ""

View File

@ -176,7 +176,7 @@ func parseBlock(c *caddy.Controller, f *Forward) error {
if len(ignore) == 0 {
return c.ArgErr()
}
for i := 0; i < len(ignore); i++ {
for i := range ignore {
f.ignored = append(f.ignored, plugin.Host(ignore[i]).NormalizeExact()...)
}
case "max_fails":

View File

@ -103,7 +103,7 @@ func parseBlock(c *caddy.Controller, g *GRPC) error {
if len(ignore) == 0 {
return c.ArgErr()
}
for i := 0; i < len(ignore); i++ {
for i := range ignore {
g.ignored = append(g.ignored, plugin.Host(ignore[i]).NormalizeExact()...)
}
case "tls":

View File

@ -70,7 +70,7 @@ func BenchmarkController(b *testing.B) {
m.SetQuestion("svc1.testns.svc.cluster.local.", dns.TypeA)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for range b.N {
k.ServeDNS(ctx, rw, m)
}
}

View File

@ -259,7 +259,7 @@ func emitAddressRecord(c chan<- []dns.RR, s msg.Service) string {
func calcSRVWeight(numservices int) uint16 {
var services []msg.Service
for i := 0; i < numservices; i++ {
for range numservices {
services = append(services, msg.Service{})
}

View File

@ -72,7 +72,7 @@ func roundRobinShuffle(records []dns.RR) {
records[0], records[1] = records[1], records[0]
}
default:
for j := 0; j < l; j++ {
for j := range l {
p := j + (int(dns.Id()) % (l - j))
if j == p {
continue

View File

@ -274,7 +274,7 @@ func BenchmarkLogged(b *testing.B) {
rec := dnstest.NewRecorder(&test.ResponseWriter{})
b.StartTimer()
for i := 0; i < b.N; i++ {
for range b.N {
logger.ServeDNS(ctx, rec, r)
}
}

View File

@ -38,7 +38,7 @@ func New(size int) *Cache {
c := &Cache{}
// Initialize all the shards
for i := 0; i < shardSize; i++ {
for i := range shardSize {
c.shards[i] = newShard(ssize)
}
return c

View File

@ -13,10 +13,10 @@ func TestCacheAddAndGet(t *testing.T) {
t.Fatal("Failed to find inserted record")
}
for i := 0; i < N; i++ {
for i := range N {
c.Add(uint64(i), 1)
}
for i := 0; i < N; i++ {
for i := range N {
c.Add(uint64(i), 1)
if c.Len() != N {
t.Fatal("A item was unnecessarily evicted from the cache")
@ -45,7 +45,7 @@ func TestCacheLen(t *testing.T) {
func TestCacheSharding(t *testing.T) {
c := New(shardSize)
for i := 0; i < shardSize*2; i++ {
for i := range shardSize * 2 {
c.Add(uint64(i), 1)
}
for i, s := range c.shards {
@ -58,7 +58,7 @@ func TestCacheSharding(t *testing.T) {
func TestCacheWalk(t *testing.T) {
c := New(10)
exp := make([]int, 10*2)
for i := 0; i < 10*2; i++ {
for i := range 10 * 2 {
c.Add(uint64(i), 1)
exp[i] = 1
}
@ -78,7 +78,7 @@ func BenchmarkCache(b *testing.B) {
b.ReportAllocs()
c := New(4)
for n := 0; n < b.N; n++ {
for range b.N {
c.Add(1, 1)
c.Get(1)
}

View File

@ -26,11 +26,11 @@ func TestAddEvict(t *testing.T) {
const size = 1024
s := newShard(size)
for i := uint64(0); i < size; i++ {
s.Add(i, 1)
for i := range size {
s.Add(uint64(i), 1)
}
for i := uint64(0); i < size; i++ {
s.Add(i, 1)
for i := range size {
s.Add(uint64(i), 1)
if s.Len() != size {
t.Fatal("A item was unnecessarily evicted from the cache")
}
@ -86,7 +86,7 @@ func TestShardLenEvict(t *testing.T) {
// Make sure we don't accidentally evict an element when
// we the key is already stored.
for i := 0; i < 4; i++ {
for range 4 {
s.Add(5, 1)
if l := s.Len(); l != 4 {
t.Fatalf("Shard size should %d, got %d", 4, l)
@ -96,12 +96,12 @@ func TestShardLenEvict(t *testing.T) {
func TestShardEvictParallel(t *testing.T) {
s := newShard(shardSize)
for i := uint64(0); i < shardSize; i++ {
s.Add(i, struct{}{})
for i := range shardSize {
s.Add(uint64(i), struct{}{})
}
start := make(chan struct{})
var wg sync.WaitGroup
for i := 0; i < shardSize; i++ {
for range shardSize {
wg.Add(1)
go func() {
<-start
@ -119,7 +119,7 @@ func TestShardEvictParallel(t *testing.T) {
func BenchmarkShard(b *testing.B) {
s := newShard(shardSize)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for i := range b.N {
k := uint64(i) % shardSize * 2
s.Add(k, 1)
s.Get(k)

View File

@ -71,7 +71,7 @@ func Reverse(nets []string) []string {
nearest := (bits - ones) + mod
offset := 0
var end bool
for i := 0; i < nearest/sizeDigit; i++ {
for range nearest / sizeDigit {
offset, end = dns.NextLabel(r, offset)
if end {
break

View File

@ -28,7 +28,7 @@ func NewServer(f dns.HandlerFunc) *Server {
s1 := &dns.Server{} // udp
s2 := &dns.Server{} // tcp
for i := 0; i < 5; i++ { // 5 attempts
for range 5 { // 5 attempts
s2.Listener, _ = reuseport.Listen("tcp", ":0")
if s2.Listener == nil {
continue

View File

@ -43,7 +43,7 @@ func IsReverse(name string) int {
}
func reverse(slice []string) string {
for i := 0; i < len(slice)/2; i++ {
for i := range len(slice) / 2 {
j := len(slice) - i - 1
slice[i], slice[j] = slice[j], slice[i]
}
@ -58,12 +58,12 @@ func reverse(slice []string) string {
// b.a.9.8.7.6.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2
// is reversed to 2001:db8::567:89ab
func reverse6(slice []string) string {
for i := 0; i < len(slice)/2; i++ {
for i := range len(slice) / 2 {
j := len(slice) - i - 1
slice[i], slice[j] = slice[j], slice[i]
}
slice6 := []string{}
for i := 0; i < len(slice)/4; i++ {
for i := range len(slice) / 4 {
slice6 = append(slice6, strings.Join(slice[i*4:i*4+4], ""))
}
ip := net.ParseIP(strings.Join(slice6, ":")).To16()

View File

@ -63,7 +63,7 @@ func BenchmarkMinimalTTL(b *testing.B) {
mt, _ := response.Typify(m, utc)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for range b.N {
dur := MinimalTTL(m, mt)
if dur != 1000*time.Second {
b.Fatalf("Wrong MinimalTTL %d, expected %d", dur, 1000*time.Second)

View File

@ -242,7 +242,7 @@ func TestDial_MultipleCallsAfterStop(t *testing.T) {
tr.Stop()
time.Sleep(50 * time.Millisecond)
for i := 0; i < 3; i++ {
for i := range 3 {
_, _, err := tr.Dial("udp")
if err == nil {
t.Errorf("Attempt %d: %s: %s", i+1, testMsgExpectedError, testMsgUnexpectedNilError)

View File

@ -47,7 +47,7 @@ func TestIntDeterministic(t *testing.T) {
r2 := New(seed)
// They should produce the same sequence
for i := 0; i < 10; i++ {
for i := range 10 {
val1 := r1.Int()
val2 := r2.Int()
if val1 != val2 {
@ -123,11 +123,11 @@ func TestConcurrentAccess(t *testing.T) {
errors := make(chan error, numGoroutines*numOperations)
// Test concurrent Int() calls
for i := 0; i < numGoroutines; i++ {
for range numGoroutines {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < numOperations; j++ {
for range numOperations {
val := r.Int()
if val < 0 {
errors <- nil
@ -137,11 +137,11 @@ func TestConcurrentAccess(t *testing.T) {
}
// Test concurrent Perm() calls
for i := 0; i < numGoroutines; i++ {
for range numGoroutines {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < numOperations; j++ {
for range numOperations {
perm := r.Perm(5)
if len(perm) != 5 {
errors <- nil
@ -172,11 +172,11 @@ func TestConcurrentMixedOperations(t *testing.T) {
errors := make(chan error, numGoroutines*numOperations)
// Mix of Int() and Perm() operations running concurrently
for i := 0; i < numGoroutines; i++ {
for i := range numGoroutines {
wg.Add(1)
go func(id int) {
defer wg.Done()
for j := 0; j < numOperations; j++ {
for j := range numOperations {
if j%2 == 0 {
val := r.Int()
if val < 0 {

View File

@ -276,7 +276,7 @@ func BenchmarkReplacer(b *testing.B) {
b.ReportAllocs()
replacer := New()
for i := 0; i < b.N; i++ {
for range b.N {
replacer.Replace(context.TODO(), state, nil, "{type} {name} {size}")
}
}
@ -297,13 +297,13 @@ func BenchmarkReplacer_CommonLogFormat(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for range b.N {
replacer.Replace(ctxt, state, w, CommonLogFormat)
}
}
func BenchmarkParseFormat(b *testing.B) {
for i := 0; i < b.N; i++ {
for range b.N {
parseFormat(CommonLogFormat)
}
}

View File

@ -63,7 +63,7 @@ func TestDoDupSuppress(t *testing.T) {
const n = 10
var wg sync.WaitGroup
for i := 0; i < n; i++ {
for range n {
wg.Add(1)
go func() {
v, err := g.Do(1, fn)

View File

@ -428,7 +428,7 @@ func hasClosingDot(s string) bool {
// getSubExprUsage returns the number of subexpressions used in s.
func getSubExprUsage(s string) int {
subExprUsage := 0
for i := 0; i <= 100; i++ {
for i := range 101 {
if strings.Contains(s, "{"+strconv.Itoa(i)+"}") {
subExprUsage++
}

View File

@ -278,7 +278,7 @@ func (h *Route53) updateZones(ctx context.Context) error {
// Collect errors (if any). This will also sync on all zones updates
// completion.
var errs []string
for i := 0; i < len(h.zones); i++ {
for range len(h.zones) {
err := <-errc
if err != nil {
errs = append(errs, err.Error())

View File

@ -50,7 +50,7 @@ func setup(c *caddy.Controller) error {
args := c.RemainingArgs()
for i := 0; i < len(args); i++ {
for i := range args {
parts := strings.SplitN(args[i], ":", 2)
if len(parts) != 2 {
return plugin.Error("route53", c.Errf("invalid zone %q", args[i]))

View File

@ -41,7 +41,7 @@ func sendNotify(c *dns.Client, m *dns.Msg, s string) error {
var err error
code := dns.RcodeServerFailure
for i := 0; i < 3; i++ {
for range 3 {
ret, _, err := c.Exchange(m, s)
if err != nil {
continue

View File

@ -257,15 +257,15 @@ func TestTruncation(t *testing.T) {
reply := new(dns.Msg)
reply.SetReply(m)
for i := 0; i < 61; i++ {
for i := range 61 {
reply.Answer = append(reply.Answer, test.SRV(fmt.Sprintf("http.service.tcp.srv.k8s.example.org. 5 IN SRV 0 0 80 10-144-230-%d.default.pod.k8s.example.org.", i)))
}
for i := 0; i < 5; i++ {
for i := range 5 {
reply.Extra = append(reply.Extra, test.A(fmt.Sprintf("ip-10-10-52-5%d.subdomain.example.org. 5 IN A 10.10.52.5%d", i, i)))
}
for i := 0; i < 5; i++ {
for i := range 5 {
reply.Ns = append(reply.Ns, test.NS(fmt.Sprintf("srv.subdomain.example.org. 5 IN NS ip-10-10-33-6%d.subdomain.example.org.", i)))
}
@ -319,7 +319,7 @@ func TestRequestMatch(t *testing.T) {
func BenchmarkRequestDo(b *testing.B) {
st := testRequest()
for i := 0; i < b.N; i++ {
for range b.N {
st.Do()
}
}
@ -327,7 +327,7 @@ func BenchmarkRequestDo(b *testing.B) {
func BenchmarkRequestSize(b *testing.B) {
st := testRequest()
for i := 0; i < b.N; i++ {
for range b.N {
st.Size()
}
}
@ -347,7 +347,7 @@ func BenchmarkRequestScrub(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for range b.N {
st.Scrub(reply.Copy())
}
}

View File

@ -46,7 +46,7 @@ func TestCompressScrub(t *testing.T) {
// compression. This means we're looking for a combo where the pointers is detected and the offset is 12
// the position of the first name after the header. The erratic plugin adds 30 RRs that should all be compressed.
found := 0
for i := 0; i < len(buf)-1; i++ {
for i := range len(buf) - 1 {
if buf[i]&0xC0 == 0xC0 {
off := (int(buf[i])^0xC0)<<8 | int(buf[i+1])
if off == 12 {

View File

@ -17,7 +17,7 @@ func TestLargeAXFR(t *testing.T) {
const numAAAAs = 6553
sb.WriteString("example.com. IN SOA . . 1 60 60 60 60\n")
sb.WriteString("example.com. IN NS ns.example.\n")
for i := 0; i < numAAAAs; i++ {
for i := range numAAAAs {
sb.WriteString(fmt.Sprintf("%d.example.com. IN AAAA 2001:db8::1\n", i))
}

View File

@ -163,7 +163,7 @@ func TestMetricsRewriteRequestSize(t *testing.T) {
}
// Send multiple requests
for i := 0; i < numRequests; i++ {
for range numRequests {
if _, err = dns.Exchange(m, udp); err != nil {
t.Fatalf("Could not send message: %s", err)
}
@ -195,7 +195,7 @@ func TestMetricsRewriteRequestSize(t *testing.T) {
defer srv2.Stop()
// Send the same requests with rewrite
for i := 0; i < numRequests; i++ {
for range numRequests {
if _, err = dns.Exchange(m, udp2); err != nil {
t.Fatalf("Could not send message: %s", err)
}

View File

@ -65,7 +65,7 @@ func TestProxyThreeWay(t *testing.T) {
c := new(dns.Client)
c.Timeout = 10 * time.Millisecond
for i := 0; i < 10; i++ {
for range 10 {
r, _, err := c.Exchange(m, addr)
if err != nil {
continue

View File

@ -71,7 +71,7 @@ func BenchmarkProxyLookup(b *testing.B) {
m.SetQuestion("example.org.", dns.TypeA)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for range b.N {
if _, err := dns.Exchange(m, udp); err != nil {
b.Fatal("Expected to receive reply, but didn't")
}

View File

@ -157,7 +157,7 @@ func TestQUICStreamLimits(t *testing.T) {
streamsMu := sync.Mutex{}
// Attempt to open exactly the configured number of streams
for i := 0; i < streamCount; i++ {
for i := range streamCount {
wg.Add(1)
go func(idx int) {
defer wg.Done()
@ -237,7 +237,7 @@ func TestQUICStreamLimits(t *testing.T) {
done := make(chan struct{})
// Launch goroutines to attempt opening additional streams
for i := 0; i < extraCount; i++ {
for i := range extraCount {
extraWg.Add(1)
go func(idx int) {
defer extraWg.Done()

View File

@ -181,7 +181,7 @@ func TestReloadSeveralTimeMetrics(t *testing.T) {
t.Errorf("Prometheus is not listening : %s", err)
}
reloadCount := 2
for i := 0; i < reloadCount; i++ {
for i := range reloadCount {
serverReload, err := serverWithMetrics.Restart(
NewInput(corefileWithMetrics),
)
@ -305,7 +305,7 @@ func TestMetricsAvailableAfterReloadAndFailedReload(t *testing.T) {
t.Errorf("Could not scrap one of expected stats : %s", err)
}
for i := 0; i < 2; i++ {
for range 2 {
// now provide a failed reload
invInst, err := inst.Restart(
NewInput(invalidCorefileWithMetrics),

View File

@ -72,7 +72,7 @@ func TestSecondaryZoneTransfer(t *testing.T) {
var r *dns.Msg
// This is now async; we need to wait for it to be transferred.
for i := 0; i < 10; i++ {
for range 10 {
r, _ = dns.Exchange(m, udp)
if len(r.Answer) != 0 {
break
@ -114,7 +114,7 @@ func TestIxfrResponse(t *testing.T) {
c := new(dns.Client)
c.Net = "tcp"
// This is now async; we need to wait for it to be transferred.
for i := 0; i < 10; i++ {
for range 10 {
r, _, _ = c.Exchange(m, tcp)
if len(r.Answer) != 0 {
break

View File

@ -127,7 +127,7 @@ func TestMultiZoneBlockConfigs(t *testing.T) {
server *caddy.Instance
err error
)
for j := 0; j < 3; j++ {
for j := range 3 {
corefile := `.:%d .:%d .:%d {
debug
}`
@ -150,7 +150,7 @@ func TestMultiZoneBlockConfigs(t *testing.T) {
configs := reflect.ValueOf(ctxVal2.Interface()).Elem().FieldByName("configs")
configs2 := reflect.NewAt(configs.Type(), unsafe.Pointer(configs.UnsafeAddr())).Elem()
for i := 0; i < 3; i++ {
for i := range 3 {
v := configs2.Index(i)
config := v.Interface().(*dnsserver.Config)
if !config.Debug {