diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 6034bcbf8..3ea512e73 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -1,3 +1,4 @@ +--- name: golangci-lint on: push: diff --git a/.golangci.yml b/.golangci.yml index d9efa75c7..bedb09e6a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,31 @@ -# Run only staticcheck for now. Additional linters will be enabled one-by-one. +--- + +run: + deadline: 5m + +output: + sort-results: true + linters: enable: - - staticcheck - disable-all: true + - gofumpt + - goimports + - revive + - misspell + +issues: + max-same-issues: 0 + exclude-rules: + - path: _test.go + linters: + - errcheck + - govet + - structcheck + +linters-settings: + errcheck: + exclude: scripts/errcheck_excludes.txt + goimports: + local-prefixes: github.com/prometheus/client_golang + gofumpt: + extra-rules: true diff --git a/api/client_test.go b/api/client_test.go index 4215c73db..874387868 100644 --- a/api/client_test.go +++ b/api/client_test.go @@ -134,7 +134,6 @@ func BenchmarkClient(b *testing.B) { for _, sizeKB := range []int{4, 50, 1000, 2000} { b.Run(fmt.Sprintf("%dKB", sizeKB), func(b *testing.B) { - testServer := httptest.NewServer(serveSpaces{sizeKB}) defer testServer.Close() diff --git a/api/prometheus/v1/api.go b/api/prometheus/v1/api.go index c45e03dde..bc89cb4ae 100644 --- a/api/prometheus/v1/api.go +++ b/api/prometheus/v1/api.go @@ -109,7 +109,6 @@ func marshalPointJSON(ptr unsafe.Pointer, stream *json.Stream) { stream.WriteRaw(`"`) stream.WriteArrayEnd() - } func marshalPointJSONIsEmpty(ptr unsafe.Pointer) bool { @@ -230,25 +229,25 @@ type API interface { // Config returns the current Prometheus configuration. Config(ctx context.Context) (ConfigResult, error) // DeleteSeries deletes data for a selection of series in a time range. - DeleteSeries(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) error + DeleteSeries(ctx context.Context, matches []string, startTime, endTime time.Time) error // Flags returns the flag values that Prometheus was launched with. Flags(ctx context.Context) (FlagsResult, error) // LabelNames returns the unique label names present in the block in sorted order by given time range and matchers. - LabelNames(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) ([]string, Warnings, error) + LabelNames(ctx context.Context, matches []string, startTime, endTime time.Time) ([]string, Warnings, error) // LabelValues performs a query for the values of the given label, time range and matchers. - LabelValues(ctx context.Context, label string, matches []string, startTime time.Time, endTime time.Time) (model.LabelValues, Warnings, error) + LabelValues(ctx context.Context, label string, matches []string, startTime, endTime time.Time) (model.LabelValues, Warnings, error) // Query performs a query for the given time. Query(ctx context.Context, query string, ts time.Time, opts ...Option) (model.Value, Warnings, error) // QueryRange performs a query for the given range. QueryRange(ctx context.Context, query string, r Range, opts ...Option) (model.Value, Warnings, error) // QueryExemplars performs a query for exemplars by the given query and time range. - QueryExemplars(ctx context.Context, query string, startTime time.Time, endTime time.Time) ([]ExemplarQueryResult, error) + QueryExemplars(ctx context.Context, query string, startTime, endTime time.Time) ([]ExemplarQueryResult, error) // Buildinfo returns various build information properties about the Prometheus server Buildinfo(ctx context.Context) (BuildinfoResult, error) // Runtimeinfo returns the various runtime information properties about the Prometheus server. Runtimeinfo(ctx context.Context) (RuntimeinfoResult, error) // Series finds series by label matchers. - Series(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) ([]model.LabelSet, Warnings, error) + Series(ctx context.Context, matches []string, startTime, endTime time.Time) ([]model.LabelSet, Warnings, error) // Snapshot creates a snapshot of all current data into snapshots/- // under the TSDB's data directory and returns the directory as response. Snapshot(ctx context.Context, skipHead bool) (SnapshotResult, error) @@ -257,9 +256,9 @@ type API interface { // Targets returns an overview of the current state of the Prometheus target discovery. Targets(ctx context.Context) (TargetsResult, error) // TargetsMetadata returns metadata about metrics currently scraped by the target. - TargetsMetadata(ctx context.Context, matchTarget string, metric string, limit string) ([]MetricMetadata, error) + TargetsMetadata(ctx context.Context, matchTarget, metric, limit string) ([]MetricMetadata, error) // Metadata returns metadata about metrics currently scraped by the metric name. - Metadata(ctx context.Context, metric string, limit string) (map[string][]Metadata, error) + Metadata(ctx context.Context, metric, limit string) (map[string][]Metadata, error) // TSDB returns the cardinality statistics. TSDB(ctx context.Context) (TSDBResult, error) // WalReplay returns the current replay status of the wal. @@ -699,7 +698,7 @@ func (h *httpAPI) Config(ctx context.Context) (ConfigResult, error) { return res, json.Unmarshal(body, &res) } -func (h *httpAPI) DeleteSeries(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) error { +func (h *httpAPI) DeleteSeries(ctx context.Context, matches []string, startTime, endTime time.Time) error { u := h.client.URL(epDeleteSeries, nil) q := u.Query() @@ -772,7 +771,7 @@ func (h *httpAPI) Runtimeinfo(ctx context.Context) (RuntimeinfoResult, error) { return res, json.Unmarshal(body, &res) } -func (h *httpAPI) LabelNames(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) ([]string, Warnings, error) { +func (h *httpAPI) LabelNames(ctx context.Context, matches []string, startTime, endTime time.Time) ([]string, Warnings, error) { u := h.client.URL(epLabels, nil) q := u.Query() q.Set("start", formatTime(startTime)) @@ -795,7 +794,7 @@ func (h *httpAPI) LabelNames(ctx context.Context, matches []string, startTime ti return labelNames, w, json.Unmarshal(body, &labelNames) } -func (h *httpAPI) LabelValues(ctx context.Context, label string, matches []string, startTime time.Time, endTime time.Time) (model.LabelValues, Warnings, error) { +func (h *httpAPI) LabelValues(ctx context.Context, label string, matches []string, startTime, endTime time.Time) (model.LabelValues, Warnings, error) { u := h.client.URL(epLabelValues, map[string]string{"name": label}) q := u.Query() q.Set("start", formatTime(startTime)) @@ -833,7 +832,6 @@ func WithTimeout(timeout time.Duration) Option { } func (h *httpAPI) Query(ctx context.Context, query string, ts time.Time, opts ...Option) (model.Value, Warnings, error) { - u := h.client.URL(epQuery, nil) q := u.Query() @@ -890,7 +888,7 @@ func (h *httpAPI) QueryRange(ctx context.Context, query string, r Range, opts .. return model.Value(qres.v), warnings, json.Unmarshal(body, &qres) } -func (h *httpAPI) Series(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) ([]model.LabelSet, Warnings, error) { +func (h *httpAPI) Series(ctx context.Context, matches []string, startTime, endTime time.Time) ([]model.LabelSet, Warnings, error) { u := h.client.URL(epSeries, nil) q := u.Query() @@ -973,7 +971,7 @@ func (h *httpAPI) Targets(ctx context.Context) (TargetsResult, error) { return res, json.Unmarshal(body, &res) } -func (h *httpAPI) TargetsMetadata(ctx context.Context, matchTarget string, metric string, limit string) ([]MetricMetadata, error) { +func (h *httpAPI) TargetsMetadata(ctx context.Context, matchTarget, metric, limit string) ([]MetricMetadata, error) { u := h.client.URL(epTargetsMetadata, nil) q := u.Query() @@ -997,7 +995,7 @@ func (h *httpAPI) TargetsMetadata(ctx context.Context, matchTarget string, metri return res, json.Unmarshal(body, &res) } -func (h *httpAPI) Metadata(ctx context.Context, metric string, limit string) (map[string][]Metadata, error) { +func (h *httpAPI) Metadata(ctx context.Context, metric, limit string) (map[string][]Metadata, error) { u := h.client.URL(epMetadata, nil) q := u.Query() @@ -1054,7 +1052,7 @@ func (h *httpAPI) WalReplay(ctx context.Context) (WalReplayStatus, error) { return res, json.Unmarshal(body, &res) } -func (h *httpAPI) QueryExemplars(ctx context.Context, query string, startTime time.Time, endTime time.Time) ([]ExemplarQueryResult, error) { +func (h *httpAPI) QueryExemplars(ctx context.Context, query string, startTime, endTime time.Time) ([]ExemplarQueryResult, error) { u := h.client.URL(epQueryExemplars, nil) q := u.Query() @@ -1162,7 +1160,6 @@ func (h *apiClientImpl) Do(ctx context.Context, req *http.Request) (*http.Respon } return resp, []byte(result.Data), result.Warnings, err - } // DoGetFallback will attempt to do the request as-is, and on a 405 or 501 it diff --git a/api/prometheus/v1/api_test.go b/api/prometheus/v1/api_test.go index 82c234bbd..9fbd29be1 100644 --- a/api/prometheus/v1/api_test.go +++ b/api/prometheus/v1/api_test.go @@ -65,7 +65,6 @@ func (c *apiTestClient) URL(ep string, args map[string]string) *url.URL { } func (c *apiTestClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, Warnings, error) { - test := c.curTest if req.URL.Path != test.reqPath { @@ -101,7 +100,6 @@ func (c *apiTestClient) DoGetFallback(ctx context.Context, u *url.URL, args url. } func TestAPIs(t *testing.T) { - testTime := time.Now() tc := &apiTestClient{ @@ -131,7 +129,7 @@ func TestAPIs(t *testing.T) { } } - doDeleteSeries := func(matcher string, startTime time.Time, endTime time.Time) func() (interface{}, Warnings, error) { + doDeleteSeries := func(matcher string, startTime, endTime time.Time) func() (interface{}, Warnings, error) { return func() (interface{}, Warnings, error) { return nil, nil, promAPI.DeleteSeries(context.Background(), []string{matcher}, startTime, endTime) } @@ -182,7 +180,7 @@ func TestAPIs(t *testing.T) { } } - doSeries := func(matcher string, startTime time.Time, endTime time.Time) func() (interface{}, Warnings, error) { + doSeries := func(matcher string, startTime, endTime time.Time) func() (interface{}, Warnings, error) { return func() (interface{}, Warnings, error) { return promAPI.Series(context.Background(), []string{matcher}, startTime, endTime) } @@ -209,14 +207,14 @@ func TestAPIs(t *testing.T) { } } - doTargetsMetadata := func(matchTarget string, metric string, limit string) func() (interface{}, Warnings, error) { + doTargetsMetadata := func(matchTarget, metric, limit string) func() (interface{}, Warnings, error) { return func() (interface{}, Warnings, error) { v, err := promAPI.TargetsMetadata(context.Background(), matchTarget, metric, limit) return v, nil, err } } - doMetadata := func(metric string, limit string) func() (interface{}, Warnings, error) { + doMetadata := func(metric, limit string) func() (interface{}, Warnings, error) { return func() (interface{}, Warnings, error) { v, err := promAPI.Metadata(context.Background(), metric, limit) return v, nil, err @@ -237,7 +235,7 @@ func TestAPIs(t *testing.T) { } } - doQueryExemplars := func(query string, startTime time.Time, endTime time.Time) func() (interface{}, Warnings, error) { + doQueryExemplars := func(query string, startTime, endTime time.Time) func() (interface{}, Warnings, error) { return func() (interface{}, Warnings, error) { v, err := promAPI.QueryExemplars(context.Background(), query, startTime, endTime) return v, nil, err @@ -471,7 +469,8 @@ func TestAPIs(t *testing.T) { { "__name__": "up", "job": "prometheus", - "instance": "localhost:9090"}, + "instance": "localhost:9090", + }, }, reqMethod: "GET", reqPath: "/api/v1/series", @@ -495,7 +494,8 @@ func TestAPIs(t *testing.T) { { "__name__": "up", "job": "prometheus", - "instance": "localhost:9090"}, + "instance": "localhost:9090", + }, }, inWarnings: []string{"a"}, reqMethod: "GET", @@ -586,7 +586,8 @@ func TestAPIs(t *testing.T) { { "__name__": "up", "job": "prometheus", - "instance": "localhost:9090"}, + "instance": "localhost:9090", + }, }, reqMethod: "POST", reqPath: "/api/v1/admin/tsdb/delete_series", @@ -1115,7 +1116,7 @@ func TestAPIs(t *testing.T) { "limit": []string{"1"}, }, res: map[string][]Metadata{ - "go_goroutines": []Metadata{ + "go_goroutines": { { Type: "gauge", Help: "Number of goroutines that currently exist.", @@ -1523,7 +1524,6 @@ func TestAPIClientDo(t *testing.T) { for i, test := range tests { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { - tc.ch <- test _, body, warnings, err := client.Do(context.Background(), tc.req) @@ -1564,7 +1564,6 @@ func TestAPIClientDo(t *testing.T) { t.Fatalf("expected body :%v, but got:%v", test.expectedBody, string(body)) } }) - } } diff --git a/api/prometheus/v1/example_test.go b/api/prometheus/v1/example_test.go index f0ee3b667..5876572ad 100644 --- a/api/prometheus/v1/example_test.go +++ b/api/prometheus/v1/example_test.go @@ -22,9 +22,10 @@ import ( "os" "time" + "github.com/prometheus/common/config" + "github.com/prometheus/client_golang/api" v1 "github.com/prometheus/client_golang/api/prometheus/v1" - "github.com/prometheus/common/config" ) func ExampleAPI_query() { diff --git a/prometheus/collector_test.go b/prometheus/collector_test.go index 45eab3ea4..a1fd228bc 100644 --- a/prometheus/collector_test.go +++ b/prometheus/collector_test.go @@ -30,7 +30,6 @@ func (c collectorDescribedByCollect) Describe(ch chan<- *Desc) { } func TestDescribeByCollect(t *testing.T) { - goodCollector := collectorDescribedByCollect{ cnt: NewCounter(CounterOpts{Name: "c1", Help: "help c1"}), gge: NewGauge(GaugeOpts{Name: "g1", Help: "help g1"}), diff --git a/prometheus/collectors/go_collector_latest.go b/prometheus/collectors/go_collector_latest.go index 01790e885..9435e9614 100644 --- a/prometheus/collectors/go_collector_latest.go +++ b/prometheus/collectors/go_collector_latest.go @@ -72,7 +72,8 @@ const ( // // The current default is GoRuntimeMemStatsCollection, so the compatibility mode with // client_golang pre v1.12 (move to runtime/metrics). -func WithGoCollections(flags GoCollectionOption) goOption { +//nolint:staticcheck // Ignore SA1019 until v2. +func WithGoCollections(flags GoCollectionOption) func(options *prometheus.GoCollectorOptions) { return func(o *goOptions) { o.EnabledCollections = uint32(flags) } diff --git a/prometheus/counter_test.go b/prometheus/counter_test.go index 9d099dc87..40ba4278b 100644 --- a/prometheus/counter_test.go +++ b/prometheus/counter_test.go @@ -231,7 +231,7 @@ func TestCounterExemplar(t *testing.T) { } expectedExemplar := &dto.Exemplar{ Label: []*dto.LabelPair{ - &dto.LabelPair{Name: proto.String("foo"), Value: proto.String("bar")}, + {Name: proto.String("foo"), Value: proto.String("bar")}, }, Value: proto.Float64(42), Timestamp: ts, diff --git a/prometheus/desc.go b/prometheus/desc.go index ee81107c8..8bc5e44e2 100644 --- a/prometheus/desc.go +++ b/prometheus/desc.go @@ -20,6 +20,7 @@ import ( "strings" "github.com/cespare/xxhash/v2" + "github.com/prometheus/client_golang/prometheus/internal" //nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility. diff --git a/prometheus/example_metricvec_test.go b/prometheus/example_metricvec_test.go index 54f924b6d..173196d0b 100644 --- a/prometheus/example_metricvec_test.go +++ b/prometheus/example_metricvec_test.go @@ -108,7 +108,6 @@ func (v *InfoVec) MustCurryWith(labels prometheus.Labels) *InfoVec { } func ExampleMetricVec() { - infoVec := NewInfoVec( "library_version_info", "Versions of the libraries used in this binary.", diff --git a/prometheus/example_timer_complex_test.go b/prometheus/example_timer_complex_test.go index c5e7de5e5..a20498a6d 100644 --- a/prometheus/example_timer_complex_test.go +++ b/prometheus/example_timer_complex_test.go @@ -19,27 +19,25 @@ import ( "github.com/prometheus/client_golang/prometheus" ) -var ( - // apiRequestDuration tracks the duration separate for each HTTP status - // class (1xx, 2xx, ...). This creates a fair amount of time series on - // the Prometheus server. Usually, you would track the duration of - // serving HTTP request without partitioning by outcome. Do something - // like this only if needed. Also note how only status classes are - // tracked, not every single status code. The latter would create an - // even larger amount of time series. Request counters partitioned by - // status code are usually OK as each counter only creates one time - // series. Histograms are way more expensive, so partition with care and - // only where you really need separate latency tracking. Partitioning by - // status class is only an example. In concrete cases, other partitions - // might make more sense. - apiRequestDuration = prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "api_request_duration_seconds", - Help: "Histogram for the request duration of the public API, partitioned by status class.", - Buckets: prometheus.ExponentialBuckets(0.1, 1.5, 5), - }, - []string{"status_class"}, - ) +// apiRequestDuration tracks the duration separate for each HTTP status +// class (1xx, 2xx, ...). This creates a fair amount of time series on +// the Prometheus server. Usually, you would track the duration of +// serving HTTP request without partitioning by outcome. Do something +// like this only if needed. Also note how only status classes are +// tracked, not every single status code. The latter would create an +// even larger amount of time series. Request counters partitioned by +// status code are usually OK as each counter only creates one time +// series. Histograms are way more expensive, so partition with care and +// only where you really need separate latency tracking. Partitioning by +// status class is only an example. In concrete cases, other partitions +// might make more sense. +var apiRequestDuration = prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Name: "api_request_duration_seconds", + Help: "Histogram for the request duration of the public API, partitioned by status class.", + Buckets: prometheus.ExponentialBuckets(0.1, 1.5, 5), + }, + []string{"status_class"}, ) func handler(w http.ResponseWriter, r *http.Request) { diff --git a/prometheus/example_timer_gauge_test.go b/prometheus/example_timer_gauge_test.go index 7184a0d1d..85afdac63 100644 --- a/prometheus/example_timer_gauge_test.go +++ b/prometheus/example_timer_gauge_test.go @@ -19,17 +19,15 @@ import ( "github.com/prometheus/client_golang/prometheus" ) -var ( - // If a function is called rarely (i.e. not more often than scrapes - // happen) or ideally only once (like in a batch job), it can make sense - // to use a Gauge for timing the function call. For timing a batch job - // and pushing the result to a Pushgateway, see also the comprehensive - // example in the push package. - funcDuration = prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "example_function_duration_seconds", - Help: "Duration of the last call of an example function.", - }) -) +// If a function is called rarely (i.e. not more often than scrapes +// happen) or ideally only once (like in a batch job), it can make sense +// to use a Gauge for timing the function call. For timing a batch job +// and pushing the result to a Pushgateway, see also the comprehensive +// example in the push package. +var funcDuration = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "example_function_duration_seconds", + Help: "Duration of the last call of an example function.", +}) func run() error { // The Set method of the Gauge is used to observe the duration. diff --git a/prometheus/example_timer_test.go b/prometheus/example_timer_test.go index bd86bb472..e851a5765 100644 --- a/prometheus/example_timer_test.go +++ b/prometheus/example_timer_test.go @@ -20,13 +20,11 @@ import ( "github.com/prometheus/client_golang/prometheus" ) -var ( - requestDuration = prometheus.NewHistogram(prometheus.HistogramOpts{ - Name: "example_request_duration_seconds", - Help: "Histogram for the runtime of a simple example function.", - Buckets: prometheus.LinearBuckets(0.01, 0.01, 10), - }) -) +var requestDuration = prometheus.NewHistogram(prometheus.HistogramOpts{ + Name: "example_request_duration_seconds", + Help: "Histogram for the runtime of a simple example function.", + Buckets: prometheus.LinearBuckets(0.01, 0.01, 10), +}) func ExampleTimer() { // timer times this example function. It uses a Histogram, but a Summary diff --git a/prometheus/go_collector_latest.go b/prometheus/go_collector_latest.go index a0fe95eb1..68a7a156c 100644 --- a/prometheus/go_collector_latest.go +++ b/prometheus/go_collector_latest.go @@ -54,7 +54,8 @@ const ( ) // runtime/metrics names required for runtimeMemStats like logic. -var rmForMemStats = []string{goGCHeapTinyAllocsObjects, +var rmForMemStats = []string{ + goGCHeapTinyAllocsObjects, goGCHeapAllocsObjects, goGCHeapFreesObjects, goGCHeapAllocsBytes, diff --git a/prometheus/graphite/bridge.go b/prometheus/graphite/bridge.go index 09c31b5cd..84eac0de9 100644 --- a/prometheus/graphite/bridge.go +++ b/prometheus/graphite/bridge.go @@ -240,9 +240,8 @@ func writeMetric(buf *bufio.Writer, m model.Metric, useTags bool) error { } if useTags { return writeTags(buf, m) - } else { - return writeLabels(buf, m, numLabels) } + return writeLabels(buf, m, numLabels) } return nil } diff --git a/prometheus/histogram_test.go b/prometheus/histogram_test.go index b96eff9e1..e0999a92f 100644 --- a/prometheus/histogram_test.go +++ b/prometheus/histogram_test.go @@ -354,7 +354,8 @@ func TestBuckets(t *testing.T) { } got = ExponentialBucketsRange(1, 100, 10) - want = []float64{1.0, 1.6681005372000588, 2.782559402207125, + want = []float64{ + 1.0, 1.6681005372000588, 2.782559402207125, 4.641588833612779, 7.742636826811273, 12.915496650148842, 21.544346900318846, 35.93813663804629, 59.94842503189414, 100.00000000000007, diff --git a/prometheus/internal/difflib.go b/prometheus/internal/difflib.go index 178900619..12b2d70b4 100644 --- a/prometheus/internal/difflib.go +++ b/prometheus/internal/difflib.go @@ -106,8 +106,8 @@ func NewMatcher(a, b []string) *SequenceMatcher { } func NewMatcherWithJunk(a, b []string, autoJunk bool, - isJunk func(string) bool) *SequenceMatcher { - + isJunk func(string) bool, +) *SequenceMatcher { m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} m.SetSeqs(a, b) return &m @@ -163,12 +163,12 @@ func (m *SequenceMatcher) chainB() { m.bJunk = map[string]struct{}{} if m.IsJunk != nil { junk := m.bJunk - for s, _ := range b2j { + for s := range b2j { if m.IsJunk(s) { junk[s] = struct{}{} } } - for s, _ := range junk { + for s := range junk { delete(b2j, s) } } @@ -183,7 +183,7 @@ func (m *SequenceMatcher) chainB() { popular[s] = struct{}{} } } - for s, _ := range popular { + for s := range popular { delete(b2j, s) } } @@ -270,7 +270,7 @@ func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { for besti+bestsize < ahi && bestj+bestsize < bhi && !m.isBJunk(m.b[bestj+bestsize]) && m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 + bestsize++ } // Now that we have a wholly interesting match (albeit possibly @@ -287,7 +287,7 @@ func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { for besti+bestsize < ahi && bestj+bestsize < bhi && m.isBJunk(m.b[bestj+bestsize]) && m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 + bestsize++ } return Match{A: besti, B: bestj, Size: bestsize} @@ -439,8 +439,10 @@ func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { // End the current group and start a new one whenever // there is a large range with no changes. if c.Tag == 'e' && i2-i1 > nn { - group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), - j1, min(j2, j1+n)}) + group = append(group, OpCode{ + c.Tag, i1, min(i2, i1+n), + j1, min(j2, j1+n), + }) groups = append(groups, group) group = []OpCode{} i1, j1 = max(i1, i2-n), max(j1, j2-n) @@ -498,7 +500,7 @@ func (m *SequenceMatcher) QuickRatio() float64 { } avail[s] = n - 1 if n > 0 { - matches += 1 + matches++ } } return calculateRatio(matches, len(m.a)+len(m.b)) @@ -522,7 +524,7 @@ func formatRangeUnified(start, stop int) string { return fmt.Sprintf("%d", beginning) } if length == 0 { - beginning -= 1 // empty ranges begin at line just before the range + beginning-- // empty ranges begin at line just before the range } return fmt.Sprintf("%d,%d", beginning, length) } @@ -637,7 +639,7 @@ func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { w := &bytes.Buffer{} err := WriteUnifiedDiff(w, diff) - return string(w.Bytes()), err + return w.String(), err } // Split a string on "\n" while preserving them. The output can be used diff --git a/prometheus/internal/difflib_test.go b/prometheus/internal/difflib_test.go index 1a2bb34d8..820bbc6b7 100644 --- a/prometheus/internal/difflib_test.go +++ b/prometheus/internal/difflib_test.go @@ -58,7 +58,7 @@ func TestGetOptCodes(t *testing.T) { fmt.Fprintf(w, "%s a[%d:%d], (%s) b[%d:%d] (%s)\n", string(op.Tag), op.I1, op.I2, a[op.I1:op.I2], op.J1, op.J2, b[op.J1:op.J2]) } - result := string(w.Bytes()) + result := w.String() expected := `d a[0:1], (q) b[0:0] () e a[1:3], (ab) b[0:2] (ab) r a[3:4], (x) b[2:3] (y) @@ -93,7 +93,7 @@ func TestGroupedOpCodes(t *testing.T) { op.I1, op.I2, op.J1, op.J2) } } - result := string(w.Bytes()) + result := w.String() expected := `group e, 5, 8, 5, 8 i, 8, 8, 8, 9 @@ -185,14 +185,14 @@ func TestWithAsciiBJunk(t *testing.T) { sm = NewMatcherWithJunk(splitChars(rep("a", 40)+rep("b", 40)), splitChars(rep("a", 44)+rep("b", 40)+rep(" ", 20)), false, isJunk) - assertEqual(t, sm.bJunk, map[string]struct{}{" ": struct{}{}}) + assertEqual(t, sm.bJunk, map[string]struct{}{" ": {}}) isJunk = func(s string) bool { return s == " " || s == "b" } sm = NewMatcherWithJunk(splitChars(rep("a", 40)+rep("b", 40)), splitChars(rep("a", 44)+rep("b", 40)+rep(" ", 20)), false, isJunk) - assertEqual(t, sm.bJunk, map[string]struct{}{" ": struct{}{}, "b": struct{}{}}) + assertEqual(t, sm.bJunk, map[string]struct{}{" ": {}, "b": {}}) } func TestSFBugsRatioForNullSeqn(t *testing.T) { diff --git a/prometheus/metric_test.go b/prometheus/metric_test.go index 445b838dc..61d807cdc 100644 --- a/prometheus/metric_test.go +++ b/prometheus/metric_test.go @@ -75,5 +75,4 @@ func TestWithExemplarsMetric(t *testing.T) { } } }) - } diff --git a/prometheus/promhttp/delegator.go b/prometheus/promhttp/delegator.go index e7c0d0546..9819917b8 100644 --- a/prometheus/promhttp/delegator.go +++ b/prometheus/promhttp/delegator.go @@ -76,16 +76,19 @@ func (r *responseWriterDelegator) Write(b []byte) (int, error) { return n, err } -type closeNotifierDelegator struct{ *responseWriterDelegator } -type flusherDelegator struct{ *responseWriterDelegator } -type hijackerDelegator struct{ *responseWriterDelegator } -type readerFromDelegator struct{ *responseWriterDelegator } -type pusherDelegator struct{ *responseWriterDelegator } +type ( + closeNotifierDelegator struct{ *responseWriterDelegator } + flusherDelegator struct{ *responseWriterDelegator } + hijackerDelegator struct{ *responseWriterDelegator } + readerFromDelegator struct{ *responseWriterDelegator } + pusherDelegator struct{ *responseWriterDelegator } +) func (d closeNotifierDelegator) CloseNotify() <-chan bool { //nolint:staticcheck // Ignore SA1019. http.CloseNotifier is deprecated but we keep it here to not break existing users. return d.ResponseWriter.(http.CloseNotifier).CloseNotify() } + func (d flusherDelegator) Flush() { // If applicable, call WriteHeader here so that observeWriteHeader is // handled appropriately. @@ -94,9 +97,11 @@ func (d flusherDelegator) Flush() { } d.ResponseWriter.(http.Flusher).Flush() } + func (d hijackerDelegator) Hijack() (net.Conn, *bufio.ReadWriter, error) { return d.ResponseWriter.(http.Hijacker).Hijack() } + func (d readerFromDelegator) ReadFrom(re io.Reader) (int64, error) { // If applicable, call WriteHeader here so that observeWriteHeader is // handled appropriately. @@ -107,6 +112,7 @@ func (d readerFromDelegator) ReadFrom(re io.Reader) (int64, error) { d.written += n return n, err } + func (d pusherDelegator) Push(target string, opts *http.PushOptions) error { return d.ResponseWriter.(http.Pusher).Push(target, opts) } @@ -261,7 +267,7 @@ func init() { http.Flusher }{d, pusherDelegator{d}, hijackerDelegator{d}, flusherDelegator{d}} } - pickDelegator[pusher+hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { //23 + pickDelegator[pusher+hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 23 return struct { *responseWriterDelegator http.Pusher diff --git a/prometheus/promhttp/http_test.go b/prometheus/promhttp/http_test.go index 53204c5fc..36d231a5d 100644 --- a/prometheus/promhttp/http_test.go +++ b/prometheus/promhttp/http_test.go @@ -24,8 +24,9 @@ import ( "testing" "time" - "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" + + "github.com/prometheus/client_golang/prometheus" ) type errorCollector struct{} diff --git a/prometheus/promhttp/instrument_server.go b/prometheus/promhttp/instrument_server.go index a23f0edc6..1397a1ed0 100644 --- a/prometheus/promhttp/instrument_server.go +++ b/prometheus/promhttp/instrument_server.go @@ -246,7 +246,7 @@ func InstrumentHandlerResponseSize(obs prometheus.ObserverVec, next http.Handler // Collector does not have a Desc or has more than one Desc or its Desc is // invalid. It also panics if the Collector has any non-const, non-curried // labels that are not named "code" or "method". -func checkLabels(c prometheus.Collector) (code bool, method bool) { +func checkLabels(c prometheus.Collector) (code, method bool) { // TODO(beorn7): Remove this hacky way to check for instance labels // once Descriptors can have their dimensionality queried. var ( diff --git a/prometheus/promhttp/instrument_server_test.go b/prometheus/promhttp/instrument_server_test.go index fbd8fa916..a3720c2ec 100644 --- a/prometheus/promhttp/instrument_server_test.go +++ b/prometheus/promhttp/instrument_server_test.go @@ -279,7 +279,7 @@ func TestLabels(t *testing.T) { ok: false, }, } - checkLabels := func(labels []string) (gotCode bool, gotMethod bool) { + checkLabels := func(labels []string) (gotCode, gotMethod bool) { for _, label := range labels { switch label { case "code": diff --git a/prometheus/promhttp/option_test.go b/prometheus/promhttp/option_test.go index 301fd0612..5d856558a 100644 --- a/prometheus/promhttp/option_test.go +++ b/prometheus/promhttp/option_test.go @@ -50,11 +50,10 @@ func ExampleInstrumentHandlerWithExtraMethods() { // Instrument the handlers with all the metrics, injecting the "handler" // label by currying. - pullChain := - InstrumentHandlerDuration(duration.MustCurryWith(prometheus.Labels{"handler": "pull"}), - InstrumentHandlerCounter(counter, pullHandler, opts), - opts, - ) + pullChain := InstrumentHandlerDuration(duration.MustCurryWith(prometheus.Labels{"handler": "pull"}), + InstrumentHandlerCounter(counter, pullHandler, opts), + opts, + ) http.Handle("/metrics", Handler()) http.Handle("/pull", pullChain) diff --git a/prometheus/push/push.go b/prometheus/push/push.go index 3bb1466eb..a0d009c21 100644 --- a/prometheus/push/push.go +++ b/prometheus/push/push.go @@ -98,9 +98,7 @@ func New(url, job string) *Pusher { if !strings.Contains(url, "://") { url = "http://" + url } - if strings.HasSuffix(url, "/") { - url = url[:len(url)-1] - } + url = strings.TrimSuffix(url, "/") return &Pusher{ error: err, @@ -273,7 +271,11 @@ func (p *Pusher) push(ctx context.Context, method string) error { } } } - enc.Encode(mf) + if err := enc.Encode(mf); err != nil { + return fmt.Errorf( + "failed to encode metric familty %s, error is %w", + mf.GetName(), err) + } } req, err := http.NewRequestWithContext(ctx, method, p.fullURL(), buf) if err != nil { diff --git a/prometheus/push/push_test.go b/prometheus/push/push_test.go index e55e96672..3367a4b56 100644 --- a/prometheus/push/push_test.go +++ b/prometheus/push/push_test.go @@ -26,7 +26,6 @@ import ( ) func TestPush(t *testing.T) { - var ( lastMethod string lastBody []byte diff --git a/prometheus/registry.go b/prometheus/registry.go index 5046f7e2f..eda2892ed 100644 --- a/prometheus/registry.go +++ b/prometheus/registry.go @@ -582,7 +582,7 @@ func WriteToTextfile(filename string, g Gatherer) error { return err } - if err := os.Chmod(tmp.Name(), 0644); err != nil { + if err := os.Chmod(tmp.Name(), 0o644); err != nil { return err } return os.Rename(tmp.Name(), filename) diff --git a/prometheus/registry_test.go b/prometheus/registry_test.go index 7a959da47..0a3d746f9 100644 --- a/prometheus/registry_test.go +++ b/prometheus/registry_test.go @@ -349,7 +349,7 @@ collected metric "broken_metric" { label: label: