From 38a99938144090cd0e407c91e94b531328243c48 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Thu, 7 Nov 2024 13:16:25 +0100 Subject: [PATCH] chore: enable all rules of perfsprint linter (#6164) --- .golangci.yml | 8 +++----- cmd/agent/app/reporter/flags.go | 3 +-- cmd/collector/app/server/http_test.go | 5 +++-- cmd/ingester/app/consumer/consumer_test.go | 6 +++--- cmd/internal/status/command.go | 4 ++-- cmd/jaeger/internal/sanitizer/utf8_test.go | 8 ++++---- crossdock/services/common.go | 6 +----- crossdock/services/tracehandler_test.go | 4 ++-- examples/hotrod/pkg/log/spanlogger.go | 5 +++-- model/span_test.go | 3 ++- pkg/es/client/client.go | 2 +- pkg/es/client/ilm_client.go | 2 +- pkg/es/client/index_client.go | 16 ++++++++-------- pkg/fswatcher/fswatcher.go | 4 ++-- pkg/testutils/logger_test.go | 4 ++-- .../leaderelection/leader_election_test.go | 4 ++-- plugin/storage/badger/factory_test.go | 5 ++--- .../storage/badger/spanstore/read_write_test.go | 8 ++++---- plugin/storage/es/spanstore/reader.go | 3 ++- plugin/storage/es/spanstore/service_operation.go | 3 ++- .../storage/integration/es_index_cleaner_test.go | 4 ++-- 21 files changed, 52 insertions(+), 55 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 4386eebb341..7c4e9314df8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -18,8 +18,6 @@ issues: text: "exitAfterDefer" - linters: [gocritic] text: "appendAssign" - - linters: [perfsprint] - text: "fmt.Sprintf can be replaced" exclude-dirs-use-default: false exclude-dirs: - mocks @@ -160,15 +158,15 @@ linters-settings: - shadow perfsprint: # Optimizes even if it requires an int or uint type cast. - int-conversion: false + int-conversion: true # Optimizes into `err.Error()` even if it is only equivalent for non-nil errors. err-error: true # Optimizes `fmt.Errorf`. errorf: true # Optimizes `fmt.Sprintf` with only one argument. - sprintf1: false + sprintf1: true # Optimizes into strings concatenation. - strconcat: false + strconcat: true revive: ignore-generated-header: true severity: error diff --git a/cmd/agent/app/reporter/flags.go b/cmd/agent/app/reporter/flags.go index 7ba521b983b..5dca6444f18 100644 --- a/cmd/agent/app/reporter/flags.go +++ b/cmd/agent/app/reporter/flags.go @@ -5,7 +5,6 @@ package reporter import ( "flag" - "fmt" "github.com/spf13/viper" "go.uber.org/zap" @@ -34,7 +33,7 @@ type Options struct { // AddFlags adds flags for Options. func AddFlags(flagSet *flag.FlagSet) { - flagSet.String(reporterType, string(GRPC), fmt.Sprintf("Reporter type to use e.g. %s", string(GRPC))) + flagSet.String(reporterType, string(GRPC), "Reporter type to use e.g. "+string(GRPC)) if !setupcontext.IsAllInOne() { flagSet.String(agentTags, "", "One or more tags to be added to the Process tags of all spans passing through this agent. Ex: key1=value1,key2=${envVar:defaultValue}") } diff --git a/cmd/collector/app/server/http_test.go b/cmd/collector/app/server/http_test.go index fe2a1a9b4e0..46184bd8b89 100644 --- a/cmd/collector/app/server/http_test.go +++ b/cmd/collector/app/server/http_test.go @@ -9,6 +9,7 @@ import ( "net" "net/http" "net/http/httptest" + "strconv" "testing" "time" @@ -207,7 +208,7 @@ func TestSpanCollectorHTTPS(t *testing.T) { defer test.clientTLS.Close() require.NoError(t, err0) dialer := &net.Dialer{Timeout: 2 * time.Second} - conn, clientError := tls.DialWithDialer(dialer, "tcp", "localhost:"+fmt.Sprintf("%d", ports.CollectorHTTP), clientTLSCfg) + conn, clientError := tls.DialWithDialer(dialer, "tcp", "localhost:"+strconv.Itoa(ports.CollectorHTTP), clientTLSCfg) var clientClose func() error clientClose = nil if conn != nil { @@ -230,7 +231,7 @@ func TestSpanCollectorHTTPS(t *testing.T) { }, } - response, requestError := client.Post("https://localhost:"+fmt.Sprintf("%d", ports.CollectorHTTP), "", nil) + response, requestError := client.Post("https://localhost:"+strconv.Itoa(ports.CollectorHTTP), "", nil) if test.expectClientError { require.Error(t, requestError) diff --git a/cmd/ingester/app/consumer/consumer_test.go b/cmd/ingester/app/consumer/consumer_test.go index 05180ddd469..f69f2a78362 100644 --- a/cmd/ingester/app/consumer/consumer_test.go +++ b/cmd/ingester/app/consumer/consumer_test.go @@ -5,7 +5,7 @@ package consumer import ( "errors" - "fmt" + "strconv" "sync" "testing" "time" @@ -163,7 +163,7 @@ func TestSaramaConsumerWrapper_start_Messages(t *testing.T) { tags := map[string]string{ "topic": topic, - "partition": fmt.Sprint(partition), + "partition": strconv.Itoa(int(partition)), } localFactory.AssertCounterMetrics(t, metricstest.ExpectedMetric{ Name: "sarama-consumer.messages", @@ -217,7 +217,7 @@ func TestSaramaConsumerWrapper_start_Errors(t *testing.T) { tags := map[string]string{ "topic": topic, - "partition": fmt.Sprint(partition), + "partition": strconv.Itoa(int(partition)), } localFactory.AssertCounterMetrics(t, metricstest.ExpectedMetric{ Name: "sarama-consumer.errors", diff --git a/cmd/internal/status/command.go b/cmd/internal/status/command.go index ef8f3002784..02f2e48683a 100644 --- a/cmd/internal/status/command.go +++ b/cmd/internal/status/command.go @@ -58,7 +58,7 @@ func flags(flagSet *flag.FlagSet, adminPort int) *flag.FlagSet { func convert(httpHostPort string) string { if strings.HasPrefix(httpHostPort, ":") { - return fmt.Sprintf("http://127.0.0.1%s", httpHostPort) + return "http://127.0.0.1" + httpHostPort } - return fmt.Sprintf("http://%s", httpHostPort) + return "http://" + httpHostPort } diff --git a/cmd/jaeger/internal/sanitizer/utf8_test.go b/cmd/jaeger/internal/sanitizer/utf8_test.go index 4956d7e8d62..29c65faf92e 100644 --- a/cmd/jaeger/internal/sanitizer/utf8_test.go +++ b/cmd/jaeger/internal/sanitizer/utf8_test.go @@ -43,7 +43,7 @@ var utf8EncodingTests = []struct { key: invalidUTF8(), value: "value", expectedKey: "invalid-tag-key-1", - expectedValue: getBytesValueFromString(fmt.Sprintf("%s:value", invalidUTF8())), + expectedValue: getBytesValueFromString(invalidUTF8() + ":value"), }, { name: "valid key + invalid value", @@ -264,7 +264,7 @@ func TestUTF8Sanitizer_SanitizesNonStringAttributeValueWithInvalidKey(t *testing Attributes(). Get("invalid-tag-key-1") require.True(t, ok) - require.EqualValues(t, getBytesValueFromString(fmt.Sprintf("%s:99", invalidUTF8())), value) + require.EqualValues(t, getBytesValueFromString(invalidUTF8()+":99"), value) } func TestUTF8Sanitizer_SanitizesMultipleAttributesWithInvalidKeys(t *testing.T) { @@ -290,8 +290,8 @@ func TestUTF8Sanitizer_SanitizesMultipleAttributesWithInvalidKeys(t *testing.T) require.Equal(t, 2, got.Len()) expectedValues := []pcommon.Value{ - getBytesValueFromString(fmt.Sprintf("%s:v1", k1)), - getBytesValueFromString(fmt.Sprintf("%s:v2", k2)), + getBytesValueFromString(k1 + ":v1"), + getBytesValueFromString(k2 + ":v2"), } value, ok := got. Get("invalid-tag-key-1") diff --git a/crossdock/services/common.go b/crossdock/services/common.go index 891d9fd1a0e..93140ba9adb 100644 --- a/crossdock/services/common.go +++ b/crossdock/services/common.go @@ -4,10 +4,6 @@ package services -import ( - "fmt" -) - func getTracerServiceName(service string) string { - return fmt.Sprintf("crossdock-%s", service) + return "crossdock-" + service } diff --git a/crossdock/services/tracehandler_test.go b/crossdock/services/tracehandler_test.go index baf3634d8b9..64c35e3cf8e 100644 --- a/crossdock/services/tracehandler_test.go +++ b/crossdock/services/tracehandler_test.go @@ -7,10 +7,10 @@ package services import ( "encoding/json" "errors" - "fmt" "io" "net/http" "net/http/httptest" + "strconv" "sync" "testing" "time" @@ -414,7 +414,7 @@ func TestAdaptiveSamplingTestInternal(t *testing.T) { } for i, test := range tests { - t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { + t.Run(strconv.Itoa(i), func(t *testing.T) { query := &mocks.QueryService{} agent := &mocks.AgentService{} diff --git a/examples/hotrod/pkg/log/spanlogger.go b/examples/hotrod/pkg/log/spanlogger.go index 9a79951e100..72ec19cc646 100644 --- a/examples/hotrod/pkg/log/spanlogger.go +++ b/examples/hotrod/pkg/log/spanlogger.go @@ -6,6 +6,7 @@ package log import ( "fmt" + "strconv" "time" "go.opentelemetry.io/otel/attribute" @@ -138,11 +139,11 @@ func (e *bridgeFieldEncoder) AddTime(key string, value time.Time) { } func (e *bridgeFieldEncoder) AddUint(key string, value uint) { - e.pairs = append(e.pairs, attribute.String(key, fmt.Sprintf("%d", value))) + e.pairs = append(e.pairs, attribute.String(key, strconv.FormatUint(uint64(value), 10))) } func (e *bridgeFieldEncoder) AddUint64(key string, value uint64) { - e.pairs = append(e.pairs, attribute.String(key, fmt.Sprintf("%d", value))) + e.pairs = append(e.pairs, attribute.String(key, strconv.FormatUint(value, 10))) } func (e *bridgeFieldEncoder) AddUint32(key string, value uint32) { diff --git a/model/span_test.go b/model/span_test.go index 4e4844e7256..1c86746df42 100644 --- a/model/span_test.go +++ b/model/span_test.go @@ -7,6 +7,7 @@ package model_test import ( "bytes" "fmt" + "strconv" "testing" "time" @@ -482,7 +483,7 @@ func TestGetSamplerParams(t *testing.T) { for i, test := range tests { tt := test - t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { + t.Run(strconv.Itoa(i), func(t *testing.T) { span := &model.Span{} span.Tags = tt.tags actualType, actualParam := span.GetSamplerParams(logger) diff --git a/pkg/es/client/client.go b/pkg/es/client/client.go index 05900b9506e..3db076b9113 100644 --- a/pkg/es/client/client.go +++ b/pkg/es/client/client.go @@ -92,7 +92,7 @@ func (c *Client) request(esRequest elasticRequest) ([]byte, error) { func (c *Client) setAuthorization(r *http.Request) { if c.BasicAuth != "" { - r.Header.Add("Authorization", fmt.Sprintf("Basic %s", c.BasicAuth)) + r.Header.Add("Authorization", "Basic "+c.BasicAuth) } } diff --git a/pkg/es/client/ilm_client.go b/pkg/es/client/ilm_client.go index 7559becc275..7fd87ce9c9d 100644 --- a/pkg/es/client/ilm_client.go +++ b/pkg/es/client/ilm_client.go @@ -20,7 +20,7 @@ type ILMClient struct { // Exists verify if a ILM policy exists func (i ILMClient) Exists(name string) (bool, error) { _, err := i.request(elasticRequest{ - endpoint: fmt.Sprintf("_ilm/policy/%s", name), + endpoint: "_ilm/policy/" + name, method: http.MethodGet, }) diff --git a/pkg/es/client/index_client.go b/pkg/es/client/index_client.go index 4c8c4572590..0c46dd25c1f 100644 --- a/pkg/es/client/index_client.go +++ b/pkg/es/client/index_client.go @@ -57,7 +57,7 @@ func (i *IndicesClient) GetJaegerIndices(prefix string) ([]Index, error) { prefix += "jaeger-*" body, err := i.request(elasticRequest{ - endpoint: fmt.Sprintf("%s?flat_settings=true&filter_path=*.aliases,*.settings", prefix), + endpoint: prefix + "?flat_settings=true&filter_path=*.aliases,*.settings", method: http.MethodGet, }) if err != nil { @@ -101,7 +101,7 @@ func (i *IndicesClient) indexDeleteRequest(concatIndices string) error { var responseError ResponseError if errors.As(err, &responseError) { if responseError.StatusCode != http.StatusOK { - return responseError.prefixMessage(fmt.Sprintf("failed to delete indices: %s", concatIndices)) + return responseError.prefixMessage("failed to delete indices: " + concatIndices) } } return fmt.Errorf("failed to delete indices: %w", err) @@ -146,7 +146,7 @@ func (i *IndicesClient) CreateIndex(index string) error { var responseError ResponseError if errors.As(err, &responseError) { if responseError.StatusCode != http.StatusOK { - return responseError.prefixMessage(fmt.Sprintf("failed to create index: %s", index)) + return responseError.prefixMessage("failed to create index: " + index) } } return fmt.Errorf("failed to create index: %w", err) @@ -161,7 +161,7 @@ func (i *IndicesClient) CreateAlias(aliases []Alias) error { var responseError ResponseError if errors.As(err, &responseError) { if responseError.StatusCode != http.StatusOK { - return responseError.prefixMessage(fmt.Sprintf("failed to create aliases: %s", i.aliasesString(aliases))) + return responseError.prefixMessage("failed to create aliases: " + i.aliasesString(aliases)) } } return fmt.Errorf("failed to create aliases: %w", err) @@ -176,7 +176,7 @@ func (i *IndicesClient) DeleteAlias(aliases []Alias) error { var responseError ResponseError if errors.As(err, &responseError) { if responseError.StatusCode != http.StatusOK { - return responseError.prefixMessage(fmt.Sprintf("failed to delete aliases: %s", i.aliasesString(aliases))) + return responseError.prefixMessage("failed to delete aliases: " + i.aliasesString(aliases)) } } return fmt.Errorf("failed to delete aliases: %w", err) @@ -247,7 +247,7 @@ func (i IndicesClient) CreateTemplate(template, name string) error { var responseError ResponseError if errors.As(err, &responseError) { if responseError.StatusCode != http.StatusOK { - return responseError.prefixMessage(fmt.Sprintf("failed to create template: %s", name)) + return responseError.prefixMessage("failed to create template: " + name) } } return fmt.Errorf("failed to create template: %w", err) @@ -258,7 +258,7 @@ func (i IndicesClient) CreateTemplate(template, name string) error { // Rollover create a rollover for certain index/alias func (i IndicesClient) Rollover(rolloverTarget string, conditions map[string]any) error { esReq := elasticRequest{ - endpoint: fmt.Sprintf("%s/_rollover/", rolloverTarget), + endpoint: rolloverTarget + "/_rollover/", method: http.MethodPost, } if len(conditions) > 0 { @@ -276,7 +276,7 @@ func (i IndicesClient) Rollover(rolloverTarget string, conditions map[string]any var responseError ResponseError if errors.As(err, &responseError) { if responseError.StatusCode != http.StatusOK { - return responseError.prefixMessage(fmt.Sprintf("failed to create rollover target: %s", rolloverTarget)) + return responseError.prefixMessage("failed to create rollover target: " + rolloverTarget) } } return fmt.Errorf("failed to create rollover: %w", err) diff --git a/pkg/fswatcher/fswatcher.go b/pkg/fswatcher/fswatcher.go index 56695425df9..36f194b6522 100644 --- a/pkg/fswatcher/fswatcher.go +++ b/pkg/fswatcher/fswatcher.go @@ -5,7 +5,7 @@ package fswatcher import ( "crypto/sha256" - "fmt" + "encoding/hex" "io" "os" "path" @@ -154,5 +154,5 @@ func hashFile(file string) (string, error) { return "", err } - return fmt.Sprintf("%x", h.Sum(nil)), nil + return hex.EncodeToString(h.Sum(nil)), nil } diff --git a/pkg/testutils/logger_test.go b/pkg/testutils/logger_test.go index 9a3c907c418..1849f171e3f 100644 --- a/pkg/testutils/logger_test.go +++ b/pkg/testutils/logger_test.go @@ -5,7 +5,7 @@ package testutils import ( - "fmt" + "strconv" "sync" "testing" @@ -79,7 +79,7 @@ func TestLogMatcher(t *testing.T) { } for i, tt := range tests { test := tt - t.Run(fmt.Sprintf("%v", i), func(t *testing.T) { + t.Run(strconv.Itoa(i), func(t *testing.T) { match, errMsg := LogMatcher(test.occurrences, test.subStr, test.logs) assert.Equal(t, test.expected, match) assert.Equal(t, test.errMsg, errMsg) diff --git a/plugin/sampling/leaderelection/leader_election_test.go b/plugin/sampling/leaderelection/leader_election_test.go index c3c6cd499b9..98fc3241984 100644 --- a/plugin/sampling/leaderelection/leader_election_test.go +++ b/plugin/sampling/leaderelection/leader_election_test.go @@ -5,8 +5,8 @@ package leaderelection import ( "errors" - "fmt" "io" + "strconv" "testing" "time" @@ -42,7 +42,7 @@ func TestAcquireLock(t *testing.T) { } for i, test := range tests { - t.Run(fmt.Sprintf("%v", i), func(t *testing.T) { + t.Run(strconv.Itoa(i), func(t *testing.T) { logger, logBuffer := testutils.NewLogger() mockLock := &lmocks.Lock{} mockLock.On("Acquire", "sampling_lock", followerInterval).Return(test.acquiredLock, test.err) diff --git a/plugin/storage/badger/factory_test.go b/plugin/storage/badger/factory_test.go index ad46b90833c..9e979487652 100644 --- a/plugin/storage/badger/factory_test.go +++ b/plugin/storage/badger/factory_test.go @@ -5,7 +5,6 @@ package badger import ( "expvar" - "fmt" "io" "os" "testing" @@ -24,8 +23,8 @@ func TestInitializationErrors(t *testing.T) { f := NewFactory() v, command := config.Viperize(f.AddFlags) dir := "/root/this_should_fail" // If this test fails, you have some issues in your system - keyParam := fmt.Sprintf("--badger.directory-key=%s", dir) - valueParam := fmt.Sprintf("--badger.directory-value=%s", dir) + keyParam := "--badger.directory-key=" + dir + valueParam := "--badger.directory-value=" + dir command.ParseFlags([]string{ "--badger.ephemeral=false", diff --git a/plugin/storage/badger/spanstore/read_write_test.go b/plugin/storage/badger/spanstore/read_write_test.go index 6fa17c497a8..9c4d8f22be7 100644 --- a/plugin/storage/badger/spanstore/read_write_test.go +++ b/plugin/storage/badger/spanstore/read_write_test.go @@ -376,8 +376,8 @@ func TestPersist(t *testing.T) { cfg := badger.DefaultConfig() v, command := config.Viperize(cfg.AddFlags) - keyParam := fmt.Sprintf("--badger.directory-key=%s", dir) - valueParam := fmt.Sprintf("--badger.directory-value=%s", dir) + keyParam := "--badger.directory-key=" + dir + valueParam := "--badger.directory-value=" + dir command.ParseFlags([]string{ "--badger.ephemeral=false", @@ -604,8 +604,8 @@ func runLargeFactoryTest(tb testing.TB, test func(tb testing.TB, sw spanstore.Wr dir := filepath.Join(tb.TempDir(), "badger-testRun") err := os.MkdirAll(dir, 0o700) assertion.NoError(err) - keyParam := fmt.Sprintf("--badger.directory-key=%s", dir) - valueParam := fmt.Sprintf("--badger.directory-value=%s", dir) + keyParam := "--badger.directory-key=" + dir + valueParam := "--badger.directory-value=" + dir command.ParseFlags([]string{ "--badger.ephemeral=false", diff --git a/plugin/storage/es/spanstore/reader.go b/plugin/storage/es/spanstore/reader.go index accd1932e53..47bd6dbcec2 100644 --- a/plugin/storage/es/spanstore/reader.go +++ b/plugin/storage/es/spanstore/reader.go @@ -10,6 +10,7 @@ import ( "encoding/json" "errors" "fmt" + "strconv" "time" "github.com/olivere/elastic" @@ -474,7 +475,7 @@ func buildTraceByIDQuery(traceID model.TraceID) elastic.Query { // TODO remove in newer versions, added in Jaeger 1.16 var legacyTraceID string if traceID.High == 0 { - legacyTraceID = fmt.Sprintf("%x", traceID.Low) + legacyTraceID = strconv.FormatUint(traceID.Low, 16) } else { legacyTraceID = fmt.Sprintf("%x%016x", traceID.High, traceID.Low) } diff --git a/plugin/storage/es/spanstore/service_operation.go b/plugin/storage/es/spanstore/service_operation.go index d5bb428f6ee..8343abb565b 100644 --- a/plugin/storage/es/spanstore/service_operation.go +++ b/plugin/storage/es/spanstore/service_operation.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "hash/fnv" + "strconv" "time" "github.com/olivere/elastic" @@ -130,5 +131,5 @@ func hashCode(s dbmodel.Service) string { h := fnv.New64a() h.Write([]byte(s.ServiceName)) h.Write([]byte(s.OperationName)) - return fmt.Sprintf("%x", h.Sum64()) + return strconv.FormatUint(h.Sum64(), 16) } diff --git a/plugin/storage/integration/es_index_cleaner_test.go b/plugin/storage/integration/es_index_cleaner_test.go index 3f9ad14fdcd..48ae48d5c12 100644 --- a/plugin/storage/integration/es_index_cleaner_test.go +++ b/plugin/storage/integration/es_index_cleaner_test.go @@ -202,7 +202,7 @@ func createEsIndices(client *elastic.Client, indices []string) error { func runEsCleaner(days int, envs []string) error { var dockerEnv string for _, e := range envs { - dockerEnv += fmt.Sprintf(" -e %s", e) + dockerEnv += " -e " + e } args := fmt.Sprintf("docker run %s --rm --net=host %s %d http://%s", dockerEnv, indexCleanerImage, days, queryHostPort) cmd := exec.Command("/bin/sh", "-c", args) @@ -214,7 +214,7 @@ func runEsCleaner(days int, envs []string) error { func runEsRollover(action string, envs []string, adaptiveSampling bool) error { var dockerEnv string for _, e := range envs { - dockerEnv += fmt.Sprintf(" -e %s", e) + dockerEnv += " -e " + e } args := fmt.Sprintf("docker run %s --rm --net=host %s %s --adaptive-sampling=%t http://%s", dockerEnv, rolloverImage, action, adaptiveSampling, queryHostPort) cmd := exec.Command("/bin/sh", "-c", args)