Skip to content

Commit

Permalink
Refactor with golangci-lint suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
BigPapaChas committed Jul 15, 2022
1 parent b451ca4 commit ba1a618
Show file tree
Hide file tree
Showing 10 changed files with 158 additions and 100 deletions.
11 changes: 1 addition & 10 deletions cmd/gogok8s/main.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,11 @@
package main

import (
"errors"
"os"

"github.com/BigPapaChas/gogok8s/internal/commands"
"github.com/BigPapaChas/gogok8s/internal/terminal"
)

func main() {
if err := commands.Execute(); err != nil {
if errors.Is(err, terminal.ErrUserQuit) {
os.Exit(130)
}

terminal.PrintError(err.Error())
os.Exit(1)
}
os.Exit(commands.Execute())
}
6 changes: 3 additions & 3 deletions internal/clusters/clusters.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ func GetPatchFromAccounts(accounts []EKSAccount) PatchResult {
patch := PatchResult{
Patch: &kubecfg.KubeConfigPatch{},
}
c := make(chan PatchResult, len(accounts))
resultChan := make(chan PatchResult, len(accounts))

spinner, _ := terminal.StartNewSpinner("Fetching EKS clusters from accounts...")

for _, account := range accounts {
go func(account EKSAccount) {
accountPatch, accountErrors := account.GenerateKubeConfigPatch()

c <- PatchResult{
resultChan <- PatchResult{
Patch: accountPatch,
Errors: accountErrors,
AccountName: account.Name,
Expand All @@ -32,7 +32,7 @@ func GetPatchFromAccounts(accounts []EKSAccount) PatchResult {
}

for range accounts {
result := <-c
result := <-resultChan
patch.Patch.Users = append(patch.Patch.Users, result.Patch.Users...)
patch.Patch.Clusters = append(patch.Patch.Clusters, result.Patch.Clusters...)
patch.Patch.Contexts = append(patch.Patch.Contexts, result.Patch.Contexts...)
Expand Down
20 changes: 10 additions & 10 deletions internal/clusters/eks.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,30 +60,30 @@ func (a *EKSAccount) GenerateKubeConfigPatch() (*kubecfg.KubeConfigPatch, []erro

var allErrors []error

c := make(chan DescribeRegionResult, len(a.Regions))

resultChan := make(chan DescribeRegionResult, len(a.Regions))
client := eks.NewFromConfig(cfg)

for _, region := range a.Regions {
go func(eksClient *eks.Client, eksRegion string) {
clusterNames, err := listClusters(eksClient, eksRegion)
if err != nil {
c <- DescribeRegionResult{
resultChan <- DescribeRegionResult{
Errors: []error{fmt.Errorf("account='%s' region='%s': %w", a.Name, eksRegion, err)},
}

return
}

clusters, errors := getClusters(eksClient, clusterNames, eksRegion)
c <- DescribeRegionResult{
resultChan <- DescribeRegionResult{
Clusters: clusters,
Errors: errors,
}
}(client, region)
}

for range a.Regions {
result := <-c
result := <-resultChan
allClusters = append(allClusters, result.Clusters...)
allErrors = append(allErrors, result.Errors...)
}
Expand Down Expand Up @@ -171,20 +171,20 @@ func getClusters(client *eks.Client, clusterNames []string, region string) ([]*E

var errors []error

c := make(chan DescribeClusterResult, len(clusterNames))
resultChan := make(chan DescribeClusterResult, len(clusterNames))

for _, clusterName := range clusterNames {
go func(client *eks.Client, clusterName, region string) {
description, err := describeCluster(client, clusterName, region)
if err != nil {
c <- DescribeClusterResult{Error: err}
resultChan <- DescribeClusterResult{Error: err}

return
}

decodedCertData, _ := base64.StdEncoding.DecodeString(*description.Cluster.CertificateAuthority.Data)

c <- DescribeClusterResult{
resultChan <- DescribeClusterResult{
Cluster: &EKSCluster{
Name: clusterName,
Region: region,
Expand All @@ -198,7 +198,7 @@ func getClusters(client *eks.Client, clusterNames []string, region string) ([]*E
}

for range clusterNames {
result := <-c
result := <-resultChan
if result.Error != nil {
// DescribeCluster encountered an error, add to list of errors and continue to next result
errors = append(errors, result.Error)
Expand Down Expand Up @@ -238,7 +238,7 @@ func listClusters(client *eks.Client, region string) ([]string, error) {
o.Region = region
})
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to list EKS clusters: %w", err)
}

return output.Clusters, nil
Expand Down
25 changes: 16 additions & 9 deletions internal/commands/configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ import (
"path"

"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/BigPapaChas/gogok8s/internal/clusters"
"github.com/BigPapaChas/gogok8s/internal/config"
"github.com/BigPapaChas/gogok8s/internal/terminal"
)

//nolint:gochecknoglobals
var configCmd = &cobra.Command{
Use: "configure",
Short: "create a new account entry within the .gogok8s.yaml file",
Expand All @@ -21,8 +23,13 @@ var configCmd = &cobra.Command{
if debug {
terminal.EnableDebug()
}
if cfg != nil {
return cfg.Validate()

if cfg == nil {
return nil
}

if err := cfg.Validate(); err != nil {
return fmt.Errorf("error validating config: %w", err)
}

return nil
Expand All @@ -34,7 +41,7 @@ var configCmd = &cobra.Command{
// An existing gogok8s config file was not found, prompt user for filename to use
home, err := os.UserHomeDir()
if err != nil {
return err
return fmt.Errorf("failed to find user home directory: %w", err)
}

var defaultFilename string
Expand All @@ -45,25 +52,25 @@ var configCmd = &cobra.Command{
}
filename, err = terminal.PromptDefault("Gogok8s config file", defaultFilename)
if err != nil {
return err
return fmt.Errorf("failed to get gogok8s config file: %w", err)
}

cfg = config.NewConfig()
}

accountName, err := terminal.PromptWithValidate("Account name", "", cfg.IsValidAccountName)
if err != nil {
return err
return fmt.Errorf("failed to select AWS account: %w", err)
}

profile, err := terminal.PromptDefault("AWS Profile", "")
if err != nil {
return err
return fmt.Errorf("failed to select AWS profile: %w", err)
}

regions, err := terminal.MultiSelect("AWS regions", config.ValidRegions)
if err != nil {
return err
return fmt.Errorf("failed to select AWS regions: %w", err)
}

account := clusters.EKSAccount{
Expand All @@ -77,12 +84,12 @@ var configCmd = &cobra.Command{
// A new configuration file was created, write the updated config to the user-specified filename
terminal.PrintDebug(filename)
if err := cfg.WriteToFile(filename); err != nil {
return err
return fmt.Errorf("failed to write %s config: %w", filename, err)
}
} else {
// An existing configuration is being modified, write to the location that was used when running the command
if err := cfg.Write(); err != nil {
return err
return fmt.Errorf("failed to write %s config: %w", viper.ConfigFileUsed(), err)
}
}
terminal.TextSuccess(fmt.Sprintf("account %s added", accountName))
Expand Down
32 changes: 27 additions & 5 deletions internal/commands/root.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package commands

import (
"errors"
"os"

"github.com/spf13/cobra"
Expand All @@ -10,18 +11,26 @@ import (
"github.com/BigPapaChas/gogok8s/internal/terminal"
)

const (
exitCodeUserQuit = 130
exitCodeError = 1
exitCodeNoError = 0
)

var (
cfgFile string
cfg *config.Config
debug bool
cfgFile string //nolint:gochecknoglobals
cfg *config.Config //nolint:gochecknoglobals
debug bool //nolint:gochecknoglobals
)

//nolint:gochecknoglobals
var rootCmd = &cobra.Command{
Use: "gogok8s",
Short: "gogok8s helps manage your k8s cluster kubeconfig(s)",
Version: "v0.0.9",
}

//nolint:gochecknoinits
func init() {
cobra.OnInitialize(initConfig)

Expand Down Expand Up @@ -58,6 +67,19 @@ func initConfig() {
}
}

func Execute() error {
return rootCmd.Execute()
func Execute() int {
var code int

if err := rootCmd.Execute(); err != nil {
if errors.Is(errors.Unwrap(err), terminal.ErrUserQuit) {
code = exitCodeUserQuit
} else {
terminal.PrintError(err.Error())
code = exitCodeError
}
} else {
code = exitCodeNoError
}

return code
}
9 changes: 7 additions & 2 deletions internal/commands/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

var errConfigNotExist = errors.New("couldn't find .gogok8s.yaml in home directory, try running `gogok8s configure`")

//nolint:gochecknoglobals
var syncCommand = &cobra.Command{
Use: "sync [accounts]",
Short: "syncs your kubeconfig with all available k8s clusters",
Expand All @@ -24,7 +25,11 @@ var syncCommand = &cobra.Command{
return errConfigNotExist
}

return cfg.Validate()
if err := cfg.Validate(); err != nil {
return fmt.Errorf("error validating config: %w", err)
}

return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
dryRun, _ := cmd.Flags().GetBool("dry-run")
Expand Down Expand Up @@ -75,7 +80,7 @@ func syncKubernetesClusters(dryRun, purge bool, accounts []string) error {

err = kubecfg.Write(kubeconfig)
if err != nil {
return err
return fmt.Errorf("failed to write to kubeconfig: %w", err)
}

terminal.TextSuccess("kubeconfig updated")
Expand Down
Loading

0 comments on commit ba1a618

Please sign in to comment.