fix(backend): enable more Go linters

This commit is contained in:
Łukasz Mierzwa
2022-07-15 18:32:07 +01:00
committed by Łukasz Mierzwa
parent f325dd7590
commit 689866a64c
40 changed files with 136 additions and 50 deletions
+40
View File
@@ -0,0 +1,40 @@
run:
deadline: 5m
output:
sort-results: true
linters:
enable:
- depguard
- gofumpt
- goimports
- revive
- misspell
- staticcheck
- promlinter
- tenv
- errorlint
- exportloopref
- predeclared
- maligned
issues:
max-same-issues: 0
exclude-rules:
- path: _test.go
linters:
- maligned
linters-settings:
depguard:
list-type: blacklist
include-go-root: true
packages-with-error-message:
- io/ioutil: "Use corresponding 'os' or 'io' functions instead."
goimports:
local-prefixes: github.com/prymitive/karma
gofumpt:
extra-rules: true
maligned:
suggest-new: true
+1 -3
View File
@@ -17,9 +17,7 @@ const (
aclActionAllow = "allow"
)
var (
allACLActions = []string{aclActionAllow, aclActionBlock, aclActionRequireMatcher}
)
var allACLActions = []string{aclActionAllow, aclActionBlock, aclActionRequireMatcher}
type silenceFilter struct {
Name string
+1 -1
View File
@@ -25,7 +25,7 @@ func getFiltersFromQuery(filterStrings []string) []filters.FilterT {
return matchFilters
}
func countLabel(countStore map[string]map[string]int, key string, val string) {
func countLabel(countStore map[string]map[string]int, key, val string) {
if _, found := countStore[key]; !found {
countStore[key] = make(map[string]int)
}
+1 -1
View File
@@ -18,7 +18,7 @@ func contentText(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
}
func serveFileOr404(path string, contentType string) http.HandlerFunc {
func serveFileOr404(path, contentType string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
if path == "" {
+2 -2
View File
@@ -124,7 +124,7 @@ func TestStaticFiles(t *testing.T) {
mime string
}
var staticFileTests = []staticFileTestCase{
staticFileTests := []staticFileTestCase{
{
path: "/favicon.ico",
code: 200,
@@ -185,7 +185,7 @@ func TestStaticFilesPrefix(t *testing.T) {
mime string
}
var staticFilePrefixTests = []staticFileTestCase{
staticFilePrefixTests := []staticFileTestCase{
{
path: "/sub/favicon.ico",
code: 200,
+3 -2
View File
@@ -64,7 +64,7 @@ func TestAuthHeader(t *testing.T) {
defer httpmock.DeactivateAndReset()
for _, testCase := range authHeaderTests {
testCase := testCase //scopelint pin
testCase := testCase // scopelint pin
for _, version := range mock.ListAllMocks() {
apiCache, _ = lru.New(100)
@@ -85,7 +85,8 @@ func TestAuthHeader(t *testing.T) {
"metrics",
"api/v2/status",
"api/v2/silences",
"api/v2/alerts/groups"} {
"api/v2/alerts/groups",
} {
uri := fmt.Sprintf("%s/%s", testCase.alertmanagerURI, m)
+3 -2
View File
@@ -167,7 +167,7 @@ func setupRouter(router *chi.Mux, historyPoller *historyPoller) {
}
}
walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
walkFunc := func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
log.Debug().
Str("method", method).
Str("route", route).
@@ -235,6 +235,7 @@ func setupUpstreams() error {
func msgFormatter(msg any) string {
return fmt.Sprintf("msg=%q", msg)
}
func lvlFormatter(level any) string {
if level == nil {
return ""
@@ -425,7 +426,7 @@ func writePidFile() error {
if pidFile != "" {
log.Info().Str("path", pidFile).Msg("Writing PID file")
pid := os.Getpid()
err := os.WriteFile(pidFile, []byte(strconv.Itoa(pid)), 0644)
err := os.WriteFile(pidFile, []byte(strconv.Itoa(pid)), 0o644)
if err != nil {
return fmt.Errorf("failed to write a PID file: %w", err)
}
+1 -1
View File
@@ -213,7 +213,7 @@ func TestProxyHeaders(t *testing.T) {
defer httpmock.DeactivateAndReset()
for _, testCase := range proxyHeaderTests {
testCase := testCase //scopelint pin
testCase := testCase // scopelint pin
r := testRouter()
am, err := alertmanager.NewAlertmanager(
"cluster",
-1
View File
@@ -43,7 +43,6 @@ func TestMain(m *testing.M) {
ecode = 1
}
os.Exit(ecode)
}
func TestScripts(t *testing.T) {
@@ -209,9 +209,9 @@ level=info msg=" key: \"\""
level=info msg=" port: 1234"
level=info msg=" prefix: /prefix/"
level=info msg="log:"
level=info msg=" config: true"
level=info msg=" level: info"
level=info msg=" format: text"
level=info msg=" config: true"
level=info msg=" requests: false"
level=info msg=" timestamp: false"
level=info msg="receivers:"
@@ -242,9 +242,9 @@ level=info msg=" key: \"\""
level=info msg=" port: 8080"
level=info msg=" prefix: /"
level=info msg="log:"
level=info msg=" config: true"
level=info msg=" level: info"
level=info msg=" format: text"
level=info msg=" config: true"
level=info msg=" requests: false"
level=info msg=" timestamp: false"
level=info msg="receivers:"
@@ -104,9 +104,9 @@ level=info msg=" key: \"\""
level=info msg=" port: 8080"
level=info msg=" prefix: /"
level=info msg="log:"
level=info msg=" config: true"
level=info msg=" level: info"
level=info msg=" format: text"
level=info msg=" config: true"
level=info msg=" requests: false"
level=info msg=" timestamp: false"
level=info msg="receivers:"
+1 -1
View File
@@ -104,9 +104,9 @@ level=info msg=" key: \"\""
level=info msg=" port: 8080"
level=info msg=" prefix: /"
level=info msg="log:"
level=info msg=" config: true"
level=info msg=" level: info"
level=info msg=" format: text"
level=info msg=" config: true"
level=info msg=" requests: false"
level=info msg=" timestamp: false"
level=info msg="receivers:"
+1 -1
View File
@@ -104,9 +104,9 @@ level=info msg=" key: \"\""
level=info msg=" port: 8080"
level=info msg=" prefix: /"
level=info msg="log:"
level=info msg=" config: true"
level=info msg=" level: info"
level=info msg=" format: text"
level=info msg=" config: true"
level=info msg=" requests: false"
level=info msg=" timestamp: false"
level=info msg="receivers:"
@@ -114,9 +114,9 @@ level=info msg=" key: \"\""
level=info msg=" port: 8080"
level=info msg=" prefix: /"
level=info msg="log:"
level=info msg=" config: true"
level=info msg=" level: info"
level=info msg=" format: text"
level=info msg=" config: true"
level=info msg=" requests: false"
level=info msg=" timestamp: false"
level=info msg="receivers:"
@@ -104,9 +104,9 @@ level=info msg=" key: \"\""
level=info msg=" port: 8080"
level=info msg=" prefix: /"
level=info msg="log:"
level=info msg=" config: true"
level=info msg=" level: info"
level=info msg=" format: text"
level=info msg=" config: true"
level=info msg=" requests: false"
level=info msg=" timestamp: false"
level=info msg="receivers:"
+1 -1
View File
@@ -680,7 +680,7 @@ func silences(w http.ResponseWriter, r *http.Request) {
recentFirst = false
}
sort.Slice(dedupedSilences, func(i int, j int) bool {
sort.Slice(dedupedSilences, func(i, j int) bool {
if dedupedSilences[i].Silence.EndsAt.Equal(dedupedSilences[j].Silence.EndsAt) {
if dedupedSilences[i].Silence.StartsAt.Equal(dedupedSilences[j].Silence.StartsAt) {
return dedupedSilences[i].Silence.ID < dedupedSilences[j].Silence.ID
+1
View File
@@ -3044,6 +3044,7 @@ func (ew *gzErrWriter) Write(p []byte) (n int, err error) {
}
return len(p), nil
}
func (ew *gzErrWriter) Close() error {
if ew.failClose {
return errors.New("Close error")
-1
View File
@@ -242,7 +242,6 @@ func DedupKnownLabelValues(name string) []string {
for _, alert := range ag.Alerts {
if v := alert.Labels.Get(name); v != nil {
dedupedValues[v.Value] = true
}
}
}
+1
View File
@@ -37,6 +37,7 @@ type HealthCheck struct {
}
// Alertmanager represents Alertmanager upstream instance
// nolint: maligned
type Alertmanager struct {
URI string `json:"uri"`
ExternalURI string `json:"-"`
+1 -3
View File
@@ -18,9 +18,7 @@ import (
// Option allows to pass functional options to NewAlertmanager()
type Option func(am *Alertmanager) error
var (
upstreams = map[string]*Alertmanager{}
)
var upstreams = map[string]*Alertmanager{}
// NewAlertmanager creates a new Alertmanager instance
func NewAlertmanager(cluster, name, upstreamURI string, opts ...Option) (*Alertmanager, error) {
+2 -4
View File
@@ -26,10 +26,8 @@ import (
yaml "gopkg.in/yaml.v3"
)
var (
// Config will hold final configuration read from the file and flags
Config *configSchema
)
// Config will hold final configuration read from the file and flags
var Config *configSchema
func init() {
Config = &configSchema{}
+1 -1
View File
@@ -133,9 +133,9 @@ listen:
port: 80
prefix: /
log:
config: false
level: info
format: text
config: false
requests: false
timestamp: false
receivers:
+3 -1
View File
@@ -107,6 +107,7 @@ type configSchema struct {
Author string
Comment string
} `yaml:"alertAcknowledgement" koanf:"alertAcknowledgement"`
// nolint: maligned
Annotations struct {
Default struct {
Hidden bool
@@ -182,9 +183,9 @@ type configSchema struct {
Prefix string
}
Log struct {
Config bool
Level string
Format string
Config bool
Requests bool
Timestamp bool
}
@@ -205,6 +206,7 @@ type configSchema struct {
Labels []string
}
} `yaml:"silenceForm" koanf:"silenceForm"`
// nolint: maligned
UI struct {
Refresh time.Duration
HideFiltersWhenIdle bool `yaml:"hideFiltersWhenIdle" koanf:"hideFiltersWhenIdle"`
+2 -1
View File
@@ -63,7 +63,8 @@ var acTests = []acTest{
CreatedBy: "me@example.com",
TicketID: "JIRA-1",
},
}},
},
},
},
SilencedBy: []string{"1234567890"},
},
-1
View File
@@ -30,7 +30,6 @@ func (filter *alertmanagerClusterFilter) Match(alert *models.Alert, matches int)
func (filter *alertmanagerClusterFilter) MatchAlertmanager(am *models.AlertmanagerInstance) bool {
return filter.Matcher.Compare(am.Cluster, filter.Value)
}
func newAlertmanagerClusterFilter() FilterT {
+1 -1
View File
@@ -21,7 +21,7 @@ func (hrt *headersRoundTripper) RoundTrip(r *http.Request) (*http.Response, erro
return hrt.inner.RoundTrip(r)
}
func SetAuth(inner http.RoundTripper, username string, password string) http.RoundTripper {
func SetAuth(inner http.RoundTripper, username, password string) http.RoundTripper {
return &authRoundTripper{
inner: inner,
Username: username,
+3 -3
View File
@@ -10,21 +10,21 @@ import (
)
// GetAbsoluteMockPath returns absolute path for given mock file
func GetAbsoluteMockPath(filename string, version string) string {
func GetAbsoluteMockPath(filename, version string) string {
_, f, _, _ := runtime.Caller(0)
cwd := filepath.Dir(f)
return path.Join(cwd, version, filename)
}
// GetMockResponder returns a httpmock.Responder for given file/version
func GetMockResponder(url string, version string, filename string) httpmock.Responder {
func GetMockResponder(url, version, filename string) httpmock.Responder {
fullPath := GetAbsoluteMockPath(filename, version)
mockJSON, _ := os.ReadFile(fullPath)
return httpmock.NewBytesResponder(200, mockJSON)
}
// RegisterURL for given url and return 200 status register mock http responder
func RegisterURL(url string, version string, filename string) {
func RegisterURL(url, version, filename string) {
httpmock.RegisterResponder("GET", url, GetMockResponder(url, version, filename))
}
+2 -1
View File
@@ -26,11 +26,12 @@ type Annotations []Annotation
func (a Annotations) Len() int {
return len(a)
}
func (a Annotations) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a Annotations) Less(i, j int) bool {
// Sort the anotations listed in config.Config.Annotations.Order first, in
// the order they appear in that list; remaining annotations are sorted alphabetically.
+6 -1
View File
@@ -59,9 +59,11 @@ type LabelValueStatsList []LabelValueStats
func (lvsl LabelValueStatsList) Len() int {
return len(lvsl)
}
func (lvsl LabelValueStatsList) Swap(i, j int) {
lvsl[i], lvsl[j] = lvsl[j], lvsl[i]
}
func (lvsl LabelValueStatsList) Less(i, j int) bool {
if lvsl[i].Hits == lvsl[j].Hits {
return sortorder.NaturalLess(lvsl[i].Value, lvsl[j].Value)
@@ -81,9 +83,11 @@ type LabelNameStatsList []LabelNameStats
func (lnsl LabelNameStatsList) Len() int {
return len(lnsl)
}
func (lnsl LabelNameStatsList) Swap(i, j int) {
lnsl[i], lnsl[j] = lnsl[j], lnsl[i]
}
func (lnsl LabelNameStatsList) Less(i, j int) bool {
if lnsl[i].Hits == lnsl[j].Hits {
return lnsl[i].Name < lnsl[j].Name
@@ -144,7 +148,6 @@ func (ag *APIAlertGroup) dedupLabels() {
}
ag.Shared.Labels = sharedLabels
}
func (ag *APIAlertGroup) removeGroupingLabels(dropNames []string) {
@@ -417,6 +420,7 @@ type LabelSettings struct {
type LabelsSettings map[string]LabelSettings
// Settings is used to export karma configuration that is used by UI
// nolint: maligned
type Settings struct {
AnnotationsDefaultHidden bool `json:"annotationsDefaultHidden"`
AnnotationsHidden []string `json:"annotationsHidden"`
@@ -444,6 +448,7 @@ type APIGrid struct {
StateCount map[string]int `json:"stateCount"`
}
// nolint: maligned
type AlertsRequest struct {
Filters []string `json:"filters"`
GridLabel string `json:"gridLabel"`
+1 -1
View File
@@ -183,7 +183,7 @@ func TestDedupWithBadSource(t *testing.T) {
}
func TestNameStatsSort(t *testing.T) {
var nameStats = models.LabelNameStatsList{
nameStats := models.LabelNameStatsList{
{
Name: "@state",
Hits: 24,
-1
View File
@@ -17,7 +17,6 @@ func WrapRegexWithAnchors(r string) string {
}
func MustCompileAnchored(r string) *regexp.Regexp {
return regexp.MustCompile(WrapRegexWithAnchors(r))
}
+1 -1
View File
@@ -36,7 +36,7 @@ func StringSliceToSHA1(stringArray []string) (string, error) {
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
func StringSliceDiff(slice1 []string, slice2 []string) ([]string, []string) {
func StringSliceDiff(slice1, slice2 []string) ([]string, []string) {
missing := []string{}
extra := []string{}
+2 -2
View File
@@ -15,7 +15,7 @@ import (
plcolors "gopkg.in/go-playground/colors.v1"
)
func labelToSeed(key string, val string) int64 {
func labelToSeed(key, val string) int64 {
h := sha1.New()
_, _ = io.WriteString(h, key)
_, _ = io.WriteString(h, val)
@@ -66,7 +66,7 @@ func parseCustomColor(colorStore models.LabelsColorMap, key, val, customColor st
// ColorLabel update karmaColorMap object with a color object generated
// from label key and value passed here
// It's used to generate unique colors for configured labels
func ColorLabel(colorStore models.LabelsColorMap, key string, val string) {
func ColorLabel(colorStore models.LabelsColorMap, key, val string) {
// first handle custom colors
_, ok := config.Config.Labels.Color.Custom[key]
if ok {
+2 -1
View File
@@ -13,7 +13,8 @@ import (
// it takes the list of label keys to ignore and alert label map
// it will return label map without labels found on the ignore list
func StripLables(keptLabels, ignoredLabels []string, keptLabelsRegex, ignoredLabelsRegex []*regexp.Regexp,
sourceLabels models.Labels) models.Labels {
sourceLabels models.Labels,
) models.Labels {
// empty keep lists means keep everything by default
keepAll := len(keptLabels) == 0 && len(keptLabelsRegex) == 0
labels := models.Labels{}
+1 -1
View File
@@ -8,7 +8,7 @@ import (
// JoinURL can be used to join a base url (http(s)://domain.com) and a path (/my/path)
// it will return a joined string or an error (if you supply invalid url)
func JoinURL(base string, sub string) (string, error) {
func JoinURL(base, sub string) (string, error) {
u, err := url.Parse(base)
if err != nil {
return "", err
+6 -4
View File
@@ -39,13 +39,15 @@ $(GOBIN)/golangci-lint: tools/golangci-lint/go.mod tools/golangci-lint/go.sum
go install -modfile=tools/golangci-lint/go.mod github.com/golangci/golangci-lint/cmd/golangci-lint
.PHONY: lint-go
lint-go: $(GOBIN)/golangci-lint lint-go-looppointer
$(ENV) golangci-lint run -v --timeout 5m -E staticcheck,misspell,promlinter,revive,tenv,errorlint,exportloopref,predeclared
$(ENV) golangci-lint run -v
$(GOBIN)/lint-go-goimports: tools/goimports/go.mod tools/goimports/go.sum
$(GOBIN)/goimports: tools/goimports/go.mod tools/goimports/go.sum
go install -modfile=tools/goimports/go.mod golang.org/x/tools/cmd/goimports
$(GOBIN)/gofumpt: tools/gofumpt/go.mod tools/gofumpt/go.sum
go install -modfile=tools/gofumpt/go.mod mvdan.cc/gofumpt
.PHONY: format-go
format-go: $(GOBIN)/lint-go-goimports
gofmt -l -s -w .
format-go: $(GOBIN)/goimports $(GOBIN)/gofumpt
gofumpt -extra -w .
goimports -local github.com/prymitive/karma -w .
.PHONY: download-deps-go
+13
View File
@@ -0,0 +1,13 @@
module _
go 1.18
require mvdan.cc/gofumpt v0.3.1
require (
github.com/google/go-cmp v0.5.7 // indirect
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8 // indirect
golang.org/x/tools v0.1.10 // indirect
)
+20
View File
@@ -0,0 +1,20 @@
github.com/frankban/quicktest v1.14.2 h1:SPb1KFFmM+ybpEjPUhCCkZOM5xlovT5UbrMvWnXyBns=
github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e h1:aoZm08cpOy4WuID//EZDgcC4zIxODThtZNPirFr42+A=
github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8 h1:OH54vjqzRWmbJ62fjuhxy7AxFFgoHN0/DPc/UrL8cAs=
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20=
golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
gopkg.in/errgo.v2 v2.1.0 h1:0vLT13EuvQ0hNvakwLuFZ/jYrLp5F3kcWHXdRggjCE8=
mvdan.cc/gofumpt v0.3.1 h1:avhhrOmv0IuvQVK7fvwV91oFSGAk5/6Po8GXTzICeu8=
mvdan.cc/gofumpt v0.3.1/go.mod h1:w3ymliuxvzVx8DAutBnVyDqYb1Niy/yCJt/lk821YCE=
+7
View File
@@ -0,0 +1,7 @@
//go:build tools
package tools
import (
_ "mvdan.cc/gofumpt"
)