Commit 3d3a7cbb by Arve Knudsen Committed by GitHub

Chore: Fix staticcheck issues (#28860)

* 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>

* Chore: Fix issues reported by staticcheck

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

* Fix test

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

* Fix test

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
parent 7897c6b7
......@@ -111,7 +111,7 @@ func TestAdminApiEndpoint(t *testing.T) {
respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes())
So(err, ShouldBeNil)
So(respJSON.Get("message").MustString(), ShouldEqual, "User not found")
So(respJSON.Get("message").MustString(), ShouldEqual, "user not found")
So(userId, ShouldEqual, 42)
So(isDisabled, ShouldEqual, false)
......@@ -124,7 +124,7 @@ func TestAdminApiEndpoint(t *testing.T) {
respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes())
So(err, ShouldBeNil)
So(respJSON.Get("message").MustString(), ShouldEqual, "User not found")
So(respJSON.Get("message").MustString(), ShouldEqual, "user not found")
So(userId, ShouldEqual, 42)
So(isDisabled, ShouldEqual, true)
......@@ -175,7 +175,7 @@ func TestAdminApiEndpoint(t *testing.T) {
respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes())
So(err, ShouldBeNil)
So(respJSON.Get("message").MustString(), ShouldEqual, "User not found")
So(respJSON.Get("message").MustString(), ShouldEqual, "user not found")
So(userId, ShouldEqual, 42)
})
......@@ -252,7 +252,7 @@ func TestAdminApiEndpoint(t *testing.T) {
respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes())
So(err, ShouldBeNil)
So(respJSON.Get("message").MustString(), ShouldEqual, "Organization not found")
So(respJSON.Get("message").MustString(), ShouldEqual, "organization not found")
So(userLogin, ShouldEqual, TestLogin)
So(orgId, ShouldEqual, 1000)
......@@ -276,7 +276,7 @@ func TestAdminApiEndpoint(t *testing.T) {
respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes())
So(err, ShouldBeNil)
So(respJSON.Get("error").MustString(), ShouldEqual, "User already exists")
So(respJSON.Get("error").MustString(), ShouldEqual, "user already exists")
})
})
}
......
......@@ -57,7 +57,7 @@ func createExternalDashboardSnapshot(cmd models.CreateDashboardSnapshotCommand)
defer response.Body.Close()
if response.StatusCode != 200 {
return nil, fmt.Errorf("Create external snapshot response status code %d", response.StatusCode)
return nil, fmt.Errorf("create external snapshot response status code %d", response.StatusCode)
}
if err := json.NewDecoder(response.Body).Decode(&createSnapshotResponse); err != nil {
......@@ -196,7 +196,7 @@ func deleteExternalDashboardSnapshot(externalUrl string) error {
}
}
return fmt.Errorf("Unexpected response when deleting external snapshot. Status code: %d", response.StatusCode)
return fmt.Errorf("unexpected response when deleting external snapshot, status code: %d", response.StatusCode)
}
// GET /api/snapshots-delete/:deleteKey
......
......@@ -199,11 +199,11 @@ func (hs *HTTPServer) configureHttps() error {
}
if _, err := os.Stat(setting.CertFile); os.IsNotExist(err) {
return fmt.Errorf(`Cannot find SSL cert_file at %v`, setting.CertFile)
return fmt.Errorf(`cannot find SSL cert_file at %q`, setting.CertFile)
}
if _, err := os.Stat(setting.KeyFile); os.IsNotExist(err) {
return fmt.Errorf(`Cannot find SSL key_file at %v`, setting.KeyFile)
return fmt.Errorf(`cannot find SSL key_file at %q`, setting.KeyFile)
}
tlsCfg := &tls.Config{
......@@ -241,11 +241,11 @@ func (hs *HTTPServer) configureHttp2() error {
}
if _, err := os.Stat(setting.CertFile); os.IsNotExist(err) {
return fmt.Errorf(`Cannot find SSL cert_file at %v`, setting.CertFile)
return fmt.Errorf(`cannot find SSL cert_file at %q`, setting.CertFile)
}
if _, err := os.Stat(setting.KeyFile); os.IsNotExist(err) {
return fmt.Errorf(`Cannot find SSL key_file at %v`, setting.KeyFile)
return fmt.Errorf(`cannot find SSL key_file at %q`, setting.KeyFile)
}
tlsCfg := &tls.Config{
......
......@@ -21,7 +21,7 @@ var (
logger = log.New("LDAP.debug")
errOrganizationNotFound = func(orgId int64) error {
return fmt.Errorf("Unable to find organization with ID '%d'", orgId)
return fmt.Errorf("unable to find organization with ID '%d'", orgId)
}
)
......
......@@ -145,7 +145,7 @@ func TestGetUserFromLDAPApiEndpoint_OrgNotfound(t *testing.T) {
expected := `
{
"error": "Unable to find organization with ID '2'",
"error": "unable to find organization with ID '2'",
"message": "An organization was not found - Please verify your LDAP configuration"
}
`
......@@ -467,7 +467,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_WhenUserNotFound(t *testing.T) {
expected := `
{
"message": "User not found"
"message": "user not found"
}
`
......
......@@ -218,30 +218,30 @@ func (proxy *DataSourceProxy) getDirector() func(req *http.Request) {
func (proxy *DataSourceProxy) validateRequest() error {
if !checkWhiteList(proxy.ctx, proxy.targetUrl.Host) {
return errors.New("Target url is not a valid target")
return errors.New("target URL is not a valid target")
}
if proxy.ds.Type == models.DS_PROMETHEUS {
if proxy.ctx.Req.Request.Method == "DELETE" {
return errors.New("Deletes not allowed on proxied Prometheus datasource")
return errors.New("deletes not allowed on proxied Prometheus datasource")
}
if proxy.ctx.Req.Request.Method == "PUT" {
return errors.New("Puts not allowed on proxied Prometheus datasource")
return errors.New("puts not allowed on proxied Prometheus datasource")
}
if proxy.ctx.Req.Request.Method == "POST" && !(proxy.proxyPath == "api/v1/query" || proxy.proxyPath == "api/v1/query_range") {
return errors.New("Posts not allowed on proxied Prometheus datasource except on /query and /query_range")
return errors.New("posts not allowed on proxied Prometheus datasource except on /query and /query_range")
}
}
if proxy.ds.Type == models.DS_ES {
if proxy.ctx.Req.Request.Method == "DELETE" {
return errors.New("Deletes not allowed on proxied Elasticsearch datasource")
return errors.New("deletes not allowed on proxied Elasticsearch datasource")
}
if proxy.ctx.Req.Request.Method == "PUT" {
return errors.New("Puts not allowed on proxied Elasticsearch datasource")
return errors.New("puts not allowed on proxied Elasticsearch datasource")
}
if proxy.ctx.Req.Request.Method == "POST" && proxy.proxyPath != "_msearch" {
return errors.New("Posts not allowed on proxied Elasticsearch datasource except on /_msearch")
return errors.New("posts not allowed on proxied Elasticsearch datasource except on /_msearch")
}
}
......@@ -255,7 +255,7 @@ func (proxy *DataSourceProxy) validateRequest() error {
if route.ReqRole.IsValid() {
if !proxy.ctx.HasUserRole(route.ReqRole) {
return errors.New("Plugin proxy route access denied")
return errors.New("plugin proxy route access denied")
}
}
......
......@@ -40,7 +40,7 @@ func InterpolateURL(anURL *url.URL, route *plugins.AppPluginRoute, orgID int64,
if err == nil {
result, err = url.Parse(interpolatedResult)
if err != nil {
return nil, fmt.Errorf("Error parsing plugin route url %v", err)
return nil, fmt.Errorf("error parsing plugin route URL: %w", err)
}
}
}
......
......@@ -24,25 +24,25 @@ func (hs *HTTPServer) RenderToPng(c *models.ReqContext) {
width, err := strconv.Atoi(queryReader.Get("width", "800"))
if err != nil {
c.Handle(400, "Render parameters error", fmt.Errorf("Cannot parse width as int: %s", err))
c.Handle(400, "Render parameters error", fmt.Errorf("cannot parse width as int: %s", err))
return
}
height, err := strconv.Atoi(queryReader.Get("height", "400"))
if err != nil {
c.Handle(400, "Render parameters error", fmt.Errorf("Cannot parse height as int: %s", err))
c.Handle(400, "Render parameters error", fmt.Errorf("cannot parse height as int: %s", err))
return
}
timeout, err := strconv.Atoi(queryReader.Get("timeout", "60"))
if err != nil {
c.Handle(400, "Render parameters error", fmt.Errorf("Cannot parse timeout as int: %s", err))
c.Handle(400, "Render parameters error", fmt.Errorf("cannot parse timeout as int: %s", err))
return
}
scale, err := strconv.ParseFloat(queryReader.Get("scale", "1"), 64)
if err != nil {
c.Handle(400, "Render parameters error", fmt.Errorf("Cannot parse scale as float: %s", err))
c.Handle(400, "Render parameters error", fmt.Errorf("cannot parse scale as float: %s", err))
return
}
......
......@@ -30,7 +30,7 @@ func (pd *profilingDiagnostics) overrideWithEnv() error {
if enabledEnv != "" {
enabled, err := strconv.ParseBool(enabledEnv)
if err != nil {
return fmt.Errorf("Failed to parse %s environment variable as bool", profilingEnabledEnvName)
return fmt.Errorf("failed to parse %s environment variable as bool", profilingEnabledEnvName)
}
pd.enabled = enabled
}
......@@ -39,7 +39,7 @@ func (pd *profilingDiagnostics) overrideWithEnv() error {
if portEnv != "" {
port, parseErr := strconv.ParseUint(portEnv, 0, 64)
if parseErr != nil {
return fmt.Errorf("Failed to parse %s environment variable to unsigned integer", profilingPortEnvName)
return fmt.Errorf("failed to parse %s environment variable to unsigned integer", profilingPortEnvName)
}
pd.port = port
}
......@@ -64,7 +64,7 @@ func (td *tracingDiagnostics) overrideWithEnv() error {
if enabledEnv != "" {
enabled, err := strconv.ParseBool(enabledEnv)
if err != nil {
return fmt.Errorf("Failed to parse %s environment variable as bool", tracingEnabledEnvName)
return fmt.Errorf("failed to parse %s environment variable as bool", tracingEnabledEnvName)
}
td.enabled = enabled
}
......
......@@ -8,7 +8,7 @@ import (
"github.com/grafana/grafana/pkg/util"
)
var ErrInvalidApiKey = errors.New("Invalid Api Key")
var ErrInvalidApiKey = errors.New("invalid API key")
type KeyGenResult struct {
HashedKey string
......
......@@ -245,7 +245,7 @@ func (f *JSONFormatter) processItem(value interface{}, deltas []diff.Delta, posi
case map[string]interface{}:
// ok
default:
return errors.New("Type mismatch")
return errors.New("type mismatch")
}
o := value.(map[string]interface{})
......@@ -270,7 +270,7 @@ func (f *JSONFormatter) processItem(value interface{}, deltas []diff.Delta, posi
case []interface{}:
// ok
default:
return errors.New("Type mismatch")
return errors.New("type mismatch")
}
a := value.([]interface{})
......@@ -310,7 +310,7 @@ func (f *JSONFormatter) processItem(value interface{}, deltas []diff.Delta, posi
f.printRecursive(positionStr, matchedDelta.Value, ChangeDeleted)
default:
return errors.New("Unknown Delta type detected")
return errors.New("unknown Delta type detected")
}
}
} else {
......
......@@ -70,7 +70,7 @@ func NewImageUploader() (ImageUploader, error) {
url := webdavSec.Key("url").String()
if url == "" {
return nil, fmt.Errorf("Could not find url key for image.uploader.webdav")
return nil, fmt.Errorf("could not find URL key for image.uploader.webdav")
}
public_url := webdavSec.Key("public_url").String()
......@@ -153,5 +153,5 @@ func getRegionAndBucketFromUrl(url string) (*s3Info, error) {
return info, nil
}
return nil, fmt.Errorf("Could not find bucket setting for image.uploader.s3")
return nil, fmt.Errorf("could not find bucket setting for image.uploader.s3")
}
......@@ -79,7 +79,7 @@ func (u *WebdavUploader) Upload(ctx context.Context, pa string) (string, error)
if res.StatusCode != http.StatusCreated {
body, _ := ioutil.ReadAll(res.Body)
return "", fmt.Errorf("Failed to upload image. Returned statuscode %v body %s", res.StatusCode, body)
return "", fmt.Errorf("failed to upload image, statuscode: %d, body: %s", res.StatusCode, body)
}
if u.public_url != "" {
......
......@@ -193,12 +193,12 @@ func (w *FileLogWriter) DoRotate() error {
// close fd before rename
// Rename the file to its newfound home
if err = os.Rename(w.Filename, fname); err != nil {
return fmt.Errorf("Rotate: %s", err)
return fmt.Errorf("rotate: %s", err)
}
// re-start logger
if err = w.StartLogger(); err != nil {
return fmt.Errorf("Rotate StartLogger: %s", err)
return fmt.Errorf("rotate StartLogger: %s", err)
}
go w.deleteOldLog()
......@@ -212,7 +212,7 @@ func (w *FileLogWriter) deleteOldLog() {
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) (returnErr error) {
defer func() {
if r := recover(); r != nil {
returnErr = fmt.Errorf("Unable to delete old log '%s', error: %+v", path, r)
returnErr = fmt.Errorf("unable to delete old log '%s', error: %+v", path, r)
}
}()
......
......@@ -13,13 +13,13 @@ import (
func (im *InternalMetricsService) readSettings() error {
var section, err = im.Cfg.Raw.GetSection("metrics")
if err != nil {
return fmt.Errorf("Unable to find metrics config section %v", err)
return fmt.Errorf("unable to find metrics config section: %w", err)
}
im.intervalSeconds = section.Key("interval_seconds").MustInt64(10)
if err := im.parseGraphiteSettings(); err != nil {
return fmt.Errorf("Unable to parse metrics graphite section, %v", err)
return fmt.Errorf("unable to parse metrics graphite section: %w", err)
}
return nil
......
......@@ -10,17 +10,17 @@ import (
)
var (
ErrEmailNotAllowed = errors.New("Required email domain not fulfilled")
ErrInvalidCredentials = errors.New("Invalid Username or Password")
ErrNoEmail = errors.New("Login provider didn't return an email address")
ErrProviderDeniedRequest = errors.New("Login provider denied login request")
ErrSignUpNotAllowed = errors.New("Signup is not allowed for this adapter")
ErrTooManyLoginAttempts = errors.New("Too many consecutive incorrect login attempts for user. Login for user temporarily blocked")
ErrPasswordEmpty = errors.New("No password provided")
ErrUserDisabled = errors.New("User is disabled")
ErrAbsoluteRedirectTo = errors.New("Absolute urls are not allowed for redirect_to cookie value")
ErrInvalidRedirectTo = errors.New("Invalid redirect_to cookie value")
ErrForbiddenRedirectTo = errors.New("Forbidden redirect_to cookie value")
ErrEmailNotAllowed = errors.New("required email domain not fulfilled")
ErrInvalidCredentials = errors.New("invalid username or password")
ErrNoEmail = errors.New("login provider didn't return an email address")
ErrProviderDeniedRequest = errors.New("login provider denied login request")
ErrSignUpNotAllowed = errors.New("signup is not allowed for this adapter")
ErrTooManyLoginAttempts = errors.New("too many consecutive incorrect login attempts for user - login for user temporarily blocked")
ErrPasswordEmpty = errors.New("no password provided")
ErrUserDisabled = errors.New("user is disabled")
ErrAbsoluteRedirectTo = errors.New("absolute URLs are not allowed for redirect_to cookie value")
ErrInvalidRedirectTo = errors.New("invalid redirect_to cookie value")
ErrForbiddenRedirectTo = errors.New("forbidden redirect_to cookie value")
)
var loginLogger = log.New("login")
......
......@@ -11,7 +11,7 @@ import (
. "github.com/smartystreets/goconvey/convey"
)
var errTest = errors.New("Test error")
var errTest = errors.New("test error")
func TestLDAPLogin(t *testing.T) {
Convey("Login using ldap", t, func() {
......
......@@ -105,11 +105,11 @@ func (s *SocialGitlab) UserInfo(client *http.Client, token *oauth2.Token) (*Basi
err = json.Unmarshal(response.Body, &data)
if err != nil {
return nil, fmt.Errorf("Error getting user info: %s", err)
return nil, fmt.Errorf("error getting user info: %s", err)
}
if data.State != "active" {
return nil, fmt.Errorf("User %s is inactive", data.Username)
return nil, fmt.Errorf("user %s is inactive", data.Username)
}
groups := s.GetGroups(client)
......
......@@ -243,7 +243,7 @@ func GetOAuthHttpClient(name string) (*http.Client, error) {
name = strings.TrimPrefix(name, "oauth_")
info, ok := setting.OAuthService.OAuthInfos[name]
if !ok {
return nil, fmt.Errorf("Could not find %s in OAuth Settings", name)
return nil, fmt.Errorf("could not find %q in OAuth Settings", name)
}
// handle call back
......@@ -261,7 +261,7 @@ func GetOAuthHttpClient(name string) (*http.Client, error) {
cert, err := tls.LoadX509KeyPair(info.TlsClientCert, info.TlsClientKey)
if err != nil {
logger.Error("Failed to setup TlsClientCert", "oauth", name, "error", err)
return nil, fmt.Errorf("Failed to setup TlsClientCert")
return nil, fmt.Errorf("failed to setup TlsClientCert: %w", err)
}
tr.TLSClientConfig.Certificates = append(tr.TLSClientConfig.Certificates, cert)
......@@ -271,7 +271,7 @@ func GetOAuthHttpClient(name string) (*http.Client, error) {
caCert, err := ioutil.ReadFile(info.TlsClientCa)
if err != nil {
logger.Error("Failed to setup TlsClientCa", "oauth", name, "error", err)
return nil, fmt.Errorf("Failed to setup TlsClientCa")
return nil, fmt.Errorf("failed to setup TlsClientCa: %w", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
......@@ -285,7 +285,7 @@ func GetConnector(name string) (SocialConnector, error) {
provider := strings.TrimPrefix(name, "oauth_")
connector, ok := SocialMap[provider]
if !ok {
return nil, fmt.Errorf("Failed to find oauth provider for %s", name)
return nil, fmt.Errorf("failed to find oauth provider for %q", name)
}
return connector, nil
}
......@@ -140,7 +140,7 @@ func (auth *AuthProxy) IsAllowedIP() (bool, *Error) {
}
err := fmt.Errorf(
"Request for user (%s) from %s is not from the authentication proxy", auth.header,
"request for user (%s) from %s is not from the authentication proxy", auth.header,
sourceIP,
)
......
......@@ -33,11 +33,11 @@ func Logger() macaron.Handler {
rw := res.(macaron.ResponseWriter)
c.Next()
timeTakenMs := time.Since(start) / time.Millisecond
timeTaken := time.Since(start) / time.Millisecond
if timer, ok := c.Data["perfmon.timer"]; ok {
timerTyped := timer.(prometheus.Summary)
timerTyped.Observe(float64(timeTakenMs))
timerTyped.Observe(float64(timeTaken))
}
status := rw.Status()
......@@ -50,9 +50,11 @@ func Logger() macaron.Handler {
if ctx, ok := c.Data["ctx"]; ok {
ctxTyped := ctx.(*models.ReqContext)
if status == 500 {
ctxTyped.Logger.Error("Request Completed", "method", req.Method, "path", req.URL.Path, "status", status, "remote_addr", c.RemoteAddr(), "time_ms", int64(timeTakenMs), "size", rw.Size(), "referer", req.Referer())
ctxTyped.Logger.Error("Request Completed", "method", req.Method, "path", req.URL.Path, "status", status,
"remote_addr", c.RemoteAddr(), "time_ms", int64(timeTaken), "size", rw.Size(), "referer", req.Referer())
} else {
ctxTyped.Logger.Info("Request Completed", "method", req.Method, "path", req.URL.Path, "status", status, "remote_addr", c.RemoteAddr(), "time_ms", int64(timeTakenMs), "size", rw.Size(), "referer", req.Referer())
ctxTyped.Logger.Info("Request Completed", "method", req.Method, "path", req.URL.Path, "status", status,
"remote_addr", c.RemoteAddr(), "time_ms", int64(timeTaken), "size", rw.Size(), "referer", req.Referer())
}
}
}
......
......@@ -5,13 +5,13 @@ import (
"net/http"
"net/http/httptest"
. "github.com/smartystreets/goconvey/convey"
"gopkg.in/macaron.v1"
"github.com/grafana/grafana/pkg/infra/remotecache"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/setting"
"github.com/smartystreets/goconvey/convey"
)
type scenarioContext struct {
......@@ -49,7 +49,7 @@ func (sc *scenarioContext) withAuthorizationHeader(authHeader string) *scenarioC
func (sc *scenarioContext) fakeReq(method, url string) *scenarioContext {
sc.resp = httptest.NewRecorder()
req, err := http.NewRequest(method, url, nil)
So(err, ShouldBeNil)
convey.So(err, convey.ShouldBeNil)
sc.req = req
return sc
......@@ -63,7 +63,7 @@ func (sc *scenarioContext) fakeReqWithParams(method, url string, queryParams map
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
So(err, ShouldBeNil)
convey.So(err, convey.ShouldBeNil)
sc.req = req
return sc
......@@ -94,7 +94,7 @@ func (sc *scenarioContext) exec() {
if sc.resp.Header().Get("Content-Type") == "application/json; charset=UTF-8" {
err := json.NewDecoder(sc.resp.Body).Decode(&sc.respJson)
So(err, ShouldBeNil)
convey.So(err, convey.ShouldBeNil)
}
}
......
......@@ -34,7 +34,7 @@ const (
)
var (
ErrCannotChangeStateOnPausedAlert = fmt.Errorf("Cannot change state on pause alert")
ErrCannotChangeStateOnPausedAlert = fmt.Errorf("cannot change state on pause alert")
ErrRequiresNewState = fmt.Errorf("update alert state requires a new state")
)
......@@ -97,13 +97,13 @@ func (alert *Alert) ShouldUpdateState(newState AlertStateType) bool {
return alert.State != newState
}
func (this *Alert) ContainsUpdates(other *Alert) bool {
func (a *Alert) ContainsUpdates(other *Alert) bool {
result := false
result = result || this.Name != other.Name
result = result || this.Message != other.Message
result = result || a.Name != other.Name
result = result || a.Message != other.Message
if this.Settings != nil && other.Settings != nil {
json1, err1 := this.Settings.Encode()
if a.Settings != nil && other.Settings != nil {
json1, err1 := a.Settings.Encode()
json2, err2 := other.Settings.Encode()
if err1 != nil || err2 != nil {
......
......@@ -9,13 +9,13 @@ import (
)
var (
ErrAlertNotificationNotFound = errors.New("Alert notification not found")
ErrNotificationFrequencyNotFound = errors.New("Notification frequency not specified")
ErrAlertNotificationNotFound = errors.New("alert notification not found")
ErrNotificationFrequencyNotFound = errors.New("notification frequency not specified")
ErrAlertNotificationStateNotFound = errors.New("alert notification state not found")
ErrAlertNotificationStateVersionConflict = errors.New("alert notification state update version conflict")
ErrAlertNotificationStateAlreadyExist = errors.New("alert notification state already exists")
ErrAlertNotificationFailedGenerateUniqueUid = errors.New("Failed to generate unique alert notification uid")
ErrAlertNotificationFailedTranslateUniqueID = errors.New("Failed to translate Notification Id to Uid")
ErrAlertNotificationFailedGenerateUniqueUid = errors.New("failed to generate unique alert notification uid")
ErrAlertNotificationFailedTranslateUniqueID = errors.New("failed to translate Notification Id to Uid")
ErrAlertNotificationWithSameNameExists = errors.New("alert notification with same name already exists")
ErrAlertNotificationWithSameUIDExists = errors.New("alert notification with same uid already exists")
)
......
......@@ -5,9 +5,9 @@ import (
"time"
)
var ErrInvalidApiKey = errors.New("Invalid API Key")
var ErrInvalidApiKeyExpiration = errors.New("Negative value for SecondsToLive")
var ErrDuplicateApiKey = errors.New("API Key Organization ID And Name Must Be Unique")
var ErrInvalidApiKey = errors.New("invalid API key")
var ErrInvalidApiKeyExpiration = errors.New("negative value for SecondsToLive")
var ErrDuplicateApiKey = errors.New("API key, organization ID and name must be unique")
type ApiKey struct {
Id int64
......
......@@ -8,8 +8,8 @@ import (
)
var (
ErrDashboardVersionNotFound = errors.New("Dashboard version not found")
ErrNoVersionsForDashboardId = errors.New("No dashboard versions found for the given DashboardId")
ErrDashboardVersionNotFound = errors.New("dashboard version not found")
ErrNoVersionsForDashboardId = errors.New("no dashboard versions found for the given DashboardId")
)
// A DashboardVersion represents the comparable data in a dashboard, allowing
......
......@@ -30,13 +30,13 @@ const (
)
var (
ErrDataSourceNotFound = errors.New("Data source not found")
ErrDataSourceNameExists = errors.New("Data source with the same name already exists")
ErrDataSourceUidExists = errors.New("Data source with the same uid already exists")
ErrDataSourceUpdatingOldVersion = errors.New("Trying to update old version of datasource")
ErrDatasourceIsReadOnly = errors.New("Data source is readonly. Can only be updated from configuration")
ErrDataSourceAccessDenied = errors.New("Data source access denied")
ErrDataSourceFailedGenerateUniqueUid = errors.New("Failed to generate unique datasource id")
ErrDataSourceNotFound = errors.New("data source not found")
ErrDataSourceNameExists = errors.New("data source with the same name already exists")
ErrDataSourceUidExists = errors.New("data source with the same uid already exists")
ErrDataSourceUpdatingOldVersion = errors.New("trying to update old version of datasource")
ErrDatasourceIsReadOnly = errors.New("data source is readonly, can only be updated from configuration")
ErrDataSourceAccessDenied = errors.New("data source access denied")
ErrDataSourceFailedGenerateUniqueUid = errors.New("failed to generate unique datasource ID")
)
type DsAccess string
......
......@@ -224,7 +224,7 @@ func (ds *DataSource) GetTLSConfig() (*tls.Config, error) {
caPool := x509.NewCertPool()
ok := caPool.AppendCertsFromPEM([]byte(decrypted["tlsCACert"]))
if !ok {
return nil, errors.New("Failed to parse TLS CA PEM certificate")
return nil, errors.New("failed to parse TLS CA PEM certificate")
}
tlsConfig.RootCAs = caPool
}
......
......@@ -8,13 +8,13 @@ import (
// Typed errors
var (
ErrFolderNotFound = errors.New("Folder not found")
ErrFolderVersionMismatch = errors.New("The folder has been changed by someone else")
ErrFolderTitleEmpty = errors.New("Folder title cannot be empty")
ErrFolderWithSameUIDExists = errors.New("A folder/dashboard with the same uid already exists")
ErrFolderSameNameExists = errors.New("A folder or dashboard in the general folder with the same name already exists")
ErrFolderFailedGenerateUniqueUid = errors.New("Failed to generate unique folder id")
ErrFolderAccessDenied = errors.New("Access denied to folder")
ErrFolderNotFound = errors.New("folder not found")
ErrFolderVersionMismatch = errors.New("the folder has been changed by someone else")
ErrFolderTitleEmpty = errors.New("folder title cannot be empty")
ErrFolderWithSameUIDExists = errors.New("a folder/dashboard with the same uid already exists")
ErrFolderSameNameExists = errors.New("a folder or dashboard in the general folder with the same name already exists")
ErrFolderFailedGenerateUniqueUid = errors.New("failed to generate unique folder ID")
ErrFolderAccessDenied = errors.New("access denied to folder")
)
type Folder struct {
......
......@@ -2,7 +2,7 @@ package models
import "errors"
var ErrInvalidEmailCode = errors.New("Invalid or expired email code")
var ErrInvalidEmailCode = errors.New("invalid or expired email code")
var ErrSmtpNotEnabled = errors.New("SMTP not configured, check your grafana.ini config file's [smtp] section")
// SendEmailAttachFile is a definition of the attached files without path
......
......@@ -7,8 +7,8 @@ import (
// Typed errors
var (
ErrOrgNotFound = errors.New("Organization not found")
ErrOrgNameTaken = errors.New("Organization name is taken")
ErrOrgNotFound = errors.New("organization not found")
ErrOrgNameTaken = errors.New("organization name is taken")
)
type Org struct {
......
......@@ -9,10 +9,10 @@ import (
// Typed errors
var (
ErrInvalidRoleType = errors.New("Invalid role type")
ErrLastOrgAdmin = errors.New("Cannot remove last organization admin")
ErrOrgUserNotFound = errors.New("Cannot find the organization user")
ErrOrgUserAlreadyAdded = errors.New("User is already added to organization")
ErrInvalidRoleType = errors.New("invalid role type")
ErrLastOrgAdmin = errors.New("cannot remove last organization admin")
ErrOrgUserNotFound = errors.New("cannot find the organization user")
ErrOrgUserAlreadyAdded = errors.New("user is already added to organization")
)
type RoleType string
......
......@@ -6,8 +6,8 @@ import (
// Typed errors
var (
ErrPlaylistNotFound = errors.New("Playlist not found")
ErrPlaylistWithSameNameExists = errors.New("A playlist with the same name already exists")
ErrPlaylistNotFound = errors.New("playlist not found")
ErrPlaylistWithSameNameExists = errors.New("a playlist with the same name already exists")
)
// Playlist model
......@@ -50,7 +50,7 @@ type PlaylistItem struct {
Title string
}
func (this PlaylistDashboard) TableName() string {
func (p PlaylistDashboard) TableName() string {
return "dashboard"
}
......
......@@ -8,7 +8,7 @@ import (
)
var (
ErrPluginSettingNotFound = errors.New("Plugin setting not found")
ErrPluginSettingNotFound = errors.New("plugin setting not found")
)
type PluginSetting struct {
......
......@@ -7,7 +7,7 @@ import (
"github.com/grafana/grafana/pkg/setting"
)
var ErrInvalidQuotaTarget = errors.New("Invalid quota target")
var ErrInvalidQuotaTarget = errors.New("invalid quota target")
type Quota struct {
Id int64
......
......@@ -2,7 +2,7 @@ package models
import "errors"
var ErrCommandValidationFailed = errors.New("Command missing required fields")
var ErrCommandValidationFailed = errors.New("command missing required fields")
type Star struct {
Id int64
......
......@@ -7,12 +7,12 @@ import (
// Typed errors
var (
ErrTeamNotFound = errors.New("Team not found")
ErrTeamNameTaken = errors.New("Team name is taken")
ErrTeamMemberNotFound = errors.New("Team member not found")
ErrLastTeamAdmin = errors.New("Not allowed to remove last admin")
ErrNotAllowedToUpdateTeam = errors.New("User not allowed to update team")
ErrNotAllowedToUpdateTeamInDifferentOrg = errors.New("User not allowed to update team in another org")
ErrTeamNotFound = errors.New("team not found")
ErrTeamNameTaken = errors.New("team name is taken")
ErrTeamMemberNotFound = errors.New("team member not found")
ErrLastTeamAdmin = errors.New("not allowed to remove last admin")
ErrNotAllowedToUpdateTeam = errors.New("user not allowed to update team")
ErrNotAllowedToUpdateTeamInDifferentOrg = errors.New("user not allowed to update team in another org")
)
// Team model
......
......@@ -7,9 +7,9 @@ import (
// Typed errors
var (
ErrUserNotFound = errors.New("User not found")
ErrUserAlreadyExists = errors.New("User already exists")
ErrLastGrafanaAdmin = errors.New("Cannot remove last grafana admin")
ErrUserNotFound = errors.New("user not found")
ErrUserAlreadyExists = errors.New("user already exists")
ErrLastGrafanaAdmin = errors.New("cannot remove last grafana admin")
)
type Password string
......
......@@ -23,7 +23,6 @@ import (
"github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/metrics"
_ "github.com/grafana/grafana/pkg/infra/metrics"
_ "github.com/grafana/grafana/pkg/infra/remotecache"
_ "github.com/grafana/grafana/pkg/infra/serverlock"
_ "github.com/grafana/grafana/pkg/infra/tracing"
......
......@@ -71,7 +71,7 @@ func TestApiKeyDataAccess(t *testing.T) {
query := models.GetApiKeyByNameQuery{KeyName: "key-with-negative-lifespan", OrgId: 1}
err = GetApiKeyByName(&query)
assert.EqualError(t, err, "Invalid API Key")
assert.EqualError(t, err, "invalid API key")
})
t.Run("Add keys", func(t *testing.T) {
......
......@@ -552,7 +552,7 @@ func loadSpecifiedConfigFile(configFile string, masterFile *ini.File) error {
userConfig, err := ini.Load(configFile)
if err != nil {
return fmt.Errorf("Failed to parse %v, %v", configFile, err)
return fmt.Errorf("failed to parse %q: %w", configFile, err)
}
userConfig.BlockMode = false
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment