From 982391315f5559de2a3854b9fd45fe91d99f67a4 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Tue, 29 Jul 2025 18:20:32 +0200 Subject: [PATCH] chore: enable gocritic linter (#7095) #### Description Enable and fixes several rules from [gocritic](https://golangci-lint.run/usage/linters/#gocritic) linter --------- Signed-off-by: Matthieu MOREL Co-authored-by: Tyler Yahn --- .golangci.yml | 23 ++++++--- attribute/encoder.go | 6 +-- attribute/filter.go | 4 +- baggage/baggage.go | 4 +- bridge/opencensus/trace_test.go | 8 ++- bridge/opentracing/bridge_test.go | 2 +- exporters/otlp/otlplog/otlploggrpc/client.go | 7 +-- exporters/otlp/otlplog/otlploggrpc/config.go | 2 +- .../otlp/otlplog/otlploggrpc/config_test.go | 6 +-- exporters/otlp/otlplog/otlploghttp/client.go | 4 +- .../otlp/otlplog/otlploghttp/config_test.go | 6 +-- .../otlp/otlpmetric/otlpmetrichttp/client.go | 4 +- .../otlp/otlptrace/otlptracehttp/client.go | 6 +-- exporters/prometheus/exporter.go | 4 +- exporters/zipkin/model.go | 14 ++--- exporters/zipkin/zipkin.go | 2 +- exporters/zipkin/zipkin_test.go | 2 +- internal/global/internal_logging_test.go | 2 +- propagation/baggage_test.go | 10 ++-- propagation/trace_context_benchmark_test.go | 6 +-- sdk/internal/x/x.go | 2 +- sdk/log/ring_test.go | 6 +-- sdk/metric/exemplar/fixed_size_reservoir.go | 12 ++--- .../aggregate/exponential_histogram.go | 10 ++-- .../aggregate/exponential_histogram_test.go | 6 +-- sdk/metric/meter.go | 2 +- sdk/metric/pipeline_test.go | 51 +++++++++---------- sdk/resource/os_release_unix.go | 4 +- sdk/trace/batch_span_processor_test.go | 4 +- sdk/trace/internal/x/x.go | 2 +- sdk/trace/tracer.go | 7 +-- semconv/internal/http_test.go | 2 +- semconv/internal/v2/http.go | 22 ++++---- semconv/internal/v3/http.go | 22 ++++---- semconv/internal/v4/http.go | 22 ++++---- trace/trace.go | 2 +- trace/tracestate.go | 6 +-- 37 files changed, 158 insertions(+), 146 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index ce845c6a3..5a2196d59 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,6 +10,7 @@ linters: - depguard - errcheck - errorlint + - gocritic - godot - gosec - govet @@ -86,6 +87,20 @@ linters: deny: - pkg: go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal desc: Do not use cross-module internal packages. + gocritic: + disabled-checks: + - appendAssign + - commentedOutCode + - dupArg + - hugeParam + - importShadow + - paramTypeCombine + - ptrToRefParam + - preferDecodeRune + - rangeValCopy + - unnamedResult + - whyNoLint + enable-all: true godot: exclude: # Exclude links. @@ -225,10 +240,6 @@ linters: - linters: - gosec text: 'G402: TLS MinVersion too low.' - paths: - - third_party$ - - builtin$ - - examples$ issues: max-issues-per-linter: 0 max-same-issues: 0 @@ -245,7 +256,3 @@ formatters: max-len: 120 exclusions: generated: lax - paths: - - third_party$ - - builtin$ - - examples$ diff --git a/attribute/encoder.go b/attribute/encoder.go index 739b9c9ae..6333d34b3 100644 --- a/attribute/encoder.go +++ b/attribute/encoder.go @@ -96,11 +96,11 @@ func (d *defaultAttrEncoder) Encode(iter Iterator) string { for iter.Next() { i, keyValue := iter.IndexedAttribute() if i > 0 { - _, _ = buf.WriteRune(',') + _ = buf.WriteByte(',') } copyAndEscape(buf, string(keyValue.Key)) - _, _ = buf.WriteRune('=') + _ = buf.WriteByte('=') if keyValue.Value.Type() == STRING { copyAndEscape(buf, keyValue.Value.AsString()) @@ -122,7 +122,7 @@ func copyAndEscape(buf *bytes.Buffer, val string) { for _, ch := range val { switch ch { case '=', ',', escapeChar: - _, _ = buf.WriteRune(escapeChar) + _ = buf.WriteByte(escapeChar) } _, _ = buf.WriteRune(ch) } diff --git a/attribute/filter.go b/attribute/filter.go index 3eeaa5d44..74e011a9c 100644 --- a/attribute/filter.go +++ b/attribute/filter.go @@ -15,7 +15,7 @@ type Filter func(KeyValue) bool // // If keys is empty a deny-all filter is returned. func NewAllowKeysFilter(keys ...Key) Filter { - if len(keys) <= 0 { + if len(keys) == 0 { return func(kv KeyValue) bool { return false } } @@ -34,7 +34,7 @@ func NewAllowKeysFilter(keys ...Key) Filter { // // If keys is empty an allow-all filter is returned. func NewDenyKeysFilter(keys ...Key) Filter { - if len(keys) <= 0 { + if len(keys) == 0 { return func(kv KeyValue) bool { return true } } diff --git a/baggage/baggage.go b/baggage/baggage.go index 0e1fe2422..f83a448ec 100644 --- a/baggage/baggage.go +++ b/baggage/baggage.go @@ -812,7 +812,7 @@ var safeKeyCharset = [utf8.RuneSelf]bool{ // validateBaggageName checks if the string is a valid OpenTelemetry Baggage name. // Baggage name is a valid, non-empty UTF-8 string. func validateBaggageName(s string) bool { - if len(s) == 0 { + if s == "" { return false } @@ -828,7 +828,7 @@ func validateBaggageValue(s string) bool { // validateKey checks if the string is a valid W3C Baggage key. func validateKey(s string) bool { - if len(s) == 0 { + if s == "" { return false } diff --git a/bridge/opencensus/trace_test.go b/bridge/opencensus/trace_test.go index b4e7dbdd7..b8fe722a3 100644 --- a/bridge/opencensus/trace_test.go +++ b/bridge/opencensus/trace_test.go @@ -134,12 +134,10 @@ func TestOTelSpanContextToOC(t *testing.T) { gotTraceState = strings.Join(gotTraceStateEntries, ",") } assert.Equal(t, expectedTraceState, gotTraceState, "Tracestate should preserve entries") - } else { + } else if got.Tracestate != nil { // For empty tracestate cases, ensure the field is properly handled - if got.Tracestate != nil { - entries := got.Tracestate.Entries() - assert.Empty(t, entries, "Empty tracestate should result in empty entries") - } + entries := got.Tracestate.Entries() + assert.Empty(t, entries, "Empty tracestate should result in empty entries") } }) } diff --git a/bridge/opentracing/bridge_test.go b/bridge/opentracing/bridge_test.go index 941f17444..e85469194 100644 --- a/bridge/opentracing/bridge_test.go +++ b/bridge/opentracing/bridge_test.go @@ -135,7 +135,7 @@ var ( type testTextMapPropagator struct{} func (t testTextMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) { - carrier.Set(testHeader, strings.Join([]string{traceID.String(), spanID.String()}, ":")) + carrier.Set(testHeader, traceID.String()+":"+spanID.String()) // Test for panic _ = carrier.Get("test") diff --git a/exporters/otlp/otlplog/otlploggrpc/client.go b/exporters/otlp/otlplog/otlploggrpc/client.go index 1add3f333..b2987f755 100644 --- a/exporters/otlp/otlplog/otlploggrpc/client.go +++ b/exporters/otlp/otlplog/otlploggrpc/client.go @@ -86,11 +86,12 @@ func newGRPCDialOptions(cfg config) []grpc.DialOption { dialOpts = append(dialOpts, grpc.WithDefaultServiceConfig(cfg.serviceConfig.Value)) } // Prioritize GRPCCredentials over Insecure (passing both is an error). - if cfg.gRPCCredentials.Value != nil { + switch { + case cfg.gRPCCredentials.Value != nil: dialOpts = append(dialOpts, grpc.WithTransportCredentials(cfg.gRPCCredentials.Value)) - } else if cfg.insecure.Value { + case cfg.insecure.Value: dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials())) - } else { + default: // Default to using the host's root CA. dialOpts = append(dialOpts, grpc.WithTransportCredentials( credentials.NewTLS(nil), diff --git a/exporters/otlp/otlplog/otlploggrpc/config.go b/exporters/otlp/otlplog/otlploggrpc/config.go index d0cc79d54..3fda9fcb0 100644 --- a/exporters/otlp/otlplog/otlploggrpc/config.go +++ b/exporters/otlp/otlplog/otlploggrpc/config.go @@ -563,7 +563,7 @@ func loadCertificates(certPath, keyPath string) ([]tls.Certificate, error) { func insecureFromScheme(prev setting[bool], scheme string) setting[bool] { if scheme == "https" { return newSetting(false) - } else if len(scheme) > 0 { + } else if scheme != "" { return newSetting(true) } diff --git a/exporters/otlp/otlplog/otlploggrpc/config_test.go b/exporters/otlp/otlplog/otlploggrpc/config_test.go index e7a0cf1c9..5005d9cca 100644 --- a/exporters/otlp/otlplog/otlploggrpc/config_test.go +++ b/exporters/otlp/otlplog/otlploggrpc/config_test.go @@ -525,10 +525,8 @@ func assertTLSConfig(t *testing.T, want, got setting[*tls.Config]) { if want.Value.RootCAs == nil { assert.Nil(t, got.Value.RootCAs, "*tls.Config.RootCAs") - } else { - if assert.NotNil(t, got.Value.RootCAs, "RootCAs") { - assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal") - } + } else if assert.NotNil(t, got.Value.RootCAs, "RootCAs") { + assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal") } assert.Equal(t, want.Value.Certificates, got.Value.Certificates, "Certificates") } diff --git a/exporters/otlp/otlplog/otlploghttp/client.go b/exporters/otlp/otlplog/otlploghttp/client.go index 5287a5221..c2611967e 100644 --- a/exporters/otlp/otlplog/otlploghttp/client.go +++ b/exporters/otlp/otlplog/otlploghttp/client.go @@ -200,7 +200,7 @@ func (c *httpClient) uploadLogs(ctx context.Context, data []*logpb.ResourceLogs) return err } respStr := strings.TrimSpace(respData.String()) - if len(respStr) == 0 { + if respStr == "" { respStr = "(empty)" } bodyErr := fmt.Errorf("body: %s", respStr) @@ -232,7 +232,7 @@ func (c *httpClient) newRequest(ctx context.Context, body []byte) (request, erro switch c.compression { case NoCompression: - r.ContentLength = (int64)(len(body)) + r.ContentLength = int64(len(body)) req.bodyReader = bodyReader(body) case GzipCompression: // Ensure the content length is not used. diff --git a/exporters/otlp/otlplog/otlploghttp/config_test.go b/exporters/otlp/otlplog/otlploghttp/config_test.go index a6863e380..e9a8a66fe 100644 --- a/exporters/otlp/otlplog/otlploghttp/config_test.go +++ b/exporters/otlp/otlplog/otlploghttp/config_test.go @@ -460,10 +460,8 @@ func assertTLSConfig(t *testing.T, want, got setting[*tls.Config]) { if want.Value.RootCAs == nil { assert.Nil(t, got.Value.RootCAs, "*tls.Config.RootCAs") - } else { - if assert.NotNil(t, got.Value.RootCAs, "RootCAs") { - assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal") - } + } else if assert.NotNil(t, got.Value.RootCAs, "RootCAs") { + assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal") } assert.Equal(t, want.Value.Certificates, got.Value.Certificates, "Certificates") } diff --git a/exporters/otlp/otlpmetric/otlpmetrichttp/client.go b/exporters/otlp/otlpmetric/otlpmetrichttp/client.go index 4de224160..dca587832 100644 --- a/exporters/otlp/otlpmetric/otlpmetrichttp/client.go +++ b/exporters/otlp/otlpmetric/otlpmetrichttp/client.go @@ -203,7 +203,7 @@ func (c *client) UploadMetrics(ctx context.Context, protoMetrics *metricpb.Resou return err } respStr := strings.TrimSpace(respData.String()) - if len(respStr) == 0 { + if respStr == "" { respStr = "(empty)" } bodyErr := fmt.Errorf("body: %s", respStr) @@ -235,7 +235,7 @@ func (c *client) newRequest(ctx context.Context, body []byte) (request, error) { switch c.compression { case NoCompression: - r.ContentLength = (int64)(len(body)) + r.ContentLength = int64(len(body)) req.bodyReader = bodyReader(body) case GzipCompression: // Ensure the content length is not used. diff --git a/exporters/otlp/otlptrace/otlptracehttp/client.go b/exporters/otlp/otlptrace/otlptracehttp/client.go index ff67b7508..2de0f9dfb 100644 --- a/exporters/otlp/otlptrace/otlptracehttp/client.go +++ b/exporters/otlp/otlptrace/otlptracehttp/client.go @@ -209,7 +209,7 @@ func (d *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc return err } respStr := strings.TrimSpace(respData.String()) - if len(respStr) == 0 { + if respStr == "" { respStr = "(empty)" } bodyErr := fmt.Errorf("body: %s", respStr) @@ -230,7 +230,7 @@ func (d *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc func (d *client) newRequest(body []byte) (request, error) { u := url.URL{Scheme: d.getScheme(), Host: d.cfg.Endpoint, Path: d.cfg.URLPath} - r, err := http.NewRequest(http.MethodPost, u.String(), nil) + r, err := http.NewRequest(http.MethodPost, u.String(), http.NoBody) if err != nil { return request{Request: r}, err } @@ -246,7 +246,7 @@ func (d *client) newRequest(body []byte) (request, error) { req := request{Request: r} switch Compression(d.cfg.Compression) { case NoCompression: - r.ContentLength = (int64)(len(body)) + r.ContentLength = int64(len(body)) req.bodyReader = bodyReader(body) case GzipCompression: // Ensure the content length is not used. diff --git a/exporters/prometheus/exporter.go b/exporters/prometheus/exporter.go index 361e360f9..b130d9e9a 100644 --- a/exporters/prometheus/exporter.go +++ b/exporters/prometheus/exporter.go @@ -640,8 +640,8 @@ func addExemplars[N int64 | float64]( for i, exemplar := range exemplars { labels := attributesToLabels(exemplar.FilteredAttributes, labelNamer) // Overwrite any existing trace ID or span ID attributes - labels[otlptranslator.ExemplarTraceIDKey] = hex.EncodeToString(exemplar.TraceID[:]) - labels[otlptranslator.ExemplarSpanIDKey] = hex.EncodeToString(exemplar.SpanID[:]) + labels[otlptranslator.ExemplarTraceIDKey] = hex.EncodeToString(exemplar.TraceID) + labels[otlptranslator.ExemplarSpanIDKey] = hex.EncodeToString(exemplar.SpanID) promExemplars[i] = prometheus.Exemplar{ Value: float64(exemplar.Value), Timestamp: exemplar.Time, diff --git a/exporters/zipkin/model.go b/exporters/zipkin/model.go index 2dfdf659a..00bff2372 100644 --- a/exporters/zipkin/model.go +++ b/exporters/zipkin/model.go @@ -150,11 +150,11 @@ func toZipkinAnnotations(events []tracesdk.Event) []zkmodel.Annotation { func attributesToJSONMapString(attributes []attribute.KeyValue) string { m := make(map[string]any, len(attributes)) for _, a := range attributes { - m[(string)(a.Key)] = a.Value.AsInterface() + m[string(a.Key)] = a.Value.AsInterface() } // if an error happens, the result will be an empty string jsonBytes, _ := json.Marshal(m) - return (string)(jsonBytes) + return string(jsonBytes) } // attributeToStringPair serializes each attribute to a string pair. @@ -163,18 +163,18 @@ func attributeToStringPair(kv attribute.KeyValue) (string, string) { // For slice attributes, serialize as JSON list string. case attribute.BOOLSLICE: data, _ := json.Marshal(kv.Value.AsBoolSlice()) - return (string)(kv.Key), (string)(data) + return string(kv.Key), string(data) case attribute.INT64SLICE: data, _ := json.Marshal(kv.Value.AsInt64Slice()) - return (string)(kv.Key), (string)(data) + return string(kv.Key), string(data) case attribute.FLOAT64SLICE: data, _ := json.Marshal(kv.Value.AsFloat64Slice()) - return (string)(kv.Key), (string)(data) + return string(kv.Key), string(data) case attribute.STRINGSLICE: data, _ := json.Marshal(kv.Value.AsStringSlice()) - return (string)(kv.Key), (string)(data) + return string(kv.Key), string(data) default: - return (string)(kv.Key), kv.Value.Emit() + return string(kv.Key), kv.Value.Emit() } } diff --git a/exporters/zipkin/zipkin.go b/exporters/zipkin/zipkin.go index 58a69afdc..bdd149eba 100644 --- a/exporters/zipkin/zipkin.go +++ b/exporters/zipkin/zipkin.go @@ -146,7 +146,7 @@ func (e *Exporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpa req.Header.Set("Content-Type", "application/json") for k, v := range e.headers { - if strings.ToLower(k) == "host" { + if strings.EqualFold(k, "host") { req.Host = v } else { req.Header.Set(k, v) diff --git a/exporters/zipkin/zipkin_test.go b/exporters/zipkin/zipkin_test.go index 13b6170ef..45a8d1941 100644 --- a/exporters/zipkin/zipkin_test.go +++ b/exporters/zipkin/zipkin_test.go @@ -171,7 +171,7 @@ type logStore struct { } func (s *logStore) Write(p []byte) (n int, err error) { - msg := (string)(p) + msg := string(p) if s.T != nil { s.T.Logf("%s", msg) } diff --git a/internal/global/internal_logging_test.go b/internal/global/internal_logging_test.go index 96287146a..b6af22ac9 100644 --- a/internal/global/internal_logging_test.go +++ b/internal/global/internal_logging_test.go @@ -91,7 +91,7 @@ func TestLogLevel(t *testing.T) { func newBuffLogger(buf *bytes.Buffer, verbosity int) logr.Logger { return funcr.New(func(prefix, args string) { - _, _ = buf.Write([]byte(args)) + _, _ = buf.WriteString(args) }, funcr.Options{ Verbosity: verbosity, }) diff --git a/propagation/baggage_test.go b/propagation/baggage_test.go index 8ce34bdec..4aeb29648 100644 --- a/propagation/baggage_test.go +++ b/propagation/baggage_test.go @@ -124,7 +124,7 @@ func TestExtractValidBaggage(t *testing.T) { t.Run(tt.name, func(t *testing.T) { mapCarr := propagation.MapCarrier{} mapCarr["baggage"] = tt.header - req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) + req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody) req.Header.Set("baggage", tt.header) // test with http header carrier (which implements ValuesGetter) @@ -183,7 +183,7 @@ func TestExtractValidMultipleBaggageHeaders(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) + req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody) req.Header["Baggage"] = tt.headers ctx := context.Background() @@ -239,7 +239,7 @@ func TestExtractInvalidDistributedContextFromHTTPReq(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) + req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody) req.Header.Set("baggage", tt.header) expected := tt.has.Baggage(t) @@ -292,7 +292,7 @@ func TestInjectBaggageToHTTPReq(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) + req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody) ctx := baggage.ContextWithBaggage(context.Background(), tt.mems.Baggage(t)) propagator.Inject(ctx, propagation.HeaderCarrier(req.Header)) @@ -339,7 +339,7 @@ func TestBaggageInjectExtractRoundtrip(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { b := tt.mems.Baggage(t) - req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) + req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody) ctx := baggage.ContextWithBaggage(context.Background(), b) propagator.Inject(ctx, propagation.HeaderCarrier(req.Header)) diff --git a/propagation/trace_context_benchmark_test.go b/propagation/trace_context_benchmark_test.go index 041d2f664..711e82aeb 100644 --- a/propagation/trace_context_benchmark_test.go +++ b/propagation/trace_context_benchmark_test.go @@ -56,7 +56,7 @@ func BenchmarkExtract(b *testing.B) { func extractSubBenchmarks(b *testing.B, fn func(*testing.B, *http.Request)) { b.Run("Sampled", func(b *testing.B) { - req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) + req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody) req.Header.Set("traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01") b.ReportAllocs() @@ -64,14 +64,14 @@ func extractSubBenchmarks(b *testing.B, fn func(*testing.B, *http.Request)) { }) b.Run("BogusVersion", func(b *testing.B) { - req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) + req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody) req.Header.Set("traceparent", "qw-00000000000000000000000000000000-0000000000000000-01") b.ReportAllocs() fn(b, req) }) b.Run("FutureAdditionalData", func(b *testing.B) { - req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) + req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody) req.Header.Set("traceparent", "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09-XYZxsf09") b.ReportAllocs() fn(b, req) diff --git a/sdk/internal/x/x.go b/sdk/internal/x/x.go index 44eb839a4..1be472e91 100644 --- a/sdk/internal/x/x.go +++ b/sdk/internal/x/x.go @@ -19,7 +19,7 @@ import ( // to the case-insensitive string value of "true" (i.e. "True" and "TRUE" // will also enable this). var Resource = newFeature("RESOURCE", func(v string) (string, bool) { - if strings.ToLower(v) == "true" { + if strings.EqualFold(v, "true") { return v, true } return "", false diff --git a/sdk/log/ring_test.go b/sdk/log/ring_test.go index fe2046aa8..5a95aee56 100644 --- a/sdk/log/ring_test.go +++ b/sdk/log/ring_test.go @@ -15,9 +15,9 @@ import ( "go.opentelemetry.io/otel/log" ) -func verifyRing(t *testing.T, r *ring, N int, sum int) { +func verifyRing(t *testing.T, r *ring, num int, sum int) { // Length. - assert.Equal(t, N, r.Len(), "r.Len()") + assert.Equal(t, num, r.Len(), "r.Len()") // Iteration. var n, s int @@ -28,7 +28,7 @@ func verifyRing(t *testing.T, r *ring, N int, sum int) { s += int(body.AsInt64()) } }) - assert.Equal(t, N, n, "number of forward iterations") + assert.Equal(t, num, n, "number of forward iterations") if sum >= 0 { assert.Equal(t, sum, s, "forward ring sum") } diff --git a/sdk/metric/exemplar/fixed_size_reservoir.go b/sdk/metric/exemplar/fixed_size_reservoir.go index 1fb1e0095..08fdefbde 100644 --- a/sdk/metric/exemplar/fixed_size_reservoir.go +++ b/sdk/metric/exemplar/fixed_size_reservoir.go @@ -125,13 +125,11 @@ func (r *FixedSizeReservoir) Offer(ctx context.Context, t time.Time, n Value, a if int(r.count) < cap(r.store) { r.store[r.count] = newMeasurement(ctx, t, n, a) - } else { - if r.count == r.next { - // Overwrite a random existing measurement with the one offered. - idx := int(rand.Int64N(int64(cap(r.store)))) - r.store[idx] = newMeasurement(ctx, t, n, a) - r.advance() - } + } else if r.count == r.next { + // Overwrite a random existing measurement with the one offered. + idx := int(rand.Int64N(int64(cap(r.store)))) + r.store[idx] = newMeasurement(ctx, t, n, a) + r.advance() } r.count++ } diff --git a/sdk/metric/internal/aggregate/exponential_histogram.go b/sdk/metric/internal/aggregate/exponential_histogram.go index ae1f59344..b3266bd12 100644 --- a/sdk/metric/internal/aggregate/exponential_histogram.go +++ b/sdk/metric/internal/aggregate/exponential_histogram.go @@ -183,8 +183,8 @@ func (p *expoHistogramDataPoint[N]) scaleChange(bin, startBin int32, length int) var count int32 for high-low >= p.maxSize { - low = low >> 1 - high = high >> 1 + low >>= 1 + high >>= 1 count++ if count > expoMaxScale-expoMinScale { return count @@ -225,7 +225,7 @@ func (b *expoBuckets) record(bin int32) { b.counts = append(b.counts, make([]uint64, newLength-len(b.counts))...) } - copy(b.counts[shift:origLen+int(shift)], b.counts[:]) + copy(b.counts[shift:origLen+int(shift)], b.counts) b.counts = b.counts[:newLength] for i := 1; i < int(shift); i++ { b.counts[i] = 0 @@ -264,7 +264,7 @@ func (b *expoBuckets) downscale(delta int32) { // new Counts: [4, 14, 30, 10] if len(b.counts) <= 1 || delta < 1 { - b.startBin = b.startBin >> delta + b.startBin >>= delta return } @@ -282,7 +282,7 @@ func (b *expoBuckets) downscale(delta int32) { lastIdx := (len(b.counts) - 1 + int(offset)) / int(steps) b.counts = b.counts[:lastIdx+1] - b.startBin = b.startBin >> delta + b.startBin >>= delta } // newExponentialHistogram returns an Aggregator that summarizes a set of diff --git a/sdk/metric/internal/aggregate/exponential_histogram_test.go b/sdk/metric/internal/aggregate/exponential_histogram_test.go index 04950935f..c0ad6d53e 100644 --- a/sdk/metric/internal/aggregate/exponential_histogram_test.go +++ b/sdk/metric/internal/aggregate/exponential_histogram_test.go @@ -656,7 +656,7 @@ func BenchmarkPrepend(b *testing.B) { n := math.MaxFloat64 for range 1024 { agg.record(n) - n = n / 2 + n /= 2 } } } @@ -667,7 +667,7 @@ func BenchmarkAppend(b *testing.B) { n := smallestNonZeroNormalFloat64 for range 1024 { agg.record(n) - n = n * 2 + n *= 2 } } } @@ -1061,7 +1061,7 @@ func FuzzGetBin(f *testing.F) { f.Fuzz(func(t *testing.T, v float64, scale int32) { // GetBin only works on positive values. if math.Signbit(v) { - v = v * -1 + v *= -1 } // GetBin Doesn't work on zero. if v == 0.0 { diff --git a/sdk/metric/meter.go b/sdk/metric/meter.go index c500fd9f2..fd66fc034 100644 --- a/sdk/metric/meter.go +++ b/sdk/metric/meter.go @@ -423,7 +423,7 @@ func (m *meter) Float64ObservableGauge( } func validateInstrumentName(name string) error { - if len(name) == 0 { + if name == "" { return fmt.Errorf("%w: %s: is empty", ErrInstrumentName, name) } if len(name) > 255 { diff --git a/sdk/metric/pipeline_test.go b/sdk/metric/pipeline_test.go index f17acb087..b601e2242 100644 --- a/sdk/metric/pipeline_test.go +++ b/sdk/metric/pipeline_test.go @@ -653,32 +653,31 @@ func TestPipelineProduceErrors(t *testing.T) { var shouldReturnError bool // When true, the third callback returns an error var callbackCounts [3]int - // Callback 1: cancels the context during execution but continues to populate data - pipe.callbacks = append(pipe.callbacks, func(ctx context.Context) error { - callbackCounts[0]++ - for _, m := range pipe.int64Measures[testObsID] { - m(ctx, 123, *attribute.EmptySet()) - } - return nil - }) - - // Callback 2: populates int64 observable data - pipe.callbacks = append(pipe.callbacks, func(ctx context.Context) error { - callbackCounts[1]++ - if shouldCancelContext { - cancelCtx() - } - return nil - }) - - // Callback 3: return an error - pipe.callbacks = append(pipe.callbacks, func(ctx context.Context) error { - callbackCounts[2]++ - if shouldReturnError { - return fmt.Errorf("test callback error") - } - return nil - }) + pipe.callbacks = append(pipe.callbacks, + // Callback 1: cancels the context during execution but continues to populate data + func(ctx context.Context) error { + callbackCounts[0]++ + for _, m := range pipe.int64Measures[testObsID] { + m(ctx, 123, *attribute.EmptySet()) + } + return nil + }, + // Callback 2: populates int64 observable data + func(ctx context.Context) error { + callbackCounts[1]++ + if shouldCancelContext { + cancelCtx() + } + return nil + }, + // Callback 3: return an error + func(ctx context.Context) error { + callbackCounts[2]++ + if shouldReturnError { + return fmt.Errorf("test callback error") + } + return nil + }) assertMetrics := func(rm *metricdata.ResourceMetrics, expectVal int64) { require.Len(t, rm.ScopeMetrics, 1) diff --git a/sdk/resource/os_release_unix.go b/sdk/resource/os_release_unix.go index b9a886c67..7252af79f 100644 --- a/sdk/resource/os_release_unix.go +++ b/sdk/resource/os_release_unix.go @@ -68,7 +68,7 @@ func parseOSReleaseFile(file io.Reader) map[string]string { func skip(line string) bool { line = strings.TrimSpace(line) - return len(line) == 0 || strings.HasPrefix(line, "#") + return line == "" || strings.HasPrefix(line, "#") } // parse attempts to split the provided line on the first '=' character, and then @@ -76,7 +76,7 @@ func skip(line string) bool { func parse(line string) (string, string, bool) { k, v, found := strings.Cut(line, "=") - if !found || len(k) == 0 { + if !found || k == "" { return "", "", false } diff --git a/sdk/trace/batch_span_processor_test.go b/sdk/trace/batch_span_processor_test.go index 010d5d2bc..f3f4596e1 100644 --- a/sdk/trace/batch_span_processor_test.go +++ b/sdk/trace/batch_span_processor_test.go @@ -505,7 +505,7 @@ func TestBatchSpanProcessorDropBatchIfFailed(t *testing.T) { func assertMaxSpanDiff(t *testing.T, want, got, maxDif int) { spanDifference := want - got if spanDifference < 0 { - spanDifference = spanDifference * -1 + spanDifference *= -1 } if spanDifference > maxDif { t.Errorf("number of exported span not equal to or within %d less than: got %+v, want %+v\n", @@ -514,7 +514,7 @@ func assertMaxSpanDiff(t *testing.T, want, got, maxDif int) { } type indefiniteExporter struct { - stop chan (struct{}) + stop chan struct{} } func newIndefiniteExporter(t *testing.T) indefiniteExporter { diff --git a/sdk/trace/internal/x/x.go b/sdk/trace/internal/x/x.go index c650ee715..2fcbbcc66 100644 --- a/sdk/trace/internal/x/x.go +++ b/sdk/trace/internal/x/x.go @@ -16,7 +16,7 @@ import ( // to the case-insensitive string value of "true" (i.e. "True" and "TRUE" // will also enable this). var SelfObservability = newFeature("SELF_OBSERVABILITY", func(v string) (string, bool) { - if strings.ToLower(v) == "true" { + if strings.EqualFold(v, "true") { return v, true } return "", false diff --git a/sdk/trace/tracer.go b/sdk/trace/tracer.go index 07683efa5..ddb72cb77 100644 --- a/sdk/trace/tracer.go +++ b/sdk/trace/tracer.go @@ -92,13 +92,14 @@ func (tr *tracer) Start( // Determine the sampling result and create the corresponding attribute. var attrSamplingResult attribute.KeyValue - if s.SpanContext().IsSampled() && s.IsRecording() { + switch { + case s.SpanContext().IsSampled() && s.IsRecording(): attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult( otelconv.SpanSamplingResultRecordAndSample, ) - } else if s.IsRecording() { + case s.IsRecording(): attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(otelconv.SpanSamplingResultRecordOnly) - } else { + default: attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(otelconv.SpanSamplingResultDrop) } diff --git a/semconv/internal/http_test.go b/semconv/internal/http_test.go index d600f1cc3..b9fcd2019 100644 --- a/semconv/internal/http_test.go +++ b/semconv/internal/http_test.go @@ -1008,7 +1008,7 @@ func kvStr(kvs []attribute.KeyValue) string { if idx > 0 { _, _ = sb.WriteString(", ") } - _, _ = sb.WriteString((string)(attr.Key)) + _, _ = sb.WriteString(string(attr.Key)) _, _ = sb.WriteString(": ") _, _ = sb.WriteString(attr.Value.Emit()) } diff --git a/semconv/internal/v2/http.go b/semconv/internal/v2/http.go index 3709ef099..d88c7f5df 100644 --- a/semconv/internal/v2/http.go +++ b/semconv/internal/v2/http.go @@ -91,8 +91,7 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue { } attrs := make([]attribute.KeyValue, 0, n) - attrs = append(attrs, c.method(req.Method)) - attrs = append(attrs, c.proto(req.Proto)) + attrs = append(attrs, c.method(req.Method), c.proto(req.Proto)) var u string if req.URL != nil { @@ -103,9 +102,11 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue { // Restore any username/password info that was removed. req.URL.User = userinfo } - attrs = append(attrs, c.HTTPURLKey.String(u)) - - attrs = append(attrs, c.NetConv.PeerName(peer)) + attrs = append( + attrs, + c.HTTPURLKey.String(u), + c.NetConv.PeerName(peer), + ) if port > 0 { attrs = append(attrs, c.NetConv.PeerPort(port)) } @@ -191,10 +192,13 @@ func (c *HTTPConv) ServerRequest(server string, req *http.Request) []attribute.K } attrs := make([]attribute.KeyValue, 0, n) - attrs = append(attrs, c.method(req.Method)) - attrs = append(attrs, c.scheme(req.TLS != nil)) - attrs = append(attrs, c.proto(req.Proto)) - attrs = append(attrs, c.NetConv.HostName(host)) + attrs = append( + attrs, + c.method(req.Method), + c.scheme(req.TLS != nil), + c.proto(req.Proto), + c.NetConv.HostName(host), + ) if hostPort > 0 { attrs = append(attrs, c.NetConv.HostPort(hostPort)) diff --git a/semconv/internal/v3/http.go b/semconv/internal/v3/http.go index bc503642f..f24fd3ef4 100644 --- a/semconv/internal/v3/http.go +++ b/semconv/internal/v3/http.go @@ -91,8 +91,7 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue { } attrs := make([]attribute.KeyValue, 0, n) - attrs = append(attrs, c.method(req.Method)) - attrs = append(attrs, c.proto(req.Proto)) + attrs = append(attrs, c.method(req.Method), c.proto(req.Proto)) var u string if req.URL != nil { @@ -103,9 +102,11 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue { // Restore any username/password info that was removed. req.URL.User = userinfo } - attrs = append(attrs, c.HTTPURLKey.String(u)) - - attrs = append(attrs, c.NetConv.PeerName(peer)) + attrs = append( + attrs, + c.HTTPURLKey.String(u), + c.NetConv.PeerName(peer), + ) if port > 0 { attrs = append(attrs, c.NetConv.PeerPort(port)) } @@ -191,10 +192,13 @@ func (c *HTTPConv) ServerRequest(server string, req *http.Request) []attribute.K } attrs := make([]attribute.KeyValue, 0, n) - attrs = append(attrs, c.method(req.Method)) - attrs = append(attrs, c.scheme(req.TLS != nil)) - attrs = append(attrs, c.proto(req.Proto)) - attrs = append(attrs, c.NetConv.HostName(host)) + attrs = append( + attrs, + c.method(req.Method), + c.scheme(req.TLS != nil), + c.proto(req.Proto), + c.NetConv.HostName(host), + ) if hostPort > 0 { attrs = append(attrs, c.NetConv.HostPort(hostPort)) diff --git a/semconv/internal/v4/http.go b/semconv/internal/v4/http.go index 347d69935..c02dafcc6 100644 --- a/semconv/internal/v4/http.go +++ b/semconv/internal/v4/http.go @@ -92,8 +92,7 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue { } attrs := make([]attribute.KeyValue, 0, n) - attrs = append(attrs, c.method(req.Method)) - attrs = append(attrs, c.proto(req.Proto)) + attrs = append(attrs, c.method(req.Method), c.proto(req.Proto)) var u string if req.URL != nil { @@ -104,9 +103,11 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue { // Restore any username/password info that was removed. req.URL.User = userinfo } - attrs = append(attrs, c.HTTPURLKey.String(u)) - - attrs = append(attrs, c.NetConv.PeerName(peer)) + attrs = append( + attrs, + c.HTTPURLKey.String(u), + c.NetConv.PeerName(peer), + ) if port > 0 { attrs = append(attrs, c.NetConv.PeerPort(port)) } @@ -192,10 +193,13 @@ func (c *HTTPConv) ServerRequest(server string, req *http.Request) []attribute.K } attrs := make([]attribute.KeyValue, 0, n) - attrs = append(attrs, c.method(req.Method)) - attrs = append(attrs, c.scheme(req.TLS != nil)) - attrs = append(attrs, c.proto(req.Proto)) - attrs = append(attrs, c.NetConv.HostName(host)) + attrs = append( + attrs, + c.method(req.Method), + c.scheme(req.TLS != nil), + c.proto(req.Proto), + c.NetConv.HostName(host), + ) if hostPort > 0 { attrs = append(attrs, c.NetConv.HostPort(hostPort)) diff --git a/trace/trace.go b/trace/trace.go index da2c28d04..c8d9618b3 100644 --- a/trace/trace.go +++ b/trace/trace.go @@ -165,7 +165,7 @@ func (tf TraceFlags) MarshalJSON() ([]byte, error) { // String returns the hex string representation form of TraceFlags. func (tf TraceFlags) String() string { - return hex.EncodeToString([]byte{byte(tf)}[:]) + return hex.EncodeToString([]byte{byte(tf)}) } // SpanContextConfig contains mutable fields usable for constructing diff --git a/trace/tracestate.go b/trace/tracestate.go index dc5e34cad..073adae2f 100644 --- a/trace/tracestate.go +++ b/trace/tracestate.go @@ -80,7 +80,7 @@ func checkKeyRemain(key string) bool { // // param n is remain part length, should be 255 in simple-key or 13 in system-id. func checkKeyPart(key string, n int) bool { - if len(key) == 0 { + if key == "" { return false } first := key[0] // key's first char @@ -102,7 +102,7 @@ func isAlphaNum(c byte) bool { // // param n is remain part length, should be 240 exactly. func checkKeyTenant(key string, n int) bool { - if len(key) == 0 { + if key == "" { return false } return isAlphaNum(key[0]) && len(key[1:]) <= n && checkKeyRemain(key[1:]) @@ -191,7 +191,7 @@ func ParseTraceState(ts string) (TraceState, error) { for ts != "" { var memberStr string memberStr, ts, _ = strings.Cut(ts, listDelimiters) - if len(memberStr) == 0 { + if memberStr == "" { continue }