Pull request 2195: upd-go-code

Squashed commit of the following:

commit a1bd3c249be043108c84a902d2e88bf80946d444
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Thu Apr 4 14:59:37 2024 +0300

    all: upd more

commit 9e55bbb02c2af2064aa2a2ca7b49fd28b544a02c
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Thu Apr 4 14:12:45 2024 +0300

    all: upd go code
This commit is contained in:
Ainar Garipov 2024-04-04 15:52:39 +03:00
parent 0e1e568899
commit ee619b2dbd
34 changed files with 64 additions and 111 deletions

2
go.mod
View File

@ -34,7 +34,7 @@ require (
go.etcd.io/bbolt v1.3.9 go.etcd.io/bbolt v1.3.9
golang.org/x/crypto v0.21.0 golang.org/x/crypto v0.21.0
golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 golang.org/x/exp v0.0.0-20240222234643-814bf88cf225
golang.org/x/net v0.22.0 golang.org/x/net v0.23.0
golang.org/x/sys v0.18.0 golang.org/x/sys v0.18.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1 gopkg.in/natefinch/lumberjack.v2 v2.2.1
gopkg.in/yaml.v3 v3.0.1 gopkg.in/yaml.v3 v3.0.1

4
go.sum
View File

@ -145,8 +145,8 @@ golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc=
golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc= golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=

View File

@ -10,29 +10,8 @@ import (
"golang.org/x/exp/constraints" "golang.org/x/exp/constraints"
) )
// Coalesce returns the first non-zero value. It is named after function
// COALESCE in SQL. If values or all its elements are empty, it returns a zero
// value.
//
// T is comparable, because Go currently doesn't have a comparableWithZeroValue
// constraint.
//
// TODO(a.garipov): Think of ways to merge with [CoalesceSlice].
func Coalesce[T comparable](values ...T) (res T) {
var zero T
for _, v := range values {
if v != zero {
return v
}
}
return zero
}
// CoalesceSlice returns the first non-zero value. It is named after function // CoalesceSlice returns the first non-zero value. It is named after function
// COALESCE in SQL. If values or all its elements are empty, it returns nil. // COALESCE in SQL. If values or all its elements are empty, it returns nil.
//
// TODO(a.garipov): Think of ways to merge with [Coalesce].
func CoalesceSlice[E any, S []E](values ...S) (res S) { func CoalesceSlice[E any, S []E](values ...S) (res S) {
for _, v := range values { for _, v := range values {
if v != nil { if v != nil {

View File

@ -33,7 +33,7 @@ func elements(b *aghalg.RingBuffer[int], n uint, reverse bool) (es []int) {
func TestNewRingBuffer(t *testing.T) { func TestNewRingBuffer(t *testing.T) {
t.Run("success_and_clear", func(t *testing.T) { t.Run("success_and_clear", func(t *testing.T) {
b := aghalg.NewRingBuffer[int](5) b := aghalg.NewRingBuffer[int](5)
for i := 0; i < 10; i++ { for i := range 10 {
b.Append(i) b.Append(i)
} }
assert.Equal(t, []int{5, 6, 7, 8, 9}, elements(b, b.Len(), false)) assert.Equal(t, []int{5, 6, 7, 8, 9}, elements(b, b.Len(), false))
@ -44,7 +44,7 @@ func TestNewRingBuffer(t *testing.T) {
t.Run("zero", func(t *testing.T) { t.Run("zero", func(t *testing.T) {
b := aghalg.NewRingBuffer[int](0) b := aghalg.NewRingBuffer[int](0)
for i := 0; i < 10; i++ { for i := range 10 {
b.Append(i) b.Append(i)
bufLen := b.Len() bufLen := b.Len()
assert.EqualValues(t, 0, bufLen) assert.EqualValues(t, 0, bufLen)
@ -55,7 +55,7 @@ func TestNewRingBuffer(t *testing.T) {
t.Run("single", func(t *testing.T) { t.Run("single", func(t *testing.T) {
b := aghalg.NewRingBuffer[int](1) b := aghalg.NewRingBuffer[int](1)
for i := 0; i < 10; i++ { for i := range 10 {
b.Append(i) b.Append(i)
bufLen := b.Len() bufLen := b.Len()
assert.EqualValues(t, 1, bufLen) assert.EqualValues(t, 1, bufLen)
@ -94,7 +94,7 @@ func TestRingBuffer_Range(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
for i := 0; i < tc.count; i++ { for i := range tc.count {
b.Append(i) b.Append(i)
} }

View File

@ -11,7 +11,7 @@ func TestNewSortedMap(t *testing.T) {
var m SortedMap[string, int] var m SortedMap[string, int]
letters := []string{} letters := []string{}
for i := 0; i < 10; i++ { for i := range 10 {
r := string('a' + rune(i)) r := string('a' + rune(i))
letters = append(letters, r) letters = append(letters, r)
} }

View File

@ -97,6 +97,8 @@ func (fw FileWalker) Walk(fsys fs.FS, initial ...string) (ok bool, err error) {
var filename string var filename string
defer func() { err = errors.Annotate(err, "checking %q: %w", filename) }() defer func() { err = errors.Annotate(err, "checking %q: %w", filename) }()
// TODO(e.burkov): Redo this loop, as it modifies the very same slice it
// iterates over.
for i := 0; i < len(src); i++ { for i := 0; i < len(src); i++ {
var patterns []string var patterns []string
var cont bool var cont bool

View File

@ -78,7 +78,6 @@ func TestWithDeferredCleanup(t *testing.T) {
}} }}
for _, tc := range testCases { for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
t.Parallel() t.Parallel()

View File

@ -91,8 +91,6 @@ func TestDefaultAddrProc_Process_rDNS(t *testing.T) {
}} }}
for _, tc := range testCases { for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
t.Parallel() t.Parallel()
@ -186,8 +184,6 @@ func TestDefaultAddrProc_Process_WHOIS(t *testing.T) {
}} }}
for _, tc := range testCases { for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
t.Parallel() t.Parallel()

View File

@ -1,5 +1,7 @@
package configmigrate package configmigrate
import "github.com/AdguardTeam/golibs/errors"
// migrateTo15 performs the following changes: // migrateTo15 performs the following changes:
// //
// # BEFORE: // # BEFORE:
@ -43,7 +45,7 @@ func migrateTo15(diskConf yobj) (err error) {
} }
diskConf["querylog"] = qlog diskConf["querylog"] = qlog
return coalesceError( return errors.Join(
moveVal[bool](dns, qlog, "querylog_enabled", "enabled"), moveVal[bool](dns, qlog, "querylog_enabled", "enabled"),
moveVal[bool](dns, qlog, "querylog_file_enabled", "file_enabled"), moveVal[bool](dns, qlog, "querylog_file_enabled", "file_enabled"),
moveVal[any](dns, qlog, "querylog_interval", "interval"), moveVal[any](dns, qlog, "querylog_interval", "interval"),

View File

@ -1,5 +1,7 @@
package configmigrate package configmigrate
import "github.com/AdguardTeam/golibs/errors"
// migrateTo24 performs the following changes: // migrateTo24 performs the following changes:
// //
// # BEFORE: // # BEFORE:
@ -28,7 +30,7 @@ func migrateTo24(diskConf yobj) (err error) {
diskConf["schema_version"] = 24 diskConf["schema_version"] = 24
logObj := yobj{} logObj := yobj{}
err = coalesceError( err = errors.Join(
moveVal[string](diskConf, logObj, "log_file", "file"), moveVal[string](diskConf, logObj, "log_file", "file"),
moveVal[int](diskConf, logObj, "log_max_backups", "max_backups"), moveVal[int](diskConf, logObj, "log_max_backups", "max_backups"),
moveVal[int](diskConf, logObj, "log_max_size", "max_size"), moveVal[int](diskConf, logObj, "log_max_size", "max_size"),

View File

@ -1,5 +1,7 @@
package configmigrate package configmigrate
import "github.com/AdguardTeam/golibs/errors"
// migrateTo26 performs the following changes: // migrateTo26 performs the following changes:
// //
// # BEFORE: // # BEFORE:
@ -78,7 +80,7 @@ func migrateTo26(diskConf yobj) (err error) {
} }
filteringObj := yobj{} filteringObj := yobj{}
err = coalesceError( err = errors.Join(
moveSameVal[bool](dns, filteringObj, "filtering_enabled"), moveSameVal[bool](dns, filteringObj, "filtering_enabled"),
moveSameVal[int](dns, filteringObj, "filters_update_interval"), moveSameVal[int](dns, filteringObj, "filters_update_interval"),
moveSameVal[bool](dns, filteringObj, "parental_enabled"), moveSameVal[bool](dns, filteringObj, "parental_enabled"),

View File

@ -1,5 +1,7 @@
package configmigrate package configmigrate
import "github.com/AdguardTeam/golibs/errors"
// migrateTo7 performs the following changes: // migrateTo7 performs the following changes:
// //
// # BEFORE: // # BEFORE:
@ -37,7 +39,7 @@ func migrateTo7(diskConf yobj) (err error) {
} }
dhcpv4 := yobj{} dhcpv4 := yobj{}
err = coalesceError( err = errors.Join(
moveSameVal[string](dhcp, dhcpv4, "gateway_ip"), moveSameVal[string](dhcp, dhcpv4, "gateway_ip"),
moveSameVal[string](dhcp, dhcpv4, "subnet_mask"), moveSameVal[string](dhcp, dhcpv4, "subnet_mask"),
moveSameVal[string](dhcp, dhcpv4, "range_start"), moveSameVal[string](dhcp, dhcpv4, "range_start"),

View File

@ -50,19 +50,3 @@ func moveVal[T any](src, dst yobj, srcKey, dstKey string) (err error) {
func moveSameVal[T any](src, dst yobj, key string) (err error) { func moveSameVal[T any](src, dst yobj, key string) (err error) {
return moveVal[T](src, dst, key, key) return moveVal[T](src, dst, key, key)
} }
// coalesceError returns the first non-nil error. It is named after function
// COALESCE in SQL. If all errors are nil, it returns nil.
//
// TODO(e.burkov): Replace with [errors.Join].
//
// TODO(a.garipov): Think of ways to merge with [aghalg.Coalesce].
func coalesceError(errors ...error) (res error) {
for _, err := range errors {
if err != nil {
return err
}
}
return nil
}

View File

@ -266,7 +266,6 @@ func TestServer_HandleDNSRequest_dns64(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
upsHdlr := dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) { upsHdlr := dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) {
q := req.Question[0] q := req.Question[0]

View File

@ -2,6 +2,7 @@
package dnsforward package dnsforward
import ( import (
"cmp"
"context" "context"
"fmt" "fmt"
"io" "io"
@ -15,7 +16,6 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/client" "github.com/AdguardTeam/AdGuardHome/internal/client"
"github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/AdGuardHome/internal/filtering"
@ -908,5 +908,5 @@ func (s *Server) IsBlockedClient(ip netip.Addr, clientID string) (blocked bool,
blocked = true blocked = true
} }
return blocked, aghalg.Coalesce(rule, clientID) return blocked, cmp.Or(rule, clientID)
} }

View File

@ -1,6 +1,7 @@
package dnsforward package dnsforward
import ( import (
"cmp"
"context" "context"
"crypto/ecdsa" "crypto/ecdsa"
"crypto/rand" "crypto/rand"
@ -21,7 +22,6 @@ import (
"testing/fstest" "testing/fstest"
"time" "time"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/aghtest" "github.com/AdguardTeam/AdGuardHome/internal/aghtest"
"github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/AdGuardHome/internal/filtering"
@ -190,7 +190,7 @@ func newGoogleUpstream() (u upstream.Upstream) {
return &aghtest.UpstreamMock{ return &aghtest.UpstreamMock{
OnAddress: func() (addr string) { return "google.upstream.example" }, OnAddress: func() (addr string) { return "google.upstream.example" },
OnExchange: func(req *dns.Msg) (resp *dns.Msg, err error) { OnExchange: func(req *dns.Msg) (resp *dns.Msg, err error) {
return aghalg.Coalesce( return cmp.Or(
aghtest.MatchedResponse(req, dns.TypeA, googleDomainName, "8.8.8.8"), aghtest.MatchedResponse(req, dns.TypeA, googleDomainName, "8.8.8.8"),
new(dns.Msg).SetRcode(req, dns.RcodeNameError), new(dns.Msg).SetRcode(req, dns.RcodeNameError),
), nil ), nil
@ -253,7 +253,7 @@ func sendTestMessagesAsync(t *testing.T, conn *dns.Conn) {
wg := &sync.WaitGroup{} wg := &sync.WaitGroup{}
for i := 0; i < testMessagesCount; i++ { for range testMessagesCount {
msg := createGoogleATestMessage() msg := createGoogleATestMessage()
wg.Add(1) wg.Add(1)
@ -276,7 +276,7 @@ func sendTestMessagesAsync(t *testing.T, conn *dns.Conn) {
func sendTestMessages(t *testing.T, conn *dns.Conn) { func sendTestMessages(t *testing.T, conn *dns.Conn) {
t.Helper() t.Helper()
for i := 0; i < testMessagesCount; i++ { for i := range testMessagesCount {
req := createGoogleATestMessage() req := createGoogleATestMessage()
err := conn.WriteMsg(req) err := conn.WriteMsg(req)
assert.NoErrorf(t, err, "cannot write message #%d: %s", i, err) assert.NoErrorf(t, err, "cannot write message #%d: %s", i, err)
@ -691,7 +691,7 @@ func TestServerCustomClientUpstream(t *testing.T) {
ups := aghtest.NewUpstreamMock(func(req *dns.Msg) (resp *dns.Msg, err error) { ups := aghtest.NewUpstreamMock(func(req *dns.Msg) (resp *dns.Msg, err error) {
atomic.AddUint32(&upsCalledCounter, 1) atomic.AddUint32(&upsCalledCounter, 1)
return aghalg.Coalesce( return cmp.Or(
aghtest.MatchedResponse(req, dns.TypeA, "host", "192.168.0.1"), aghtest.MatchedResponse(req, dns.TypeA, "host", "192.168.0.1"),
new(dns.Msg).SetRcode(req, dns.RcodeNameError), new(dns.Msg).SetRcode(req, dns.RcodeNameError),
), nil ), nil
@ -1152,7 +1152,7 @@ func TestRewrite(t *testing.T) {
})) }))
ups := aghtest.NewUpstreamMock(func(req *dns.Msg) (resp *dns.Msg, err error) { ups := aghtest.NewUpstreamMock(func(req *dns.Msg) (resp *dns.Msg, err error) {
return aghalg.Coalesce( return cmp.Or(
aghtest.MatchedResponse(req, dns.TypeA, "example.org", "4.3.2.1"), aghtest.MatchedResponse(req, dns.TypeA, "example.org", "4.3.2.1"),
new(dns.Msg).SetRcode(req, dns.RcodeNameError), new(dns.Msg).SetRcode(req, dns.RcodeNameError),
), nil ), nil
@ -1481,7 +1481,7 @@ func TestServer_Exchange(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
extUpsHdlr := dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) { extUpsHdlr := dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) {
resp := aghalg.Coalesce( resp := cmp.Or(
aghtest.MatchedResponse(req, dns.TypePTR, onesRevExtIPv4, dns.Fqdn(onesHost)), aghtest.MatchedResponse(req, dns.TypePTR, onesRevExtIPv4, dns.Fqdn(onesHost)),
doubleTTL(aghtest.MatchedResponse(req, dns.TypePTR, twosRevExtIPv4, dns.Fqdn(twosHost))), doubleTTL(aghtest.MatchedResponse(req, dns.TypePTR, twosRevExtIPv4, dns.Fqdn(twosHost))),
new(dns.Msg).SetRcode(req, dns.RcodeNameError), new(dns.Msg).SetRcode(req, dns.RcodeNameError),
@ -1495,7 +1495,7 @@ func TestServer_Exchange(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
locUpsHdlr := dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) { locUpsHdlr := dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) {
resp := aghalg.Coalesce( resp := cmp.Or(
aghtest.MatchedResponse(req, dns.TypePTR, revLocIPv4, dns.Fqdn(localDomainHost)), aghtest.MatchedResponse(req, dns.TypePTR, revLocIPv4, dns.Fqdn(localDomainHost)),
new(dns.Msg).SetRcode(req, dns.RcodeNameError), new(dns.Msg).SetRcode(req, dns.RcodeNameError),
) )

View File

@ -1,11 +1,11 @@
package dnsforward package dnsforward
import ( import (
"cmp"
"net" "net"
"net/netip" "net/netip"
"testing" "testing"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghtest" "github.com/AdguardTeam/AdGuardHome/internal/aghtest"
"github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/proxy"
@ -70,8 +70,6 @@ func TestServer_ProcessInitial(t *testing.T) {
}} }}
for _, tc := range testCases { for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
t.Parallel() t.Parallel()
@ -171,8 +169,6 @@ func TestServer_ProcessFilteringAfterResponse(t *testing.T) {
}} }}
for _, tc := range testCases { for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
t.Parallel() t.Parallel()
@ -667,7 +663,7 @@ func TestServer_ProcessRestrictLocal(t *testing.T) {
) )
localUpsHdlr := dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) { localUpsHdlr := dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) {
resp := aghalg.Coalesce( resp := cmp.Or(
aghtest.MatchedResponse(req, dns.TypePTR, extPTRQuestion, extPTRAnswer), aghtest.MatchedResponse(req, dns.TypePTR, extPTRQuestion, extPTRAnswer),
aghtest.MatchedResponse(req, dns.TypePTR, intPTRQuestion, intPTRAnswer), aghtest.MatchedResponse(req, dns.TypePTR, intPTRQuestion, intPTRAnswer),
new(dns.Msg).SetRcode(req, dns.RcodeNameError), new(dns.Msg).SetRcode(req, dns.RcodeNameError),
@ -756,7 +752,7 @@ func TestServer_ProcessLocalPTR_usingResolvers(t *testing.T) {
const reqAddr = "1.1.168.192.in-addr.arpa." const reqAddr = "1.1.168.192.in-addr.arpa."
localUpsHdlr := dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) { localUpsHdlr := dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) {
resp := aghalg.Coalesce( resp := cmp.Or(
aghtest.MatchedResponse(req, dns.TypePTR, reqAddr, locDomain), aghtest.MatchedResponse(req, dns.TypePTR, reqAddr, locDomain),
new(dns.Msg).SetRcode(req, dns.RcodeNameError), new(dns.Msg).SetRcode(req, dns.RcodeNameError),
) )

View File

@ -200,7 +200,7 @@ func TestParallelSB(t *testing.T) {
t.Cleanup(d.Close) t.Cleanup(d.Close)
t.Run("group", func(t *testing.T) { t.Run("group", func(t *testing.T) {
for i := 0; i < 100; i++ { for i := range 100 {
t.Run(fmt.Sprintf("aaa%d", i), func(t *testing.T) { t.Run(fmt.Sprintf("aaa%d", i), func(t *testing.T) {
t.Parallel() t.Parallel()
d.checkMatch(t, sbBlocked, setts) d.checkMatch(t, sbBlocked, setts)
@ -670,7 +670,7 @@ func BenchmarkSafeBrowsing(b *testing.B) {
}, nil) }, nil)
b.Cleanup(d.Close) b.Cleanup(d.Close)
for n := 0; n < b.N; n++ { for range b.N {
res, err := d.CheckHost(sbBlocked, dns.TypeA, setts) res, err := d.CheckHost(sbBlocked, dns.TypeA, setts)
require.NoError(b, err) require.NoError(b, err)

View File

@ -63,8 +63,6 @@ func TestIDGenerator_Fix(t *testing.T) {
}} }}
for _, tc := range testCases { for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
g := newIDGenerator(1) g := newIDGenerator(1)
g.fix(tc.in) g.fix(tc.in)

View File

@ -132,7 +132,6 @@ func TestParser_Parse(t *testing.T) {
}} }}
for _, tc := range testCases { for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
t.Parallel() t.Parallel()
@ -216,7 +215,7 @@ func BenchmarkParser_Parse(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for range b.N {
resSink, errSink = p.Parse(dst, src, buf) resSink, errSink = p.Parse(dst, src, buf)
dst.Reset() dst.Reset()
} }

View File

@ -127,7 +127,7 @@ var dnsRewriteSink *rules.DNSRewrite
func BenchmarkSafeSearch(b *testing.B) { func BenchmarkSafeSearch(b *testing.B) {
ss := newForTest(b, defaultSafeSearchConf) ss := newForTest(b, defaultSafeSearchConf)
for n := 0; n < b.N; n++ { for range b.N {
dnsRewriteSink = ss.searchHost(googleHost, testQType) dnsRewriteSink = ss.searchHost(googleHost, testQType)
} }

View File

@ -434,7 +434,7 @@ func (clients *clientsContainer) handleUpdateClient(w http.ResponseWriter, r *ht
func (clients *clientsContainer) handleFindClient(w http.ResponseWriter, r *http.Request) { func (clients *clientsContainer) handleFindClient(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query() q := r.URL.Query()
data := []map[string]*clientJSON{} data := []map[string]*clientJSON{}
for i := 0; i < len(q); i++ { for i := range len(q) {
idStr := q.Get(fmt.Sprintf("ip%d", i)) idStr := q.Get(fmt.Sprintf("ip%d", i))
if idStr == "" { if idStr == "" {
break break

View File

@ -1,13 +1,13 @@
package home package home
import ( import (
"cmp"
"fmt" "fmt"
"path/filepath" "path/filepath"
"runtime" "runtime"
"github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/stringutil"
"gopkg.in/natefinch/lumberjack.v2" "gopkg.in/natefinch/lumberjack.v2"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
@ -76,8 +76,7 @@ func getLogSettings(opts options) (ls *logSettings) {
ls.Verbose = true ls.Verbose = true
} }
// TODO(a.garipov): Use cmp.Or in Go 1.22. ls.File = cmp.Or(opts.logFile, ls.File)
ls.File = stringutil.Coalesce(opts.logFile, ls.File)
if opts.runningAsService && ls.File == "" && runtime.GOOS == "windows" { if opts.runningAsService && ls.File == "" && runtime.GOOS == "windows" {
// When running as a Windows service, use eventlog by default if // When running as a Windows service, use eventlog by default if

View File

@ -3,6 +3,7 @@
package home package home
import ( import (
"cmp"
"fmt" "fmt"
"os" "os"
"os/signal" "os/signal"
@ -14,7 +15,6 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/stringutil"
"github.com/kardianos/service" "github.com/kardianos/service"
) )
@ -76,7 +76,7 @@ func (*openbsdRunComService) Platform() (p string) {
// String implements service.Service interface for *openbsdRunComService. // String implements service.Service interface for *openbsdRunComService.
func (s *openbsdRunComService) String() string { func (s *openbsdRunComService) String() string {
return stringutil.Coalesce(s.cfg.DisplayName, s.cfg.Name) return cmp.Or(s.cfg.DisplayName, s.cfg.Name)
} }
// getBool returns the value of the given name from kv, assuming the value is a // getBool returns the value of the given name from kv, assuming the value is a

View File

@ -147,7 +147,7 @@ func BenchmarkManager_LookupHost(b *testing.B) {
b.Run("long", func(b *testing.B) { b.Run("long", func(b *testing.B) {
const name = "a.very.long.domain.name.inside.the.domain.example.com" const name = "a.very.long.domain.name.inside.the.domain.example.com"
for i := 0; i < b.N; i++ { for range b.N {
ipsetPropsSink = m.lookupHost(name) ipsetPropsSink = m.lookupHost(name)
} }
@ -156,7 +156,7 @@ func BenchmarkManager_LookupHost(b *testing.B) {
b.Run("short", func(b *testing.B) { b.Run("short", func(b *testing.B) {
const name = "example.net" const name = "example.net"
for i := 0; i < b.N; i++ { for range b.N {
ipsetPropsSink = m.lookupHost(name) ipsetPropsSink = m.lookupHost(name)
} }

View File

@ -303,7 +303,7 @@ func BenchmarkAnonymizeIP(b *testing.B) {
b.Run(bc.name, func(b *testing.B) { b.Run(bc.name, func(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
for i := 0; i < b.N; i++ { for range b.N {
AnonymizeIP(bc.ip) AnonymizeIP(bc.ip)
} }
@ -313,7 +313,7 @@ func BenchmarkAnonymizeIP(b *testing.B) {
b.Run(bc.name+"_slow", func(b *testing.B) { b.Run(bc.name+"_slow", func(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
for i := 0; i < b.N; i++ { for range b.N {
anonymizeIPSlow(bc.ip) anonymizeIPSlow(bc.ip)
} }

View File

@ -143,13 +143,13 @@ func TestQueryLogOffsetLimit(t *testing.T) {
secondPageDomain = "second.example.org" secondPageDomain = "second.example.org"
) )
// Add entries to the log. // Add entries to the log.
for i := 0; i < entNum; i++ { for range entNum {
addEntry(l, secondPageDomain, net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1)) addEntry(l, secondPageDomain, net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1))
} }
// Write them to the first file. // Write them to the first file.
require.NoError(t, l.flushLogBuffer()) require.NoError(t, l.flushLogBuffer())
// Add more to the in-memory part of log. // Add more to the in-memory part of log.
for i := 0; i < entNum; i++ { for range entNum {
addEntry(l, firstPageDomain, net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1)) addEntry(l, firstPageDomain, net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1))
} }
@ -215,7 +215,7 @@ func TestQueryLogMaxFileScanEntries(t *testing.T) {
const entNum = 10 const entNum = 10
// Add entries to the log. // Add entries to the log.
for i := 0; i < entNum; i++ { for range entNum {
addEntry(l, "example.org", net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1)) addEntry(l, "example.org", net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1))
} }
// Write them to disk. // Write them to disk.

View File

@ -37,7 +37,7 @@ func prepareTestFile(t *testing.T, dir string, linesNum int) (name string) {
var lineIP uint32 var lineIP uint32
lineTime := time.Date(2020, 2, 18, 19, 36, 35, 920973000, time.UTC) lineTime := time.Date(2020, 2, 18, 19, 36, 35, 920973000, time.UTC)
for i := 0; i < linesNum; i++ { for range linesNum {
lineIP++ lineIP++
lineTime = lineTime.Add(time.Second) lineTime = lineTime.Add(time.Second)

View File

@ -68,13 +68,13 @@ func TestStats_races(t *testing.T) {
startWG, finWG := &sync.WaitGroup{}, &sync.WaitGroup{} startWG, finWG := &sync.WaitGroup{}, &sync.WaitGroup{}
waitCh := make(chan unit) waitCh := make(chan unit)
for i := 0; i < writersNum; i++ { for i := range writersNum {
startWG.Add(1) startWG.Add(1)
finWG.Add(1) finWG.Add(1)
go writeFunc(startWG, finWG, waitCh, i) go writeFunc(startWG, finWG, waitCh, i)
} }
for i := 0; i < readersNum; i++ { for range readersNum {
startWG.Add(1) startWG.Add(1)
finWG.Add(1) finWG.Add(1)
go readFunc(startWG, finWG, waitCh) go readFunc(startWG, finWG, waitCh)
@ -111,7 +111,7 @@ func TestStatsCtx_FillCollectedStats_daily(t *testing.T) {
dailyData := []*unitDB{} dailyData := []*unitDB{}
for i := 0; i < daysCount*24; i++ { for i := range daysCount * 24 {
n := uint64(i) n := uint64(i)
nResult := make([]uint64, resultLast) nResult := make([]uint64, resultLast)
nResult[RFiltered] = n nResult[RFiltered] = n

View File

@ -195,7 +195,7 @@ func TestLargeNumbers(t *testing.T) {
for h := 0; h < hoursNum; h++ { for h := 0; h < hoursNum; h++ {
atomic.AddUint32(&curHour, 1) atomic.AddUint32(&curHour, 1)
for i := 0; i < cliNumPerHour; i++ { for i := range cliNumPerHour {
ip := net.IP{127, 0, byte((i & 0xff00) >> 8), byte(i & 0xff)} ip := net.IP{127, 0, byte((i & 0xff00) >> 8), byte(i & 0xff)}
e := &stats.Entry{ e := &stats.Entry{
Domain: fmt.Sprintf("domain%d.hour%d", i, h), Domain: fmt.Sprintf("domain%d.hour%d", i, h),

View File

@ -525,9 +525,8 @@ func (s *StatsCtx) fillCollectedStatsDaily(
hours := countHours(curHour, days) hours := countHours(curHour, days)
units = units[len(units)-hours:] units = units[len(units)-hours:]
for i := 0; i < len(units); i++ { for i, u := range units {
day := i / 24 day := i / 24
u := units[i]
data.DNSQueries[day] += u.NTotal data.DNSQueries[day] += u.NTotal
data.BlockedFiltering[day] += u.NResult[RFiltered] data.BlockedFiltering[day] += u.NResult[RFiltered]

View File

@ -3,6 +3,7 @@ package whois
import ( import (
"bytes" "bytes"
"cmp"
"context" "context"
"fmt" "fmt"
"io" "io"
@ -17,7 +18,6 @@ import (
"github.com/AdguardTeam/golibs/ioutil" "github.com/AdguardTeam/golibs/ioutil"
"github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/stringutil"
"github.com/bluele/gcache" "github.com/bluele/gcache"
) )
@ -174,7 +174,7 @@ func whoisParse(data []byte, maxLen int) (info map[string]string) {
val = trimValue(val, maxLen) val = trimValue(val, maxLen)
case "descr", "netname": case "descr", "netname":
key = "orgname" key = "orgname"
val = stringutil.Coalesce(orgname, val) val = cmp.Or(orgname, val)
orgname = val orgname = val
case "whois": case "whois":
key = "whois" key = "whois"
@ -232,7 +232,7 @@ func (w *Default) queryAll(ctx context.Context, target string) (info map[string]
server := net.JoinHostPort(w.serverAddr, w.portStr) server := net.JoinHostPort(w.serverAddr, w.portStr)
var data []byte var data []byte
for i := 0; i < w.maxRedirects; i++ { for range w.maxRedirects {
data, err = w.query(ctx, target, server) data, err = w.query(ctx, target, server)
if err != nil { if err != nil {
// Don't wrap the error since it's informative enough as is. // Don't wrap the error since it's informative enough as is.

View File

@ -48,7 +48,7 @@ func (c *twoskyClient) download() (err error) {
failed := &sync.Map{} failed := &sync.Map{}
uriCh := make(chan *url.URL, len(c.langs)) uriCh := make(chan *url.URL, len(c.langs))
for i := 0; i < numWorker; i++ { for range numWorker {
wg.Add(1) wg.Add(1)
go downloadWorker(wg, failed, client, uriCh) go downloadWorker(wg, failed, client, uriCh)
} }

View File

@ -5,6 +5,7 @@ package main
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"cmp"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/url" "net/url"
@ -204,19 +205,13 @@ type twoskyClient struct {
func (t *twoskyConfig) toClient() (cli *twoskyClient, err error) { func (t *twoskyConfig) toClient() (cli *twoskyClient, err error) {
defer func() { err = errors.Annotate(err, "filling config: %w") }() defer func() { err = errors.Annotate(err, "filling config: %w") }()
uriStr := os.Getenv("TWOSKY_URI") uriStr := cmp.Or(os.Getenv("TWOSKY_URI"), twoskyURI)
if uriStr == "" {
uriStr = twoskyURI
}
uri, err := url.Parse(uriStr) uri, err := url.Parse(uriStr)
if err != nil { if err != nil {
return nil, err return nil, err
} }
projectID := os.Getenv("TWOSKY_PROJECT_ID") projectID := cmp.Or(os.Getenv("TWOSKY_PROJECT_ID"), defaultProjectID)
if projectID == "" {
projectID = defaultProjectID
}
baseLang := t.BaseLangcode baseLang := t.BaseLangcode
uLangStr := os.Getenv("UPLOAD_LANGUAGE") uLangStr := os.Getenv("UPLOAD_LANGUAGE")