Skip to content

Commit

Permalink
Merge pull request #2279 from konstructio/golangci
Browse files Browse the repository at this point in the history
Clean up code using GolangCI-Lint
  • Loading branch information
patrickdappollonio authored Sep 18, 2024
2 parents eec56ad + b2d8624 commit 55f3e82
Show file tree
Hide file tree
Showing 59 changed files with 1,237 additions and 1,282 deletions.
10 changes: 7 additions & 3 deletions .github/workflows/check-unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: "go.mod"
- name: Running Golang tests
run: go test -v -short ./...
go-version-file: go.mod
- name: Run GolangCI-Lint
uses: golangci/golangci-lint-action@v6
with:
version: v1.60.3
- name: Test application
run: go test -short -v ./...
121 changes: 121 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
run:
tests: false
concurrency: 5
timeout: 5m

linters:
disable-all: true
enable:
- gosimple
- govet
- ineffassign
- staticcheck
- unused
- asasalint
- asciicheck
- bidichk
- bodyclose
- contextcheck
- decorder
- dogsled
- dupl
- dupword
- durationcheck
- errchkjson
- errname
- errorlint
- exhaustive
- copyloopvar
- ginkgolinter
- gocheckcompilerdirectives
- gochecksumtype
- gocritic
- gocyclo
- gofmt
- gofumpt
- goheader
- goimports
- gomodguard
- goprintffuncname
- gosec
- gosmopolitan
- grouper
- importas
- inamedparam
- interfacebloat
- ireturn
- loggercheck
- makezero
- mirror
- misspell
- nakedret
- nilerr
- nilnil
- nonamedreturns
- nosprintfhostport
- paralleltest
- prealloc
- predeclared
- promlinter
- protogetter
- reassign
- revive
- rowserrcheck
- sloglint
- spancheck
- sqlclosecheck
- stylecheck
- tenv
- testableexamples
- testifylint
- testpackage
- thelper
- tparallel
- unconvert
- unparam
- usestdlibvars
- wastedassign
- whitespace
- wrapcheck
- zerologlint

linters-settings:
perfsprint:
int-conversion: false
err-error: false
errorf: true
sprintf1: true
strconcat: false

ireturn:
allow:
- anon
- error
- empty
- stdlib
- ssh.PublicKey
- tea.Model

gosec:
confidence: medium
excludes:
- G107 # Potential HTTP request made with variable url: these are often false positives or intentional
- G110 # Decompression bombs: we can check these manually when submitting code
- G306 # Poor file permissions used when creating a directory: we can check these manually when submitting code
- G404 # Use of weak random number generator (math/rand instead of crypto/rand): we can live with these

stylecheck:
checks:
- "all"
- "-ST1003" # this is covered by a different linter

gocyclo:
min-complexity: 60

