Merge pull request #13392 from mjtrangoni/fix-goconst-issues

Fix goconst issues
This commit is contained in:
Torkel Ödegaard
2018-09-26 20:12:44 +02:00
committed by GitHub
12 changed files with 80 additions and 40 deletions

View File

@@ -22,6 +22,11 @@ import (
"time" "time"
) )
const (
windows = "windows"
linux = "linux"
)
var ( var (
//versionRe = regexp.MustCompile(`-[0-9]{1,3}-g[0-9a-f]{5,10}`) //versionRe = regexp.MustCompile(`-[0-9]{1,3}-g[0-9a-f]{5,10}`)
goarch string goarch string
@@ -110,13 +115,13 @@ func main() {
case "package": case "package":
grunt(gruntBuildArg("build")...) grunt(gruntBuildArg("build")...)
grunt(gruntBuildArg("package")...) grunt(gruntBuildArg("package")...)
if goos == "linux" { if goos == linux {
createLinuxPackages() createLinuxPackages()
} }
case "package-only": case "package-only":
grunt(gruntBuildArg("package")...) grunt(gruntBuildArg("package")...)
if goos == "linux" { if goos == linux {
createLinuxPackages() createLinuxPackages()
} }
@@ -378,7 +383,7 @@ func ensureGoPath() {
} }
func grunt(params ...string) { func grunt(params ...string) {
if runtime.GOOS == "windows" { if runtime.GOOS == windows {
runPrint(`.\node_modules\.bin\grunt`, params...) runPrint(`.\node_modules\.bin\grunt`, params...)
} else { } else {
runPrint("./node_modules/.bin/grunt", params...) runPrint("./node_modules/.bin/grunt", params...)
@@ -420,7 +425,7 @@ func build(binaryName, pkg string, tags []string) {
binary = fmt.Sprintf("./bin/%s", binaryName) binary = fmt.Sprintf("./bin/%s", binaryName)
} }
if goos == "windows" { if goos == windows {
binary += ".exe" binary += ".exe"
} }
@@ -484,11 +489,11 @@ func clean() {
func setBuildEnv() { func setBuildEnv() {
os.Setenv("GOOS", goos) os.Setenv("GOOS", goos)
if goos == "windows" { if goos == windows {
// require windows >=7 // require windows >=7
os.Setenv("CGO_CFLAGS", "-D_WIN32_WINNT=0x0601") os.Setenv("CGO_CFLAGS", "-D_WIN32_WINNT=0x0601")
} }
if goarch != "amd64" || goos != "linux" { if goarch != "amd64" || goos != linux {
// needed for all other archs // needed for all other archs
cgo = true cgo = true
} }

View File

@@ -22,6 +22,10 @@ import (
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
const (
anonString = "Anonymous"
)
func isDashboardStarredByUser(c *m.ReqContext, dashID int64) (bool, error) { func isDashboardStarredByUser(c *m.ReqContext, dashID int64) (bool, error) {
if !c.IsSignedIn { if !c.IsSignedIn {
return false, nil return false, nil
@@ -64,7 +68,7 @@ func GetDashboard(c *m.ReqContext) Response {
} }
// Finding creator and last updater of the dashboard // Finding creator and last updater of the dashboard
updater, creator := "Anonymous", "Anonymous" updater, creator := anonString, anonString
if dash.UpdatedBy > 0 { if dash.UpdatedBy > 0 {
updater = getUserLogin(dash.UpdatedBy) updater = getUserLogin(dash.UpdatedBy)
} }
@@ -128,7 +132,7 @@ func getUserLogin(userID int64) string {
query := m.GetUserByIdQuery{Id: userID} query := m.GetUserByIdQuery{Id: userID}
err := bus.Dispatch(&query) err := bus.Dispatch(&query)
if err != nil { if err != nil {
return "Anonymous" return anonString
} }
return query.Result.Login return query.Result.Login
} }
@@ -403,7 +407,7 @@ func GetDashboardVersion(c *m.ReqContext) Response {
return Error(500, fmt.Sprintf("Dashboard version %d not found for dashboardId %d", query.Version, dashID), err) return Error(500, fmt.Sprintf("Dashboard version %d not found for dashboardId %d", query.Version, dashID), err)
} }
creator := "Anonymous" creator := anonString
if query.Result.CreatedBy > 0 { if query.Result.CreatedBy > 0 {
creator = getUserLogin(query.Result.CreatedBy) creator = getUserLogin(query.Result.CreatedBy)
} }

View File

@@ -95,7 +95,7 @@ func toFolderDto(g guardian.DashboardGuardian, folder *m.Folder) dtos.Folder {
canAdmin, _ := g.CanAdmin() canAdmin, _ := g.CanAdmin()
// Finding creator and last updater of the folder // Finding creator and last updater of the folder
updater, creator := "Anonymous", "Anonymous" updater, creator := anonString, anonString
if folder.CreatedBy > 0 { if folder.CreatedBy > 0 {
creator = getUserLogin(folder.CreatedBy) creator = getUserLogin(folder.CreatedBy)
} }

View File

@@ -11,6 +11,12 @@ import (
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
) )
const (
// Themes
lightName = "light"
darkName = "dark"
)
func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) { func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) {
settings, err := getFrontendSettingsMap(c) settings, err := getFrontendSettingsMap(c)
if err != nil { if err != nil {
@@ -60,7 +66,7 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) {
OrgRole: c.OrgRole, OrgRole: c.OrgRole,
GravatarUrl: dtos.GetGravatarUrl(c.Email), GravatarUrl: dtos.GetGravatarUrl(c.Email),
IsGrafanaAdmin: c.IsGrafanaAdmin, IsGrafanaAdmin: c.IsGrafanaAdmin,
LightTheme: prefs.Theme == "light", LightTheme: prefs.Theme == lightName,
Timezone: prefs.Timezone, Timezone: prefs.Timezone,
Locale: locale, Locale: locale,
HelpFlags1: c.HelpFlags1, HelpFlags1: c.HelpFlags1,
@@ -88,12 +94,12 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) {
} }
themeURLParam := c.Query("theme") themeURLParam := c.Query("theme")
if themeURLParam == "light" { if themeURLParam == lightName {
data.User.LightTheme = true data.User.LightTheme = true
data.Theme = "light" data.Theme = lightName
} else if themeURLParam == "dark" { } else if themeURLParam == darkName {
data.User.LightTheme = false data.User.LightTheme = false
data.Theme = "dark" data.Theme = darkName
} }
if hasEditPermissionInFoldersQuery.Result { if hasEditPermissionInFoldersQuery.Result {

View File

@@ -8,6 +8,10 @@ import (
"strconv" "strconv"
) )
const (
nullString = "null"
)
// Float is a nullable float64. // Float is a nullable float64.
// It does not consider zero values to be null. // It does not consider zero values to be null.
// It will decode to null, not zero, if null. // It will decode to null, not zero, if null.
@@ -68,7 +72,7 @@ func (f *Float) UnmarshalJSON(data []byte) error {
// It will return an error if the input is not an integer, blank, or "null". // It will return an error if the input is not an integer, blank, or "null".
func (f *Float) UnmarshalText(text []byte) error { func (f *Float) UnmarshalText(text []byte) error {
str := string(text) str := string(text)
if str == "" || str == "null" { if str == "" || str == nullString {
f.Valid = false f.Valid = false
return nil return nil
} }
@@ -82,7 +86,7 @@ func (f *Float) UnmarshalText(text []byte) error {
// It will encode null if this Float is null. // It will encode null if this Float is null.
func (f Float) MarshalJSON() ([]byte, error) { func (f Float) MarshalJSON() ([]byte, error) {
if !f.Valid { if !f.Valid {
return []byte("null"), nil return []byte(nullString), nil
} }
return []byte(strconv.FormatFloat(f.Float64, 'f', -1, 64)), nil return []byte(strconv.FormatFloat(f.Float64, 'f', -1, 64)), nil
} }
@@ -100,7 +104,7 @@ func (f Float) MarshalText() ([]byte, error) {
// It will encode a blank string if this Float is null. // It will encode a blank string if this Float is null.
func (f Float) String() string { func (f Float) String() string {
if !f.Valid { if !f.Valid {
return "null" return nullString
} }
return fmt.Sprintf("%1.3f", f.Float64) return fmt.Sprintf("%1.3f", f.Float64)
@@ -109,7 +113,7 @@ func (f Float) String() string {
// FullString returns float as string in full precision // FullString returns float as string in full precision
func (f Float) FullString() string { func (f Float) FullString() string {
if !f.Valid { if !f.Valid {
return "null" return nullString
} }
return fmt.Sprintf("%f", f.Float64) return fmt.Sprintf("%f", f.Float64)

View File

@@ -11,6 +11,10 @@ import (
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
) )
const (
triggMetrString = "Triggered metrics:\n\n"
)
type NotifierBase struct { type NotifierBase struct {
Name string Name string
Type string Type string

View File

@@ -61,7 +61,7 @@ func (this *KafkaNotifier) Notify(evalContext *alerting.EvalContext) error {
state := evalContext.Rule.State state := evalContext.Rule.State
customData := "Triggered metrics:\n\n" customData := triggMetrString
for _, evt := range evalContext.EvalMatches { for _, evt := range evalContext.EvalMatches {
customData = customData + fmt.Sprintf("%s: %v\n", evt.Metric, evt.Value) customData = customData + fmt.Sprintf("%s: %v\n", evt.Metric, evt.Value)
} }

View File

@@ -95,7 +95,7 @@ func (this *OpsGenieNotifier) createAlert(evalContext *alerting.EvalContext) err
return err return err
} }
customData := "Triggered metrics:\n\n" customData := triggMetrString
for _, evt := range evalContext.EvalMatches { for _, evt := range evalContext.EvalMatches {
customData = customData + fmt.Sprintf("%s: %v\n", evt.Metric, evt.Value) customData = customData + fmt.Sprintf("%s: %v\n", evt.Metric, evt.Value)
} }

View File

@@ -76,7 +76,7 @@ func (this *PagerdutyNotifier) Notify(evalContext *alerting.EvalContext) error {
if evalContext.Rule.State == m.AlertStateOK { if evalContext.Rule.State == m.AlertStateOK {
eventType = "resolve" eventType = "resolve"
} }
customData := "Triggered metrics:\n\n" customData := triggMetrString
for _, evt := range evalContext.EvalMatches { for _, evt := range evalContext.EvalMatches {
customData = customData + fmt.Sprintf("%s: %v\n", evt.Metric, evt.Value) customData = customData + fmt.Sprintf("%s: %v\n", evt.Metric, evt.Value)
} }

View File

@@ -46,10 +46,14 @@ func (e *Error) Error() string {
return e.s return e.s
} }
const (
grafanaCom = "grafana_com"
)
var ( var (
SocialBaseUrl = "/login/" SocialBaseUrl = "/login/"
SocialMap = make(map[string]SocialConnector) SocialMap = make(map[string]SocialConnector)
allOauthes = []string{"github", "gitlab", "google", "generic_oauth", "grafananet", "grafana_com"} allOauthes = []string{"github", "gitlab", "google", "generic_oauth", "grafananet", grafanaCom}
) )
func NewOAuthService() { func NewOAuthService() {
@@ -82,7 +86,7 @@ func NewOAuthService() {
} }
if name == "grafananet" { if name == "grafananet" {
name = "grafana_com" name = grafanaCom
} }
setting.OAuthService.OAuthInfos[name] = info setting.OAuthService.OAuthInfos[name] = info
@@ -159,7 +163,7 @@ func NewOAuthService() {
} }
} }
if name == "grafana_com" { if name == grafanaCom {
config = oauth2.Config{ config = oauth2.Config{
ClientID: info.ClientId, ClientID: info.ClientId,
ClientSecret: info.ClientSecret, ClientSecret: info.ClientSecret,
@@ -171,7 +175,7 @@ func NewOAuthService() {
Scopes: info.Scopes, Scopes: info.Scopes,
} }
SocialMap["grafana_com"] = &SocialGrafanaCom{ SocialMap[grafanaCom] = &SocialGrafanaCom{
SocialBase: &SocialBase{ SocialBase: &SocialBase{
Config: &config, Config: &config,
log: logger, log: logger,
@@ -194,7 +198,7 @@ var GetOAuthProviders = func(cfg *setting.Cfg) map[string]bool {
for _, name := range allOauthes { for _, name := range allOauthes {
if name == "grafananet" { if name == "grafananet" {
name = "grafana_com" name = grafanaCom
} }
sec := cfg.Raw.Section("auth." + name) sec := cfg.Raw.Section("auth." + name)

View File

@@ -13,6 +13,19 @@ import (
"github.com/grafana/grafana/pkg/tsdb/elasticsearch/client" "github.com/grafana/grafana/pkg/tsdb/elasticsearch/client"
) )
const (
// Metric types
countType = "count"
percentilesType = "percentiles"
extendedStatsType = "extended_stats"
// Bucket types
dateHistType = "date_histogram"
histogramType = "histogram"
filtersType = "filters"
termsType = "terms"
geohashGridType = "geohash_grid"
)
type responseParser struct { type responseParser struct {
Responses []*es.SearchResponse Responses []*es.SearchResponse
Targets []*Query Targets []*Query
@@ -81,7 +94,7 @@ func (rp *responseParser) processBuckets(aggs map[string]interface{}, target *Qu
} }
if depth == maxDepth { if depth == maxDepth {
if aggDef.Type == "date_histogram" { if aggDef.Type == dateHistType {
err = rp.processMetrics(esAgg, target, series, props) err = rp.processMetrics(esAgg, target, series, props)
} else { } else {
err = rp.processAggregationDocs(esAgg, aggDef, target, table, props) err = rp.processAggregationDocs(esAgg, aggDef, target, table, props)
@@ -149,7 +162,7 @@ func (rp *responseParser) processMetrics(esAgg *simplejson.Json, target *Query,
} }
switch metric.Type { switch metric.Type {
case "count": case countType:
newSeries := tsdb.TimeSeries{ newSeries := tsdb.TimeSeries{
Tags: make(map[string]string), Tags: make(map[string]string),
} }
@@ -164,10 +177,10 @@ func (rp *responseParser) processMetrics(esAgg *simplejson.Json, target *Query,
for k, v := range props { for k, v := range props {
newSeries.Tags[k] = v newSeries.Tags[k] = v
} }
newSeries.Tags["metric"] = "count" newSeries.Tags["metric"] = countType
*series = append(*series, &newSeries) *series = append(*series, &newSeries)
case "percentiles": case percentilesType:
buckets := esAgg.Get("buckets").MustArray() buckets := esAgg.Get("buckets").MustArray()
if len(buckets) == 0 { if len(buckets) == 0 {
break break
@@ -198,7 +211,7 @@ func (rp *responseParser) processMetrics(esAgg *simplejson.Json, target *Query,
} }
*series = append(*series, &newSeries) *series = append(*series, &newSeries)
} }
case "extended_stats": case extendedStatsType:
buckets := esAgg.Get("buckets").MustArray() buckets := esAgg.Get("buckets").MustArray()
metaKeys := make([]string, 0) metaKeys := make([]string, 0)
@@ -312,9 +325,9 @@ func (rp *responseParser) processAggregationDocs(esAgg *simplejson.Json, aggDef
for _, metric := range target.Metrics { for _, metric := range target.Metrics {
switch metric.Type { switch metric.Type {
case "count": case countType:
addMetricValue(&values, rp.getMetricName(metric.Type), castToNullFloat(bucket.Get("doc_count"))) addMetricValue(&values, rp.getMetricName(metric.Type), castToNullFloat(bucket.Get("doc_count")))
case "extended_stats": case extendedStatsType:
metaKeys := make([]string, 0) metaKeys := make([]string, 0)
meta := metric.Meta.MustMap() meta := metric.Meta.MustMap()
for k := range meta { for k := range meta {
@@ -366,7 +379,7 @@ func (rp *responseParser) processAggregationDocs(esAgg *simplejson.Json, aggDef
func (rp *responseParser) trimDatapoints(series *tsdb.TimeSeriesSlice, target *Query) { func (rp *responseParser) trimDatapoints(series *tsdb.TimeSeriesSlice, target *Query) {
var histogram *BucketAgg var histogram *BucketAgg
for _, bucketAgg := range target.BucketAggs { for _, bucketAgg := range target.BucketAggs {
if bucketAgg.Type == "date_histogram" { if bucketAgg.Type == dateHistType {
histogram = bucketAgg histogram = bucketAgg
break break
} }

View File

@@ -75,15 +75,15 @@ func (e *timeSeriesQuery) execute() (*tsdb.Response, error) {
// iterate backwards to create aggregations bottom-down // iterate backwards to create aggregations bottom-down
for _, bucketAgg := range q.BucketAggs { for _, bucketAgg := range q.BucketAggs {
switch bucketAgg.Type { switch bucketAgg.Type {
case "date_histogram": case dateHistType:
aggBuilder = addDateHistogramAgg(aggBuilder, bucketAgg, from, to) aggBuilder = addDateHistogramAgg(aggBuilder, bucketAgg, from, to)
case "histogram": case histogramType:
aggBuilder = addHistogramAgg(aggBuilder, bucketAgg) aggBuilder = addHistogramAgg(aggBuilder, bucketAgg)
case "filters": case filtersType:
aggBuilder = addFiltersAgg(aggBuilder, bucketAgg) aggBuilder = addFiltersAgg(aggBuilder, bucketAgg)
case "terms": case termsType:
aggBuilder = addTermsAgg(aggBuilder, bucketAgg, q.Metrics) aggBuilder = addTermsAgg(aggBuilder, bucketAgg, q.Metrics)
case "geohash_grid": case geohashGridType:
aggBuilder = addGeoHashGridAgg(aggBuilder, bucketAgg) aggBuilder = addGeoHashGridAgg(aggBuilder, bucketAgg)
} }
} }