Debian Codegraph @

prometheus/testutil/lint.go

raw
1 // Copyright 2020 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package testutil
15
16 import (
17 "fmt"
18
19 "github.com/prometheus/client_golang/prometheus"
20 "github.com/prometheus/client_golang/prometheus/testutil/promlint"
21 )
22
23 // CollectAndLint registers the provided Collector with a newly created pedantic
24 // Registry. It then calls GatherAndLint with that Registry and with the
25 // provided metricNames.
26 func CollectAndLint(c prometheus.Collector, metricNames ...string) ([]promlint.Problem, error) {
27 reg := prometheus.NewPedanticRegistry()
28 if err := reg.Register(c); err != nil {
29 return nil, fmt.Errorf("registering collector failed: %w", err)
30 }
31 return GatherAndLint(reg, metricNames...)
32 }
33
34 // GatherAndLint gathers all metrics from the provided Gatherer and checks them
35 // with the linter in the promlint package. If any metricNames are provided,
36 // only metrics with those names are checked.
37 func GatherAndLint(g prometheus.Gatherer, metricNames ...string) ([]promlint.Problem, error) {
38 got, err := g.Gather()
39 if err != nil {
40 return nil, fmt.Errorf("gathering metrics failed: %w", err)
41 }
42 if metricNames != nil {
43 got = filterMetrics(got, metricNames)
44 }
45 return promlint.NewWithMetricFamilies(got).Lint()
46 }