From fff529dfd2a3e9125cf3a8d3c7fde73a441d64b4 Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Tue, 6 Aug 2024 06:44:53 +0000 Subject: [PATCH] style: format code with Go fmt This commit fixes the style issues introduced in f0016ad according to the output from Go fmt. Details: None --- build.go | 1 + pkg/api/docs/definitions/meta.go | 11 ++-- .../imguploader/azureblobuploader.go | 44 ++++++------- pkg/components/loki/logproto/types.go | 4 +- pkg/components/simplejson/simplejson.go | 61 +++++++++++-------- pkg/expr/classic/reduce.go | 2 +- pkg/ifaces/gcsifaces/gcsifaces.go | 1 + pkg/infra/filestorage/cdk_blob_filestorage.go | 2 +- pkg/infra/filestorage/db_filestorage.go | 2 +- pkg/infra/log/log.go | 7 ++- pkg/infra/log/term/terminal_logger.go | 5 +- pkg/infra/remotecache/remotecache.go | 2 +- pkg/models/dashboard_acl.go | 2 - pkg/plugins/manager/signature/manifest.go | 3 +- pkg/services/accesscontrol/resolvers.go | 2 +- .../conditions/query_interval_test.go | 4 +- .../alerting/conditions/query_test.go | 4 +- pkg/services/alerting/conditions/reducer.go | 2 +- pkg/services/alerting/notifier.go | 2 +- pkg/services/alerting/notifiers/googlechat.go | 3 +- pkg/services/alerting/ticker.go | 8 +-- pkg/services/dashboards/dashboard.go | 12 ++-- pkg/services/dashboards/folder.go | 3 +- pkg/services/featuremgmt/strcase/snake.go | 2 +- pkg/services/libraryelements/database.go | 2 +- .../ngalert/api/tooling/definitions/api.go | 25 ++++---- pkg/services/ngalert/eval/eval.go | 30 ++++----- pkg/services/ngalert/eval/evaluator_mock.go | 10 +-- pkg/services/ngalert/models/alert_rule.go | 3 +- .../ngalert/notifier/channels/testing.go | 11 ++-- .../ngalert/notifier/channels/util.go | 1 + pkg/services/ngalert/provisioning/persist.go | 3 + .../ngalert/provisioning/persist_mock.go | 8 +-- .../provisioning/provisioning_store_mock.go | 26 ++++---- .../provisioning/quota_checker_mock.go | 6 +- .../ngalert/schedule/alerts_sender_mock.go | 4 +- pkg/services/ngalert/schedule/registry.go | 1 + pkg/services/ngalert/schedule/schedule.go | 4 +- pkg/services/provisioning/values/values.go | 9 +-- pkg/services/publicdashboards/api/api_test.go | 2 +- .../publicdashboards/api/common_test.go | 2 +- .../publicdashboards/models/models.go | 2 - pkg/services/screenshot/screenshot.go | 1 + pkg/services/searchV2/bluge.go | 2 +- pkg/services/sqlstore/migrator/dialect.go | 2 +- pkg/services/sqlstore/org_test.go | 4 +- pkg/services/sqlstore/searchstore/doc.go | 10 +-- pkg/services/sqlstore/user.go | 2 +- pkg/services/store/entity_events.go | 1 + pkg/services/store/storage_sql.go | 7 ++- .../metrics/azuremonitor-datasource.go | 7 ++- .../cloudmonitoring/time_series_filter.go | 2 +- pkg/tsdb/influxdb/flux/builder.go | 24 ++++---- pkg/tsdb/intervalv2/intervalv2.go | 2 +- pkg/tsdb/legacydata/interval/interval.go | 2 +- pkg/tsdb/legacydata/service/service.go | 2 +- pkg/tsdb/loki/frame.go | 2 +- pkg/tsdb/postgres/macros.go | 2 +- .../prometheus/buffered/time_series_query.go | 6 +- pkg/tsdb/prometheus/models/query.go | 6 +- pkg/tsdb/sqleng/sql_engine.go | 3 +- pkg/util/cmputil/reporter.go | 10 +-- pkg/util/errutil/doc.go | 11 +++- pkg/util/errutil/errors.go | 7 ++- scripts/build/ci-wix/Magefile.go | 3 +- 65 files changed, 253 insertions(+), 203 deletions(-) diff --git a/build.go b/build.go index 50b8e4e2c3596..2050605652a1e 100644 --- a/build.go +++ b/build.go @@ -1,3 +1,4 @@ +//go:build ignore // +build ignore package main diff --git a/pkg/api/docs/definitions/meta.go b/pkg/api/docs/definitions/meta.go index 560196f4291db..129bc8bac7f56 100644 --- a/pkg/api/docs/definitions/meta.go +++ b/pkg/api/docs/definitions/meta.go @@ -21,11 +21,14 @@ // // SecurityDefinitions: // basic: -// type: basic +// +// type: basic +// // api_key: -// type: apiKey -// name: Authorization -// in: header +// +// type: apiKey +// name: Authorization +// in: header // // swagger:meta package definitions diff --git a/pkg/components/imguploader/azureblobuploader.go b/pkg/components/imguploader/azureblobuploader.go index 736de276bfa7a..b2b2dc70562a2 100644 --- a/pkg/components/imguploader/azureblobuploader.go +++ b/pkg/components/imguploader/azureblobuploader.go @@ -256,14 +256,15 @@ func tryget(headers map[string][]string, key string) string { /* Based on Azure docs: - Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element - - 1) Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. - 2) Convert each HTTP header name to lowercase. - 3) Sort the headers lexicographically by header name, in ascending order. Note that each header may appear only once in the string. - 4) Unfold the string by replacing any breaking white space with a single space. - 5) Trim any white space around the colon in the header. - 6) Finally, append a new line character to each canonicalized header in the resulting list. Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. + + Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element + + 1) Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. + 2) Convert each HTTP header name to lowercase. + 3) Sort the headers lexicographically by header name, in ascending order. Note that each header may appear only once in the string. + 4) Unfold the string by replacing any breaking white space with a single space. + 5) Trim any white space around the colon in the header. + 6) Finally, append a new line character to each canonicalized header in the resulting list. Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. */ func (a *Auth) canonicalizedHeaders(req *http.Request) string { var buffer bytes.Buffer @@ -288,25 +289,26 @@ func (a *Auth) canonicalizedHeaders(req *http.Request) string { /* Based on Azure docs - Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element -1) Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed. -2) Append the resource's encoded URI path, without any query parameters. -3) Retrieve all query parameters on the resource URI, including the comp parameter if it exists. -4) Convert all parameter names to lowercase. -5) Sort the query parameters lexicographically by parameter name, in ascending order. -6) URL-decode each query parameter name and value. -7) Append each query parameter name and value to the string in the following format, making sure to include the colon (:) between the name and the value: - parameter-name:parameter-value + Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element + + 1. Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed. + 2. Append the resource's encoded URI path, without any query parameters. + 3. Retrieve all query parameters on the resource URI, including the comp parameter if it exists. + 4. Convert all parameter names to lowercase. + 5. Sort the query parameters lexicographically by parameter name, in ascending order. + 6. URL-decode each query parameter name and value. + 7. Append each query parameter name and value to the string in the following format, making sure to include the colon (:) between the name and the value: + parameter-name:parameter-value -8) If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list: - parameter-name:parameter-value-1,parameter-value-2,parameter-value-n + 8. If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list: + parameter-name:parameter-value-1,parameter-value-2,parameter-value-n 9) Append a new line character (\n) after each name-value pair. Rules: - 1) Avoid using the new line character (\n) in values for query parameters. If it must be used, ensure that it does not affect the format of the canonicalized resource string. - 2) Avoid using commas in query parameter values. + 1. Avoid using the new line character (\n) in values for query parameters. If it must be used, ensure that it does not affect the format of the canonicalized resource string. + 2. Avoid using commas in query parameter values. */ func (a *Auth) canonicalizedResource(req *http.Request) string { var buffer bytes.Buffer diff --git a/pkg/components/loki/logproto/types.go b/pkg/components/loki/logproto/types.go index f397962d5886e..5d1ebb8f30286 100644 --- a/pkg/components/loki/logproto/types.go +++ b/pkg/components/loki/logproto/types.go @@ -108,7 +108,7 @@ func (m *Entry) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -//nolint: gocyclo +// nolint: gocyclo func (m *Stream) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -248,7 +248,7 @@ func (m *Stream) Unmarshal(dAtA []byte) error { return nil } -//nolint: gocyclo +// nolint: gocyclo func (m *Entry) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 diff --git a/pkg/components/simplejson/simplejson.go b/pkg/components/simplejson/simplejson.go index 75249fb424ded..8ba7235c0ec0b 100644 --- a/pkg/components/simplejson/simplejson.go +++ b/pkg/components/simplejson/simplejson.go @@ -154,7 +154,8 @@ func (j *Json) Del(key string) { // for `key` in its `map` representation // // useful for chaining operations (to traverse a nested JSON): -// js.Get("top_level").Get("dict").Get("value").Int() +// +// js.Get("top_level").Get("dict").Get("value").Int() func (j *Json) Get(key string) *Json { m, err := j.Map() if err == nil { @@ -168,7 +169,7 @@ func (j *Json) Get(key string) *Json { // GetPath searches for the item as specified by the branch // without the need to deep dive using Get()'s. // -// js.GetPath("top_level", "dict") +// js.GetPath("top_level", "dict") func (j *Json) GetPath(branch ...string) *Json { jin := j for _, p := range branch { @@ -182,7 +183,8 @@ func (j *Json) GetPath(branch ...string) *Json { // // this is the analog to Get when accessing elements of // a json array instead of a json object: -// js.Get("top_level").Get("array").GetIndex(1).Get("key").Int() +// +// js.Get("top_level").Get("array").GetIndex(1).Get("key").Int() func (j *Json) GetIndex(index int) *Json { a, err := j.Array() if err == nil { @@ -198,9 +200,10 @@ func (j *Json) GetIndex(index int) *Json { // indicating success or failure // // useful for chained operations when success is important: -// if data, ok := js.Get("top_level").CheckGetIndex(0); ok { -// log.Println(data) -// } +// +// if data, ok := js.Get("top_level").CheckGetIndex(0); ok { +// log.Println(data) +// } func (j *Json) CheckGetIndex(index int) (*Json, bool) { a, err := j.Array() if err == nil { @@ -226,9 +229,10 @@ func (j *Json) SetIndex(index int, val interface{}) { // a `bool` identifying success or failure // // useful for chained operations when success is important: -// if data, ok := js.Get("top_level").CheckGet("inner"); ok { -// log.Println(data) -// } +// +// if data, ok := js.Get("top_level").CheckGet("inner"); ok { +// log.Println(data) +// } func (j *Json) CheckGet(key string) (*Json, bool) { m, err := j.Map() if err == nil { @@ -303,9 +307,10 @@ func (j *Json) StringArray() ([]string, error) { // MustArray guarantees the return of a `[]interface{}` (with optional default) // // useful when you want to iterate over array values in a succinct manner: -// for i, v := range js.Get("results").MustArray() { -// fmt.Println(i, v) -// } +// +// for i, v := range js.Get("results").MustArray() { +// fmt.Println(i, v) +// } func (j *Json) MustArray(args ...[]interface{}) []interface{} { var def []interface{} @@ -328,9 +333,10 @@ func (j *Json) MustArray(args ...[]interface{}) []interface{} { // MustMap guarantees the return of a `map[string]interface{}` (with optional default) // // useful when you want to iterate over map values in a succinct manner: -// for k, v := range js.Get("dictionary").MustMap() { -// fmt.Println(k, v) -// } +// +// for k, v := range js.Get("dictionary").MustMap() { +// fmt.Println(k, v) +// } func (j *Json) MustMap(args ...map[string]interface{}) map[string]interface{} { var def map[string]interface{} @@ -353,7 +359,8 @@ func (j *Json) MustMap(args ...map[string]interface{}) map[string]interface{} { // MustString guarantees the return of a `string` (with optional default) // // useful when you explicitly want a `string` in a single value return context: -// myFunc(js.Get("param1").MustString(), js.Get("optional_param").MustString("my_default")) +// +// myFunc(js.Get("param1").MustString(), js.Get("optional_param").MustString("my_default")) func (j *Json) MustString(args ...string) string { var def string @@ -376,9 +383,10 @@ func (j *Json) MustString(args ...string) string { // MustStringArray guarantees the return of a `[]string` (with optional default) // // useful when you want to iterate over array values in a succinct manner: -// for i, s := range js.Get("results").MustStringArray() { -// fmt.Println(i, s) -// } +// +// for i, s := range js.Get("results").MustStringArray() { +// fmt.Println(i, s) +// } func (j *Json) MustStringArray(args ...[]string) []string { var def []string @@ -401,7 +409,8 @@ func (j *Json) MustStringArray(args ...[]string) []string { // MustInt guarantees the return of an `int` (with optional default) // // useful when you explicitly want an `int` in a single value return context: -// myFunc(js.Get("param1").MustInt(), js.Get("optional_param").MustInt(5150)) +// +// myFunc(js.Get("param1").MustInt(), js.Get("optional_param").MustInt(5150)) func (j *Json) MustInt(args ...int) int { var def int @@ -424,7 +433,8 @@ func (j *Json) MustInt(args ...int) int { // MustFloat64 guarantees the return of a `float64` (with optional default) // // useful when you explicitly want a `float64` in a single value return context: -// myFunc(js.Get("param1").MustFloat64(), js.Get("optional_param").MustFloat64(5.150)) +// +// myFunc(js.Get("param1").MustFloat64(), js.Get("optional_param").MustFloat64(5.150)) func (j *Json) MustFloat64(args ...float64) float64 { var def float64 @@ -447,7 +457,8 @@ func (j *Json) MustFloat64(args ...float64) float64 { // MustBool guarantees the return of a `bool` (with optional default) // // useful when you explicitly want a `bool` in a single value return context: -// myFunc(js.Get("param1").MustBool(), js.Get("optional_param").MustBool(true)) +// +// myFunc(js.Get("param1").MustBool(), js.Get("optional_param").MustBool(true)) func (j *Json) MustBool(args ...bool) bool { var def bool @@ -470,7 +481,8 @@ func (j *Json) MustBool(args ...bool) bool { // MustInt64 guarantees the return of an `int64` (with optional default) // // useful when you explicitly want an `int64` in a single value return context: -// myFunc(js.Get("param1").MustInt64(), js.Get("optional_param").MustInt64(5150)) +// +// myFunc(js.Get("param1").MustInt64(), js.Get("optional_param").MustInt64(5150)) func (j *Json) MustInt64(args ...int64) int64 { var def int64 @@ -493,7 +505,8 @@ func (j *Json) MustInt64(args ...int64) int64 { // MustUInt64 guarantees the return of an `uint64` (with optional default) // // useful when you explicitly want an `uint64` in a single value return context: -// myFunc(js.Get("param1").MustUint64(), js.Get("optional_param").MustUint64(5150)) +// +// myFunc(js.Get("param1").MustUint64(), js.Get("optional_param").MustUint64(5150)) func (j *Json) MustUint64(args ...uint64) uint64 { var def uint64 diff --git a/pkg/expr/classic/reduce.go b/pkg/expr/classic/reduce.go index 28d85bd5d85ee..a58ec14d3ffd0 100644 --- a/pkg/expr/classic/reduce.go +++ b/pkg/expr/classic/reduce.go @@ -21,7 +21,7 @@ func (cr classicReducer) ValidReduceFunc() bool { return false } -//nolint: gocyclo +// nolint: gocyclo func (cr classicReducer) Reduce(series mathexp.Series) mathexp.Number { num := mathexp.NewNumber("", nil) diff --git a/pkg/ifaces/gcsifaces/gcsifaces.go b/pkg/ifaces/gcsifaces/gcsifaces.go index b2b65500f7a84..5cee6fceea69f 100644 --- a/pkg/ifaces/gcsifaces/gcsifaces.go +++ b/pkg/ifaces/gcsifaces/gcsifaces.go @@ -1,4 +1,5 @@ // Package gcsifaces provides interfaces for Google Cloud Storage. +// //go:generate mockgen -source $GOFILE -destination ../../mocks/mock_gcsifaces/mocks.go StorageClient package gcsifaces diff --git a/pkg/infra/filestorage/cdk_blob_filestorage.go b/pkg/infra/filestorage/cdk_blob_filestorage.go index 566aa90ad57ae..cb63330449b88 100644 --- a/pkg/infra/filestorage/cdk_blob_filestorage.go +++ b/pkg/infra/filestorage/cdk_blob_filestorage.go @@ -272,7 +272,7 @@ func (c cdkBlobStorage) DeleteFolder(ctx context.Context, folderPath string, opt return lastErr } -//nolint: gocyclo +// nolint: gocyclo func (c cdkBlobStorage) list(ctx context.Context, folderPath string, paging *Paging, options *ListOptions) (*ListResponse, error) { lowerRootPath := strings.ToLower(folderPath) iterators := []*blob.ListIterator{c.bucket.List(&blob.ListOptions{ diff --git a/pkg/infra/filestorage/db_filestorage.go b/pkg/infra/filestorage/db_filestorage.go index f84f146c08a5b..39055dd4b354b 100644 --- a/pkg/infra/filestorage/db_filestorage.go +++ b/pkg/infra/filestorage/db_filestorage.go @@ -270,7 +270,7 @@ func upsertProperty(dialect migrator.Dialect, sess *sqlstore.DBSession, now time return err } -//nolint: gocyclo +// nolint: gocyclo func (s dbFileStorage) List(ctx context.Context, folderPath string, paging *Paging, options *ListOptions) (*ListResponse, error) { var resp *ListResponse diff --git a/pkg/infra/log/log.go b/pkg/infra/log/log.go index fc469f3716e59..9501b8508f6d7 100644 --- a/pkg/infra/log/log.go +++ b/pkg/infra/log/log.go @@ -205,9 +205,12 @@ func (cl *ConcreteLogger) New(ctx ...interface{}) *ConcreteLogger { // name plus additional contextual information, you must use the // Logger interface New method for it to work as expected. // Example creating a shared logger: -// requestLogger := log.New("request-logger") +// +// requestLogger := log.New("request-logger") +// // Example creating a contextual logger: -// contextualLogger := requestLogger.New("username", "user123") +// +// contextualLogger := requestLogger.New("username", "user123") func New(ctx ...interface{}) *ConcreteLogger { if len(ctx) == 0 { return root.New() diff --git a/pkg/infra/log/term/terminal_logger.go b/pkg/infra/log/term/terminal_logger.go index cc4080c90c430..e740b530c0a2d 100644 --- a/pkg/infra/log/term/terminal_logger.go +++ b/pkg/infra/log/term/terminal_logger.go @@ -34,12 +34,11 @@ type terminalLogger struct { // level output and terser human friendly timestamp. // This format should only be used for interactive programs or while developing. // -// [TIME] [LEVEL] MESSAGE key=value key=value ... +// [TIME] [LEVEL] MESSAGE key=value key=value ... // // Example: // -// [May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002 -// +// [May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002 func NewTerminalLogger(w io.Writer) gokitlog.Logger { return &terminalLogger{w} } diff --git a/pkg/infra/remotecache/remotecache.go b/pkg/infra/remotecache/remotecache.go index a5597084b3dcc..8eaca5f799d40 100644 --- a/pkg/infra/remotecache/remotecache.go +++ b/pkg/infra/remotecache/remotecache.go @@ -45,7 +45,7 @@ func ProvideService(cfg *setting.Cfg, sqlStore *sqlstore.SQLStore) (*RemoteCache // CacheStorage allows the caller to set, get and delete items in the cache. // Cached items are stored as byte arrays and marshalled using "encoding/gob" // so any struct added to the cache needs to be registered with `remotecache.Register` -// ex `remotecache.Register(CacheableStruct{})`` +// ex `remotecache.Register(CacheableStruct{})“ type CacheStorage interface { // Get reads object from Cache Get(ctx context.Context, key string) (interface{}, error) diff --git a/pkg/models/dashboard_acl.go b/pkg/models/dashboard_acl.go index 1a7ee44f47afa..0ef3ef56bb31e 100644 --- a/pkg/models/dashboard_acl.go +++ b/pkg/models/dashboard_acl.go @@ -96,9 +96,7 @@ func (dto *DashboardAclInfoDTO) IsDuplicateOf(other *DashboardAclInfoDTO) bool { return dto.hasSameRoleAs(other) || dto.hasSameUserAs(other) || dto.hasSameTeamAs(other) } -// // QUERIES -// type GetDashboardAclInfoListQuery struct { DashboardID int64 OrgID int64 diff --git a/pkg/plugins/manager/signature/manifest.go b/pkg/plugins/manager/signature/manifest.go index fc263fb339671..f4ad9061876ac 100644 --- a/pkg/plugins/manager/signature/manifest.go +++ b/pkg/plugins/manager/signature/manifest.go @@ -27,7 +27,8 @@ import ( ) // Soon we can fetch keys from: -// https://grafana.com/api/plugins/ci/keys +// +// https://grafana.com/api/plugins/ci/keys const publicKeyText = `-----BEGIN PGP PUBLIC KEY BLOCK----- Version: OpenPGP.js v4.10.1 Comment: https://openpgpjs.org diff --git a/pkg/services/accesscontrol/resolvers.go b/pkg/services/accesscontrol/resolvers.go index ae123ec62d8f9..a615093a59602 100644 --- a/pkg/services/accesscontrol/resolvers.go +++ b/pkg/services/accesscontrol/resolvers.go @@ -120,7 +120,7 @@ func getScopeCacheKey(orgID int64, scope string) string { return fmt.Sprintf("%s-%v", scope, orgID) } -//ScopeInjector inject request params into the templated scopes. e.g. "settings:" + eval.Parameters(":id") +// ScopeInjector inject request params into the templated scopes. e.g. "settings:" + eval.Parameters(":id") func ScopeInjector(params ScopeParams) ScopeAttributeMutator { return func(_ context.Context, scope string) ([]string, error) { tmpl, err := template.New("scope").Parse(scope) diff --git a/pkg/services/alerting/conditions/query_interval_test.go b/pkg/services/alerting/conditions/query_interval_test.go index 34d169ca4f56e..180b9dc335004 100644 --- a/pkg/services/alerting/conditions/query_interval_test.go +++ b/pkg/services/alerting/conditions/query_interval_test.go @@ -126,7 +126,7 @@ type fakeIntervalTestReqHandler struct { verifier queryIntervalVerifier } -//nolint: staticcheck // legacydata.DataResponse deprecated +// nolint: staticcheck // legacydata.DataResponse deprecated func (rh fakeIntervalTestReqHandler) HandleRequest(ctx context.Context, dsInfo *datasources.DataSource, query legacydata.DataQuery) ( legacydata.DataResponse, error) { q := query.Queries[0] @@ -134,7 +134,7 @@ func (rh fakeIntervalTestReqHandler) HandleRequest(ctx context.Context, dsInfo * return rh.response, nil } -//nolint: staticcheck // legacydata.DataResponse deprecated +// nolint: staticcheck // legacydata.DataResponse deprecated func applyScenario(t *testing.T, timeRange string, dataSourceJsonData *simplejson.Json, queryModel string, verifier func(query legacydata.DataSubQuery)) { t.Run("desc", func(t *testing.T) { store := mockstore.NewSQLStoreMock() diff --git a/pkg/services/alerting/conditions/query_test.go b/pkg/services/alerting/conditions/query_test.go index 0fc9a53a9ec60..8126622561d1d 100644 --- a/pkg/services/alerting/conditions/query_test.go +++ b/pkg/services/alerting/conditions/query_test.go @@ -205,7 +205,7 @@ type queryConditionTestContext struct { condition *QueryCondition } -//nolint: staticcheck // legacydata.DataPlugin deprecated +// nolint: staticcheck // legacydata.DataPlugin deprecated func (ctx *queryConditionTestContext) exec(t *testing.T) (*alerting.ConditionResult, error) { jsonModel, err := simplejson.NewJson([]byte(`{ "type": "query", @@ -249,7 +249,7 @@ type fakeReqHandler struct { response legacydata.DataResponse } -//nolint: staticcheck // legacydata.DataPlugin deprecated +// nolint: staticcheck // legacydata.DataPlugin deprecated func (rh fakeReqHandler) HandleRequest(context.Context, *datasources.DataSource, legacydata.DataQuery) ( legacydata.DataResponse, error) { return rh.response, nil diff --git a/pkg/services/alerting/conditions/reducer.go b/pkg/services/alerting/conditions/reducer.go index be42681f2eefa..62e5bab182d8a 100644 --- a/pkg/services/alerting/conditions/reducer.go +++ b/pkg/services/alerting/conditions/reducer.go @@ -17,7 +17,7 @@ type queryReducer struct { Type string } -//nolint: gocyclo +// nolint: gocyclo func (s *queryReducer) Reduce(series legacydata.DataTimeSeries) null.Float { if len(series.Points) == 0 { return null.FloatFromPtr(nil) diff --git a/pkg/services/alerting/notifier.go b/pkg/services/alerting/notifier.go index 3df0c8abfef4e..e360558c65b45 100644 --- a/pkg/services/alerting/notifier.go +++ b/pkg/services/alerting/notifier.go @@ -16,7 +16,7 @@ import ( ) // for stubbing in tests -//nolint: gocritic +// nolint: gocritic var newImageUploaderProvider = func() (imguploader.ImageUploader, error) { return imguploader.NewImageUploader() } diff --git a/pkg/services/alerting/notifiers/googlechat.go b/pkg/services/alerting/notifiers/googlechat.go index b205bb7bba9a4..0b1e8080f9e1c 100644 --- a/pkg/services/alerting/notifiers/googlechat.go +++ b/pkg/services/alerting/notifiers/googlechat.go @@ -54,7 +54,8 @@ type GoogleChatNotifier struct { log log.Logger } -/** +/* +* Structs used to build a custom Google Hangouts Chat message card. See: https://developers.google.com/hangouts/chat/reference/message-formats/cards */ diff --git a/pkg/services/alerting/ticker.go b/pkg/services/alerting/ticker.go index d0f73ebb7bee3..f7aa36def7cd8 100644 --- a/pkg/services/alerting/ticker.go +++ b/pkg/services/alerting/ticker.go @@ -11,10 +11,10 @@ import ( ) // Ticker is a ticker to power the alerting scheduler. it's like a time.Ticker, except: -// * it doesn't drop ticks for slow receivers, rather, it queues up. so that callers are in control to instrument what's going on. -// * it ticks on interval marks or very shortly after. this provides a predictable load pattern -// (this shouldn't cause too much load contention issues because the next steps in the pipeline just process at their own pace) -// * the timestamps are used to mark "last datapoint to query for" and as such, are a configurable amount of seconds in the past +// - it doesn't drop ticks for slow receivers, rather, it queues up. so that callers are in control to instrument what's going on. +// - it ticks on interval marks or very shortly after. this provides a predictable load pattern +// (this shouldn't cause too much load contention issues because the next steps in the pipeline just process at their own pace) +// - the timestamps are used to mark "last datapoint to query for" and as such, are a configurable amount of seconds in the past type Ticker struct { C chan time.Time clock clock.Clock diff --git a/pkg/services/dashboards/dashboard.go b/pkg/services/dashboards/dashboard.go index b3a1b3cffe303..bdb3f6687fc4c 100644 --- a/pkg/services/dashboards/dashboard.go +++ b/pkg/services/dashboards/dashboard.go @@ -6,8 +6,9 @@ import ( "github.com/grafana/grafana/pkg/models" ) -//go:generate mockery --name DashboardService --structname FakeDashboardService --inpackage --filename dashboard_service_mock.go // DashboardService is a service for operating on dashboards. +// +//go:generate mockery --name DashboardService --structname FakeDashboardService --inpackage --filename dashboard_service_mock.go type DashboardService interface { BuildSaveDashboardCommand(ctx context.Context, dto *SaveDashboardDTO, shouldValidateAlerts bool, validateProvisionedDashboard bool) (*models.SaveDashboardCommand, error) DeleteDashboard(ctx context.Context, dashboardId int64, orgId int64) error @@ -31,8 +32,9 @@ type PluginService interface { GetDashboardsByPluginID(ctx context.Context, query *models.GetDashboardsByPluginIdQuery) error } -//go:generate mockery --name DashboardProvisioningService --structname FakeDashboardProvisioning --inpackage --filename dashboard_provisioning_mock.go // DashboardProvisioningService is a service for operating on provisioned dashboards. +// +//go:generate mockery --name DashboardProvisioningService --structname FakeDashboardProvisioning --inpackage --filename dashboard_provisioning_mock.go type DashboardProvisioningService interface { DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error DeleteProvisionedDashboard(ctx context.Context, dashboardID int64, orgID int64) error @@ -44,8 +46,9 @@ type DashboardProvisioningService interface { UnprovisionDashboard(ctx context.Context, dashboardID int64) error } -//go:generate mockery --name Store --structname FakeDashboardStore --inpackage --filename store_mock.go // Store is a dashboard store. +// +//go:generate mockery --name Store --structname FakeDashboardStore --inpackage --filename store_mock.go type Store interface { DeleteDashboard(ctx context.Context, cmd *models.DeleteDashboardCommand) error DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error @@ -74,8 +77,9 @@ type Store interface { FolderStore } -//go:generate mockery --name FolderStore --structname FakeFolderStore --inpackage --filename folder_store_mock.go // FolderStore is a folder store. +// +//go:generate mockery --name FolderStore --structname FakeFolderStore --inpackage --filename folder_store_mock.go type FolderStore interface { // GetFolderByTitle retrieves a folder by its title GetFolderByTitle(ctx context.Context, orgID int64, title string) (*models.Folder, error) diff --git a/pkg/services/dashboards/folder.go b/pkg/services/dashboards/folder.go index 42660db3f7613..97e7bfcb804be 100644 --- a/pkg/services/dashboards/folder.go +++ b/pkg/services/dashboards/folder.go @@ -6,8 +6,9 @@ import ( "github.com/grafana/grafana/pkg/models" ) -//go:generate mockery --name FolderService --structname FakeFolderService --inpackage --filename folder_service_mock.go // FolderService is a service for operating on folders. +// +//go:generate mockery --name FolderService --structname FakeFolderService --inpackage --filename folder_service_mock.go type FolderService interface { GetFolders(ctx context.Context, user *models.SignedInUser, orgID int64, limit int64, page int64) ([]*models.Folder, error) GetFolderByID(ctx context.Context, user *models.SignedInUser, id int64, orgID int64) (*models.Folder, error) diff --git a/pkg/services/featuremgmt/strcase/snake.go b/pkg/services/featuremgmt/strcase/snake.go index 012fdb181d263..5632b28101ddc 100644 --- a/pkg/services/featuremgmt/strcase/snake.go +++ b/pkg/services/featuremgmt/strcase/snake.go @@ -65,7 +65,7 @@ func ToDelimited(s string, delimiter uint8) string { // (in this case `delimiter = '.'; screaming = true`) // or delimited.snake.case // (in this case `delimiter = '.'; screaming = false`) -//nolint: gocyclo +// nolint: gocyclo func ToScreamingDelimited(s string, delimiter uint8, ignore string, screaming bool) string { s = strings.TrimSpace(s) n := strings.Builder{} diff --git a/pkg/services/libraryelements/database.go b/pkg/services/libraryelements/database.go index 674799c0e4a77..f3e81404f05b3 100644 --- a/pkg/services/libraryelements/database.go +++ b/pkg/services/libraryelements/database.go @@ -590,7 +590,7 @@ func (l *LibraryElementService) getConnections(c context.Context, signedInUser * return connections, err } -//getElementsForDashboardID gets all elements for a specific dashboard +// getElementsForDashboardID gets all elements for a specific dashboard func (l *LibraryElementService) getElementsForDashboardID(c context.Context, dashboardID int64) (map[string]LibraryElementDTO, error) { libraryElementMap := make(map[string]LibraryElementDTO) err := l.SQLStore.WithDbSession(c, func(session *sqlstore.DBSession) error { diff --git a/pkg/services/ngalert/api/tooling/definitions/api.go b/pkg/services/ngalert/api/tooling/definitions/api.go index 29050cf9d2dd4..b1a5b1a9fdeae 100644 --- a/pkg/services/ngalert/api/tooling/definitions/api.go +++ b/pkg/services/ngalert/api/tooling/definitions/api.go @@ -3,23 +3,22 @@ // Package definitions includes the types required for generating or consuming an OpenAPI // spec for the Grafana Alerting API. // +// Schemes: http, https +// BasePath: /api/v1 +// Version: 1.1.0 // -// Schemes: http, https -// BasePath: /api/v1 -// Version: 1.1.0 +// Consumes: +// - application/json // -// Consumes: -// - application/json +// Produces: +// - application/json // -// Produces: -// - application/json +// Security: +// - basic // -// Security: -// - basic -// -// SecurityDefinitions: -// basic: -// type: basic +// SecurityDefinitions: +// basic: +// type: basic // // swagger:meta package definitions diff --git a/pkg/services/ngalert/eval/eval.go b/pkg/services/ngalert/eval/eval.go index 24f261b8b9b1c..9628ecae7acb8 100644 --- a/pkg/services/ngalert/eval/eval.go +++ b/pkg/services/ngalert/eval/eval.go @@ -374,18 +374,18 @@ func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, no // // For example, given the following: // -// map[string]string{ -// "ref1": "datasource1", -// "ref2": "datasource1", -// "ref3": "datasource2", -// } +// map[string]string{ +// "ref1": "datasource1", +// "ref2": "datasource1", +// "ref3": "datasource2", +// } // // we would expect: // -// map[string][]string{ -// "datasource1": []string{"ref1", "ref2"}, -// "datasource2": []string{"ref3"}, -// } +// map[string][]string{ +// "datasource1": []string{"ref1", "ref2"}, +// "datasource2": []string{"ref3"}, +// } func datasourceUIDsToRefIDs(refIDsToDatasourceUIDs map[string]string) map[string][]string { if refIDsToDatasourceUIDs == nil { return nil @@ -420,12 +420,12 @@ func datasourceUIDsToRefIDs(refIDsToDatasourceUIDs map[string]string) map[string // Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned. // // Per Frame, data becomes a State based on the following rules: -// - Empty or zero length Frames result in NoData. -// - If a value: -// - 0 results in Normal. -// - Nonzero (e.g 1.2, NaN) results in Alerting. -// - nil results in noData. -// - unsupported Frame schemas results in Error. +// - Empty or zero length Frames result in NoData. +// - If a value: +// - 0 results in Normal. +// - Nonzero (e.g 1.2, NaN) results in Alerting. +// - nil results in noData. +// - unsupported Frame schemas results in Error. func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results { evalResults := make([]Result, 0) diff --git a/pkg/services/ngalert/eval/evaluator_mock.go b/pkg/services/ngalert/eval/evaluator_mock.go index 6c80a3e581807..568cd8c99a367 100644 --- a/pkg/services/ngalert/eval/evaluator_mock.go +++ b/pkg/services/ngalert/eval/evaluator_mock.go @@ -48,8 +48,8 @@ type FakeEvaluator_ConditionEval_Call struct { } // ConditionEval is a helper method to define mock.On call -// - condition models.Condition -// - now time.Time +// - condition models.Condition +// - now time.Time func (_e *FakeEvaluator_Expecter) ConditionEval(condition interface{}, now interface{}) *FakeEvaluator_ConditionEval_Call { return &FakeEvaluator_ConditionEval_Call{Call: _e.mock.On("ConditionEval", condition, now)} } @@ -95,9 +95,9 @@ type FakeEvaluator_QueriesAndExpressionsEval_Call struct { } // QueriesAndExpressionsEval is a helper method to define mock.On call -// - orgID int64 -// - data []models.AlertQuery -// - now time.Time +// - orgID int64 +// - data []models.AlertQuery +// - now time.Time func (_e *FakeEvaluator_Expecter) QueriesAndExpressionsEval(orgID interface{}, data interface{}, now interface{}) *FakeEvaluator_QueriesAndExpressionsEval_Call { return &FakeEvaluator_QueriesAndExpressionsEval_Call{Call: _e.mock.On("QueriesAndExpressionsEval", orgID, data, now)} } diff --git a/pkg/services/ngalert/models/alert_rule.go b/pkg/services/ngalert/models/alert_rule.go index 4363c3d0475d3..4f8b199c861fe 100644 --- a/pkg/services/ngalert/models/alert_rule.go +++ b/pkg/services/ngalert/models/alert_rule.go @@ -372,7 +372,8 @@ func (c Condition) IsValid() bool { // There are several exceptions: // 1. Following fields are not patched and therefore will be ignored: AlertRule.ID, AlertRule.OrgID, AlertRule.Updated, AlertRule.Version, AlertRule.UID, AlertRule.DashboardUID, AlertRule.PanelID, AlertRule.Annotations and AlertRule.Labels // 2. There are fields that are patched together: -// - AlertRule.Condition and AlertRule.Data +// - AlertRule.Condition and AlertRule.Data +// // If either of the pair is specified, neither is patched. func PatchPartialAlertRule(existingRule *AlertRule, ruleToPatch *AlertRule) { if ruleToPatch.Title == "" { diff --git a/pkg/services/ngalert/notifier/channels/testing.go b/pkg/services/ngalert/notifier/channels/testing.go index af7467cc62ec9..0af3eba1397de 100644 --- a/pkg/services/ngalert/notifier/channels/testing.go +++ b/pkg/services/ngalert/notifier/channels/testing.go @@ -104,11 +104,12 @@ func newTestImage() (string, error) { // mockTimeNow replaces function timeNow to return constant time. // It returns a function that resets the variable back to its original value. // This allows usage of this function with defer: -// func Test (t *testing.T) { -// now := time.Now() -// defer mockTimeNow(now)() -// ... -// } +// +// func Test (t *testing.T) { +// now := time.Now() +// defer mockTimeNow(now)() +// ... +// } func mockTimeNow(constTime time.Time) func() { timeNow = func() time.Time { return constTime diff --git a/pkg/services/ngalert/notifier/channels/util.go b/pkg/services/ngalert/notifier/channels/util.go index 226e540f4a626..1333e4ab4ed37 100644 --- a/pkg/services/ngalert/notifier/channels/util.go +++ b/pkg/services/ngalert/notifier/channels/util.go @@ -96,6 +96,7 @@ func withStoredImages(ctx context.Context, l log.Logger, imageStore ImageStore, // The path argument here comes from reading internal image storage, not user // input, so we ignore the security check here. +// //nolint:gosec func openImage(path string) (io.ReadCloser, error) { fp := filepath.Clean(path) diff --git a/pkg/services/ngalert/provisioning/persist.go b/pkg/services/ngalert/provisioning/persist.go index ed99265b7de7e..d8f3a715278db 100644 --- a/pkg/services/ngalert/provisioning/persist.go +++ b/pkg/services/ngalert/provisioning/persist.go @@ -9,6 +9,7 @@ import ( ) // AMStore is a store of Alertmanager configurations. +// //go:generate mockery --name AMConfigStore --structname MockAMConfigStore --inpackage --filename persist_mock.go --with-expecter type AMConfigStore interface { GetLatestAlertmanagerConfiguration(ctx context.Context, query *models.GetLatestAlertmanagerConfigurationQuery) error @@ -16,6 +17,7 @@ type AMConfigStore interface { } // ProvisioningStore is a store of provisioning data for arbitrary objects. +// //go:generate mockery --name ProvisioningStore --structname MockProvisioningStore --inpackage --filename provisioning_store_mock.go --with-expecter type ProvisioningStore interface { GetProvenance(ctx context.Context, o models.Provisionable, org int64) (models.Provenance, error) @@ -40,6 +42,7 @@ type RuleStore interface { } // QuotaChecker represents the ability to evaluate whether quotas are met. +// //go:generate mockery --name QuotaChecker --structname MockQuotaChecker --inpackage --filename quota_checker_mock.go --with-expecter type QuotaChecker interface { CheckQuotaReached(ctx context.Context, target string, scopeParams *quota.ScopeParameters) (bool, error) diff --git a/pkg/services/ngalert/provisioning/persist_mock.go b/pkg/services/ngalert/provisioning/persist_mock.go index 5f292cacd937a..7a0c1c1d0be50 100644 --- a/pkg/services/ngalert/provisioning/persist_mock.go +++ b/pkg/services/ngalert/provisioning/persist_mock.go @@ -44,8 +44,8 @@ type MockAMConfigStore_GetLatestAlertmanagerConfiguration_Call struct { } // GetLatestAlertmanagerConfiguration is a helper method to define mock.On call -// - ctx context.Context -// - query *models.GetLatestAlertmanagerConfigurationQuery +// - ctx context.Context +// - query *models.GetLatestAlertmanagerConfigurationQuery func (_e *MockAMConfigStore_Expecter) GetLatestAlertmanagerConfiguration(ctx interface{}, query interface{}) *MockAMConfigStore_GetLatestAlertmanagerConfiguration_Call { return &MockAMConfigStore_GetLatestAlertmanagerConfiguration_Call{Call: _e.mock.On("GetLatestAlertmanagerConfiguration", ctx, query)} } @@ -82,8 +82,8 @@ type MockAMConfigStore_UpdateAlertmanagerConfiguration_Call struct { } // UpdateAlertmanagerConfiguration is a helper method to define mock.On call -// - ctx context.Context -// - cmd *models.SaveAlertmanagerConfigurationCmd +// - ctx context.Context +// - cmd *models.SaveAlertmanagerConfigurationCmd func (_e *MockAMConfigStore_Expecter) UpdateAlertmanagerConfiguration(ctx interface{}, cmd interface{}) *MockAMConfigStore_UpdateAlertmanagerConfiguration_Call { return &MockAMConfigStore_UpdateAlertmanagerConfiguration_Call{Call: _e.mock.On("UpdateAlertmanagerConfiguration", ctx, cmd)} } diff --git a/pkg/services/ngalert/provisioning/provisioning_store_mock.go b/pkg/services/ngalert/provisioning/provisioning_store_mock.go index 878ae95f25e27..ebc65ef885752 100644 --- a/pkg/services/ngalert/provisioning/provisioning_store_mock.go +++ b/pkg/services/ngalert/provisioning/provisioning_store_mock.go @@ -44,9 +44,9 @@ type MockProvisioningStore_DeleteProvenance_Call struct { } // DeleteProvenance is a helper method to define mock.On call -// - ctx context.Context -// - o models.Provisionable -// - org int64 +// - ctx context.Context +// - o models.Provisionable +// - org int64 func (_e *MockProvisioningStore_Expecter) DeleteProvenance(ctx interface{}, o interface{}, org interface{}) *MockProvisioningStore_DeleteProvenance_Call { return &MockProvisioningStore_DeleteProvenance_Call{Call: _e.mock.On("DeleteProvenance", ctx, o, org)} } @@ -90,9 +90,9 @@ type MockProvisioningStore_GetProvenance_Call struct { } // GetProvenance is a helper method to define mock.On call -// - ctx context.Context -// - o models.Provisionable -// - org int64 +// - ctx context.Context +// - o models.Provisionable +// - org int64 func (_e *MockProvisioningStore_Expecter) GetProvenance(ctx interface{}, o interface{}, org interface{}) *MockProvisioningStore_GetProvenance_Call { return &MockProvisioningStore_GetProvenance_Call{Call: _e.mock.On("GetProvenance", ctx, o, org)} } @@ -138,9 +138,9 @@ type MockProvisioningStore_GetProvenances_Call struct { } // GetProvenances is a helper method to define mock.On call -// - ctx context.Context -// - org int64 -// - resourceType string +// - ctx context.Context +// - org int64 +// - resourceType string func (_e *MockProvisioningStore_Expecter) GetProvenances(ctx interface{}, org interface{}, resourceType interface{}) *MockProvisioningStore_GetProvenances_Call { return &MockProvisioningStore_GetProvenances_Call{Call: _e.mock.On("GetProvenances", ctx, org, resourceType)} } @@ -177,10 +177,10 @@ type MockProvisioningStore_SetProvenance_Call struct { } // SetProvenance is a helper method to define mock.On call -// - ctx context.Context -// - o models.Provisionable -// - org int64 -// - p models.Provenance +// - ctx context.Context +// - o models.Provisionable +// - org int64 +// - p models.Provenance func (_e *MockProvisioningStore_Expecter) SetProvenance(ctx interface{}, o interface{}, org interface{}, p interface{}) *MockProvisioningStore_SetProvenance_Call { return &MockProvisioningStore_SetProvenance_Call{Call: _e.mock.On("SetProvenance", ctx, o, org, p)} } diff --git a/pkg/services/ngalert/provisioning/quota_checker_mock.go b/pkg/services/ngalert/provisioning/quota_checker_mock.go index 0d52a5bf207f5..f545dd1b5ec90 100644 --- a/pkg/services/ngalert/provisioning/quota_checker_mock.go +++ b/pkg/services/ngalert/provisioning/quota_checker_mock.go @@ -51,9 +51,9 @@ type MockQuotaChecker_CheckQuotaReached_Call struct { } // CheckQuotaReached is a helper method to define mock.On call -// - ctx context.Context -// - target string -// - scopeParams *quota.ScopeParameters +// - ctx context.Context +// - target string +// - scopeParams *quota.ScopeParameters func (_e *MockQuotaChecker_Expecter) CheckQuotaReached(ctx interface{}, target interface{}, scopeParams interface{}) *MockQuotaChecker_CheckQuotaReached_Call { return &MockQuotaChecker_CheckQuotaReached_Call{Call: _e.mock.On("CheckQuotaReached", ctx, target, scopeParams)} } diff --git a/pkg/services/ngalert/schedule/alerts_sender_mock.go b/pkg/services/ngalert/schedule/alerts_sender_mock.go index 04acf185a3ef5..6f0a28eb122fe 100644 --- a/pkg/services/ngalert/schedule/alerts_sender_mock.go +++ b/pkg/services/ngalert/schedule/alerts_sender_mock.go @@ -33,8 +33,8 @@ type AlertsSenderMock_Send_Call struct { } // Send is a helper method to define mock.On call -// - key models.AlertRuleKey -// - alerts definitions.PostableAlerts +// - key models.AlertRuleKey +// - alerts definitions.PostableAlerts func (_e *AlertsSenderMock_Expecter) Send(key interface{}, alerts interface{}) *AlertsSenderMock_Send_Call { return &AlertsSenderMock_Send_Call{Call: _e.mock.On("Send", key, alerts)} } diff --git a/pkg/services/ngalert/schedule/registry.go b/pkg/services/ngalert/schedule/registry.go index dc1e14833d15e..5338ffa47bb4b 100644 --- a/pkg/services/ngalert/schedule/registry.go +++ b/pkg/services/ngalert/schedule/registry.go @@ -89,6 +89,7 @@ func newAlertRuleInfo(parent context.Context) *alertRuleInfo { // Returns a tuple where first element is // - true when message was sent // - false when the send operation is stopped +// // the second element contains a dropped message that was sent by a concurrent sender. func (a *alertRuleInfo) eval(t time.Time, version int64) (bool, *evaluation) { // read the channel in unblocking manner to make sure that there is no concurrent send operation. diff --git a/pkg/services/ngalert/schedule/schedule.go b/pkg/services/ngalert/schedule/schedule.go index deb0d2b09e311..1a3beac4fc748 100644 --- a/pkg/services/ngalert/schedule/schedule.go +++ b/pkg/services/ngalert/schedule/schedule.go @@ -25,6 +25,7 @@ import ( // ScheduleService is an interface for a service that schedules the evaluation // of alert rules. +// //go:generate mockery --name ScheduleService --structname FakeScheduleService --inpackage --filename schedule_mock.go type ScheduleService interface { // Run the scheduler until the context is canceled or the scheduler returns @@ -44,8 +45,9 @@ type ScheduleService interface { folderUpdateHandler(ctx context.Context, evt *events.FolderUpdated) error } -//go:generate mockery --name AlertsSender --structname AlertsSenderMock --inpackage --filename alerts_sender_mock.go --with-expecter // AlertsSender is an interface for a service that is responsible for sending notifications to the end-user. +// +//go:generate mockery --name AlertsSender --structname AlertsSenderMock --inpackage --filename alerts_sender_mock.go --with-expecter type AlertsSender interface { Send(key ngmodels.AlertRuleKey, alerts definitions.PostableAlerts) } diff --git a/pkg/services/provisioning/values/values.go b/pkg/services/provisioning/values/values.go index ce771310799fd..f23ba0e4fa5a3 100644 --- a/pkg/services/provisioning/values/values.go +++ b/pkg/services/provisioning/values/values.go @@ -1,13 +1,14 @@ // Package values is a set of value types to use in provisioning. They add custom unmarshaling logic that puts the string values // through os.ExpandEnv. // Usage: -// type Data struct { -// Field StringValue `yaml:"field"` // Instead of string -// } +// +// type Data struct { +// Field StringValue `yaml:"field"` // Instead of string +// } +// // d := &Data{} // // unmarshal into d // d.Field.Value() // returns the final interpolated value from the yaml file -// package values import ( diff --git a/pkg/services/publicdashboards/api/api_test.go b/pkg/services/publicdashboards/api/api_test.go index 4eb0ea1ad4e13..94cfeba01d145 100644 --- a/pkg/services/publicdashboards/api/api_test.go +++ b/pkg/services/publicdashboards/api/api_test.go @@ -265,7 +265,7 @@ func TestApiSavePublicDashboardConfig(t *testing.T) { } } -// `/public/dashboards/:uid/query`` endpoint test +// `/public/dashboards/:uid/query“ endpoint test func TestAPIQueryPublicDashboard(t *testing.T) { cacheService := &fakeDatasources.FakeCacheService{ DataSources: []*datasources.DataSource{ diff --git a/pkg/services/publicdashboards/api/common_test.go b/pkg/services/publicdashboards/api/common_test.go index d500c8d6e9056..c08aa8a452ac4 100644 --- a/pkg/services/publicdashboards/api/common_test.go +++ b/pkg/services/publicdashboards/api/common_test.go @@ -137,7 +137,7 @@ func buildQueryDataService(t *testing.T, cs datasources.CacheService, fpc *fakeP ) } -//copied from pkg/api/metrics_test.go +// copied from pkg/api/metrics_test.go type fakePluginRequestValidator struct { err error } diff --git a/pkg/services/publicdashboards/models/models.go b/pkg/services/publicdashboards/models/models.go index 31983d5308837..e1d2f8bca0822 100644 --- a/pkg/services/publicdashboards/models/models.go +++ b/pkg/services/publicdashboards/models/models.go @@ -94,9 +94,7 @@ func (pd PublicDashboard) BuildTimeSettings(dashboard *models.Dashboard) *TimeSe return ts } -// // DTO for transforming user input in the api -// type SavePublicDashboardConfigDTO struct { DashboardUid string OrgId int64 diff --git a/pkg/services/screenshot/screenshot.go b/pkg/services/screenshot/screenshot.go index e963448099e83..8d6797ff79121 100644 --- a/pkg/services/screenshot/screenshot.go +++ b/pkg/services/screenshot/screenshot.go @@ -77,6 +77,7 @@ func (s ScreenshotOptions) SetDefaults() ScreenshotOptions { } // ScreenshotService is an interface for taking screenshots. +// //go:generate mockgen -destination=mock.go -package=screenshot github.com/grafana/grafana/pkg/services/screenshot ScreenshotService type ScreenshotService interface { Take(ctx context.Context, opts ScreenshotOptions) (*Screenshot, error) diff --git a/pkg/services/searchV2/bluge.go b/pkg/services/searchV2/bluge.go index 93658636fb0a1..70992939bfb6a 100644 --- a/pkg/services/searchV2/bluge.go +++ b/pkg/services/searchV2/bluge.go @@ -353,7 +353,7 @@ func getDashboardLocation(index *orgIndex, dashboardUID string) (string, bool, e return dashboardLocation, found, err } -//nolint: gocyclo +// nolint: gocyclo func doSearchQuery( ctx context.Context, logger log.Logger, diff --git a/pkg/services/sqlstore/migrator/dialect.go b/pkg/services/sqlstore/migrator/dialect.go index 740704c6f4093..8d79068543430 100644 --- a/pkg/services/sqlstore/migrator/dialect.go +++ b/pkg/services/sqlstore/migrator/dialect.go @@ -312,7 +312,7 @@ func (b *BaseDialect) TruncateDBTables() error { return nil } -//UpsertSQL returns empty string +// UpsertSQL returns empty string func (b *BaseDialect) UpsertSQL(tableName string, keyCols, updateCols []string) string { return "" } diff --git a/pkg/services/sqlstore/org_test.go b/pkg/services/sqlstore/org_test.go index 69057ea193b43..515f3d8c3e2ac 100644 --- a/pkg/services/sqlstore/org_test.go +++ b/pkg/services/sqlstore/org_test.go @@ -415,7 +415,7 @@ func TestIntegrationAccountDataAccess(t *testing.T) { }) } -//TODO: Use FakeDashboardStore when org has its own service +// TODO: Use FakeDashboardStore when org has its own service func insertTestDashboard(t *testing.T, sqlStore *SQLStore, title string, orgId int64, folderId int64, isFolder bool, tags ...interface{}) *models.Dashboard { t.Helper() @@ -472,7 +472,7 @@ func insertTestDashboard(t *testing.T, sqlStore *SQLStore, title string, orgId i return dash } -//TODO: Use FakeDashboardStore when org has its own service +// TODO: Use FakeDashboardStore when org has its own service func updateDashboardAcl(t *testing.T, sqlStore *SQLStore, dashboardID int64, items ...*models.DashboardAcl) error { t.Helper() diff --git a/pkg/services/sqlstore/searchstore/doc.go b/pkg/services/sqlstore/searchstore/doc.go index dcd2e056681ee..228817a4e43fe 100644 --- a/pkg/services/sqlstore/searchstore/doc.go +++ b/pkg/services/sqlstore/searchstore/doc.go @@ -21,11 +21,11 @@ // // Filters will be applied in order with the final result like such: // -// SELECT id FROM dashboard LEFT OUTER JOIN -// WHERE AND ... AND -// GROUP BY -// ORDER BY -// LIMIT OFFSET <(page-1)*limit>; +// SELECT id FROM dashboard LEFT OUTER JOIN +// WHERE AND ... AND +// GROUP BY +// ORDER BY +// LIMIT OFFSET <(page-1)*limit>; // // This structure is intended to isolate the filters from each other // and implementors are expected to add all the required joins, where diff --git a/pkg/services/sqlstore/user.go b/pkg/services/sqlstore/user.go index 9b1cbddc47af8..707d37778e6d4 100644 --- a/pkg/services/sqlstore/user.go +++ b/pkg/services/sqlstore/user.go @@ -178,7 +178,7 @@ func (ss *SQLStore) createUser(ctx context.Context, sess *DBSession, args user.C return usr, nil } -// deprecated method, use only for tests +// deprecated method, use only for tests func (ss *SQLStore) CreateUser(ctx context.Context, cmd user.CreateUserCommand) (*user.User, error) { var user user.User createErr := ss.WithTransactionalDbSession(ctx, func(sess *DBSession) (err error) { diff --git a/pkg/services/store/entity_events.go b/pkg/services/store/entity_events.go index 1c4055908d487..59f1a778ae68d 100644 --- a/pkg/services/store/entity_events.go +++ b/pkg/services/store/entity_events.go @@ -58,6 +58,7 @@ type EventHandler func(ctx context.Context, e *EntityEvent) error // EntityEventsService is a temporary solution to support change notifications in an HA setup // With this service each system can query for any events that have happened since a fixed time +// //go:generate mockery --name EntityEventsService --structname MockEntityEventsService --inpackage --filename entity_events_mock.go type EntityEventsService interface { registry.BackgroundService diff --git a/pkg/services/store/storage_sql.go b/pkg/services/store/storage_sql.go index e2e4f3ac79aee..35cc97fab0c33 100644 --- a/pkg/services/store/storage_sql.go +++ b/pkg/services/store/storage_sql.go @@ -21,9 +21,10 @@ type rootStorageSQL struct { // getDbRootFolder creates a DB path prefix for a given storage name and orgId. // example: -// orgId: 5 -// storageName: "upload" -// => prefix: "/5/upload/" +// +// orgId: 5 +// storageName: "upload" +// => prefix: "/5/upload/" func getDbStoragePathPrefix(orgId int64, storageName string) string { return filestorage.Join(fmt.Sprintf("%d", orgId), storageName+filestorage.Delimiter) } diff --git a/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource.go b/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource.go index f7c73a8ef182b..ea97c0b4c9328 100644 --- a/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource.go +++ b/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource.go @@ -461,9 +461,12 @@ func formatAzureMonitorLegendKey(alias string, resourceName string, metricName s } // Map values from: -// https://docs.microsoft.com/en-us/rest/api/monitor/metrics/list#unit +// +// https://docs.microsoft.com/en-us/rest/api/monitor/metrics/list#unit +// // to -// https://github.com/grafana/grafana/blob/main/packages/grafana-data/src/valueFormats/categories.ts#L24 +// +// https://github.com/grafana/grafana/blob/main/packages/grafana-data/src/valueFormats/categories.ts#L24 func toGrafanaUnit(unit string) string { switch unit { case "BitsPerSecond": diff --git a/pkg/tsdb/cloudmonitoring/time_series_filter.go b/pkg/tsdb/cloudmonitoring/time_series_filter.go index e1e131c1122f8..62122497a375a 100644 --- a/pkg/tsdb/cloudmonitoring/time_series_filter.go +++ b/pkg/tsdb/cloudmonitoring/time_series_filter.go @@ -82,7 +82,7 @@ func (timeSeriesFilter *cloudMonitoringTimeSeriesFilter) run(ctx context.Context return dr, d, r.URL.RawQuery, nil } -//nolint: gocyclo +// nolint: gocyclo func (timeSeriesFilter *cloudMonitoringTimeSeriesFilter) parseResponse(queryRes *backend.DataResponse, response cloudMonitoringResponse, executedQueryString string) error { frames := data.Frames{} diff --git a/pkg/tsdb/influxdb/flux/builder.go b/pkg/tsdb/influxdb/flux/builder.go index bca81dda24ea6..d8f6dcdcbf7bb 100644 --- a/pkg/tsdb/influxdb/flux/builder.go +++ b/pkg/tsdb/influxdb/flux/builder.go @@ -29,18 +29,18 @@ const ( // // we also try to detect some often used patterns in the data, // and make the data easier to graph in the browser for such cases: -// - if there is only one timestamp-column and it's named "_time", -// we will not add the labels to this data-column, because timestamp -// columns usually do not have labels in grafana. -// we use the `columnInfo.shouldGetLabels` attribute to handle this. -// - if there is only one timestamp-column and it's named "_time", -// and there is only one non-timestamp-column and it's named "_value", -// we rename "_time" to "Time" (using `columnInfo.isTheSimpleTime`), -// and we rename "_value" too (using `columnInfo.isTheSimpleValue`): -// if there is a tag called "_field" we use it's value as the name -// (because that's the usual approach in influxdb), and if there is not, -// we name it "Value". with these new names, they are more compatible -// with the visualizations in grafana. +// - if there is only one timestamp-column and it's named "_time", +// we will not add the labels to this data-column, because timestamp +// columns usually do not have labels in grafana. +// we use the `columnInfo.shouldGetLabels` attribute to handle this. +// - if there is only one timestamp-column and it's named "_time", +// and there is only one non-timestamp-column and it's named "_value", +// we rename "_time" to "Time" (using `columnInfo.isTheSimpleTime`), +// and we rename "_value" too (using `columnInfo.isTheSimpleValue`): +// if there is a tag called "_field" we use it's value as the name +// (because that's the usual approach in influxdb), and if there is not, +// we name it "Value". with these new names, they are more compatible +// with the visualizations in grafana. type columnInfo struct { name string converter *data.FieldConverter diff --git a/pkg/tsdb/intervalv2/intervalv2.go b/pkg/tsdb/intervalv2/intervalv2.go index 77a66f591d815..b573627dd0641 100644 --- a/pkg/tsdb/intervalv2/intervalv2.go +++ b/pkg/tsdb/intervalv2/intervalv2.go @@ -156,7 +156,7 @@ func FormatDuration(inter time.Duration) string { return "1ms" } -//nolint: gocyclo +// nolint: gocyclo func roundInterval(interval time.Duration) time.Duration { switch { // 0.01s diff --git a/pkg/tsdb/legacydata/interval/interval.go b/pkg/tsdb/legacydata/interval/interval.go index ab165819c49c3..199b8cff59682 100644 --- a/pkg/tsdb/legacydata/interval/interval.go +++ b/pkg/tsdb/legacydata/interval/interval.go @@ -146,7 +146,7 @@ func FormatDuration(inter time.Duration) string { return "1ms" } -//nolint: gocyclo +// nolint: gocyclo func roundInterval(interval time.Duration) time.Duration { switch { // 0.015s diff --git a/pkg/tsdb/legacydata/service/service.go b/pkg/tsdb/legacydata/service/service.go index b5a8e6df967e1..d7d915a384c0f 100644 --- a/pkg/tsdb/legacydata/service/service.go +++ b/pkg/tsdb/legacydata/service/service.go @@ -40,7 +40,7 @@ func ProvideService(pluginsClient plugins.Client, oAuthTokenService oauthtoken.O } } -//nolint: staticcheck // legacydata.DataResponse deprecated +// nolint: staticcheck // legacydata.DataResponse deprecated func (h *Service) HandleRequest(ctx context.Context, ds *datasources.DataSource, query legacydata.DataQuery) (legacydata.DataResponse, error) { decryptedJsonData, err := h.dataSourcesService.DecryptedValues(ctx, ds) if err != nil { diff --git a/pkg/tsdb/loki/frame.go b/pkg/tsdb/loki/frame.go index aa574270c1c07..568a30bd1379d 100644 --- a/pkg/tsdb/loki/frame.go +++ b/pkg/tsdb/loki/frame.go @@ -189,7 +189,7 @@ func formatNamePrometheusStyle(labels map[string]string) string { return fmt.Sprintf("{%s}", strings.Join(parts, ", ")) } -//If legend (using of name or pattern instead of time series name) is used, use that name/pattern for formatting +// If legend (using of name or pattern instead of time series name) is used, use that name/pattern for formatting func formatName(labels map[string]string, query *lokiQuery) string { if query.LegendFormat == "" { return formatNamePrometheusStyle(labels) diff --git a/pkg/tsdb/postgres/macros.go b/pkg/tsdb/postgres/macros.go index c6524786c8396..e2f5084ed7463 100644 --- a/pkg/tsdb/postgres/macros.go +++ b/pkg/tsdb/postgres/macros.go @@ -65,7 +65,7 @@ func (m *postgresMacroEngine) Interpolate(query *backend.DataQuery, timeRange ba return sql, nil } -//nolint: gocyclo +// nolint: gocyclo func (m *postgresMacroEngine) evaluateMacro(timeRange backend.TimeRange, query *backend.DataQuery, name string, args []string) (string, error) { switch name { case "__time": diff --git a/pkg/tsdb/prometheus/buffered/time_series_query.go b/pkg/tsdb/prometheus/buffered/time_series_query.go index 914f906f9c749..c721bf96714da 100644 --- a/pkg/tsdb/prometheus/buffered/time_series_query.go +++ b/pkg/tsdb/prometheus/buffered/time_series_query.go @@ -24,7 +24,7 @@ import ( "go.opentelemetry.io/otel/attribute" ) -//Internal interval and range variables +// Internal interval and range variables const ( varInterval = "$__interval" varIntervalMs = "$__interval_ms" @@ -34,8 +34,8 @@ const ( varRateInterval = "$__rate_interval" ) -//Internal interval and range variables with {} syntax -//Repetitive code, we should have functionality to unify these +// Internal interval and range variables with {} syntax +// Repetitive code, we should have functionality to unify these const ( varIntervalAlt = "${__interval}" varIntervalMsAlt = "${__interval_ms}" diff --git a/pkg/tsdb/prometheus/models/query.go b/pkg/tsdb/prometheus/models/query.go index bdd48d08ed54f..e83ddb3927d52 100644 --- a/pkg/tsdb/prometheus/models/query.go +++ b/pkg/tsdb/prometheus/models/query.go @@ -11,7 +11,7 @@ import ( "github.com/grafana/grafana/pkg/tsdb/intervalv2" ) -//Internal interval and range variables +// Internal interval and range variables const ( varInterval = "$__interval" varIntervalMs = "$__interval_ms" @@ -21,8 +21,8 @@ const ( varRateInterval = "$__rate_interval" ) -//Internal interval and range variables with {} syntax -//Repetitive code, we should have functionality to unify these +// Internal interval and range variables with {} syntax +// Repetitive code, we should have functionality to unify these const ( varIntervalAlt = "${__interval}" varIntervalMsAlt = "${__interval_ms}" diff --git a/pkg/tsdb/sqleng/sql_engine.go b/pkg/tsdb/sqleng/sql_engine.go index d47e8e9a343c5..1ab2d5d1aa9b8 100644 --- a/pkg/tsdb/sqleng/sql_engine.go +++ b/pkg/tsdb/sqleng/sql_engine.go @@ -43,6 +43,7 @@ type SqlQueryResultTransformer interface { var sqlIntervalCalculator = intervalv2.NewCalculator() // NewXormEngine is an xorm.Engine factory, that can be stubbed by tests. +// //nolint:gocritic var NewXormEngine = func(driverName string, connectionString string) (*xorm.Engine, error) { return xorm.NewEngine(driverName, connectionString) @@ -886,7 +887,7 @@ func convertSQLTimeColumnToEpochMS(frame *data.Frame, timeIndex int) error { } // convertSQLValueColumnToFloat converts timeseries value column to float. -//nolint: gocyclo +// nolint: gocyclo func convertSQLValueColumnToFloat(frame *data.Frame, Index int) (*data.Frame, error) { if Index < 0 || Index >= len(frame.Fields) { return frame, fmt.Errorf("metricIndex %d is out of range", Index) diff --git a/pkg/util/cmputil/reporter.go b/pkg/util/cmputil/reporter.go index ec97571a29f46..a7297c42a5249 100644 --- a/pkg/util/cmputil/reporter.go +++ b/pkg/util/cmputil/reporter.go @@ -115,8 +115,9 @@ func describeReflectValue(v reflect.Value) interface{} { } // IsAddOperation returns true when -// - Left does not have value and Right has -// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Left is less than length of Right +// - Left does not have value and Right has +// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Left is less than length of Right +// // In all other cases it returns false. // NOTE: this is applicable to diff of Maps and Slices only func (d *Diff) IsAddOperation() bool { @@ -125,8 +126,9 @@ func (d *Diff) IsAddOperation() bool { } // IsDeleteOperation returns true when -// - Right does not have value and Left has -// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Right is less than length of Left +// - Right does not have value and Left has +// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Right is less than length of Left +// // In all other cases it returns false. // NOTE: this is applicable to diff of Maps and Slices only func (d *Diff) IsDeleteOperation() bool { diff --git a/pkg/util/errutil/doc.go b/pkg/util/errutil/doc.go index a1742adc96f7a..884191be88c11 100644 --- a/pkg/util/errutil/doc.go +++ b/pkg/util/errutil/doc.go @@ -26,16 +26,21 @@ // service using the NewBase constructor with a CoreStatus and a unique // static message ID that identifies the general structure of the public // message attached to the specific error. -// var errNotFound = errutil.NewBase(errutil.StatusNotFound, "service.not-found") +// +// var errNotFound = errutil.NewBase(errutil.StatusNotFound, "service.not-found") +// // This Base can now be used to construct a regular Go error with the // Base.Errorf method using the same structure as fmt.Errorf: -// return errNotFound.Errorf("looked for thing with ID %d, but it wasn't there: %w", id, err) +// +// return errNotFound.Errorf("looked for thing with ID %d, but it wasn't there: %w", id, err) // // By default, the end user will be sent the static message ID and a // message which is the string representation of the CoreStatus. It is // possible to override the message sent to the end user by using // the WithPublicMessage functional option when creating a new Base -// var errNotFound = errutil.NewBase(errutil.StatusNotFound "service.not-found", WithPublicMessage("The thing is missing.")) +// +// var errNotFound = errutil.NewBase(errutil.StatusNotFound "service.not-found", WithPublicMessage("The thing is missing.")) +// // If a dynamic message is needed, the Template type extends Base with a // Go template using text/template from the standard library, refer to // the documentation related to the Template type for usage examples. diff --git a/pkg/util/errutil/errors.go b/pkg/util/errutil/errors.go index afdba2604f3c0..eab107bb84d65 100644 --- a/pkg/util/errutil/errors.go +++ b/pkg/util/errutil/errors.go @@ -23,9 +23,10 @@ type Base struct { // to serve as the base for user facing error messages. // // msgID should be structured as component.error-brief, for example -// login.failed-authentication -// dashboards.validation-error -// dashboards.uid-already-exists +// +// login.failed-authentication +// dashboards.validation-error +// dashboards.uid-already-exists func NewBase(reason StatusReason, msgID string, opts ...BaseOpt) Base { b := Base{ reason: reason, diff --git a/scripts/build/ci-wix/Magefile.go b/scripts/build/ci-wix/Magefile.go index 905f41f03f6e5..795263e10bebc 100644 --- a/scripts/build/ci-wix/Magefile.go +++ b/scripts/build/ci-wix/Magefile.go @@ -1,4 +1,5 @@ -//+build mage +//go:build mage +// +build mage package main