Skip to content

Commit

Permalink
Addressing various linting changes
Browse files Browse the repository at this point in the history
  • Loading branch information
safaci2000 committed Sep 28, 2023
1 parent 7101d4f commit ac5f68b
Show file tree
Hide file tree
Showing 21 changed files with 74 additions and 69 deletions.
16 changes: 10 additions & 6 deletions Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,22 @@ tasks:
default:
cmds:
- task: build
install_tools:
desc: "Install required Dev tools by GDG"
cmds:
- go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
format:
desc: "Format code"
cmds:
- gofmt -w -s .
lint:
desc: "Lint project"
desc: "Lint project, skipping test files."
cmds:
- golangci-lint run --skip-dirs "(^|/)test($|/)" --skip-files "_test.go" ./...
lint_tests:
desc: "Lint project, including test files."
cmds:
- golangci-lint run ./...
- golangci-lint run ./...
authors:
desc: "Building GDG"
cmds:
Expand Down Expand Up @@ -57,10 +65,6 @@ tasks:
desc: "Tidy Deps"
cmds:
- go mod tidy
build-alpine:
desc: "building {{ .BIN_NAME }} {{. VERSION }}"
cmds:
- go build -ldflags '{{ .LD_FLAGS }} -linkmode external -extldflags "-static"' -o bin/{{ .BIN_NAME}}
pakcage:
desc: "building image {{ .BIN_NAME }} {{ .VERSION }} {{ .GIT_COMMIT }}"
cmds:
Expand Down
4 changes: 1 addition & 3 deletions cmd/backup/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ import (
"strings"
)

var (
skipConfirmAction bool
)
var skipConfirmAction bool