exhaustive:
check-generated: false
explicit-exhaustive-switch: false
explicit-exhaustive-map: false
default-case-required: false
default-signifies-exhaustive: true
package-scope-only: false
11 changes: 5 additions & 6 deletions cmd/akamai/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func NewCommand() *cobra.Command {
Use: "akamai",
Short: "kubefirst akamai installation",
Long: "kubefirst akamai",
Run: func(cmd *cobra.Command, args []string) {
Run: func(_ *cobra.Command, _ []string) {
fmt.Println("To learn more about akamai in kubefirst, run:")
fmt.Println(" kubefirst beta akamai --help")

Expand Down Expand Up @@ -89,12 +89,12 @@ func Create() *cobra.Command {
createCmd.Flags().StringVar(&clusterTypeFlag, "cluster-type", "mgmt", "the type of cluster to create (i.e. mgmt|workload)")
createCmd.Flags().StringVar(&nodeCountFlag, "node-count", akamaiDefaults.NodeCount, "the node count for the cluster")
createCmd.Flags().StringVar(&nodeTypeFlag, "node-type", akamaiDefaults.InstanceSize, "the instance size of the cluster to create")
createCmd.Flags().StringVar(&dnsProviderFlag, "dns-provider", "cloudflare", fmt.Sprintf("the dns provider - one of: %s", supportedDNSProviders))
createCmd.Flags().StringVar(&dnsProviderFlag, "dns-provider", "cloudflare", fmt.Sprintf("the dns provider - one of: %q", supportedDNSProviders))
createCmd.Flags().StringVar(&subdomainNameFlag, "subdomain", "", "the subdomain to use for DNS records (Cloudflare)")
createCmd.Flags().StringVar(&domainNameFlag, "domain-name", "", "the DNS Name to use for DNS records (i.e. your-domain.com|subdomain.your-domain.com) (required)")
createCmd.MarkFlagRequired("domain-name")
createCmd.Flags().StringVar(&gitProviderFlag, "git-provider", "github", fmt.Sprintf("the git provider - one of: %s", supportedGitProviders))
createCmd.Flags().StringVar(&gitProtocolFlag, "git-protocol", "https", fmt.Sprintf("the git protocol - one of: %s", supportedGitProtocolOverride))
createCmd.Flags().StringVar(&gitProviderFlag, "git-provider", "github", fmt.Sprintf("the git provider - one of: %q", supportedGitProviders))
createCmd.Flags().StringVar(&gitProtocolFlag, "git-protocol", "https", fmt.Sprintf("the git protocol - one of: %q", supportedGitProtocolOverride))
createCmd.Flags().StringVar(&githubOrgFlag, "github-org", "", "the GitHub organization for the new gitops and metaphor repositories - required if using github")
createCmd.Flags().StringVar(&gitlabGroupFlag, "gitlab-group", "", "the GitLab group for the new gitops and metaphor projects - required if using gitlab")
createCmd.Flags().StringVar(&gitopsTemplateBranchFlag, "gitops-template-branch", "", "the branch to clone for the gitops-template repository")
Expand All @@ -112,7 +112,6 @@ func Destroy() *cobra.Command {
Short: "destroy the kubefirst platform",
Long: "destroy the kubefirst platform running in akamai and remove all resources",
RunE: common.Destroy,
// PreRun: common.CheckDocker,
}

return destroyCmd
Expand All @@ -126,7 +125,7 @@ func RootCredentials() *cobra.Command {
RunE: common.GetRootCredentials,
}

authCmd.Flags().BoolVar(&copyArgoCDPasswordToClipboardFlag, "argocd", false, "copy the argocd password to the clipboard (optional)")
authCmd.Flags().BoolVar(&copyArgoCDPasswordToClipboardFlag, "argocd", false, "copy the ArgoCD password to the clipboard (optional)")
authCmd.Flags().BoolVar(&copyKbotPasswordToClipboardFlag, "kbot", false, "copy the kbot password to the clipboard (optional)")
authCmd.Flags().BoolVar(&copyVaultPasswordToClipboardFlag, "vault", false, "copy the vault password to the clipboard (optional)")

Expand Down
26 changes: 12 additions & 14 deletions cmd/akamai/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import (
"github.com/spf13/viper"
)

func createAkamai(cmd *cobra.Command, args []string) error {
func createAkamai(cmd *cobra.Command, _ []string) error {
cliFlags, err := utilities.GetFlags(cmd, "akamai")
if err != nil {
progress.Error(err.Error())
Expand All @@ -42,11 +42,9 @@ func createAkamai(cmd *cobra.Command, args []string) error {
err = ValidateProvidedFlags(cliFlags.GitProvider)
if err != nil {
progress.Error(err.Error())
return fmt.Errorf("failed to validate provided flags: %w", err)
return fmt.Errorf("failed to validate flags: %w", err)
}

// If cluster setup is complete, return

utilities.CreateK1ClusterDirectory(clusterNameFlag)

gitAuth, err := gitShim.ValidateGitCredentials(cliFlags.GitProvider, cliFlags.GithubOrg, cliFlags.GitlabGroup)
Expand All @@ -55,7 +53,6 @@ func createAkamai(cmd *cobra.Command, args []string) error {
return fmt.Errorf("failed to validate git credentials: %w", err)
}

// Validate git
executionControl := viper.GetBool(fmt.Sprintf("kubefirst-checks.%s-credentials", cliFlags.GitProvider))
if !executionControl {
newRepositoryNames := []string{"gitops", "metaphor"}
Expand Down Expand Up @@ -87,13 +84,17 @@ func createAkamai(cmd *cobra.Command, args []string) error {
launch.Up(nil, true, cliFlags.UseTelemetry)
}

err = pkg.IsAppAvailable(fmt.Sprintf("%s/api/proxyHealth", cluster.GetConsoleIngresUrl()), "kubefirst api")
err = pkg.IsAppAvailable(fmt.Sprintf("%s/api/proxyHealth", cluster.GetConsoleIngressURL()), "kubefirst api")
if err != nil {
progress.Error("unable to start kubefirst api")
return fmt.Errorf("failed to check kubefirst api availability: %w", err)
}

provision.CreateMgmtCluster(gitAuth, cliFlags, catalogApps)
if err := provision.CreateMgmtCluster(gitAuth, cliFlags, catalogApps); err != nil {
progress.Error(err.Error())
return fmt.Errorf("failed to create management cluster: %w", err)
}

return nil
}

Expand All @@ -104,7 +105,6 @@ func ValidateProvidedFlags(gitProvider string) error {
return fmt.Errorf("your LINODE_TOKEN is not set - please set and re-run your last command")
}

// Validate required environment variables for dns provider
if dnsProviderFlag == "cloudflare" {
if os.Getenv("CF_API_TOKEN") == "" {
return fmt.Errorf("your CF_API_TOKEN environment variable is not set. Please set and try again")
Expand All @@ -115,17 +115,15 @@ func ValidateProvidedFlags(gitProvider string) error {
case "github":
key, err := internalssh.GetHostKey("github.com")
if err != nil {
return fmt.Errorf("known_hosts file does not exist - please run `ssh-keyscan github.com >> ~/.ssh/known_hosts` to remedy: %w", err)
} else {
log.Info().Msgf("%q %s", "github.com", key.Type())
return fmt.Errorf("failed to fetch github host key: %w", err)
}
log.Info().Msgf("%q %s", "github.com", key.Type())
case "gitlab":
key, err := internalssh.GetHostKey("gitlab.com")
if err != nil {
return fmt.Errorf("known_hosts file does not exist - please run `ssh-keyscan gitlab.com >> ~/.ssh/known_hosts` to remedy: %w", err)
} else {
log.Info().Msgf("%q %s", "gitlab.com", key.Type())
return fmt.Errorf("failed to fetch gitlab host key: %w", err)
}
log.Info().Msgf("%q %s", "gitlab.com", key.Type())
}

progress.CompleteStep("Validate provided flags")
Expand Down
8 changes: 4 additions & 4 deletions cmd/aws/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func NewCommand() *cobra.Command {
Use: "aws",
Short: "kubefirst aws installation",
Long: "kubefirst aws",
Run: func(cmd *cobra.Command, args []string) {
Run: func(_ *cobra.Command, _ []string) {
fmt.Println("To learn more about aws in kubefirst, run:")
fmt.Println(" kubefirst help")

Expand Down Expand Up @@ -85,12 +85,12 @@ func Create() *cobra.Command {
createCmd.Flags().StringVar(&clusterTypeFlag, "cluster-type", "mgmt", "the type of cluster to create (i.e. mgmt|workload)")
createCmd.Flags().StringVar(&nodeCountFlag, "node-count", awsDefaults.NodeCount, "the node count for the cluster")
createCmd.Flags().StringVar(&nodeTypeFlag, "node-type", awsDefaults.InstanceSize, "the instance size of the cluster to create")
createCmd.Flags().StringVar(&dnsProviderFlag, "dns-provider", "aws", fmt.Sprintf("the dns provider - one of: %s", supportedDNSProviders))
createCmd.Flags().StringVar(&dnsProviderFlag, "dns-provider", "aws", fmt.Sprintf("the dns provider - one of: %q", supportedDNSProviders))
createCmd.Flags().StringVar(&subdomainNameFlag, "subdomain", "", "the subdomain to use for DNS records (Cloudflare)")
createCmd.Flags().StringVar(&domainNameFlag, "domain-name", "", "the Route53/Cloudflare hosted zone name to use for DNS records (i.e. your-domain.com|subdomain.your-domain.com) (required)")
createCmd.MarkFlagRequired("domain-name")
createCmd.Flags().StringVar(&gitProviderFlag, "git-provider", "github", fmt.Sprintf("the git provider - one of: %s", supportedGitProviders))
createCmd.Flags().StringVar(&gitProtocolFlag, "git-protocol", "ssh", fmt.Sprintf("the git protocol - one of: %s", supportedGitProtocolOverride))
createCmd.Flags().StringVar(&gitProviderFlag, "git-provider", "github", fmt.Sprintf("the git provider - one of: %q", supportedGitProviders))
createCmd.Flags().StringVar(&gitProtocolFlag, "git-protocol", "ssh", fmt.Sprintf("the git protocol - one of: %q", supportedGitProtocolOverride))
createCmd.Flags().StringVar(&githubOrgFlag, "github-org", "", "the GitHub organization for the new gitops and metaphor repositories - required if using github")
createCmd.Flags().StringVar(&gitlabGroupFlag, "gitlab-group", "", "the GitLab group for the new gitops and metaphor projects - required if using gitlab")
createCmd.Flags().StringVar(&gitopsTemplateBranchFlag, "gitops-template-branch", "", "the branch to clone for the gitops-template repository")
Expand Down
40 changes: 23 additions & 17 deletions cmd/aws/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import (
"github.com/spf13/viper"
)

func createAws(cmd *cobra.Command, args []string) error {
func createAws(cmd *cobra.Command, _ []string) error {
cliFlags, err := utilities.GetFlags(cmd, "aws")
if err != nil {
progress.Error(err.Error())
Expand All @@ -38,13 +38,13 @@ func createAws(cmd *cobra.Command, args []string) error {

isValid, catalogApps, err := catalog.ValidateCatalogApps(cliFlags.InstallCatalogApps)
if !isValid {
return err
return fmt.Errorf("invalid catalog apps: %w", err)
}

err = ValidateProvidedFlags(cliFlags.GitProvider)
if err != nil {
progress.Error(err.Error())
return nil
return fmt.Errorf("failed to validate provided flags: %w", err)
}

utilities.CreateK1ClusterDirectory(cliFlags.ClusterName)
Expand All @@ -64,24 +64,26 @@ func createAws(cmd *cobra.Command, args []string) error {
creds, err := awsClient.Config.Credentials.Retrieve(aws.BackgroundContext())
if err != nil {
progress.Error(err.Error())
return nil
return fmt.Errorf("failed to retrieve AWS credentials: %w", err)
}

viper.Set("kubefirst.state-store-creds.access-key-id", creds.AccessKeyID)
viper.Set("kubefirst.state-store-creds.secret-access-key-id", creds.SecretAccessKey)
viper.Set("kubefirst.state-store-creds.token", creds.SessionToken)
viper.WriteConfig()
if err := viper.WriteConfig(); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}

_, err = awsClient.CheckAvailabilityZones(cliFlags.CloudRegion)
if err != nil {
progress.Error(err.Error())
return nil
return fmt.Errorf("failed to check availability zones: %w", err)
}

gitAuth, err := gitShim.ValidateGitCredentials(cliFlags.GitProvider, cliFlags.GithubOrg, cliFlags.GitlabGroup)
if err != nil {
progress.Error(err.Error())
return nil
return fmt.Errorf("failed to validate Git credentials: %w", err)
}

executionControl := viper.GetBool(fmt.Sprintf("kubefirst-checks.%s-credentials", cliFlags.GitProvider))
Expand All @@ -100,12 +102,14 @@ func createAws(cmd *cobra.Command, args []string) error {
err = gitShim.InitializeGitProvider(&initGitParameters)
if err != nil {
progress.Error(err.Error())
return nil
return fmt.Errorf("failed to initialize Git provider: %w", err)
}
}

viper.Set(fmt.Sprintf("kubefirst-checks.%s-credentials", cliFlags.GitProvider), true)
viper.WriteConfig()
if err := viper.WriteConfig(); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}

k3dClusterCreationComplete := viper.GetBool("launch.deployed")
isK1Debug := strings.ToLower(os.Getenv("K1_LOCAL_DEBUG")) == "true"
Expand All @@ -114,12 +118,16 @@ func createAws(cmd *cobra.Command, args []string) error {
launch.Up(nil, true, cliFlags.UseTelemetry)
}

err = pkg.IsAppAvailable(fmt.Sprintf("%s/api/proxyHealth", cluster.GetConsoleIngresUrl()), "kubefirst api")
err = pkg.IsAppAvailable(fmt.Sprintf("%s/api/proxyHealth", cluster.GetConsoleIngressURL()), "kubefirst api")
if err != nil {
progress.Error("unable to start kubefirst api")
return fmt.Errorf("failed to check kubefirst API availability: %w", err)
}

provision.CreateMgmtCluster(gitAuth, cliFlags, catalogApps)
if err := provision.CreateMgmtCluster(gitAuth, cliFlags, catalogApps); err != nil {
progress.Error(err.Error())
return fmt.Errorf("failed to create management cluster: %w", err)
}

return nil
}
Expand All @@ -138,17 +146,15 @@ func ValidateProvidedFlags(gitProvider string) error {
case "github":
key, err := internalssh.GetHostKey("github.com")
if err != nil {
return fmt.Errorf("known_hosts file does not exist - please run `ssh-keyscan github.com >> ~/.ssh/known_hosts` to remedy")
} else {
log.Info().Msgf("%s %s\n", "github.com", key.Type())
return fmt.Errorf("known_hosts file does not exist - please run `ssh-keyscan github.com >> ~/.ssh/known_hosts` to remedy: %w", err)
}
log.Info().Msgf("%q %s", "github.com", key.Type())
case "gitlab":
key, err := internalssh.GetHostKey("gitlab.com")
if err != nil {
return fmt.Errorf("known_hosts file does not exist - please run `ssh-keyscan gitlab.com >> ~/.ssh/known_hosts` to remedy")
} else {
log.Info().Msgf("%s %s\n", "gitlab.com", key.Type())
return fmt.Errorf("known_hosts file does not exist - please run `ssh-keyscan gitlab.com >> ~/.ssh/known_hosts` to remedy: %w", err)
}
log.Info().Msgf("%q %s", "gitlab.com", key.Type())
}

progress.CompleteStep("Validate provided flags")
Expand Down
Loading

0 comments on commit 55f3e82

Please sign in to comment.