Commit 5070f7a7 by Arve Knudsen Committed by GitHub

Chore: Start harmonizing linting with plugin SDK (#25854)

* Chore: Harmonize linting with plugin SDK

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>

* Chore: Fix linting issues

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
parent 942a14b4
......@@ -825,10 +825,10 @@ jobs:
name: Lint Go
command: |
# To save memory, run in two batches
golangci-lint run -v -j 4 --config scripts/go/configs/ci/.golangci.yml -E vet -E deadcode -E gofmt \
-E gosimple -E ineffassign -E structcheck -E typecheck ./pkg/...
golangci-lint run -v -j 4 --config scripts/go/configs/ci/.golangci.yml -E unconvert -E unused \
-E varcheck -E goconst -E errcheck -E staticcheck ./pkg/...
golangci-lint run -v -j 4 --config scripts/go/configs/ci/.golangci.toml -E deadcode -E depguard -E dogsled \
-E errcheck -E goconst -E golint -E gosec -E gosimple -E govet ./pkg/...
golangci-lint run -v -j 4 --config scripts/go/configs/ci/.golangci.toml -E ineffassign \
-E rowserrcheck -E staticcheck -E structcheck -E typecheck -E unconvert -E unused -E varcheck ./pkg/...
./scripts/go/bin/revive -formatter stylish -config ./scripts/go/configs/revive.toml ./pkg/...
./scripts/go/bin/revive -formatter stylish -config ./scripts/go/configs/revive-strict.toml \
-exclude ./pkg/plugins/backendplugin/pluginextensionv2/... \
......
......@@ -99,7 +99,7 @@ scripts/go/bin/golangci-lint: scripts/go/go.mod
golangci-lint: scripts/go/bin/golangci-lint
@echo "lint via golangci-lint"
@scripts/go/bin/golangci-lint run \
--config ./scripts/go/configs/.golangci.yml \
--config ./scripts/go/configs/.golangci.toml \
$(GO_FILES)
lint-go: golangci-lint revive revive-strict # Run all code checks for backend.
......
......@@ -2,6 +2,7 @@ package api
import (
"crypto/subtle"
macaron "gopkg.in/macaron.v1"
)
......
package api
import (
"github.com/grafana/grafana/pkg/util"
"net/http"
"strconv"
"github.com/grafana/grafana/pkg/util"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models"
......
......@@ -9,11 +9,12 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"net/http"
"github.com/grafana/grafana/pkg/infra/log"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert"
macaron "gopkg.in/macaron.v1"
"net/http"
)
type testLogger struct {
......
......@@ -2,6 +2,7 @@ package commandstest
import (
"flag"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/utils"
"github.com/urfave/cli/v2"
)
......
......@@ -308,7 +308,7 @@ func extractFile(file *zip.File, filePath string) (err error) {
}()
_, err = io.Copy(dst, src)
return
return err
}
// isPathSafe checks if the filePath does not resolve outside of destination. This is used to prevent
......
......@@ -8,43 +8,56 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHandleResponse(t *testing.T) {
t.Run("Returns body if status == 200", func(t *testing.T) {
bodyReader, err := handleResponse(makeResponse(200, "test"))
assert.NoError(t, err)
resp := makeResponse(200, "test")
defer resp.Body.Close()
bodyReader, err := handleResponse(resp)
require.NoError(t, err)
body, err := ioutil.ReadAll(bodyReader)
assert.NoError(t, err)
require.NoError(t, err)
assert.Equal(t, "test", string(body))
})
t.Run("Returns ErrorNotFound if status == 404", func(t *testing.T) {
_, err := handleResponse(makeResponse(404, ""))
resp := makeResponse(404, "")
defer resp.Body.Close()
_, err := handleResponse(resp)
assert.Equal(t, ErrNotFoundError, err)
})
t.Run("Returns message from body if status == 400", func(t *testing.T) {
_, err := handleResponse(makeResponse(400, "{ \"message\": \"error_message\" }"))
assert.Error(t, err)
resp := makeResponse(400, "{ \"message\": \"error_message\" }")
defer resp.Body.Close()
_, err := handleResponse(resp)
require.Error(t, err)
assert.Equal(t, "error_message", asBadRequestError(t, err).Message)
})
t.Run("Returns body if status == 400 and no message key", func(t *testing.T) {
_, err := handleResponse(makeResponse(400, "{ \"test\": \"test_message\"}"))
assert.Error(t, err)
resp := makeResponse(400, "{ \"test\": \"test_message\"}")
defer resp.Body.Close()
_, err := handleResponse(resp)
require.Error(t, err)
assert.Equal(t, "{ \"test\": \"test_message\"}", asBadRequestError(t, err).Message)
})
t.Run("Returns Bad request error if status == 400 and no body", func(t *testing.T) {
_, err := handleResponse(makeResponse(400, ""))
assert.Error(t, err)
resp := makeResponse(400, "")
defer resp.Body.Close()
_, err := handleResponse(resp)
require.Error(t, err)
_ = asBadRequestError(t, err)
})
t.Run("Returns error with invalid status if status == 500", func(t *testing.T) {
_, err := handleResponse(makeResponse(500, ""))
assert.Error(t, err)
resp := makeResponse(500, "")
defer resp.Body.Close()
_, err := handleResponse(resp)
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid status")
})
}
......
......@@ -157,7 +157,7 @@ func (s *Server) Run() (err error) {
s.notifySystemd("READY=1")
return
return err
}
func (s *Server) Shutdown(reason string) {
......
......@@ -89,6 +89,7 @@ func (u *GCSUploader) uploadFile(client *http.Client, imageDiskPath, key string)
if err != nil {
return err
}
resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("GCS response status code %d", resp.StatusCode)
......
......@@ -75,6 +75,7 @@ func (u *WebdavUploader) Upload(ctx context.Context, pa string) (string, error)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated {
body, _ := ioutil.ReadAll(res.Body)
......
package fs
import (
"github.com/stretchr/testify/require"
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/require"
)
func TestExists_NonExistent(t *testing.T) {
......
package tracing
import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGroupSplit(t *testing.T) {
......
......@@ -181,9 +181,12 @@ func (uss *UsageStatsService) sendUsageStats(oauthProviders map[string]bool) {
client := http.Client{Timeout: 5 * time.Second}
go func() {
if _, err := client.Post(usageStatsURL, "application/json", data); err != nil {
resp, err := client.Post(usageStatsURL, "application/json", data)
if err != nil {
metricsLogger.Error("Failed to send usage stats", "err", err)
return
}
resp.Body.Close()
}()
}
......
......@@ -34,7 +34,10 @@ func TestMiddlewareDashboardRedirect(t *testing.T) {
Convey("Should redirect to new dashboard url with a 301 Moved Permanently", func() {
So(sc.resp.Code, ShouldEqual, 301)
redirectURL, _ := sc.resp.Result().Location()
resp := sc.resp.Result()
defer resp.Body.Close()
redirectURL, err := resp.Location()
So(err, ShouldBeNil)
So(redirectURL.Path, ShouldEqual, models.GetDashboardUrl(fakeDash.Uid, fakeDash.Slug))
So(len(redirectURL.Query()), ShouldEqual, 2)
})
......@@ -47,7 +50,10 @@ func TestMiddlewareDashboardRedirect(t *testing.T) {
Convey("Should redirect to new dashboard url with a 301 Moved Permanently", func() {
So(sc.resp.Code, ShouldEqual, 301)
redirectURL, _ := sc.resp.Result().Location()
resp := sc.resp.Result()
defer resp.Body.Close()
redirectURL, err := resp.Location()
So(err, ShouldBeNil)
expectedURL := models.GetDashboardUrl(fakeDash.Uid, fakeDash.Slug)
expectedURL = strings.Replace(expectedURL, "/d/", "/d-solo/", 1)
So(redirectURL.Path, ShouldEqual, expectedURL)
......@@ -66,7 +72,10 @@ func TestMiddlewareDashboardRedirect(t *testing.T) {
Convey("Should redirect to new dashboard edit url with a 301 Moved Permanently", func() {
So(sc.resp.Code, ShouldEqual, 301)
redirectURL, _ := sc.resp.Result().Location()
resp := sc.resp.Result()
defer resp.Body.Close()
redirectURL, err := resp.Location()
So(err, ShouldBeNil)
So(redirectURL.String(), ShouldEqual, "/d/asd/d/asd/dash?editPanel=12&orgId=1")
})
})
......
......@@ -623,7 +623,9 @@ func TestTokenRotationAtEndOfRequest(t *testing.T) {
rotateEndOfRequestFunc(reqContext, uts, token)(reqContext.Resp)
foundLoginCookie := false
for _, c := range rr.Result().Cookies() {
resp := rr.Result()
defer resp.Body.Close()
for _, c := range resp.Cookies() {
if c.Name == "login_token" {
foundLoginCookie = true
......
......@@ -224,13 +224,10 @@ func TestDataSourceProxyCache(t *testing.T) {
// 3. Send test request which should have the Authorization header set
req := httptest.NewRequest("GET", backend.URL+"/test-headers", nil)
res, err := transport.RoundTrip(req)
if err != nil {
log.Fatal(err.Error())
}
So(err, ShouldBeNil)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err.Error())
}
So(err, ShouldBeNil)
bodyStr := string(body)
So(bodyStr, ShouldEqual, "Ok")
})
......
......@@ -2,8 +2,9 @@ package models
import (
"errors"
"github.com/grafana/grafana/pkg/setting"
"time"
"github.com/grafana/grafana/pkg/setting"
)
var ErrInvalidQuotaTarget = errors.New("Invalid quota target")
......
package cleanup
import (
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
"testing"
"time"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
func TestCleanUpTmpFiles(t *testing.T) {
......
package dashboards
import (
"time"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
"time"
)
func MakeUserAdmin(bus bus.Bus, orgId int64, userId int64, dashboardId int64, setViewAndEditPermissions bool) error {
......
package dashboards
import (
"testing"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/setting"
"testing"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
......
package sqlstore
import (
"github.com/grafana/grafana/pkg/util/errutil"
"strings"
"time"
"github.com/grafana/grafana/pkg/util/errutil"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
......
......@@ -2,10 +2,11 @@ package migrator
import (
"fmt"
"github.com/lib/pq"
"strconv"
"strings"
"github.com/lib/pq"
"github.com/grafana/grafana/pkg/util/errutil"
"xorm.io/xorm"
)
......
......@@ -2,6 +2,7 @@ package migrator
import (
"fmt"
"github.com/mattn/go-sqlite3"
"xorm.io/xorm"
)
......
package permissions
import (
"strings"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"strings"
)
type DashboardPermissionFilter struct {
......
......@@ -2,8 +2,9 @@ package searchstore
import (
"fmt"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"strings"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
)
// FilterWhere limits the set of dashboard IDs to the dashboards for
......
......@@ -159,14 +159,14 @@ func filterAlarms(alarms *cloudwatch.DescribeAlarmsOutput, namespace string, met
}
match := true
if len(dimensions) == 0 {
// all match
} else if len(alarm.Dimensions) != len(dimensions) {
match = false
} else {
for _, d := range alarm.Dimensions {
if _, ok := dimensions[*d.Name]; !ok {
match = false
if len(dimensions) != 0 {
if len(alarm.Dimensions) != len(dimensions) {
match = false
} else {
for _, d := range alarm.Dimensions {
if _, ok := dimensions[*d.Name]; !ok {
match = false
}
}
}
}
......
......@@ -81,15 +81,11 @@ func NewCloudWatchExecutor(datasource *models.DataSource) (tsdb.TsdbQueryEndpoin
}, nil
}
var (
plog log.Logger
aliasFormat *regexp.Regexp
)
var plog = log.New("tsdb.cloudwatch")
var aliasFormat = regexp.MustCompile(`\{\{\s*(.+?)\s*\}\}`)
func init() {
plog = log.New("tsdb.cloudwatch")
tsdb.RegisterTsdbQueryEndpoint("cloudwatch", NewCloudWatchExecutor)
aliasFormat = regexp.MustCompile(`\{\{\s*(.+?)\s*\}\}`)
}
func (e *CloudWatchExecutor) alertQuery(ctx context.Context, logsClient *cloudwatchlogs.CloudWatchLogs, queryContext *tsdb.TsdbQuery) (*cloudwatchlogs.GetQueryResultsOutput, error) {
......@@ -112,11 +108,14 @@ func (e *CloudWatchExecutor) alertQuery(ctx context.Context, logsClient *cloudwa
attemptCount := 1
for range ticker.C {
if res, err := e.executeGetQueryResults(ctx, logsClient, requestParams); err != nil {
res, err := e.executeGetQueryResults(ctx, logsClient, requestParams)
if err != nil {
return nil, err
} else if isTerminated(*res.Status) {
}
if isTerminated(*res.Status) {
return res, err
} else if attemptCount >= maxAttempts {
}
if attemptCount >= maxAttempts {
return res, fmt.Errorf("fetching of query results exceeded max number of attempts")
}
......
......@@ -35,7 +35,7 @@ func GetCredentials(dsInfo *DatasourceInfo) (*credentials.Credentials, error) {
credentialCacheLock.RLock()
if _, ok := awsCredentialCache[cacheKey]; ok {
if awsCredentialCache[cacheKey].expiration != nil &&
(*awsCredentialCache[cacheKey].expiration).After(time.Now().UTC()) {
awsCredentialCache[cacheKey].expiration.After(time.Now().UTC()) {
result := awsCredentialCache[cacheKey].credential
credentialCacheLock.RUnlock()
return result, nil
......
......@@ -583,7 +583,7 @@ func (e *CloudWatchExecutor) handleGetEc2InstanceAttribute(ctx context.Context,
if attr, ok := v.Interface().(*string); ok {
data = *attr
} else if attr, ok := v.Interface().(*time.Time); ok {
data = (*attr).String()
data = attr.String()
} else {
return nil, errors.New("invalid attribute path")
}
......
......@@ -144,7 +144,8 @@ func parseGetMetricDataTimeSeries(metricDataResults map[string]*cloudwatch.Metri
series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFromPtr(nil), float64(expectedTimestamp.Unix()*1000)))
}
}
series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFrom(*metricDataResult.Values[j]), float64((*t).Unix())*1000))
series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFrom(*metricDataResult.Values[j]),
float64(t.Unix())*1000))
}
result = append(result, &series)
}
......
......@@ -205,11 +205,15 @@ func (c *baseClientImpl) executeRequest(method, uriPath, uriQuery string, body [
elapsed := time.Since(start)
clientLog.Debug("Executed request", "took", elapsed)
}()
res, err := ctxhttp.Do(c.ctx, httpClient, req)
//nolint:bodyclose
resp, err := ctxhttp.Do(c.ctx, httpClient, req)
if err != nil {
return nil, err
}
return &response{
httpResponse: res,
httpResponse: resp,
reqInfo: reqInfo,
}, err
}, nil
}
func (c *baseClientImpl) ExecuteMultisearch(r *MultiSearchRequest) (*MultiSearchResponse, error) {
......
......@@ -10,7 +10,7 @@ import (
"github.com/grafana/grafana/pkg/components/null"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana/pkg/tsdb/elasticsearch/client"
es "github.com/grafana/grafana/pkg/tsdb/elasticsearch/client"
)
const (
......
......@@ -8,7 +8,7 @@ import (
"github.com/grafana/grafana/pkg/components/null"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/tsdb/elasticsearch/client"
es "github.com/grafana/grafana/pkg/tsdb/elasticsearch/client"
"github.com/grafana/grafana/pkg/tsdb"
. "github.com/smartystreets/goconvey/convey"
......
......@@ -6,7 +6,7 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana/pkg/tsdb/elasticsearch/client"
es "github.com/grafana/grafana/pkg/tsdb/elasticsearch/client"
)
type timeSeriesQuery struct {
......
......@@ -5,7 +5,7 @@ import (
"testing"
"time"
"github.com/grafana/grafana/pkg/tsdb/elasticsearch/client"
es "github.com/grafana/grafana/pkg/tsdb/elasticsearch/client"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/tsdb"
......
package graphite
import (
. "github.com/smartystreets/goconvey/convey"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestGraphiteFunctions(t *testing.T) {
......
......@@ -119,7 +119,7 @@ func FormatDuration(inter time.Duration) string {
}
func roundInterval(interval time.Duration) time.Duration {
switch true {
switch {
// 0.015s
case interval <= 15*time.Millisecond:
return time.Millisecond * 10 // 0.01s
......
......@@ -6,8 +6,9 @@ import (
"encoding/base64"
"encoding/hex"
"errors"
"golang.org/x/crypto/pbkdf2"
"strings"
"golang.org/x/crypto/pbkdf2"
)
// GetRandomString generate random string by specify chars.
......
......@@ -6,8 +6,9 @@ import (
"crypto/rand"
"crypto/sha256"
"errors"
"golang.org/x/crypto/pbkdf2"
"io"
"golang.org/x/crypto/pbkdf2"
)
const saltLength = 8
......
[run]
timeout = "10m"
[linters-settings.golint]
min-confidence = 3
[linters-settings.goconst]
min-len = 5
min-occurrences = 5
[linters]
disable-all = true
enable = [
"bodyclose",
"deadcode",
"depguard",
"dogsled",
"errcheck",
# "gochecknoinits",
"goconst",
# "gocritic",
"goimports",
"golint",
# "goprintffuncname",
"gosec",
"gosimple",
"govet",
"ineffassign",
# "interfacer",
# "misspell",
"rowserrcheck",
# "scopelint",
"staticcheck",
"structcheck",
# "stylecheck",
"typecheck",
"unconvert",
"unused",
"varcheck",
# "whitespace",
]
# Disabled linters (might want them later)
# "gocyclo",
# "unparam"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "G108"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "G110"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "G201"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "G202"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "G306"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "401"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "402"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "501"
run:
timeout: 10m
linters:
disable-all: true
enable:
- gosec
- vet
- deadcode
- gofmt
- gosimple
- ineffassign
- structcheck
- typecheck
- unconvert
- unused
- varcheck
- goconst
- staticcheck
- errcheck
linters-settings:
goconst:
# minimal length of string constant, 3 by default
min-len: 5
# minimal occurrences count to trigger, 3 by default
min-occurrences: 5
issues:
exclude-rules:
- linters:
- gosec
text: G108
- linters:
- gosec
text: G110
- linters:
- gosec
text: G201
- linters:
- gosec
text: G202
- linters:
- gosec
text: G306
- linters:
- gosec
text: G401
- linters:
- gosec
text: G402
- linters:
- gosec
text: G501
- linters:
- gosec
text: G501
[run]
timeout = "10m"
[linters-settings.golint]
min-confidence = 3
[linters-settings.goconst]
min-len = 5
min-occurrences = 5
[linters]
disable-all = true
[[issues.exclude-rules]]
linters = ["gosec"]
text = "G108"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "G110"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "G201"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "G202"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "G306"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "401"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "402"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "501"
run:
timeout: 10m
linters:
disable-all: true
linters-settings:
goconst:
# minimal length of string constant, 3 by default
min-len: 5
# minimal occurrences count to trigger, 3 by default
min-occurrences: 5
issues:
exclude-rules:
- linters:
- gosec
text: G108
- linters:
- gosec
text: G110
- linters:
- gosec
text: G201
- linters:
- gosec
text: G202
- linters:
- gosec
text: G306
- linters:
- gosec
text: G401
- linters:
- gosec
text: G402
- linters:
- gosec
text: G501
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment