Chore: Fix staticcheck issues (#28854)

* Chore: Fix issues reported by staticcheck

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

* Undo changes

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
This commit is contained in:
Arve Knudsen 2020-11-05 11:57:20 +01:00 committed by GitHub
parent 9b90ff2961
commit 7897c6b7d5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 53 additions and 55 deletions

View File

@ -509,7 +509,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_WhenGrafanaAdmin(t *testing.T) {
expected := `
{
"error": "Did not find a user",
"error": "did not find a user",
"message": "Refusing to sync grafana super admin \"ldap-daniel\" - it would be disabled"
}
`

View File

@ -35,12 +35,12 @@ type thresholdEvaluator struct {
func newThresholdEvaluator(typ string, model *simplejson.Json) (*thresholdEvaluator, error) {
params := model.Get("params").MustArray()
if len(params) == 0 || params[0] == nil {
return nil, fmt.Errorf("Evaluator '%v' is missing the threshold parameter", HumanThresholdType(typ))
return nil, fmt.Errorf("evaluator '%v' is missing the threshold parameter", HumanThresholdType(typ))
}
firstParam, ok := params[0].(json.Number)
if !ok {
return nil, fmt.Errorf("Evaluator has invalid parameter")
return nil, fmt.Errorf("evaluator has invalid parameter")
}
defaultEval := &thresholdEvaluator{Type: typ}
@ -113,7 +113,7 @@ func (e *rangedEvaluator) Eval(reducedValue null.Float) bool {
func NewAlertEvaluator(model *simplejson.Json) (AlertEvaluator, error) {
typ := model.Get("type").MustString()
if typ == "" {
return nil, fmt.Errorf("Evaluator missing type property")
return nil, fmt.Errorf("evaluator missing type property")
}
if inSlice(typ, defaultTypes) {
@ -128,7 +128,7 @@ func NewAlertEvaluator(model *simplejson.Json) (AlertEvaluator, error) {
return &noValueEvaluator{}, nil
}
return nil, fmt.Errorf("Evaluator invalid evaluator type: %s", typ)
return nil, fmt.Errorf("evaluator invalid evaluator type: %s", typ)
}
func inSlice(a string, list []string) bool {

View File

@ -113,7 +113,7 @@ func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange *
}
if err := bus.Dispatch(getDsInfo); err != nil {
return nil, fmt.Errorf("Could not find datasource %v", err)
return nil, fmt.Errorf("could not find datasource: %w", err)
}
req := c.getRequestForAlertRule(getDsInfo.Result, timeRange, context.IsDebug)
@ -159,7 +159,7 @@ func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange *
resp, err := c.HandleRequest(context.Ctx, getDsInfo.Result, req)
if err != nil {
if err == gocontext.DeadlineExceeded {
return nil, fmt.Errorf("Alert execution exceeded the timeout")
return nil, fmt.Errorf("alert execution exceeded the timeout")
}
return nil, fmt.Errorf("tsdb.HandleRequest() error %v", err)

View File

@ -2,7 +2,6 @@ package alerting
import (
"context"
"errors"
"fmt"
"time"
@ -281,7 +280,7 @@ func (n *notificationService) getNeededNotifiers(orgID int64, notificationUids [
func InitNotifier(model *models.AlertNotification) (Notifier, error) {
notifierPlugin, found := notifierFactories[model.Type]
if !found {
return nil, errors.New("Unsupported notification type")
return nil, fmt.Errorf("unsupported notification type %q", model.Type)
}
return notifierPlugin.Factory(model)

View File

@ -89,7 +89,7 @@ func createTestEvalContext(cmd *NotificationTestCommand) *EvalContext {
}
ctx.IsTestRun = true
ctx.Firing = true
ctx.Error = fmt.Errorf("This is only a test")
ctx.Error = fmt.Errorf("this is only a test")
ctx.EvalMatches = evalMatchesBasedOnState()
return ctx

View File

@ -45,7 +45,7 @@ func handleAlertTestCommand(cmd *AlertTestCommand) error {
}
}
return fmt.Errorf("Could not find alert with panel id %d", cmd.PanelID)
return fmt.Errorf("could not find alert with panel ID %d", cmd.PanelID)
}
func testAlertRule(rule *Rule) *EvalContext {

View File

@ -10,8 +10,8 @@ import (
)
var (
ErrGuardianPermissionExists = errors.New("Permission already exists")
ErrGuardianOverride = errors.New("You can only override a permission to be higher")
ErrGuardianPermissionExists = errors.New("permission already exists")
ErrGuardianOverride = errors.New("you can only override a permission to be higher")
)
// DashboardGuardian to be used for guard against operations without access on dashboard and acl

View File

@ -73,10 +73,10 @@ const UsersMaxRequest = 500
var (
// ErrInvalidCredentials is returned if username and password do not match
ErrInvalidCredentials = errors.New("Invalid Username or Password")
ErrInvalidCredentials = errors.New("invalid username or password")
// ErrCouldNotFindUser is returned when username hasn't been found (not username+password)
ErrCouldNotFindUser = errors.New("Can't find user in LDAP")
ErrCouldNotFindUser = errors.New("can't find user in LDAP")
)
// New creates the new LDAP connection

View File

@ -3,7 +3,7 @@ package login
import "errors"
var (
ErrInvalidCredentials = errors.New("Invalid Username or Password")
ErrUsersQuotaReached = errors.New("Users quota reached")
ErrGettingUserQuota = errors.New("Error getting user quota")
ErrInvalidCredentials = errors.New("invalid username or password")
ErrUsersQuotaReached = errors.New("users quota reached")
ErrGettingUserQuota = errors.New("error getting user quota")
)

View File

@ -27,10 +27,10 @@ var ErrInvalidCredentials = ldap.ErrInvalidCredentials
var ErrCouldNotFindUser = ldap.ErrCouldNotFindUser
// ErrNoLDAPServers is returned when there is no LDAP servers specified
var ErrNoLDAPServers = errors.New("No LDAP servers are configured")
var ErrNoLDAPServers = errors.New("no LDAP servers are configured")
// ErrDidNotFindUser if request for user is unsuccessful
var ErrDidNotFindUser = errors.New("Did not find a user")
var ErrDidNotFindUser = errors.New("did not find a user")
// ServerStatus holds the LDAP server status
type ServerStatus struct {

View File

@ -109,12 +109,12 @@ func (ng *AlertNG) LoadAlertCondition(dashboardID int64, panelID int64, conditio
blob, err := getDashboardQuery.Result.Data.MarshalJSON()
if err != nil {
return nil, errors.New("Failed to marshal dashboard JSON")
return nil, errors.New("failed to marshal dashboard JSON")
}
var dash minimalDashboard
err = json.Unmarshal(blob, &dash)
if err != nil {
return nil, errors.New("Failed to unmarshal dashboard JSON")
return nil, errors.New("failed to unmarshal dashboard JSON")
}
condition := Condition{}
@ -144,7 +144,7 @@ func (ng *AlertNG) LoadAlertCondition(dashboardID int64, panelID int64, conditio
}
if ds == nil {
return nil, errors.New("No datasource reference found")
return nil, errors.New("no datasource reference found")
}
if queryDatasource == "" {
@ -192,7 +192,7 @@ func (ng *AlertNG) LoadAlertCondition(dashboardID int64, panelID int64, conditio
func (c *Condition) Execute(ctx AlertExecCtx, fromStr, toStr string) (*ExecutionResults, error) {
result := ExecutionResults{}
if !c.IsValid() {
return nil, fmt.Errorf("Invalid conditions")
return nil, fmt.Errorf("invalid conditions")
}
request := &tsdb.TsdbQuery{
@ -212,7 +212,7 @@ func (c *Condition) Execute(ctx AlertExecCtx, fromStr, toStr string) (*Execution
conditionResult := resp.Results[c.RefID]
if conditionResult == nil {
err = fmt.Errorf("No GEL results")
err = fmt.Errorf("no GEL results")
result.Error = err
return &result, err
}
@ -234,24 +234,24 @@ func EvaluateExecutionResult(results *ExecutionResults) (Results, error) {
for _, f := range results.Results {
rowLen, err := f.RowLen()
if err != nil {
return nil, fmt.Errorf("Unable to get frame row length")
return nil, fmt.Errorf("unable to get frame row length")
}
if rowLen > 1 {
return nil, fmt.Errorf("Invalid frame %v: row length %v", f.Name, rowLen)
return nil, fmt.Errorf("invalid frame %v: row length %v", f.Name, rowLen)
}
if len(f.Fields) > 1 {
return nil, fmt.Errorf("Invalid frame %v: field length %v", f.Name, len(f.Fields))
return nil, fmt.Errorf("invalid frame %v: field length %v", f.Name, len(f.Fields))
}
if f.Fields[0].Type() != data.FieldTypeNullableFloat64 {
return nil, fmt.Errorf("Invalid frame %v: field type %v", f.Name, f.Fields[0].Type())
return nil, fmt.Errorf("invalid frame %v: field type %v", f.Name, f.Fields[0].Type())
}
labelsStr := f.Fields[0].Labels.String()
_, ok := labels[labelsStr]
if ok {
return nil, fmt.Errorf("Invalid frame %v: frames cannot uniquely be identified by its labels: %q", f.Name, labelsStr)
return nil, fmt.Errorf("invalid frame %v: frames cannot uniquely be identified by its labels: %q", f.Name, labelsStr)
}
labels[labelsStr] = true

View File

@ -105,7 +105,7 @@ func (ns *NotificationService) createDialer() (*gomail.Dialer, error) {
if ns.Cfg.Smtp.CertFile != "" {
cert, err := tls.LoadX509KeyPair(ns.Cfg.Smtp.CertFile, ns.Cfg.Smtp.KeyFile)
if err != nil {
return nil, fmt.Errorf("Could not load cert or key file. error: %v", err)
return nil, fmt.Errorf("could not load cert or key file: %w", err)
}
tlsconfig.Certificates = []tls.Certificate{cert}
}
@ -159,7 +159,7 @@ func (ns *NotificationService) buildEmailMessage(cmd *models.SendEmailCommand) (
subjectText, hasSubject := subjectData["value"]
if !hasSubject {
return nil, fmt.Errorf("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))

View File

@ -63,7 +63,7 @@ func (ns *NotificationService) Init() error {
}
if !util.IsEmail(ns.Cfg.Smtp.FromAddress) {
return errors.New("Invalid email address for SMTP from_address config")
return errors.New("invalid email address for SMTP from_address config")
}
if setting.EmailCodeValidMinutes == 0 {

View File

@ -20,7 +20,7 @@ import (
var (
// ErrFolderNameMissing is returned when folder name is missing.
ErrFolderNameMissing = errors.New("Folder name missing")
ErrFolderNameMissing = errors.New("folder name missing")
)
// FileReader is responsible for reading dashboards from disc and
@ -41,7 +41,7 @@ func NewDashboardFileReader(cfg *config, log log.Logger) (*FileReader, error) {
if !ok {
path, ok = cfg.Options["folder"].(string)
if !ok {
return nil, fmt.Errorf("Failed to load dashboards. path param is not a string")
return nil, fmt.Errorf("failed to load dashboards, path param is not a string")
}
log.Warn("[Deprecated] The folder property is deprecated. Please use path instead.")

View File

@ -314,7 +314,7 @@ func TestNotificationAsConfig(t *testing.T) {
cfgProvider := &configReader{log: log.New("test logger")}
_, err := cfgProvider.readConfig(unknownNotifier)
So(err, ShouldNotBeNil)
So(err.Error(), ShouldEqual, "Unsupported notification type")
So(err.Error(), ShouldEqual, `unsupported notification type "nonexisting"`)
})
Convey("Read incorrect properties", func() {

View File

@ -72,7 +72,7 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string,
resp, err := netClient.Do(req)
if err != nil {
rs.log.Error("Failed to send request to remote rendering service.", "error", err)
return nil, fmt.Errorf("Failed to send request to remote rendering service. %s", err)
return nil, fmt.Errorf("failed to send request to remote rendering service: %w", err)
}
// save response to file
@ -87,7 +87,8 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string,
// if we didn't get a 200 response, something went wrong.
if resp.StatusCode != http.StatusOK {
rs.log.Error("Remote rendering request failed", "error", resp.Status)
return nil, fmt.Errorf("Remote rendering request failed. %d: %s", resp.StatusCode, resp.Status)
return nil, fmt.Errorf("remote rendering request failed, status code: %d, status: %s", resp.StatusCode,
resp.Status)
}
out, err := os.Create(filePath)
@ -103,7 +104,7 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string,
return nil, ErrTimeout
}
rs.log.Error("Remote rendering request failed", "error", err)
return nil, fmt.Errorf("Remote rendering request failed. %s", err)
return nil, fmt.Errorf("remote rendering request failed: %w", err)
}
return &RenderResult{FilePath: filePath}, err

View File

@ -8,8 +8,8 @@ import (
"github.com/grafana/grafana/pkg/models"
)
var ErrTimeout = errors.New("Timeout error. You can set timeout in seconds with &timeout url parameter")
var ErrNoRenderer = errors.New("No renderer plugin found nor is an external render server configured")
var ErrTimeout = errors.New("timeout error - you can set timeout in seconds with &timeout url parameter")
var ErrNoRenderer = errors.New("no renderer plugin found nor is an external render server configured")
var ErrPhantomJSNotInstalled = errors.New("PhantomJS executable not found")
type Opts struct {

View File

@ -96,7 +96,7 @@ func (rs *RenderingService) renderViaPluginV2(ctx context.Context, renderKey str
return nil, err
}
if rsp.Error != "" {
return nil, fmt.Errorf("Rendering failed: %v", rsp.Error)
return nil, fmt.Errorf("rendering failed: %s", rsp.Error)
}
return &RenderResult{FilePath: pngPath}, err

View File

@ -286,7 +286,7 @@ func SetAlertState(cmd *models.SetAlertStateCommand) error {
if has, err := sess.ID(cmd.AlertId).Get(&alert); err != nil {
return err
} else if !has {
return fmt.Errorf("Could not find alert")
return fmt.Errorf("could not find alert")
}
if alert.State == models.AlertStatePaused {

View File

@ -390,7 +390,7 @@ func UpdateAlertNotification(cmd *models.UpdateAlertNotificationCommand) error {
}
if sameNameQuery.Result != nil && sameNameQuery.Result.Id != current.Id {
return fmt.Errorf("Alert notification name %s already exists", cmd.Name)
return fmt.Errorf("alert notification name %q already exists", cmd.Name)
}
// delete empty keys
@ -431,7 +431,7 @@ func UpdateAlertNotification(cmd *models.UpdateAlertNotificationCommand) error {
if affected, err := sess.ID(cmd.Id).Update(current); err != nil {
return err
} else if affected == 0 {
return fmt.Errorf("Could not update alert notification")
return fmt.Errorf("could not update alert notification")
}
cmd.Result = &current
@ -578,7 +578,7 @@ func GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCre
}
if !exist {
return errors.New("Should not happen")
return errors.New("should not happen")
}
cmd.Result = nj

View File

@ -15,7 +15,7 @@ import (
func validateTimeRange(item *annotations.Item) error {
if item.EpochEnd == 0 {
if item.Epoch == 0 {
return errors.New("Missing Time Range")
return errors.New("missing time range")
}
item.EpochEnd = item.Epoch
}
@ -78,7 +78,7 @@ func (r *SqlAnnotationRepo) Update(item *annotations.Item) error {
return err
}
if !isExist {
return errors.New("Annotation not found")
return errors.New("annotation not found")
}
existing.Updated = timeNow().UnixNano() / int64(time.Millisecond)

View File

@ -39,12 +39,10 @@ func DeleteOldLoginAttempts(cmd *models.DeleteOldLoginAttemptsCommand) error {
var maxId int64
sql := "SELECT max(id) as id FROM login_attempt WHERE created < ?"
result, err := sess.Query(sql, cmd.OlderThan.Unix())
if err != nil {
return err
}
// nolint: gosimple
if result == nil || len(result) == 0 || result[0] == nil {
if len(result) == 0 || result[0] == nil {
return nil
}

View File

@ -116,7 +116,7 @@ func (ss *SqlStore) ensureMainOrgAndAdminUser() error {
systemUserCountQuery := models.GetSystemUserCountStatsQuery{}
err := bus.DispatchCtx(ctx, &systemUserCountQuery)
if err != nil {
return fmt.Errorf("Could not determine if admin user exists: %v", err)
return fmt.Errorf("could not determine if admin user exists: %w", err)
}
if systemUserCountQuery.Result.Count > 0 {
@ -132,7 +132,7 @@ func (ss *SqlStore) ensureMainOrgAndAdminUser() error {
cmd.IsAdmin = true
if err := bus.DispatchCtx(ctx, &cmd); err != nil {
return fmt.Errorf("Failed to create admin user: %v", err)
return fmt.Errorf("failed to create admin user: %s", err)
}
ss.log.Info("Created default admin", "user", setting.AdminUser)
@ -226,7 +226,7 @@ func (ss *SqlStore) buildConnectionString() (string, error) {
cnnstr = fmt.Sprintf("file:%s?cache=%s&mode=rwc", ss.dbCfg.Path, ss.dbCfg.CacheMode)
cnnstr += ss.buildExtraConnectionString('&')
default:
return "", fmt.Errorf("Unknown database type: %s", ss.dbCfg.Type)
return "", fmt.Errorf("unknown database type: %s", ss.dbCfg.Type)
}
return cnnstr, nil

View File

@ -15,7 +15,7 @@ func makeCert(config DatabaseConfig) (*tls.Config, error) {
rootCertPool := x509.NewCertPool()
pem, err := ioutil.ReadFile(config.CaCertPath)
if err != nil {
return nil, fmt.Errorf("Could not read DB CA Cert path: %v", config.CaCertPath)
return nil, fmt.Errorf("could not read DB CA Cert path %q: %w", config.CaCertPath, err)
}
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
return nil, err