[chore]: enable perfsprint linter (#1676)

This commit is contained in:
Matthieu MOREL 2024-11-08 09:54:31 +01:00 committed by GitHub
parent 1aa11d0498
commit fcfad5c0b9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 67 additions and 55 deletions

View File

@ -25,6 +25,7 @@ linters:
- ineffassign - ineffassign
- misspell - misspell
- nolintlint - nolintlint
- perfsprint
- predeclared - predeclared
- revive - revive
- staticcheck - staticcheck
@ -66,6 +67,17 @@ linters-settings:
local-prefixes: github.com/prometheus/client_golang local-prefixes: github.com/prometheus/client_golang
gofumpt: gofumpt:
extra-rules: true extra-rules: true
perfsprint:
# Optimizes even if it requires an int or uint type cast.
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: true
# Optimizes into strings concatenation.
strconcat: true
revive: revive:
rules: rules:
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-parameter # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-parameter

View File

@ -16,13 +16,13 @@ package v1
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"io" "io"
"math" "math"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
"reflect" "reflect"
"strconv"
"strings" "strings"
"testing" "testing"
"time" "time"
@ -260,7 +260,7 @@ func TestAPIs(t *testing.T) {
}, },
{ {
do: doQuery("2", testTime), do: doQuery("2", testTime),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
reqMethod: "POST", reqMethod: "POST",
reqPath: "/api/v1/query", reqPath: "/api/v1/query",
@ -336,7 +336,7 @@ func TestAPIs(t *testing.T) {
End: testTime, End: testTime,
Step: 1 * time.Minute, Step: 1 * time.Minute,
}, WithTimeout(5*time.Second)), }, WithTimeout(5*time.Second)),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
reqMethod: "POST", reqMethod: "POST",
reqPath: "/api/v1/query_range", reqPath: "/api/v1/query_range",
@ -361,14 +361,14 @@ func TestAPIs(t *testing.T) {
{ {
do: doLabelNames(nil, testTime.Add(-100*time.Hour), testTime), do: doLabelNames(nil, testTime.Add(-100*time.Hour), testTime),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
reqMethod: "POST", reqMethod: "POST",
reqPath: "/api/v1/labels", reqPath: "/api/v1/labels",
err: errors.New("some error"), err: errors.New("some error"),
}, },
{ {
do: doLabelNames(nil, testTime.Add(-100*time.Hour), testTime), do: doLabelNames(nil, testTime.Add(-100*time.Hour), testTime),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
inWarnings: []string{"a"}, inWarnings: []string{"a"},
reqMethod: "POST", reqMethod: "POST",
reqPath: "/api/v1/labels", reqPath: "/api/v1/labels",
@ -400,14 +400,14 @@ func TestAPIs(t *testing.T) {
{ {
do: doLabelValues(nil, "mylabel", testTime.Add(-100*time.Hour), testTime), do: doLabelValues(nil, "mylabel", testTime.Add(-100*time.Hour), testTime),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/label/mylabel/values", reqPath: "/api/v1/label/mylabel/values",
err: errors.New("some error"), err: errors.New("some error"),
}, },
{ {
do: doLabelValues(nil, "mylabel", testTime.Add(-100*time.Hour), testTime), do: doLabelValues(nil, "mylabel", testTime.Add(-100*time.Hour), testTime),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
inWarnings: []string{"a"}, inWarnings: []string{"a"},
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/label/mylabel/values", reqPath: "/api/v1/label/mylabel/values",
@ -464,7 +464,7 @@ func TestAPIs(t *testing.T) {
{ {
do: doSeries("up", testTime.Add(-time.Minute), testTime), do: doSeries("up", testTime.Add(-time.Minute), testTime),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
reqMethod: "POST", reqMethod: "POST",
reqPath: "/api/v1/series", reqPath: "/api/v1/series",
err: errors.New("some error"), err: errors.New("some error"),
@ -472,7 +472,7 @@ func TestAPIs(t *testing.T) {
// Series with error and warning. // Series with error and warning.
{ {
do: doSeries("up", testTime.Add(-time.Minute), testTime), do: doSeries("up", testTime.Add(-time.Minute), testTime),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
inWarnings: []string{"a"}, inWarnings: []string{"a"},
reqMethod: "POST", reqMethod: "POST",
reqPath: "/api/v1/series", reqPath: "/api/v1/series",
@ -493,7 +493,7 @@ func TestAPIs(t *testing.T) {
{ {
do: doSnapshot(true), do: doSnapshot(true),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
reqMethod: "POST", reqMethod: "POST",
reqPath: "/api/v1/admin/tsdb/snapshot", reqPath: "/api/v1/admin/tsdb/snapshot",
err: errors.New("some error"), err: errors.New("some error"),
@ -507,7 +507,7 @@ func TestAPIs(t *testing.T) {
{ {
do: doCleanTombstones(), do: doCleanTombstones(),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
reqMethod: "POST", reqMethod: "POST",
reqPath: "/api/v1/admin/tsdb/clean_tombstones", reqPath: "/api/v1/admin/tsdb/clean_tombstones",
err: errors.New("some error"), err: errors.New("some error"),
@ -528,7 +528,7 @@ func TestAPIs(t *testing.T) {
{ {
do: doDeleteSeries("up", testTime.Add(-time.Minute), testTime), do: doDeleteSeries("up", testTime.Add(-time.Minute), testTime),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
reqMethod: "POST", reqMethod: "POST",
reqPath: "/api/v1/admin/tsdb/delete_series", reqPath: "/api/v1/admin/tsdb/delete_series",
err: errors.New("some error"), err: errors.New("some error"),
@ -550,8 +550,8 @@ func TestAPIs(t *testing.T) {
do: doConfig(), do: doConfig(),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/status/config", reqPath: "/api/v1/status/config",
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
err: fmt.Errorf("some error"), err: errors.New("some error"),
}, },
{ {
@ -578,16 +578,16 @@ func TestAPIs(t *testing.T) {
do: doFlags(), do: doFlags(),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/status/flags", reqPath: "/api/v1/status/flags",
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
err: fmt.Errorf("some error"), err: errors.New("some error"),
}, },
{ {
do: doBuildinfo(), do: doBuildinfo(),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/status/buildinfo", reqPath: "/api/v1/status/buildinfo",
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
err: fmt.Errorf("some error"), err: errors.New("some error"),
}, },
{ {
@ -616,8 +616,8 @@ func TestAPIs(t *testing.T) {
do: doRuntimeinfo(), do: doRuntimeinfo(),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/status/runtimeinfo", reqPath: "/api/v1/status/runtimeinfo",
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
err: fmt.Errorf("some error"), err: errors.New("some error"),
}, },
{ {
@ -684,8 +684,8 @@ func TestAPIs(t *testing.T) {
do: doAlertManagers(), do: doAlertManagers(),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/alertmanagers", reqPath: "/api/v1/alertmanagers",
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
err: fmt.Errorf("some error"), err: errors.New("some error"),
}, },
{ {
@ -891,8 +891,8 @@ func TestAPIs(t *testing.T) {
do: doRules(), do: doRules(),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/rules", reqPath: "/api/v1/rules",
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
err: fmt.Errorf("some error"), err: errors.New("some error"),
}, },
{ {
@ -971,8 +971,8 @@ func TestAPIs(t *testing.T) {
do: doTargets(), do: doTargets(),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/targets", reqPath: "/api/v1/targets",
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
err: fmt.Errorf("some error"), err: errors.New("some error"),
}, },
{ {
@ -1005,7 +1005,7 @@ func TestAPIs(t *testing.T) {
{ {
do: doTargetsMetadata("{job=\"prometheus\"}", "go_goroutines", "1"), do: doTargetsMetadata("{job=\"prometheus\"}", "go_goroutines", "1"),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/targets/metadata", reqPath: "/api/v1/targets/metadata",
err: errors.New("some error"), err: errors.New("some error"),
@ -1037,7 +1037,7 @@ func TestAPIs(t *testing.T) {
{ {
do: doMetadata("", "1"), do: doMetadata("", "1"),
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/metadata", reqPath: "/api/v1/metadata",
err: errors.New("some error"), err: errors.New("some error"),
@ -1047,8 +1047,8 @@ func TestAPIs(t *testing.T) {
do: doTSDB(), do: doTSDB(),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/status/tsdb", reqPath: "/api/v1/status/tsdb",
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
err: fmt.Errorf("some error"), err: errors.New("some error"),
}, },
{ {
@ -1127,8 +1127,8 @@ func TestAPIs(t *testing.T) {
do: doWalReply(), do: doWalReply(),
reqMethod: "GET", reqMethod: "GET",
reqPath: "/api/v1/status/walreplay", reqPath: "/api/v1/status/walreplay",
inErr: fmt.Errorf("some error"), inErr: errors.New("some error"),
err: fmt.Errorf("some error"), err: errors.New("some error"),
}, },
{ {
@ -1212,7 +1212,7 @@ func TestAPIs(t *testing.T) {
tests = append(tests, queryTests...) tests = append(tests, queryTests...)
for i, test := range tests { for i, test := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { t.Run(strconv.Itoa(i), func(t *testing.T) {
tc.curTest = test tc.curTest = test
res, warnings, err := test.do() res, warnings, err := test.do()
@ -1430,7 +1430,7 @@ func TestAPIClientDo(t *testing.T) {
} }
for i, test := range tests { for i, test := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { t.Run(strconv.Itoa(i), func(t *testing.T) {
tc.ch <- test tc.ch <- test
_, body, warnings, err := client.Do(context.Background(), tc.req) _, body, warnings, err := client.Do(context.Background(), tc.req)

View File

@ -17,10 +17,10 @@
package main package main
import ( import (
"fmt"
"log" "log"
"math/rand" "math/rand"
"net/http" "net/http"
"strconv"
"time" "time"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
@ -50,7 +50,7 @@ func main() {
// Record fictional latency. // Record fictional latency.
now := time.Now() now := time.Now()
requestDurations.(prometheus.ExemplarObserver).ObserveWithExemplar( requestDurations.(prometheus.ExemplarObserver).ObserveWithExemplar(
time.Since(now).Seconds(), prometheus.Labels{"dummyID": fmt.Sprint(rand.Intn(100000))}, time.Since(now).Seconds(), prometheus.Labels{"dummyID": strconv.Itoa(rand.Intn(100000))},
) )
time.Sleep(600 * time.Millisecond) time.Sleep(600 * time.Millisecond)
} }

View File

@ -18,11 +18,11 @@ package main
import ( import (
"flag" "flag"
"fmt"
"log" "log"
"math" "math"
"math/rand" "math/rand"
"net/http" "net/http"
"strconv"
"time" "time"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
@ -116,7 +116,7 @@ func main() {
// the ExemplarObserver interface and thus don't need to // the ExemplarObserver interface and thus don't need to
// check the outcome of the type assertion. // check the outcome of the type assertion.
m.rpcDurationsHistogram.(prometheus.ExemplarObserver).ObserveWithExemplar( m.rpcDurationsHistogram.(prometheus.ExemplarObserver).ObserveWithExemplar(
v, prometheus.Labels{"dummyID": fmt.Sprint(rand.Intn(100000))}, v, prometheus.Labels{"dummyID": strconv.Itoa(rand.Intn(100000))},
) )
time.Sleep(time.Duration(75*oscillationFactor()) * time.Millisecond) time.Sleep(time.Duration(75*oscillationFactor()) * time.Millisecond)
} }

View File

@ -14,7 +14,6 @@
package prometheus package prometheus
import ( import (
"fmt"
"math" "math"
"strings" "strings"
"testing" "testing"
@ -120,10 +119,10 @@ func TestCounterVecGetMetricWithInvalidLabelValues(t *testing.T) {
expectPanic(t, func() { expectPanic(t, func() {
counterVec.WithLabelValues(labelValues...) counterVec.WithLabelValues(labelValues...)
}, fmt.Sprintf("WithLabelValues: expected panic because: %s", test.desc)) }, "WithLabelValues: expected panic because: "+test.desc)
expectPanic(t, func() { expectPanic(t, func() {
counterVec.With(test.labels) counterVec.With(test.labels)
}, fmt.Sprintf("WithLabelValues: expected panic because: %s", test.desc)) }, "WithLabelValues: expected panic because: "+test.desc)
if _, err := counterVec.GetMetricWithLabelValues(labelValues...); err == nil { if _, err := counterVec.GetMetricWithLabelValues(labelValues...); err == nil {
t.Errorf("GetMetricWithLabelValues: expected error because: %s", test.desc) t.Errorf("GetMetricWithLabelValues: expected error because: %s", test.desc)

View File

@ -22,6 +22,7 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"strconv"
"strings" "strings"
) )
@ -524,7 +525,7 @@ func formatRangeUnified(start, stop int) string {
beginning := start + 1 // lines start numbering with one beginning := start + 1 // lines start numbering with one
length := stop - start length := stop - start
if length == 1 { if length == 1 {
return fmt.Sprintf("%d", beginning) return strconv.Itoa(beginning)
} }
if length == 0 { if length == 0 {
beginning-- // empty ranges begin at line just before the range beginning-- // empty ranges begin at line just before the range

View File

@ -22,9 +22,7 @@ import "C"
import "fmt" import "fmt"
func getMemory() (*memoryInfo, error) { func getMemory() (*memoryInfo, error) {
var ( var rss, vsize C.ulonglong
rss, vsize C.ulonglong
)
if err := C.get_memory_info(&rss, &vsize); err != 0 { if err := C.get_memory_info(&rss, &vsize); err != 0 {
return nil, fmt.Errorf("task_info() failed with 0x%x", int(err)) return nil, fmt.Errorf("task_info() failed with 0x%x", int(err))

View File

@ -98,7 +98,7 @@ func readCompressedBody(r io.Reader, comp Compression) (string, error) {
got, err := io.ReadAll(reader) got, err := io.ReadAll(reader)
return string(got), err return string(got), err
} }
return "", fmt.Errorf("Unsupported compression") return "", errors.New("Unsupported compression")
} }
func TestHandlerErrorHandling(t *testing.T) { func TestHandlerErrorHandling(t *testing.T) {

View File

@ -27,6 +27,7 @@ import (
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
"strconv"
"sync" "sync"
"testing" "testing"
"time" "time"
@ -1282,7 +1283,7 @@ func ExampleRegistry_grouping() {
ConstLabels: prometheus.Labels{ ConstLabels: prometheus.Labels{
// Generate a label unique to this worker so its metric doesn't // Generate a label unique to this worker so its metric doesn't
// collide with the metrics from other workers. // collide with the metrics from other workers.
"worker_id": fmt.Sprintf("%d", workerID), "worker_id": strconv.Itoa(workerID),
}, },
}) })
workerReg.MustRegister(workTime) workerReg.MustRegister(workTime)

View File

@ -14,6 +14,7 @@
package promlint_test package promlint_test
import ( import (
"errors"
"fmt" "fmt"
"reflect" "reflect"
"strings" "strings"
@ -733,7 +734,7 @@ request_duration_seconds{httpService="foo"} 10
func TestLintUnitAbbreviations(t *testing.T) { func TestLintUnitAbbreviations(t *testing.T) {
genTest := func(n string) test { genTest := func(n string) test {
return test{ return test{
name: fmt.Sprintf("%s with abbreviated unit", n), name: n + " with abbreviated unit",
in: fmt.Sprintf(` in: fmt.Sprintf(`
# HELP %s Test metric. # HELP %s Test metric.
# TYPE %s gauge # TYPE %s gauge
@ -820,7 +821,7 @@ mc_something_total 10
prefixValidation := func(mf *dto.MetricFamily) []error { prefixValidation := func(mf *dto.MetricFamily) []error {
if !strings.HasPrefix(mf.GetName(), "memcached_") { if !strings.HasPrefix(mf.GetName(), "memcached_") {
return []error{fmt.Errorf("expected metric name to start with 'memcached_'")} return []error{errors.New("expected metric name to start with 'memcached_'")}
} }
return nil return nil
} }

View File

@ -14,7 +14,7 @@
package validations package validations
import ( import (
"fmt" "errors"
"reflect" "reflect"
dto "github.com/prometheus/client_model/go" dto "github.com/prometheus/client_model/go"
@ -27,7 +27,7 @@ func LintDuplicateMetric(mf *dto.MetricFamily) []error {
for i, m := range mf.Metric { for i, m := range mf.Metric {
for _, k := range mf.Metric[i+1:] { for _, k := range mf.Metric[i+1:] {
if reflect.DeepEqual(m.Label, k.Label) { if reflect.DeepEqual(m.Label, k.Label) {
problems = append(problems, fmt.Errorf("metric not unique")) problems = append(problems, errors.New("metric not unique"))
break break
} }
} }

View File

@ -14,7 +14,6 @@
package prometheus package prometheus
import ( import (
"fmt"
"testing" "testing"
"time" "time"
@ -51,7 +50,7 @@ func TestNewConstMetricInvalidLabelValues(t *testing.T) {
expectPanic(t, func() { expectPanic(t, func() {
MustNewConstMetric(metricDesc, CounterValue, 0.3, "\xFF") MustNewConstMetric(metricDesc, CounterValue, 0.3, "\xFF")
}, fmt.Sprintf("WithLabelValues: expected panic because: %s", test.desc)) }, "WithLabelValues: expected panic because: "+test.desc)
if _, err := NewConstMetric(metricDesc, CounterValue, 0.3, "\xFF"); err == nil { if _, err := NewConstMetric(metricDesc, CounterValue, 0.3, "\xFF"); err == nil {
t.Errorf("NewConstMetric: expected error because: %s", test.desc) t.Errorf("NewConstMetric: expected error because: %s", test.desc)

View File

@ -16,6 +16,7 @@ package prometheus
import ( import (
"fmt" "fmt"
"reflect" "reflect"
"strconv"
"testing" "testing"
dto "github.com/prometheus/client_model/go" dto "github.com/prometheus/client_model/go"
@ -291,7 +292,7 @@ func testMetricVec(t *testing.T, vec *GaugeVec) {
expected := map[[2]string]int{} expected := map[[2]string]int{}
for i := 0; i < 1000; i++ { for i := 0; i < 1000; i++ {
pair[0], pair[1] = fmt.Sprint(i%4), fmt.Sprint(i%5) // Varying combinations multiples. pair[0], pair[1] = strconv.Itoa(i%4), strconv.Itoa(i%5) // Varying combinations multiples.
expected[pair]++ expected[pair]++
vec.WithLabelValues(pair[0], pair[1]).Inc() vec.WithLabelValues(pair[0], pair[1]).Inc()
@ -363,7 +364,7 @@ func testConstrainedMetricVec(t *testing.T, vec *GaugeVec, constrain func(string
expected := map[[2]string]int{} expected := map[[2]string]int{}
for i := 0; i < 1000; i++ { for i := 0; i < 1000; i++ {
pair[0], pair[1] = fmt.Sprint(i%4), fmt.Sprint(i%5) // Varying combinations multiples. pair[0], pair[1] = strconv.Itoa(i%4), strconv.Itoa(i%5) // Varying combinations multiples.
expected[[2]string{pair[0], constrain(pair[1])}]++ expected[[2]string{pair[0], constrain(pair[1])}]++
vec.WithLabelValues(pair[0], pair[1]).Inc() vec.WithLabelValues(pair[0], pair[1]).Inc()