From c5a09a3dc1b4c0ffa4483229357892b445d26cda Mon Sep 17 00:00:00 2001 From: Karsten Weiss Date: Mon, 16 Apr 2018 19:43:15 +0200 Subject: [PATCH 01/14] Remove redundant break statements (gosimple) This fixes: pkg/components/dynmap/dynmap.go:588:3: redundant break statement (S1023) pkg/components/dynmap/dynmap.go:610:3: redundant break statement (S1023) pkg/components/dynmap/dynmap.go:641:3: redundant break statement (S1023) pkg/components/dynmap/dynmap.go:690:3: redundant break statement (S1023) pkg/components/dynmap/dynmap.go:712:3: redundant break statement (S1023) pkg/components/dynmap/dynmap.go:749:3: redundant break statement (S1023) pkg/components/dynmap/dynmap.go:785:3: redundant break statement (S1023) pkg/tsdb/cloudwatch/cloudwatch.go:74:3: redundant break statement (S1023) pkg/tsdb/cloudwatch/cloudwatch.go:77:3: redundant break statement (S1023) pkg/tsdb/cloudwatch/cloudwatch.go:82:3: redundant break statement (S1023) pkg/tsdb/cloudwatch/metric_find_query.go:178:3: redundant break statement (S1023) pkg/tsdb/cloudwatch/metric_find_query.go:181:3: redundant break statement (S1023) pkg/tsdb/cloudwatch/metric_find_query.go:184:3: redundant break statement (S1023) pkg/tsdb/cloudwatch/metric_find_query.go:187:3: redundant break statement (S1023) pkg/tsdb/cloudwatch/metric_find_query.go:190:3: redundant break statement (S1023) pkg/tsdb/cloudwatch/metric_find_query.go:193:3: redundant break statement (S1023) pkg/tsdb/cloudwatch/metric_find_query.go:196:3: redundant break statement (S1023) --- pkg/components/dynmap/dynmap.go | 7 ------- pkg/tsdb/cloudwatch/cloudwatch.go | 3 --- pkg/tsdb/cloudwatch/metric_find_query.go | 7 ------- 3 files changed, 17 deletions(-) diff --git a/pkg/components/dynmap/dynmap.go b/pkg/components/dynmap/dynmap.go index 797694845cd..2b86ce384eb 100644 --- a/pkg/components/dynmap/dynmap.go +++ b/pkg/components/dynmap/dynmap.go @@ -585,7 +585,6 @@ func (v *Value) Null() error { switch v.data.(type) { case nil: valid = v.exists // Valid only if j also exists, since other values could possibly also be nil - break } if valid { @@ -607,7 +606,6 @@ func (v *Value) Array() ([]*Value, error) { switch v.data.(type) { case []interface{}: valid = true - break } // Unsure if this is a good way to use slices, it's probably not @@ -638,7 +636,6 @@ func (v *Value) Number() (json.Number, error) { switch v.data.(type) { case json.Number: valid = true - break } if valid { @@ -687,7 +684,6 @@ func (v *Value) Boolean() (bool, error) { switch v.data.(type) { case bool: valid = true - break } if valid { @@ -709,7 +705,6 @@ func (v *Value) Object() (*Object, error) { switch v.data.(type) { case map[string]interface{}: valid = true - break } if valid { @@ -746,7 +741,6 @@ func (v *Value) ObjectArray() ([]*Object, error) { switch v.data.(type) { case []interface{}: valid = true - break } // Unsure if this is a good way to use slices, it's probably not @@ -782,7 +776,6 @@ func (v *Value) String() (string, error) { switch v.data.(type) { case string: valid = true - break } if valid { diff --git a/pkg/tsdb/cloudwatch/cloudwatch.go b/pkg/tsdb/cloudwatch/cloudwatch.go index 3879dce4ea6..d98805c661d 100644 --- a/pkg/tsdb/cloudwatch/cloudwatch.go +++ b/pkg/tsdb/cloudwatch/cloudwatch.go @@ -71,15 +71,12 @@ func (e *CloudWatchExecutor) Query(ctx context.Context, dsInfo *models.DataSourc switch queryType { case "metricFindQuery": result, err = e.executeMetricFindQuery(ctx, queryContext) - break case "annotationQuery": result, err = e.executeAnnotationQuery(ctx, queryContext) - break case "timeSeriesQuery": fallthrough default: result, err = e.executeTimeSeriesQuery(ctx, queryContext) - break } return result, err diff --git a/pkg/tsdb/cloudwatch/metric_find_query.go b/pkg/tsdb/cloudwatch/metric_find_query.go index c82cff390c3..23b69f243fa 100644 --- a/pkg/tsdb/cloudwatch/metric_find_query.go +++ b/pkg/tsdb/cloudwatch/metric_find_query.go @@ -175,25 +175,18 @@ func (e *CloudWatchExecutor) executeMetricFindQuery(ctx context.Context, queryCo switch subType { case "regions": data, err = e.handleGetRegions(ctx, parameters, queryContext) - break case "namespaces": data, err = e.handleGetNamespaces(ctx, parameters, queryContext) - break case "metrics": data, err = e.handleGetMetrics(ctx, parameters, queryContext) - break case "dimension_keys": data, err = e.handleGetDimensions(ctx, parameters, queryContext) - break case "dimension_values": data, err = e.handleGetDimensionValues(ctx, parameters, queryContext) - break case "ebs_volume_ids": data, err = e.handleGetEbsVolumeIds(ctx, parameters, queryContext) - break case "ec2_instance_attribute": data, err = e.handleGetEc2InstanceAttribute(ctx, parameters, queryContext) - break } transformToTable(data, queryResult) From be2d635078b12bd3aa6cf54255d2dad9faa0be5d Mon Sep 17 00:00:00 2001 From: Karsten Weiss Date: Mon, 16 Apr 2018 19:54:23 +0200 Subject: [PATCH 02/14] Simplify error returns (gosimple) This fixes: pkg/api/avatar/avatar.go:261:2: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/log/file.go:102:2: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/metrics/graphitebridge/graphite.go:298:2: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/provisioning/provisioning.go:23:2: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/alert_notification.go:27:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/alert_notification.go:27:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/annotation.go:105:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/annotation.go:105:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/dashboard.go:351:2: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/dashboard.go:435:2: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/dashboard_acl.go:38:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/dashboard_acl.go:38:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/stats.go:22:2: 'if err != nil { return err }; return err' can be simplified to 'return err' (S1013) pkg/services/sqlstore/team.go:213:2: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/user.go:256:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/user.go:256:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/user.go:274:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/user.go:274:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/user.go:482:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) pkg/services/sqlstore/user.go:482:3: 'if err != nil { return err }; return nil' can be simplified to 'return err' (S1013) --- pkg/api/avatar/avatar.go | 7 ++----- pkg/log/file.go | 5 +---- pkg/metrics/graphitebridge/graphite.go | 6 +----- pkg/services/provisioning/provisioning.go | 6 +----- pkg/services/sqlstore/alert_notification.go | 7 +------ pkg/services/sqlstore/annotation.go | 7 ++----- pkg/services/sqlstore/dashboard.go | 14 ++------------ pkg/services/sqlstore/dashboard_acl.go | 6 ++---- pkg/services/sqlstore/stats.go | 4 ---- pkg/services/sqlstore/team.go | 6 +----- pkg/services/sqlstore/user.go | 21 ++++++--------------- pkg/tsdb/cloudwatch/metric_find_query.go | 6 +----- 12 files changed, 20 insertions(+), 75 deletions(-) diff --git a/pkg/api/avatar/avatar.go b/pkg/api/avatar/avatar.go index ce9da1e8790..9f282794076 100644 --- a/pkg/api/avatar/avatar.go +++ b/pkg/api/avatar/avatar.go @@ -258,9 +258,6 @@ func (this *thunderTask) fetch() error { this.Avatar.data = &bytes.Buffer{} writer := bufio.NewWriter(this.Avatar.data) - if _, err = io.Copy(writer, resp.Body); err != nil { - return err - } - - return nil + _, err = io.Copy(writer, resp.Body) + return err } diff --git a/pkg/log/file.go b/pkg/log/file.go index 721db1e55b3..d137adbf3de 100644 --- a/pkg/log/file.go +++ b/pkg/log/file.go @@ -99,10 +99,7 @@ func (w *FileLogWriter) StartLogger() error { return err } w.mw.SetFd(fd) - if err = w.initFd(); err != nil { - return err - } - return nil + return w.initFd() } func (w *FileLogWriter) docheck(size int) { diff --git a/pkg/metrics/graphitebridge/graphite.go b/pkg/metrics/graphitebridge/graphite.go index 68fb544fc7c..670636cedce 100644 --- a/pkg/metrics/graphitebridge/graphite.go +++ b/pkg/metrics/graphitebridge/graphite.go @@ -295,11 +295,7 @@ func writeMetric(buf *bufio.Writer, m model.Metric, mf *dto.MetricFamily) error } } - if err = addExtentionConventionForRollups(buf, mf, m); err != nil { - return err - } - - return nil + return addExtentionConventionForRollups(buf, mf, m) } func addExtentionConventionForRollups(buf *bufio.Writer, mf *dto.MetricFamily, m model.Metric) error { diff --git a/pkg/services/provisioning/provisioning.go b/pkg/services/provisioning/provisioning.go index b41ec37b797..71385994bb5 100644 --- a/pkg/services/provisioning/provisioning.go +++ b/pkg/services/provisioning/provisioning.go @@ -20,11 +20,7 @@ func Init(ctx context.Context, homePath string, cfg *ini.File) error { dashboardPath := path.Join(provisioningPath, "dashboards") _, err := dashboards.Provision(ctx, dashboardPath) - if err != nil { - return err - } - - return nil + return err } func makeAbsolute(path string, root string) string { diff --git a/pkg/services/sqlstore/alert_notification.go b/pkg/services/sqlstore/alert_notification.go index ae691c7166c..651241f7714 100644 --- a/pkg/services/sqlstore/alert_notification.go +++ b/pkg/services/sqlstore/alert_notification.go @@ -23,12 +23,7 @@ func DeleteAlertNotification(cmd *m.DeleteAlertNotificationCommand) error { return inTransaction(func(sess *DBSession) error { sql := "DELETE FROM alert_notification WHERE alert_notification.org_id = ? AND alert_notification.id = ?" _, err := sess.Exec(sql, cmd.OrgId, cmd.Id) - - if err != nil { - return err - } - - return nil + return err }) } diff --git a/pkg/services/sqlstore/annotation.go b/pkg/services/sqlstore/annotation.go index 18794281e33..076c0e250b6 100644 --- a/pkg/services/sqlstore/annotation.go +++ b/pkg/services/sqlstore/annotation.go @@ -102,11 +102,8 @@ func (r *SqlAnnotationRepo) Update(item *annotations.Item) error { existing.Tags = item.Tags - if _, err := sess.Table("annotation").Id(existing.Id).Cols("epoch", "text", "region_id", "tags").Update(existing); err != nil { - return err - } - - return nil + _, err = sess.Table("annotation").Id(existing.Id).Cols("epoch", "text", "region_id", "tags").Update(existing) + return err }) } diff --git a/pkg/services/sqlstore/dashboard.go b/pkg/services/sqlstore/dashboard.go index 8a89c3d942c..8d90d348a94 100644 --- a/pkg/services/sqlstore/dashboard.go +++ b/pkg/services/sqlstore/dashboard.go @@ -347,12 +347,7 @@ func GetDashboards(query *m.GetDashboardsQuery) error { err := x.In("id", query.DashboardIds).Find(&dashboards) query.Result = dashboards - - if err != nil { - return err - } - - return nil + return err } // GetDashboardPermissionsForUser returns the maximum permission the specified user has for a dashboard(s) @@ -431,12 +426,7 @@ func GetDashboardsByPluginId(query *m.GetDashboardsByPluginIdQuery) error { err := x.Where(whereExpr, query.OrgId, query.PluginId).Find(&dashboards) query.Result = dashboards - - if err != nil { - return err - } - - return nil + return err } type DashboardSlugDTO struct { diff --git a/pkg/services/sqlstore/dashboard_acl.go b/pkg/services/sqlstore/dashboard_acl.go index ae91d1d41f3..814dc03f9f7 100644 --- a/pkg/services/sqlstore/dashboard_acl.go +++ b/pkg/services/sqlstore/dashboard_acl.go @@ -35,10 +35,8 @@ func UpdateDashboardAcl(cmd *m.UpdateDashboardAclCommand) error { // Update dashboard HasAcl flag dashboard := m.Dashboard{HasAcl: true} - if _, err := sess.Cols("has_acl").Where("id=?", cmd.DashboardId).Update(&dashboard); err != nil { - return err - } - return nil + _, err = sess.Cols("has_acl").Where("id=?", cmd.DashboardId).Update(&dashboard) + return err }) } diff --git a/pkg/services/sqlstore/stats.go b/pkg/services/sqlstore/stats.go index cfe2d88c82c..6929c1fb9b2 100644 --- a/pkg/services/sqlstore/stats.go +++ b/pkg/services/sqlstore/stats.go @@ -19,10 +19,6 @@ func GetDataSourceStats(query *m.GetDataSourceStatsQuery) error { var rawSql = `SELECT COUNT(*) as count, type FROM data_source GROUP BY type` query.Result = make([]*m.DataSourceStats, 0) err := x.SQL(rawSql).Find(&query.Result) - if err != nil { - return err - } - return err } diff --git a/pkg/services/sqlstore/team.go b/pkg/services/sqlstore/team.go index d238301c7ce..b3ff4c81e7c 100644 --- a/pkg/services/sqlstore/team.go +++ b/pkg/services/sqlstore/team.go @@ -210,11 +210,7 @@ func GetTeamsByUser(query *m.GetTeamsByUserQuery) error { sess.Where("team.org_id=? and team_member.user_id=?", query.OrgId, query.UserId) err := sess.Find(&query.Result) - if err != nil { - return err - } - - return nil + return err } // AddTeamMember adds a user to a team diff --git a/pkg/services/sqlstore/user.go b/pkg/services/sqlstore/user.go index db7e851435c..bf64bc65602 100644 --- a/pkg/services/sqlstore/user.go +++ b/pkg/services/sqlstore/user.go @@ -253,11 +253,8 @@ func ChangeUserPassword(cmd *m.ChangeUserPasswordCommand) error { Updated: time.Now(), } - if _, err := sess.Id(cmd.UserId).Update(&user); err != nil { - return err - } - - return nil + _, err := sess.Id(cmd.UserId).Update(&user) + return err }) } @@ -271,11 +268,8 @@ func UpdateUserLastSeenAt(cmd *m.UpdateUserLastSeenAtCommand) error { LastSeenAt: time.Now(), } - if _, err := sess.Id(cmd.UserId).Update(&user); err != nil { - return err - } - - return nil + _, err := sess.Id(cmd.UserId).Update(&user) + return err }) } @@ -479,10 +473,7 @@ func SetUserHelpFlag(cmd *m.SetUserHelpFlagCommand) error { Updated: time.Now(), } - if _, err := sess.Id(cmd.UserId).Cols("help_flags1").Update(&user); err != nil { - return err - } - - return nil + _, err := sess.Id(cmd.UserId).Cols("help_flags1").Update(&user) + return err }) } diff --git a/pkg/tsdb/cloudwatch/metric_find_query.go b/pkg/tsdb/cloudwatch/metric_find_query.go index 23b69f243fa..8864819271e 100644 --- a/pkg/tsdb/cloudwatch/metric_find_query.go +++ b/pkg/tsdb/cloudwatch/metric_find_query.go @@ -566,11 +566,7 @@ func getAllMetrics(cwData *DatasourceInfo) (cloudwatch.ListMetricsOutput, error) } return !lastPage }) - if err != nil { - return resp, err - } - - return resp, nil + return resp, err } var metricsCacheLock sync.Mutex From f61e69ce753cf79404dede251786ec161bd4dc38 Mon Sep 17 00:00:00 2001 From: Karsten Weiss Date: Mon, 16 Apr 2018 20:12:59 +0200 Subject: [PATCH 03/14] Simplify comparison to bool constant (gosimple) This fixes: build.go:553:6: should omit comparison to bool constant, can be simplified to !strings.Contains(path, ".sha256") (S1002) pkg/cmd/grafana-cli/commands/ls_command.go:27:5: should omit comparison to bool constant, can be simplified to !pluginDirInfo.IsDir() (S1002) pkg/components/dynmap/dynmap_test.go:24:5: should omit comparison to bool constant, can be simplified to !value (S1002) pkg/components/dynmap/dynmap_test.go:122:14: should omit comparison to bool constant, can be simplified to b (S1002) pkg/components/dynmap/dynmap_test.go:125:14: should omit comparison to bool constant, can be simplified to !b (S1002) pkg/components/dynmap/dynmap_test.go:128:14: should omit comparison to bool constant, can be simplified to !b (S1002) pkg/models/org_user.go:51:5: should omit comparison to bool constant, can be simplified to !(*r).IsValid() (S1002) pkg/plugins/datasource/wrapper/datasource_plugin_wrapper_test.go:77:12: should omit comparison to bool constant, can be simplified to !haveBool (S1002) pkg/services/alerting/conditions/evaluator.go:23:9: should omit comparison to bool constant, can be simplified to !reducedValue.Valid (S1002) pkg/services/alerting/conditions/evaluator.go:48:5: should omit comparison to bool constant, can be simplified to !reducedValue.Valid (S1002) pkg/services/alerting/conditions/evaluator.go:91:5: should omit comparison to bool constant, can be simplified to !reducedValue.Valid (S1002) pkg/services/alerting/conditions/query.go:56:6: should omit comparison to bool constant, can be simplified to !reducedValue.Valid (S1002) pkg/services/alerting/extractor.go:107:20: should omit comparison to bool constant, can be simplified to !enabled.MustBool() (S1002) pkg/services/alerting/notifiers/telegram.go:222:41: should omit comparison to bool constant, can be simplified to this.UploadImage (S1002) pkg/services/sqlstore/apikey.go:58:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/apikey.go:72:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/dashboard.go:66:33: should omit comparison to bool constant, can be simplified to !cmd.Overwrite (S1002) pkg/services/sqlstore/dashboard.go:175:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/dashboard.go:311:13: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/dashboard.go:444:12: should omit comparison to bool constant, can be simplified to !exists (S1002) pkg/services/sqlstore/dashboard.go:472:12: should omit comparison to bool constant, can be simplified to !exists (S1002) pkg/services/sqlstore/dashboard.go:554:32: should omit comparison to bool constant, can be simplified to !cmd.Overwrite (S1002) pkg/services/sqlstore/dashboard_snapshot.go:83:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/plugin_setting.go:39:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/quota.go:34:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/quota.go:111:6: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/quota.go:136:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/quota.go:213:6: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/temp_user.go:129:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/user.go:157:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/user.go:182:5: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/user.go:191:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/user.go:212:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/services/sqlstore/user.go:307:12: should omit comparison to bool constant, can be simplified to !has (S1002) pkg/social/generic_oauth.go:185:5: should omit comparison to bool constant, can be simplified to !s.extractToken(&data, token) (S1002) pkg/tsdb/mssql/mssql.go:148:39: should omit comparison to bool constant, can be simplified to ok (S1002) pkg/tsdb/mssql/mssql.go:212:6: should omit comparison to bool constant, can be simplified to !query.Model.Get("fillNull").MustBool(false) (S1002) pkg/tsdb/mssql/mssql.go:247:56: should omit comparison to bool constant, can be simplified to ok (S1002) pkg/tsdb/mssql/mssql.go:274:7: should omit comparison to bool constant, can be simplified to !exist (S1002) pkg/tsdb/mssql/mssql.go:282:8: should omit comparison to bool constant, can be simplified to !exist (S1002) pkg/tsdb/mysql/mysql.go:221:6: should omit comparison to bool constant, can be simplified to !query.Model.Get("fillNull").MustBool(false) (S1002) pkg/tsdb/mysql/mysql.go:256:56: should omit comparison to bool constant, can be simplified to ok (S1002) pkg/tsdb/mysql/mysql.go:283:7: should omit comparison to bool constant, can be simplified to !exist (S1002) pkg/tsdb/mysql/mysql.go:291:8: should omit comparison to bool constant, can be simplified to !exist (S1002) pkg/tsdb/postgres/postgres.go:134:39: should omit comparison to bool constant, can be simplified to ok (S1002) pkg/tsdb/postgres/postgres.go:201:6: should omit comparison to bool constant, can be simplified to !query.Model.Get("fillNull").MustBool(false) (S1002) pkg/tsdb/postgres/postgres.go:236:56: should omit comparison to bool constant, can be simplified to ok (S1002) pkg/tsdb/postgres/postgres.go:263:7: should omit comparison to bool constant, can be simplified to !exist (S1002) pkg/tsdb/postgres/postgres.go:271:8: should omit comparison to bool constant, can be simplified to !exist (S1002) --- build.go | 2 +- pkg/cmd/grafana-cli/commands/ls_command.go | 2 +- pkg/components/dynmap/dynmap_test.go | 8 ++++---- pkg/models/org_user.go | 2 +- .../wrapper/datasource_plugin_wrapper_test.go | 2 +- pkg/services/alerting/conditions/evaluator.go | 6 +++--- pkg/services/alerting/conditions/query.go | 2 +- pkg/services/alerting/extractor.go | 2 +- pkg/services/alerting/notifiers/telegram.go | 2 +- pkg/services/sqlstore/apikey.go | 4 ++-- pkg/services/sqlstore/dashboard.go | 12 ++++++------ pkg/services/sqlstore/dashboard_snapshot.go | 2 +- pkg/services/sqlstore/plugin_setting.go | 2 +- pkg/services/sqlstore/quota.go | 8 ++++---- pkg/services/sqlstore/temp_user.go | 2 +- pkg/services/sqlstore/user.go | 10 +++++----- pkg/social/generic_oauth.go | 2 +- pkg/tsdb/mssql/mssql.go | 10 +++++----- pkg/tsdb/mysql/mysql.go | 8 ++++---- pkg/tsdb/postgres/postgres.go | 10 +++++----- 20 files changed, 49 insertions(+), 49 deletions(-) diff --git a/build.go b/build.go index c38c452f61f..2497017a873 100644 --- a/build.go +++ b/build.go @@ -550,7 +550,7 @@ func shaFilesInDist() { return nil } - if strings.Contains(path, ".sha256") == false { + if !strings.Contains(path, ".sha256") { err := shaFile(path) if err != nil { log.Printf("Failed to create sha file. error: %v\n", err) diff --git a/pkg/cmd/grafana-cli/commands/ls_command.go b/pkg/cmd/grafana-cli/commands/ls_command.go index 7dcecb9d725..30745ce3172 100644 --- a/pkg/cmd/grafana-cli/commands/ls_command.go +++ b/pkg/cmd/grafana-cli/commands/ls_command.go @@ -24,7 +24,7 @@ var validateLsCommand = func(pluginDir string) error { return fmt.Errorf("error: %s", err) } - if pluginDirInfo.IsDir() == false { + if !pluginDirInfo.IsDir() { return errors.New("plugin path is not a directory") } diff --git a/pkg/components/dynmap/dynmap_test.go b/pkg/components/dynmap/dynmap_test.go index 1dacee163f1..fa5f73c3719 100644 --- a/pkg/components/dynmap/dynmap_test.go +++ b/pkg/components/dynmap/dynmap_test.go @@ -21,7 +21,7 @@ func NewAssert(t *testing.T) *Assert { } func (assert *Assert) True(value bool, message string) { - if value == false { + if !value { log.Panicln("Assert: ", message) } } @@ -119,13 +119,13 @@ func TestFirst(t *testing.T) { assert.True(s == "" && err != nil, "nonexistent string fail") b, err := j.GetBoolean("true") - assert.True(b == true && err == nil, "bool true test") + assert.True(b && err == nil, "bool true test") b, err = j.GetBoolean("false") - assert.True(b == false && err == nil, "bool false test") + assert.True(!b && err == nil, "bool false test") b, err = j.GetBoolean("invalid_field") - assert.True(b == false && err != nil, "bool invalid test") + assert.True(!b && err != nil, "bool invalid test") list, err := j.GetValueArray("list") assert.True(list != nil && err == nil, "list should be an array") diff --git a/pkg/models/org_user.go b/pkg/models/org_user.go index ca32cc50060..98cc4cb3997 100644 --- a/pkg/models/org_user.go +++ b/pkg/models/org_user.go @@ -48,7 +48,7 @@ func (r *RoleType) UnmarshalJSON(data []byte) error { *r = RoleType(str) - if (*r).IsValid() == false { + if !(*r).IsValid() { if (*r) != "" { return errors.New(fmt.Sprintf("JSON validation error: invalid role value: %s", *r)) } diff --git a/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper_test.go b/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper_test.go index 834e8238e3a..7ada6fb6b03 100644 --- a/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper_test.go +++ b/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper_test.go @@ -74,7 +74,7 @@ func TestMappingRowValue(t *testing.T) { boolRowValue, _ := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_BOOL, BoolValue: true}) haveBool, ok := boolRowValue.(bool) - if !ok || haveBool != true { + if !ok || !haveBool { t.Fatalf("Expected true, was %v", haveBool) } diff --git a/pkg/services/alerting/conditions/evaluator.go b/pkg/services/alerting/conditions/evaluator.go index 1b8fb952f65..dfc058940cf 100644 --- a/pkg/services/alerting/conditions/evaluator.go +++ b/pkg/services/alerting/conditions/evaluator.go @@ -20,7 +20,7 @@ type AlertEvaluator interface { type NoValueEvaluator struct{} func (e *NoValueEvaluator) Eval(reducedValue null.Float) bool { - return reducedValue.Valid == false + return !reducedValue.Valid } type ThresholdEvaluator struct { @@ -45,7 +45,7 @@ func newThresholdEvaluator(typ string, model *simplejson.Json) (*ThresholdEvalua } func (e *ThresholdEvaluator) Eval(reducedValue null.Float) bool { - if reducedValue.Valid == false { + if !reducedValue.Valid { return false } @@ -88,7 +88,7 @@ func newRangedEvaluator(typ string, model *simplejson.Json) (*RangedEvaluator, e } func (e *RangedEvaluator) Eval(reducedValue null.Float) bool { - if reducedValue.Valid == false { + if !reducedValue.Valid { return false } diff --git a/pkg/services/alerting/conditions/query.go b/pkg/services/alerting/conditions/query.go index d499c5e8532..7d1a276c42e 100644 --- a/pkg/services/alerting/conditions/query.go +++ b/pkg/services/alerting/conditions/query.go @@ -53,7 +53,7 @@ func (c *QueryCondition) Eval(context *alerting.EvalContext) (*alerting.Conditio reducedValue := c.Reducer.Reduce(series) evalMatch := c.Evaluator.Eval(reducedValue) - if reducedValue.Valid == false { + if !reducedValue.Valid { emptySerieCount++ } diff --git a/pkg/services/alerting/extractor.go b/pkg/services/alerting/extractor.go index edd872b8fce..e1c1bfacb2e 100644 --- a/pkg/services/alerting/extractor.go +++ b/pkg/services/alerting/extractor.go @@ -104,7 +104,7 @@ func (e *DashAlertExtractor) getAlertFromPanels(jsonWithPanels *simplejson.Json, // backward compatibility check, can be removed later enabled, hasEnabled := jsonAlert.CheckGet("enabled") - if hasEnabled && enabled.MustBool() == false { + if hasEnabled && !enabled.MustBool() { continue } diff --git a/pkg/services/alerting/notifiers/telegram.go b/pkg/services/alerting/notifiers/telegram.go index 5cbdad60906..0b8efe808d5 100644 --- a/pkg/services/alerting/notifiers/telegram.go +++ b/pkg/services/alerting/notifiers/telegram.go @@ -219,7 +219,7 @@ func appendIfPossible(message string, extra string, sizeLimit int) string { func (this *TelegramNotifier) Notify(evalContext *alerting.EvalContext) error { var cmd *m.SendWebhookSync - if evalContext.ImagePublicUrl == "" && this.UploadImage == true { + if evalContext.ImagePublicUrl == "" && this.UploadImage { cmd = this.buildMessage(evalContext, true) } else { cmd = this.buildMessage(evalContext, false) diff --git a/pkg/services/sqlstore/apikey.go b/pkg/services/sqlstore/apikey.go index 0532f636625..9d41b5c809e 100644 --- a/pkg/services/sqlstore/apikey.go +++ b/pkg/services/sqlstore/apikey.go @@ -55,7 +55,7 @@ func GetApiKeyById(query *m.GetApiKeyByIdQuery) error { if err != nil { return err - } else if has == false { + } else if !has { return m.ErrInvalidApiKey } @@ -69,7 +69,7 @@ func GetApiKeyByName(query *m.GetApiKeyByNameQuery) error { if err != nil { return err - } else if has == false { + } else if !has { return m.ErrInvalidApiKey } diff --git a/pkg/services/sqlstore/dashboard.go b/pkg/services/sqlstore/dashboard.go index 8d90d348a94..c0e8ead6945 100644 --- a/pkg/services/sqlstore/dashboard.go +++ b/pkg/services/sqlstore/dashboard.go @@ -63,7 +63,7 @@ func saveDashboard(sess *DBSession, cmd *m.SaveDashboardCommand) error { } // do not allow plugin dashboard updates without overwrite flag - if existing.PluginId != "" && cmd.Overwrite == false { + if existing.PluginId != "" && !cmd.Overwrite { return m.UpdatePluginDashboardError{PluginId: existing.PluginId} } } @@ -172,7 +172,7 @@ func GetDashboard(query *m.GetDashboardQuery) error { if err != nil { return err - } else if has == false { + } else if !has { return m.ErrDashboardNotFound } @@ -308,7 +308,7 @@ func DeleteDashboard(cmd *m.DeleteDashboardCommand) error { has, err := sess.Get(&dashboard) if err != nil { return err - } else if has == false { + } else if !has { return m.ErrDashboardNotFound } @@ -441,7 +441,7 @@ func GetDashboardSlugById(query *m.GetDashboardSlugByIdQuery) error { if err != nil { return err - } else if exists == false { + } else if !exists { return m.ErrDashboardNotFound } @@ -469,7 +469,7 @@ func GetDashboardUIDById(query *m.GetDashboardRefByIdQuery) error { if err != nil { return err - } else if exists == false { + } else if !exists { return m.ErrDashboardNotFound } @@ -551,7 +551,7 @@ func getExistingDashboardByIdOrUidForUpdate(sess *DBSession, cmd *m.ValidateDash } // do not allow plugin dashboard updates without overwrite flag - if existing.PluginId != "" && cmd.Overwrite == false { + if existing.PluginId != "" && !cmd.Overwrite { return m.UpdatePluginDashboardError{PluginId: existing.PluginId} } diff --git a/pkg/services/sqlstore/dashboard_snapshot.go b/pkg/services/sqlstore/dashboard_snapshot.go index 9e82bbb2c83..2e2ea8a4783 100644 --- a/pkg/services/sqlstore/dashboard_snapshot.go +++ b/pkg/services/sqlstore/dashboard_snapshot.go @@ -80,7 +80,7 @@ func GetDashboardSnapshot(query *m.GetDashboardSnapshotQuery) error { if err != nil { return err - } else if has == false { + } else if !has { return m.ErrDashboardSnapshotNotFound } diff --git a/pkg/services/sqlstore/plugin_setting.go b/pkg/services/sqlstore/plugin_setting.go index 172995872eb..312a3bda523 100644 --- a/pkg/services/sqlstore/plugin_setting.go +++ b/pkg/services/sqlstore/plugin_setting.go @@ -36,7 +36,7 @@ func GetPluginSettingById(query *m.GetPluginSettingByIdQuery) error { has, err := x.Get(&pluginSetting) if err != nil { return err - } else if has == false { + } else if !has { return m.ErrPluginSettingNotFound } query.Result = &pluginSetting diff --git a/pkg/services/sqlstore/quota.go b/pkg/services/sqlstore/quota.go index 3db3fc2657e..539555ddc50 100644 --- a/pkg/services/sqlstore/quota.go +++ b/pkg/services/sqlstore/quota.go @@ -31,7 +31,7 @@ func GetOrgQuotaByTarget(query *m.GetOrgQuotaByTargetQuery) error { has, err := x.Get("a) if err != nil { return err - } else if has == false { + } else if !has { quota.Limit = query.Default } @@ -108,7 +108,7 @@ func UpdateOrgQuota(cmd *m.UpdateOrgQuotaCmd) error { return err } quota.Limit = cmd.Limit - if has == false { + if !has { quota.Created = time.Now() //No quota in the DB for this target, so create a new one. if _, err := sess.Insert("a); err != nil { @@ -133,7 +133,7 @@ func GetUserQuotaByTarget(query *m.GetUserQuotaByTargetQuery) error { has, err := x.Get("a) if err != nil { return err - } else if has == false { + } else if !has { quota.Limit = query.Default } @@ -210,7 +210,7 @@ func UpdateUserQuota(cmd *m.UpdateUserQuotaCmd) error { return err } quota.Limit = cmd.Limit - if has == false { + if !has { quota.Created = time.Now() //No quota in the DB for this target, so create a new one. if _, err := sess.Insert("a); err != nil { diff --git a/pkg/services/sqlstore/temp_user.go b/pkg/services/sqlstore/temp_user.go index 43e1f027057..e93ba2fd641 100644 --- a/pkg/services/sqlstore/temp_user.go +++ b/pkg/services/sqlstore/temp_user.go @@ -126,7 +126,7 @@ func GetTempUserByCode(query *m.GetTempUserByCodeQuery) error { if err != nil { return err - } else if has == false { + } else if !has { return m.ErrTempUserNotFound } diff --git a/pkg/services/sqlstore/user.go b/pkg/services/sqlstore/user.go index bf64bc65602..6d8bd0c5279 100644 --- a/pkg/services/sqlstore/user.go +++ b/pkg/services/sqlstore/user.go @@ -154,7 +154,7 @@ func GetUserById(query *m.GetUserByIdQuery) error { if err != nil { return err - } else if has == false { + } else if !has { return m.ErrUserNotFound } @@ -179,7 +179,7 @@ func GetUserByLogin(query *m.GetUserByLoginQuery) error { return err } - if has == false && strings.Contains(query.LoginOrEmail, "@") { + if !has && strings.Contains(query.LoginOrEmail, "@") { // If the user wasn't found, and it contains an "@" fallback to finding the // user by email. user = &m.User{Email: query.LoginOrEmail} @@ -188,7 +188,7 @@ func GetUserByLogin(query *m.GetUserByLoginQuery) error { if err != nil { return err - } else if has == false { + } else if !has { return m.ErrUserNotFound } @@ -209,7 +209,7 @@ func GetUserByEmail(query *m.GetUserByEmailQuery) error { if err != nil { return err - } else if has == false { + } else if !has { return m.ErrUserNotFound } @@ -304,7 +304,7 @@ func GetUserProfile(query *m.GetUserProfileQuery) error { if err != nil { return err - } else if has == false { + } else if !has { return m.ErrUserNotFound } diff --git a/pkg/social/generic_oauth.go b/pkg/social/generic_oauth.go index b92d64ad9fc..8c02076096d 100644 --- a/pkg/social/generic_oauth.go +++ b/pkg/social/generic_oauth.go @@ -182,7 +182,7 @@ func (s *SocialGenericOAuth) UserInfo(client *http.Client, token *oauth2.Token) var data UserInfoJson var err error - if s.extractToken(&data, token) != true { + if !s.extractToken(&data, token) { response, err := HttpGet(client, s.apiUrl) if err != nil { return nil, fmt.Errorf("Error getting user info: %s", err) diff --git a/pkg/tsdb/mssql/mssql.go b/pkg/tsdb/mssql/mssql.go index 3a440859f9f..a598b7239ed 100644 --- a/pkg/tsdb/mssql/mssql.go +++ b/pkg/tsdb/mssql/mssql.go @@ -145,7 +145,7 @@ func (e MssqlQueryEndpoint) getTypedRowData(types []*sql.ColumnType, rows *core. // convert types not handled by denisenkom/go-mssqldb // unhandled types are returned as []byte for i := 0; i < len(types); i++ { - if value, ok := values[i].([]byte); ok == true { + if value, ok := values[i].([]byte); ok { switch types[i].DatabaseTypeName() { case "MONEY", "SMALLMONEY", "DECIMAL": if v, err := strconv.ParseFloat(string(value), 64); err == nil { @@ -209,7 +209,7 @@ func (e MssqlQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core. fillValue := null.Float{} if fillMissing { fillInterval = query.Model.Get("fillInterval").MustFloat64() * 1000 - if query.Model.Get("fillNull").MustBool(false) == false { + if !query.Model.Get("fillNull").MustBool(false) { fillValue.Float64 = query.Model.Get("fillValue").MustFloat64() fillValue.Valid = true } @@ -244,7 +244,7 @@ func (e MssqlQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core. } if metricIndex >= 0 { - if columnValue, ok := values[metricIndex].(string); ok == true { + if columnValue, ok := values[metricIndex].(string); ok { metric = columnValue } else { return fmt.Errorf("Column metric must be of type CHAR, VARCHAR, NCHAR or NVARCHAR. metric column name: %s type: %s but datatype is %T", columnNames[metricIndex], columnTypes[metricIndex].DatabaseTypeName(), values[metricIndex]) @@ -271,7 +271,7 @@ func (e MssqlQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core. } series, exist := pointsBySeries[metric] - if exist == false { + if !exist { series = &tsdb.TimeSeries{Name: metric} pointsBySeries[metric] = series seriesByQueryOrder.PushBack(metric) @@ -279,7 +279,7 @@ func (e MssqlQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core. if fillMissing { var intervalStart float64 - if exist == false { + if !exist { intervalStart = float64(tsdbQuery.TimeRange.MustGetFrom().UnixNano() / 1e6) } else { intervalStart = series.Points[len(series.Points)-1][1].Float64 + fillInterval diff --git a/pkg/tsdb/mysql/mysql.go b/pkg/tsdb/mysql/mysql.go index 83027d4b210..4f5cd1b0784 100644 --- a/pkg/tsdb/mysql/mysql.go +++ b/pkg/tsdb/mysql/mysql.go @@ -218,7 +218,7 @@ func (e MysqlQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core. fillValue := null.Float{} if fillMissing { fillInterval = query.Model.Get("fillInterval").MustFloat64() * 1000 - if query.Model.Get("fillNull").MustBool(false) == false { + if !query.Model.Get("fillNull").MustBool(false) { fillValue.Float64 = query.Model.Get("fillValue").MustFloat64() fillValue.Valid = true } @@ -253,7 +253,7 @@ func (e MysqlQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core. } if metricIndex >= 0 { - if columnValue, ok := values[metricIndex].(string); ok == true { + if columnValue, ok := values[metricIndex].(string); ok { metric = columnValue } else { return fmt.Errorf("Column metric must be of type char,varchar or text, got: %T %v", values[metricIndex], values[metricIndex]) @@ -280,7 +280,7 @@ func (e MysqlQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core. } series, exist := pointsBySeries[metric] - if exist == false { + if !exist { series = &tsdb.TimeSeries{Name: metric} pointsBySeries[metric] = series seriesByQueryOrder.PushBack(metric) @@ -288,7 +288,7 @@ func (e MysqlQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core. if fillMissing { var intervalStart float64 - if exist == false { + if !exist { intervalStart = float64(tsdbQuery.TimeRange.MustGetFrom().UnixNano() / 1e6) } else { intervalStart = series.Points[len(series.Points)-1][1].Float64 + fillInterval diff --git a/pkg/tsdb/postgres/postgres.go b/pkg/tsdb/postgres/postgres.go index e17cc783f38..72d50b32d04 100644 --- a/pkg/tsdb/postgres/postgres.go +++ b/pkg/tsdb/postgres/postgres.go @@ -131,7 +131,7 @@ func (e PostgresQueryEndpoint) getTypedRowData(rows *core.Rows) (tsdb.RowValues, // convert types not handled by lib/pq // unhandled types are returned as []byte for i := 0; i < len(types); i++ { - if value, ok := values[i].([]byte); ok == true { + if value, ok := values[i].([]byte); ok { switch types[i].DatabaseTypeName() { case "NUMERIC": if v, err := strconv.ParseFloat(string(value), 64); err == nil { @@ -198,7 +198,7 @@ func (e PostgresQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *co fillValue := null.Float{} if fillMissing { fillInterval = query.Model.Get("fillInterval").MustFloat64() * 1000 - if query.Model.Get("fillNull").MustBool(false) == false { + if !query.Model.Get("fillNull").MustBool(false) { fillValue.Float64 = query.Model.Get("fillValue").MustFloat64() fillValue.Valid = true } @@ -233,7 +233,7 @@ func (e PostgresQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *co } if metricIndex >= 0 { - if columnValue, ok := values[metricIndex].(string); ok == true { + if columnValue, ok := values[metricIndex].(string); ok { metric = columnValue } else { return fmt.Errorf("Column metric must be of type char,varchar or text, got: %T %v", values[metricIndex], values[metricIndex]) @@ -260,7 +260,7 @@ func (e PostgresQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *co } series, exist := pointsBySeries[metric] - if exist == false { + if !exist { series = &tsdb.TimeSeries{Name: metric} pointsBySeries[metric] = series seriesByQueryOrder.PushBack(metric) @@ -268,7 +268,7 @@ func (e PostgresQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *co if fillMissing { var intervalStart float64 - if exist == false { + if !exist { intervalStart = float64(tsdbQuery.TimeRange.MustGetFrom().UnixNano() / 1e6) } else { intervalStart = series.Points[len(series.Points)-1][1].Float64 + fillInterval From da5654ad04e45316b36ec7ce360c8e34a965b4a0 Mon Sep 17 00:00:00 2001 From: Karsten Weiss Date: Mon, 16 Apr 2018 20:17:04 +0200 Subject: [PATCH 04/14] Simplify if expression (gosimple) pkg/util/shortid_generator.go:20:2: should use 'return ' instead of 'if { return }; return ' (S1008) --- pkg/util/shortid_generator.go | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/pkg/util/shortid_generator.go b/pkg/util/shortid_generator.go index d87b6f70fe6..f900cb8275e 100644 --- a/pkg/util/shortid_generator.go +++ b/pkg/util/shortid_generator.go @@ -17,11 +17,7 @@ func init() { // IsValidShortUid checks if short unique identifier contains valid characters func IsValidShortUid(uid string) bool { - if !validUidPattern(uid) { - return false - } - - return true + return validUidPattern(uid) } // GenerateShortUid generates a short unique identifier. From cb3b9f8b66f38ff1aa0763d031b9b1d9108942f7 Mon Sep 17 00:00:00 2001 From: Karsten Weiss Date: Mon, 16 Apr 2018 20:19:19 +0200 Subject: [PATCH 05/14] Use raw strings to avoid double escapes (gosimple) This fixes: pkg/services/alerting/rule.go:58:21: should use raw string (`...`) with regexp.MustCompile to avoid having to escape twice (S1007\) pkg/services/alerting/rule.go:59:21: should use raw string (`...`) with regexp.MustCompile to avoid having to escape twice (S1007) --- pkg/services/alerting/rule.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/services/alerting/rule.go b/pkg/services/alerting/rule.go index bdf53798e34..027ff96d6c0 100644 --- a/pkg/services/alerting/rule.go +++ b/pkg/services/alerting/rule.go @@ -55,8 +55,8 @@ func (e ValidationError) Error() string { } var ( - ValueFormatRegex = regexp.MustCompile("^\\d+") - UnitFormatRegex = regexp.MustCompile("\\w{1}$") + ValueFormatRegex = regexp.MustCompile(`^\d+`) + UnitFormatRegex = regexp.MustCompile(`\w{1}$`) ) var unitMultiplier = map[string]int{ From 4d87cb03c543a7e808209de8cc3e8ade43ecfa64 Mon Sep 17 00:00:00 2001 From: Karsten Weiss Date: Mon, 16 Apr 2018 20:22:12 +0200 Subject: [PATCH 06/14] Simplify make() (gosimple) This fixes: pkg/api/http_server.go:142:89: should use make(map[string]func(*http.Server, *tls.Conn, http.Handler)) instead (S1019) pkg/services/alerting/scheduler.go:18:30: should use make(map[int64]*Job) instead (S1019) pkg/services/alerting/scheduler.go:26:31: should use make(map[int64]*Job) instead (S1019) --- pkg/api/http_server.go | 2 +- pkg/services/alerting/scheduler.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/api/http_server.go b/pkg/api/http_server.go index 387a543ca89..8e01e869329 100644 --- a/pkg/api/http_server.go +++ b/pkg/api/http_server.go @@ -139,7 +139,7 @@ func (hs *HTTPServer) listenAndServeTLS(certfile, keyfile string) error { } hs.httpSrv.TLSConfig = tlsCfg - hs.httpSrv.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0) + hs.httpSrv.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler)) return hs.httpSrv.ListenAndServeTLS(setting.CertFile, setting.KeyFile) } diff --git a/pkg/services/alerting/scheduler.go b/pkg/services/alerting/scheduler.go index b0a3f8303c4..b7555ae8d89 100644 --- a/pkg/services/alerting/scheduler.go +++ b/pkg/services/alerting/scheduler.go @@ -15,7 +15,7 @@ type SchedulerImpl struct { func NewScheduler() Scheduler { return &SchedulerImpl{ - jobs: make(map[int64]*Job, 0), + jobs: make(map[int64]*Job), log: log.New("alerting.scheduler"), } } @@ -23,7 +23,7 @@ func NewScheduler() Scheduler { func (s *SchedulerImpl) Update(rules []*Rule) { s.log.Debug("Scheduling update", "ruleCount", len(rules)) - jobs := make(map[int64]*Job, 0) + jobs := make(map[int64]*Job) for i, rule := range rules { var job *Job From 4d6386e97bb30138c270828b9f290ab5b2ac53a4 Mon Sep 17 00:00:00 2001 From: Karsten Weiss Date: Mon, 16 Apr 2018 20:25:48 +0200 Subject: [PATCH 07/14] Use fmt.Errorf() (gosimple) This fixes: pkg/cmd/grafana-cli/commands/install_command.go:36:11: should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...)) (S1028) pkg/models/org_user.go:53:11: should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...)) (S1028) pkg/services/notifications/mailer.go:138:16: should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...)) (S1028) --- pkg/cmd/grafana-cli/commands/install_command.go | 2 +- pkg/models/org_user.go | 2 +- pkg/services/notifications/mailer.go | 3 +-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/pkg/cmd/grafana-cli/commands/install_command.go b/pkg/cmd/grafana-cli/commands/install_command.go index 6f6849ccddf..9bdb73a5858 100644 --- a/pkg/cmd/grafana-cli/commands/install_command.go +++ b/pkg/cmd/grafana-cli/commands/install_command.go @@ -33,7 +33,7 @@ func validateInput(c CommandLine, pluginFolder string) error { fileInfo, err := os.Stat(pluginsDir) if err != nil { if err = os.MkdirAll(pluginsDir, os.ModePerm); err != nil { - return errors.New(fmt.Sprintf("pluginsDir (%s) is not a writable directory", pluginsDir)) + return fmt.Errorf("pluginsDir (%s) is not a writable directory", pluginsDir) } return nil } diff --git a/pkg/models/org_user.go b/pkg/models/org_user.go index 98cc4cb3997..9231d18cfd6 100644 --- a/pkg/models/org_user.go +++ b/pkg/models/org_user.go @@ -50,7 +50,7 @@ func (r *RoleType) UnmarshalJSON(data []byte) error { if !(*r).IsValid() { if (*r) != "" { - return errors.New(fmt.Sprintf("JSON validation error: invalid role value: %s", *r)) + return fmt.Errorf("JSON validation error: invalid role value: %s", *r) } *r = ROLE_VIEWER diff --git a/pkg/services/notifications/mailer.go b/pkg/services/notifications/mailer.go index 05c2e53c748..1bac5025244 100644 --- a/pkg/services/notifications/mailer.go +++ b/pkg/services/notifications/mailer.go @@ -7,7 +7,6 @@ package notifications import ( "bytes" "crypto/tls" - "errors" "fmt" "html/template" "net" @@ -135,7 +134,7 @@ func buildEmailMessage(cmd *m.SendEmailCommand) (*Message, error) { subjectText, hasSubject := subjectData["value"] if !hasSubject { - return nil, errors.New(fmt.Sprintf("Missing subject in Template %s", cmd.Template)) + return nil, fmt.Errorf("Missing subject in Template %s", cmd.Template) } subjectTmpl, err := template.New("subject").Parse(subjectText.(string)) From 5d95601720d2a742b94d88ca6c958d6a679810af Mon Sep 17 00:00:00 2001 From: Karsten Weiss Date: Mon, 16 Apr 2018 20:33:59 +0200 Subject: [PATCH 08/14] Merge variable declaration with assignment (gosimple) This fixes: pkg/cmd/grafana-cli/commands/upgrade_all_command.go:56:3: should merge variable declaration with assignment on next line (S1021) pkg/login/ldap.go:406:4: should merge variable declaration with assignment on next line (S1021) pkg/services/sqlstore/migrator/dialect.go:87:2: should merge variable declaration with assignment on next line (S1021) pkg/services/sqlstore/migrator/dialect.go:165:2: should merge variable declaration with assignment on next line (S1021) pkg/tsdb/cloudwatch/metric_find_query_test.go:185:2: should merge variable declaration with assignment on next line (S1021) --- pkg/cmd/grafana-cli/commands/upgrade_all_command.go | 3 +-- pkg/login/ldap.go | 3 +-- pkg/services/sqlstore/migrator/dialect.go | 6 ++---- pkg/tsdb/cloudwatch/metric_find_query_test.go | 5 +---- 4 files changed, 5 insertions(+), 12 deletions(-) diff --git a/pkg/cmd/grafana-cli/commands/upgrade_all_command.go b/pkg/cmd/grafana-cli/commands/upgrade_all_command.go index 636292cce11..e01df2dab60 100644 --- a/pkg/cmd/grafana-cli/commands/upgrade_all_command.go +++ b/pkg/cmd/grafana-cli/commands/upgrade_all_command.go @@ -53,8 +53,7 @@ func upgradeAllCommand(c CommandLine) error { for _, p := range pluginsToUpgrade { logger.Infof("Updating %v \n", p.Id) - var err error - err = s.RemoveInstalledPlugin(pluginsDir, p.Id) + err := s.RemoveInstalledPlugin(pluginsDir, p.Id) if err != nil { return err } diff --git a/pkg/login/ldap.go b/pkg/login/ldap.go index be3babac02e..9f2338d653c 100644 --- a/pkg/login/ldap.go +++ b/pkg/login/ldap.go @@ -403,8 +403,7 @@ func (a *ldapAuther) searchForUser(username string) (*LdapUserInfo, error) { // If we are using a POSIX LDAP schema it won't support memberOf, so we manually search the groups var groupSearchResult *ldap.SearchResult for _, groupSearchBase := range a.server.GroupSearchBaseDNs { - var filter_replace string - filter_replace = getLdapAttr(a.server.GroupSearchFilterUserAttribute, searchResult) + filter_replace := getLdapAttr(a.server.GroupSearchFilterUserAttribute, searchResult) if a.server.GroupSearchFilterUserAttribute == "" { filter_replace = getLdapAttr(a.server.Attr.Username, searchResult) } diff --git a/pkg/services/sqlstore/migrator/dialect.go b/pkg/services/sqlstore/migrator/dialect.go index 064b5981063..dadc7248844 100644 --- a/pkg/services/sqlstore/migrator/dialect.go +++ b/pkg/services/sqlstore/migrator/dialect.go @@ -84,8 +84,7 @@ func (db *BaseDialect) DateTimeFunc(value string) string { } func (b *BaseDialect) CreateTableSql(table *Table) string { - var sql string - sql = "CREATE TABLE IF NOT EXISTS " + sql := "CREATE TABLE IF NOT EXISTS " sql += b.dialect.Quote(table.Name) + " (\n" pkList := table.PrimaryKeys @@ -162,8 +161,7 @@ func (db *BaseDialect) RenameTable(oldName string, newName string) string { func (db *BaseDialect) DropIndexSql(tableName string, index *Index) string { quote := db.dialect.Quote - var name string - name = index.XName(tableName) + name := index.XName(tableName) return fmt.Sprintf("DROP INDEX %v ON %s", quote(name), quote(tableName)) } diff --git a/pkg/tsdb/cloudwatch/metric_find_query_test.go b/pkg/tsdb/cloudwatch/metric_find_query_test.go index bf87e7b7d41..e3903e8027e 100644 --- a/pkg/tsdb/cloudwatch/metric_find_query_test.go +++ b/pkg/tsdb/cloudwatch/metric_find_query_test.go @@ -181,10 +181,7 @@ func TestCloudWatchMetrics(t *testing.T) { } func TestParseMultiSelectValue(t *testing.T) { - - var values []string - - values = parseMultiSelectValue(" i-someInstance ") + values := parseMultiSelectValue(" i-someInstance ") assert.Equal(t, []string{"i-someInstance"}, values) values = parseMultiSelectValue("{i-05}") From de084e589175fd718c4c248e64a92a03e3445877 Mon Sep 17 00:00:00 2001 From: Karsten Weiss Date: Mon, 16 Apr 2018 20:40:19 +0200 Subject: [PATCH 09/14] Remove unnecessary fmt.Sprintf() calls (gosimple) This fixes: pkg/services/sqlstore/migrator/migrations.go:116:18: the argument is already a string, there's no need to use fmt.Sprintf (S1025) pkg/services/sqlstore/migrator/types.go:49:16: the argument is already a string, there's no need to use fmt.Sprintf (S1025) --- pkg/services/sqlstore/migrator/migrations.go | 3 +-- pkg/services/sqlstore/migrator/types.go | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/pkg/services/sqlstore/migrator/migrations.go b/pkg/services/sqlstore/migrator/migrations.go index 2fec8825fa4..5232e65d62b 100644 --- a/pkg/services/sqlstore/migrator/migrations.go +++ b/pkg/services/sqlstore/migrator/migrations.go @@ -1,7 +1,6 @@ package migrator import ( - "fmt" "strings" ) @@ -113,7 +112,7 @@ func NewDropIndexMigration(table Table, index *Index) *DropIndexMigration { func (m *DropIndexMigration) Sql(dialect Dialect) string { if m.index.Name == "" { - m.index.Name = fmt.Sprintf("%s", strings.Join(m.index.Cols, "_")) + m.index.Name = strings.Join(m.index.Cols, "_") } return dialect.DropIndexSql(m.tableName, m.index) } diff --git a/pkg/services/sqlstore/migrator/types.go b/pkg/services/sqlstore/migrator/types.go index d42eba0f58a..62ec74e7b9f 100644 --- a/pkg/services/sqlstore/migrator/types.go +++ b/pkg/services/sqlstore/migrator/types.go @@ -46,7 +46,7 @@ type Index struct { func (index *Index) XName(tableName string) string { if index.Name == "" { - index.Name = fmt.Sprintf("%s", strings.Join(index.Cols, "_")) + index.Name = strings.Join(index.Cols, "_") } if !strings.HasPrefix(index.Name, "UQE_") && From 25bb0b556961b161d2b6accfde93151aab855c75 Mon Sep 17 00:00:00 2001 From: Karsten Weiss Date: Mon, 16 Apr 2018 20:42:17 +0200 Subject: [PATCH 10/14] Remove unused return value assignment (gosimple) This fixes: pkg/tsdb/sql_engine.go:54:6: should write version := engineCache.versions[dsInfo.Id] instead of version, _ := engineCache.versions[dsInfo.Id] (S1005) --- pkg/tsdb/sql_engine.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/tsdb/sql_engine.go b/pkg/tsdb/sql_engine.go index 0f35cadf4d6..56ed2cd3cb6 100644 --- a/pkg/tsdb/sql_engine.go +++ b/pkg/tsdb/sql_engine.go @@ -51,7 +51,7 @@ func (e *DefaultSqlEngine) InitEngine(driverName string, dsInfo *models.DataSour defer engineCache.Unlock() if engine, present := engineCache.cache[dsInfo.Id]; present { - if version, _ := engineCache.versions[dsInfo.Id]; version == dsInfo.Version { + if version := engineCache.versions[dsInfo.Id]; version == dsInfo.Version { e.XormEngine = engine return nil } From ed46efa0811d39d706a90b4a24998305c45f4cd7 Mon Sep 17 00:00:00 2001 From: Karsten Weiss Date: Mon, 16 Apr 2018 20:45:59 +0200 Subject: [PATCH 11/14] Use sort.Strings() (gosimple) This fixes: pkg/tsdb/cloudwatch/metric_find_query.go:257:2: should use sort.Strings(...) instead of sort.Sort(sort.StringSlice(...)) (S1032) pkg/tsdb/cloudwatch/metric_find_query.go:286:2: should use sort.Strings(...) instead of sort.Sort(sort.StringSlice(...)) (S1032) pkg/tsdb/cloudwatch/metric_find_query.go:315:2: should use sort.Strings(...) instead of sort.Sort(sort.StringSlice(...)) (S1032) --- pkg/tsdb/cloudwatch/metric_find_query.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/tsdb/cloudwatch/metric_find_query.go b/pkg/tsdb/cloudwatch/metric_find_query.go index 8864819271e..d73516ca88f 100644 --- a/pkg/tsdb/cloudwatch/metric_find_query.go +++ b/pkg/tsdb/cloudwatch/metric_find_query.go @@ -254,7 +254,7 @@ func (e *CloudWatchExecutor) handleGetNamespaces(ctx context.Context, parameters keys = append(keys, strings.Split(customNamespaces, ",")...) } - sort.Sort(sort.StringSlice(keys)) + sort.Strings(keys) result := make([]suggestData, 0) for _, key := range keys { @@ -283,7 +283,7 @@ func (e *CloudWatchExecutor) handleGetMetrics(ctx context.Context, parameters *s return nil, errors.New("Unable to call AWS API") } } - sort.Sort(sort.StringSlice(namespaceMetrics)) + sort.Strings(namespaceMetrics) result := make([]suggestData, 0) for _, name := range namespaceMetrics { @@ -312,7 +312,7 @@ func (e *CloudWatchExecutor) handleGetDimensions(ctx context.Context, parameters return nil, errors.New("Unable to call AWS API") } } - sort.Sort(sort.StringSlice(dimensionValues)) + sort.Strings(dimensionValues) result := make([]suggestData, 0) for _, name := range dimensionValues { From b0217f5dd3f7fa74590793bf1f38fc79bc533a0d Mon Sep 17 00:00:00 2001 From: Mario Trangoni Date: Tue, 17 Apr 2018 20:45:46 +0200 Subject: [PATCH 12/14] codespell: exclude by words instead of files --- .circleci/config.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index fc04e69af6e..2399d0c19bf 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -9,9 +9,13 @@ jobs: - run: name: install codespell command: 'sudo pip install codespell' + - run: + # Important: all words have to be in lowercase, and separated by "\n". + name: exclude known exceptions + command: 'echo -e "unknwon" > words_to_ignore.txt' - run: name: check documentation spelling errors - command: 'codespell -x docs/sources/project/building_from_source.md docs/' + command: 'codespell -I ./words_to_ignore.txt docs/' test-frontend: docker: From e81330abf07dd8bbdda50c0661647209f03e255f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Tue, 17 Apr 2018 21:01:52 +0200 Subject: [PATCH 13/14] fix: sign in link should have target self to trigger full page reload, fixes #11626 --- public/app/core/components/sidemenu/sidemenu.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/app/core/components/sidemenu/sidemenu.html b/public/app/core/components/sidemenu/sidemenu.html index 9de61345cd0..3a4ce11333e 100644 --- a/public/app/core/components/sidemenu/sidemenu.html +++ b/public/app/core/components/sidemenu/sidemenu.html @@ -37,7 +37,7 @@ - +