func parseDashboardGlobalFlags(command *cobra.Command) []string {
folderFilter, _ := command.Flags().GetString("folder")
Expand Down
2 changes: 1 addition & 1 deletion cmd/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func newListContextCmd() simplecobra.Commander {
r.TableObj.AppendHeader(table.Row{"context", "active"})
contexts := config.Config().GetAppConfig().GetContexts()
activeContext := config.Config().GetAppConfig().GetContext()
for key, _ := range contexts {
for key := range contexts {
active := false
if key == strings.ToLower(activeContext) {
key = fmt.Sprintf("*%s", activeContext)
Expand Down
13 changes: 8 additions & 5 deletions cmd/support/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,13 @@ var (
DefaultConfig string
)

// RootCommand struct wraps the root command and supporting services needed
type RootCommand struct {
NameP string
isInit bool

GrafanaSvc func() service.GrafanaService

localFlagName string

persistentFlagNameC string
localFlagNameC string

ctx context.Context
initThis *simplecobra.Commandeer
initRunner *simplecobra.Commandeer
Expand All @@ -37,6 +33,7 @@ type RootCommand struct {
CommandEntries []simplecobra.Commander
}

// RootOption used to configure the Root Command struct
type RootOption func(command *RootCommand)

// NewRootCmd Allows to construct a root command passing any number of arguments to set RootCommand Options
Expand All @@ -50,10 +47,12 @@ func NewRootCmd(root *RootCommand, options ...RootOption) *RootCommand {
return root
}

// Commands returns a list of Cobra commands
func (c *RootCommand) Commands() []simplecobra.Commander {
return c.CommandEntries
}

// PreRun executed prior to command invocation
func (c *RootCommand) PreRun(this, runner *simplecobra.Commandeer) error {
c.isInit = true
c.initThis = this
Expand All @@ -62,6 +61,7 @@ func (c *RootCommand) PreRun(this, runner *simplecobra.Commandeer) error {
return nil
}

// initConfiguration Loads configuration, and setups fail over case
func (c *RootCommand) initConfiguration() {
cmd := c.initRunner.CobraCommand
configOverride, _ := cmd.Flags().GetString("config")
Expand All @@ -84,10 +84,12 @@ func (c *RootCommand) initConfiguration() {

}

// Name returns the cli command name
func (c *RootCommand) Name() string {
return c.NameP
}

// Run invokes the CLI command
func (c *RootCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
if c.failRun {
return errors.New("failRun")
Expand All @@ -96,6 +98,7 @@ func (c *RootCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args
return nil
}

// Init invoked to Initialize the RootCommand object
func (c *RootCommand) Init(cd *simplecobra.Commandeer) error {
if c.failWithCobraCommand {
return errors.New("failWithCobraCommand")
Expand Down
7 changes: 7 additions & 0 deletions cmd/support/simple.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/spf13/cobra"
)

// SimpleCommand wraps a simple command
type SimpleCommand struct {
use string
NameP string
Expand All @@ -20,25 +21,30 @@ type SimpleCommand struct {
RootCmd *RootCommand
}

// Commands is a list of subcommands
func (c *SimpleCommand) Commands() []simplecobra.Commander {
return c.CommandsList
}

// SetName Function allows name to be set
func (c *SimpleCommand) SetName(name string) {
c.NameP = name
}

// Name returns function Name
func (c *SimpleCommand) Name() string {
return c.NameP
}

// Run executes cli command
func (c *SimpleCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
if c.RunFunc == nil {
return nil
}
return c.RunFunc(ctx, cd, c.RootCmd, args)
}

// Init initializes the SimpleCommand
func (c *SimpleCommand) Init(cd *simplecobra.Commandeer) error {
c.RootCmd = cd.Root.Command.(*RootCommand)
cmd := cd.CobraCommand
Expand All @@ -53,6 +59,7 @@ func (c *SimpleCommand) Init(cd *simplecobra.Commandeer) error {
return nil
}

// PreRun executed prior to cli command execution
func (c *SimpleCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
if c.InitCFunc != nil {
return c.InitCFunc(cd, c.RootCmd)
Expand Down
2 changes: 2 additions & 0 deletions cmd/test_tools/support.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package test_tools

import "os"

// InterceptStdout is a test helper function that will redirect all stdout in and out to a different file stream.
// It returns the stdout, stderr, and a function to be invoked to close the streams.
func InterceptStdout() (*os.File, *os.File, func()) {
backupStd := os.Stdout
backupErr := os.Stderr
Expand Down
2 changes: 1 addition & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func (s *Configuration) DeleteContext(name string) {
}
delete(contexts, name)
if len(contexts) != 0 {
for key, _ := range contexts {
for key := range contexts {
s.GetAppConfig().ContextName = key
break
}
Expand Down
10 changes: 6 additions & 4 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,15 @@ import (

func DuplicateConfig(t *testing.T) string {
dir, _ := os.Getwd()
var err error
//Fix test path
if strings.Contains(dir, "config") {
os.Chdir("../..")
err = os.Chdir("../..")
assert.Nil(t, err, "Failed to change to base directory ")
}

os.Setenv("GDG_CONTEXT_NAME", "production")
err = os.Setenv("GDG_CONTEXT_NAME", "production")
assert.Nil(t, err, "Failed to set override GDG context name via ENV")
data, err := os.ReadFile("config/testing.yml")
assert.Nil(t, err, "Failed to read test configuration file")
destination := os.TempDir()
Expand Down Expand Up @@ -98,10 +101,9 @@ func validateGrafanaQA(t *testing.T, grafana *config.GrafanaConfig) {
assert.Equal(t, "qa/dashboards", grafana.GetDashboardOutput())
dsSettings := grafana.DataSourceSettings
request := models.AddDataSourceCommand{}
defaultSettings, _ := dsSettings.GetCredentials(request)
assert.Equal(t, len(grafana.DataSourceSettings.MatchingRules), 3)
//Last Entry is the default
defaultSettings = grafana.DataSourceSettings.MatchingRules[2].Auth
defaultSettings := grafana.DataSourceSettings.MatchingRules[2].Auth
assert.Equal(t, "user", defaultSettings.User)
assert.Equal(t, "password", defaultSettings.Password)

Expand Down
3 changes: 1 addition & 2 deletions internal/config/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package config

import (
"github.com/spf13/viper"
"regexp"
)

type Configuration struct {
Expand Down Expand Up @@ -98,7 +97,7 @@ type FilterOverrides struct {
type ConnectionFilters struct {
NameExclusions string `yaml:"name_exclusions"`
ConnectionTypes []string `yaml:"valid_types"`
pattern *regexp.Regexp
// pattern *regexp.Regexp
}

// GrafanaConnection Default connection credentials
Expand Down
9 changes: 0 additions & 9 deletions internal/service/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,6 @@ func getFolderFromResourcePath(storageEngine string, filePath string, resourceTy
return "", errors.New("unable to parse resource to retrieve folder name")
}

func isResourceOrgNamespaces(resourceType config.ResourceType) bool {
if resourceType == config.DashboardResource {
return true
}

return false

}

func buildResourceFolder(folderName string, resourceType config.ResourceType) string {
if resourceType == config.DashboardResource && folderName == "" {
folderName = DefaultFolderName
Expand Down
2 changes: 1 addition & 1 deletion internal/service/dashboards.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ func (s *DashNGoImpl) UploadDashboards(filterReq filters.Filter) {

var (
rawBoard []byte
folderName string = ""
folderName string
folderId int64
)
path := config.Config().GetDefaultGrafanaConfig().GetPath(config.DashboardResource)
Expand Down
5 changes: 3 additions & 2 deletions internal/service/libraryelements.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"github.com/esnet/gdg/internal/config"
"github.com/esnet/gdg/internal/service/filters"
"github.com/esnet/gdg/internal/tools"
"github.com/esnet/grafana-swagger-api-golang/goclient/client/library_elements"
"github.com/esnet/grafana-swagger-api-golang/goclient/models"
"github.com/gosimple/slug"
Expand All @@ -23,7 +24,7 @@ type LibraryElementsApi interface {
DeleteAllLibraryElements(filter filters.Filter) []string
}

var (
const (
listLibraryPanels int64 = 1
listLibraryVars int64 = 2
)
Expand Down Expand Up @@ -72,7 +73,7 @@ func (s *DashNGoImpl) ListLibraryElements(filter filters.Filter) []*models.Libra

params := library_elements.NewGetLibraryElementsParams()
params.FolderFilter = &folderList
params.Kind = &listLibraryPanels
params.Kind = tools.PtrOf(listLibraryPanels)
libraryElements, err := s.client.LibraryElements.GetLibraryElements(params, s.getAuth())
if err != nil {
log.WithError(err).Fatal("Unable to list Library Elements")
Expand Down
3 changes: 0 additions & 3 deletions internal/service/organizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,6 @@ func (s *DashNGoImpl) UploadOrganizations() []string {
result []string
rawFolder []byte
)
if s.grafanaConf.IsAdminEnabled() {

}
filesInDir, err := s.storage.FindAllFiles(config.Config().GetDefaultGrafanaConfig().GetPath(config.OrganizationResource), false)
if err != nil {
log.WithError(err).Fatal("Failed to read folders imports")
Expand Down
3 changes: 1 addition & 2 deletions internal/service/serviceaccounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ func (s *DashNGoImpl) CreateServiceAccountToken(serviceAccountId int64, name str
}

func (s *DashNGoImpl) ListServiceAccounts() []*api.ServiceAccountDTOWithTokens {
result := make([]*api.ServiceAccountDTOWithTokens, 0)
p := service_accounts.NewSearchOrgServiceAccountsWithPagingParams()
p.Disabled = tools.PtrOf(false)
p.Perpage = tools.PtrOf(int64(5000))
Expand All @@ -64,7 +63,7 @@ func (s *DashNGoImpl) ListServiceAccounts() []*api.ServiceAccountDTOWithTokens {
log.Fatal("unable to retrieve service accounts")
}
data := resp.GetPayload()
result = lo.Map(data.ServiceAccounts, func(entity *models.ServiceAccountDTO, _ int) *api.ServiceAccountDTOWithTokens {
result := lo.Map(data.ServiceAccounts, func(entity *models.ServiceAccountDTO, _ int) *api.ServiceAccountDTOWithTokens {
t := api.ServiceAccountDTOWithTokens{
ServiceAccount: entity,
}
Expand Down
3 changes: 3 additions & 0 deletions internal/service/storage_cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,9 @@ func NewCloudStorage(c context.Context) (Storage, error) {
S3ForcePathStyle: aws.Bool(true),
Region: aws.String(getMapValue(Region, "us-east-1", stringEmpty, appData)),
})
if err != nil {
errorMsg = err.Error()
}
bucketObj, err = s3blob.OpenBucket(context.Background(), sess, appData["bucket_name"], nil)
if err != nil {
errorMsg = err.Error()
Expand Down
2 changes: 1 addition & 1 deletion internal/service/storage_local.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (s *LocalStorage) getBucket(baseFolder string) (*blob.Bucket, error) {
if _, err := os.Stat(baseFolder); err != nil {
_ = os.Mkdir(baseFolder, 0750)
}
opts := fileblob.Options {
opts := fileblob.Options{
NoTempDir: true,
}
return fileblob.OpenBucket(baseFolder, &opts)
Expand Down
38 changes: 17 additions & 21 deletions internal/service/teams.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,13 @@ func NewTeamFilter(entries ...string) filters.Filter {

filterObj.AddFilter(filters.Name, teamFilter)
filterObj.AddValidation(filters.Name, func(i interface{}) bool {
switch i.(type) {
switch val := i.(type) {
case string:
{
val := i.(string)
if filterObj.GetFilter(filters.Name) == "" {
return true
} else if val == filterObj.GetFilter(filters.Name) {
return true
}
if filterObj.GetFilter(filters.Name) == "" {
return true
} else if val == filterObj.GetFilter(filters.Name) {
return true
}

default:
return false
}
Expand All @@ -59,7 +55,7 @@ func NewTeamFilter(entries ...string) filters.Filter {
return filterObj
}

// Import Teams
// DownloadTeams fetches all teams for a given Org
func (s *DashNGoImpl) DownloadTeams(filter filters.Filter) map[*models.TeamDTO][]*models.TeamMemberDTO {
teamListing := maps.Keys(s.ListTeams(filter))
importedTeams := make(map[*models.TeamDTO][]*models.TeamMemberDTO)
Expand Down Expand Up @@ -201,17 +197,17 @@ func (s *DashNGoImpl) ListTeams(filter filters.Filter) map[*models.TeamDTO][]*mo

// Get a specific Team
// Return nil if team cannot be found
func (s *DashNGoImpl) getTeam(teamName string, filter filters.Filter) *models.TeamDTO {
teamListing := maps.Keys(s.ListTeams(filter))
var team *models.TeamDTO
for ndx, item := range teamListing {
if item.Name == teamName {
team = teamListing[ndx]
break
}
}
return team
}
//func (s *DashNGoImpl) getTeam(teamName string, filter filters.Filter) *models.TeamDTO {
// teamListing := maps.Keys(s.ListTeams(filter))
// var team *models.TeamDTO
// for ndx, item := range teamListing {
// if item.Name == teamName {
// team = teamListing[ndx]
// break
// }
// }
// return team
//}

// DeleteTeam removes all Teams
func (s *DashNGoImpl) DeleteTeam(filter filters.Filter) ([]*models.TeamDTO, error) {
Expand Down
Loading

0 comments on commit ac5f68b

Please sign in to comment.