Skip to content

Commit

Permalink
lint(nilaway): Fixed nilaway errors
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Kosiewski <[email protected]>
  • Loading branch information
ThomasK33 committed Jul 10, 2024
1 parent b7562e1 commit e16b96a
Show file tree
Hide file tree
Showing 85 changed files with 943 additions and 376 deletions.
7 changes: 6 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ linters:
- misspell
- nakedret
- nilaway
- nilnil
- promlinter
- revive
- sloglint
- staticcheck
- stylecheck
- tagalign
Expand All @@ -41,7 +43,6 @@ linters:

# next linters to be enabled:
# - prealloc
# - nilnil
# - errchkjson
# - gocritic

Expand Down Expand Up @@ -82,6 +83,7 @@ linters-settings:

tagalign:
order:
- protobuf
- json
- yaml
- xml
Expand All @@ -95,6 +97,9 @@ linters-settings:
# Settings must be a "map from string to string" to mimic command line flags: the keys are
# flag names and the values are the values to the particular flags.
include-pkgs: "github.com/loft-sh/vcluster"
exclude-pkgs: "github.com/loft-sh/vcluster/test"
experimental-anonymous-function: "true"
# experimental-struct-init: "true"

issues:
# Maximum issues count per one linter. Set to 0 to disable. Default is 50.
Expand Down
14 changes: 12 additions & 2 deletions cmd/vclusterctl/cmd/disconnect.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"errors"
"fmt"

"github.com/loft-sh/log"
Expand Down Expand Up @@ -52,9 +53,14 @@ vcluster disconnect

// Run executes the functionality
func (cmd *DisconnectCmd) Run() error {
rawConfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{
clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{
CurrentContext: cmd.Context,
}).RawConfig()
})
if clientConfig == nil {
return errors.New("nil clientConfig")
}

rawConfig, err := clientConfig.RawConfig()
if err != nil {
return err
}
Expand Down Expand Up @@ -102,6 +108,10 @@ func (cmd *DisconnectCmd) Run() error {
}

func (cmd *DisconnectCmd) selectContext(kubeConfig *clientcmdapi.Config, currentContext string) (string, error) {
if kubeConfig == nil {
return "", errors.New("nil kubeConfig")
}

availableContexts := []string{}
for context := range kubeConfig.Contexts {
if context != currentContext {
Expand Down
2 changes: 1 addition & 1 deletion cmd/vclusterctl/cmd/platform/add/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ func (cmd *ClusterCmd) Run(ctx context.Context, args []string) error {
return false, err
}

return clusterInstance.Status.Phase == storagev1.ClusterStatusPhaseInitialized, nil
return clusterInstance != nil && clusterInstance.Status.Phase == storagev1.ClusterStatusPhaseInitialized, nil
})
if waitErr != nil {
return fmt.Errorf("get cluster: %w", waitErr)
Expand Down
14 changes: 9 additions & 5 deletions cmd/vclusterctl/cmd/platform/get/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ import (
"k8s.io/client-go/tools/clientcmd/api"
)

var (
ErrNotLoftContext = errors.New("current context is not a loft context, but predefined var LOFT_CLUSTER is used")
)
var ErrNotLoftContext = errors.New("current context is not a loft context, but predefined var LOFT_CLUSTER is used")

type clusterCmd struct {
*flags.GlobalFlags
Expand Down Expand Up @@ -92,7 +90,10 @@ func (c *clusterCmd) Run(ctx context.Context, _ []string) error {
return err
}

_, err = os.Stdout.Write([]byte(spaceInstance.Spec.ClusterRef.Cluster))
if spaceInstance != nil {
_, err = os.Stdout.Write([]byte(spaceInstance.Spec.ClusterRef.Cluster))
}

return err
}

Expand All @@ -117,7 +118,10 @@ func (c *clusterCmd) Run(ctx context.Context, _ []string) error {
return err
}

_, err = os.Stdout.Write([]byte(virtualClusterInstance.Spec.ClusterRef.Cluster))
if virtualClusterInstance != nil {
_, err = os.Stdout.Write([]byte(virtualClusterInstance.Spec.ClusterRef.Cluster))
}

return err
}

Expand Down
7 changes: 6 additions & 1 deletion cmd/vclusterctl/cmd/platform/get/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,14 @@ func (cmd *SecretCmd) Run(ctx context.Context, args []string) error {
keyNames = append(keyNames, k)
}

defaultValue := ""
if len(keyNames) > 0 {
defaultValue = keyNames[0]
}

keyName, err = cmd.log.Question(&survey.QuestionOptions{
Question: "Please select a secret key to read",
DefaultValue: keyNames[0],
DefaultValue: defaultValue,
Options: keyNames,
})
if err != nil {
Expand Down
9 changes: 7 additions & 2 deletions cmd/vclusterctl/cmd/platform/reset.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,12 @@ import (

type PasswordCmd struct {
*flags.GlobalFlags
Log log.Logger

User string
Password string
Create bool
Force bool

Log log.Logger
}

func NewResetCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Expand Down Expand Up @@ -127,6 +126,9 @@ func (cmd *PasswordCmd) Run() error {
return err
}
}
if user == nil {
return errors.New("could not obtain user")
}

// check if user had a password before
if user.Spec.PasswordRef == nil || user.Spec.PasswordRef.SecretName == "" || user.Spec.PasswordRef.SecretNamespace == "" || user.Spec.PasswordRef.Key == "" {
Expand Down Expand Up @@ -184,6 +186,9 @@ func (cmd *PasswordCmd) Run() error {
return errors.Wrap(err, "create password secret")
}
} else {
if passwordSecret == nil {
passwordSecret = &corev1.Secret{}
}
if passwordSecret.Data == nil {
passwordSecret.Data = map[string][]byte{}
}
Expand Down
38 changes: 21 additions & 17 deletions cmd/vclusterctl/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import (
)

// NewRootCmd returns a new root command
func NewRootCmd(log log.Logger) *cobra.Command {
func NewRootCmd(log log.Logger, globalFlags *flags.GlobalFlags) *cobra.Command {
return &cobra.Command{
Use: "vcluster",
SilenceUsage: true,
Expand Down Expand Up @@ -57,8 +57,6 @@ func NewRootCmd(log log.Logger) *cobra.Command {
}
}

var globalFlags *flags.GlobalFlags

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
Expand All @@ -69,16 +67,16 @@ func Execute() {

// start command
log := log.GetInstance()
rootCmd, err := BuildRoot(log)
rootCmd, globalFlags, err := BuildRoot(log)
if err != nil {
log.Fatalf("error building root: %+v\n", err)
}

// Execute command
err = rootCmd.ExecuteContext(context.Background())
recordAndFlush(err, log)
recordAndFlush(err, log, globalFlags)
if err != nil {
if globalFlags.Debug {
if globalFlags != nil && globalFlags.Debug {
log.Fatalf("%+v", err)
}

Expand All @@ -87,18 +85,20 @@ func Execute() {
}

// BuildRoot creates a new root command from the
func BuildRoot(log log.Logger) (*cobra.Command, error) {
rootCmd := NewRootCmd(log)
func BuildRoot(log log.Logger) (*cobra.Command, *flags.GlobalFlags, error) {
var globalFlags *flags.GlobalFlags
rootCmd := NewRootCmd(log, globalFlags)
persistentFlags := rootCmd.PersistentFlags()
globalFlags = flags.SetGlobalFlags(persistentFlags, log)

home, err := homedir.Dir()
if err != nil {
return nil, err
return nil, nil, err
}
defaults, err := defaults.NewFromPath(filepath.Join(home, defaults.ConfigFolder), defaults.ConfigFile)
if err != nil {
log.Debugf("Error loading defaults: %v", err)
return nil, err
return nil, nil, err
}

// Set version for --version flag
Expand All @@ -123,39 +123,43 @@ func BuildRoot(log log.Logger) (*cobra.Command, error) {
// add platform commands
platformCmd, err := cmdplatform.NewPlatformCmd(globalFlags)
if err != nil {
return nil, fmt.Errorf("failed to create platform command: %w", err)
return nil, nil, fmt.Errorf("failed to create platform command: %w", err)
}
rootCmd.AddCommand(platformCmd)

loginCmd, err := NewLoginCmd(globalFlags)
if err != nil {
return nil, fmt.Errorf("failed to create login command: %w", err)
return nil, nil, fmt.Errorf("failed to create login command: %w", err)
}
rootCmd.AddCommand(loginCmd)

logoutCmd, err := NewLogoutCmd(globalFlags)
if err != nil {
return nil, fmt.Errorf("failed to create logout command: %w", err)
return nil, nil, fmt.Errorf("failed to create logout command: %w", err)
}
rootCmd.AddCommand(logoutCmd)

uiCmd, err := NewUICmd(globalFlags)
if err != nil {
return nil, fmt.Errorf("failed to create ui command: %w", err)
return nil, nil, fmt.Errorf("failed to create ui command: %w", err)
}
rootCmd.AddCommand(uiCmd)
rootCmd.AddCommand(credits.NewCreditsCmd())

// add completion command
err = rootCmd.RegisterFlagCompletionFunc("namespace", completion.NewNamespaceCompletionFunc(rootCmd.Context()))
if err != nil {
return rootCmd, fmt.Errorf("failed to register completion for namespace: %w", err)
return nil, nil, fmt.Errorf("failed to register completion for namespace: %w", err)
}

return rootCmd, nil
return rootCmd, globalFlags, nil
}

func recordAndFlush(err error, log log.Logger) {
func recordAndFlush(err error, log log.Logger, globalFlags *flags.GlobalFlags) {
if globalFlags == nil {
panic("empty global flags")
}

telemetry.CollectorCLI.RecordCLI(globalFlags.LoadedConfig(log), platform.Self, err)
telemetry.CollectorCLI.Flush()
}
22 changes: 11 additions & 11 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -1226,31 +1226,31 @@ type VolumeClaim struct {
// VolumeMount describes a mounting of a Volume within a container.
type VolumeMount struct {
// This must match the Name of a Volume.
Name string `json:"name" protobuf:"bytes,1,opt,name=name"`
Name string `protobuf:"bytes,1,opt,name=name" json:"name"`

// Mounted read-only if true, read-write otherwise (false or unspecified).
// Defaults to false.
ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,2,opt,name=readOnly"`
ReadOnly bool `protobuf:"varint,2,opt,name=readOnly" json:"readOnly,omitempty"`

// Path within the container at which the volume should be mounted. Must
// not contain ':'.
MountPath string `json:"mountPath" protobuf:"bytes,3,opt,name=mountPath"`
MountPath string `protobuf:"bytes,3,opt,name=mountPath" json:"mountPath"`

// Path within the volume from which the container's volume should be mounted.
// Defaults to "" (volume's root).
SubPath string `json:"subPath,omitempty" protobuf:"bytes,4,opt,name=subPath"`
SubPath string `protobuf:"bytes,4,opt,name=subPath" json:"subPath,omitempty"`

// mountPropagation determines how mounts are propagated from the host
// to container and the other way around.
// When not set, MountPropagationNone is used.
// This field is beta in 1.10.
MountPropagation *string `json:"mountPropagation,omitempty" protobuf:"bytes,5,opt,name=mountPropagation,casttype=MountPropagationMode"`
MountPropagation *string `protobuf:"bytes,5,opt,name=mountPropagation,casttype=MountPropagationMode" json:"mountPropagation,omitempty"`

// Expanded path within the volume from which the container's volume should be mounted.
// Behaves similarly to SubPath but environment variable references $(VAR_NAME) are expanded using the container's environment.
// Defaults to "" (volume's root).
// SubPathExpr and SubPath are mutually exclusive.
SubPathExpr string `json:"subPathExpr,omitempty" protobuf:"bytes,6,opt,name=subPathExpr"`
SubPathExpr string `protobuf:"bytes,6,opt,name=subPathExpr" json:"subPathExpr,omitempty"`
}

type ControlPlaneScheduling struct {
Expand Down Expand Up @@ -1461,7 +1461,7 @@ type MutatingWebhookConfiguration struct {
type MutatingWebhook struct {
// reinvocationPolicy indicates whether this webhook should be called multiple times as part of a single admission evaluation.
// Allowed values are "Never" and "IfNeeded".
ReinvocationPolicy *string `json:"reinvocationPolicy,omitempty" protobuf:"bytes,10,opt,name=reinvocationPolicy,casttype=ReinvocationPolicyType"`
ReinvocationPolicy *string `protobuf:"bytes,10,opt,name=reinvocationPolicy,casttype=ReinvocationPolicyType" json:"reinvocationPolicy,omitempty"`

ValidatingWebhook `json:",inline"`
}
Expand Down Expand Up @@ -1963,16 +1963,16 @@ type DenyRule struct {

type RuleWithVerbs struct {
// APIGroups is the API groups the resources belong to. '*' is all groups.
APIGroups []string `json:"apiGroups,omitempty" protobuf:"bytes,1,rep,name=apiGroups"`
APIGroups []string `protobuf:"bytes,1,rep,name=apiGroups" json:"apiGroups,omitempty"`

// APIVersions is the API versions the resources belong to. '*' is all versions.
APIVersions []string `json:"apiVersions,omitempty" protobuf:"bytes,2,rep,name=apiVersions"`
APIVersions []string `protobuf:"bytes,2,rep,name=apiVersions" json:"apiVersions,omitempty"`

// Resources is a list of resources this rule applies to.
Resources []string `json:"resources,omitempty" protobuf:"bytes,3,rep,name=resources"`
Resources []string `protobuf:"bytes,3,rep,name=resources" json:"resources,omitempty"`

// Scope specifies the scope of this rule.
Scope *string `json:"scope,omitempty" protobuf:"bytes,4,rep,name=scope"`
Scope *string `protobuf:"bytes,4,rep,name=scope" json:"scope,omitempty"`

// Verb is the kube verb associated with the request for API requests, not the http verb. This includes things like list and watch.
// For non-resource requests, this is the lowercase http verb.
Expand Down
10 changes: 5 additions & 5 deletions config/legacyconfig/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,22 +267,22 @@ type RBACRoleValues struct {

type RBACRule struct {
// Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs.
Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"`
Verbs []string `protobuf:"bytes,1,rep,name=verbs" json:"verbs"`
// APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of
// the enumerated resources in any API group will be allowed. "" represents the core API group and "*" represents all API groups.
// +optional
APIGroups []string `json:"apiGroups,omitempty" protobuf:"bytes,2,rep,name=apiGroups"`
APIGroups []string `protobuf:"bytes,2,rep,name=apiGroups" json:"apiGroups,omitempty"`
// Resources is a list of resources this rule applies to. '*' represents all resources.
// +optional
Resources []string `json:"resources,omitempty" protobuf:"bytes,3,rep,name=resources"`
Resources []string `protobuf:"bytes,3,rep,name=resources" json:"resources,omitempty"`
// ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.
// +optional
ResourceNames []string `json:"resourceNames,omitempty" protobuf:"bytes,4,rep,name=resourceNames"`
ResourceNames []string `protobuf:"bytes,4,rep,name=resourceNames" json:"resourceNames,omitempty"`
// NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path
// Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding.
// Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"), but not both.
// +optional
NonResourceURLs []string `json:"nonResourceURLs,omitempty" protobuf:"bytes,5,rep,name=nonResourceURLs"`
NonResourceURLs []string `protobuf:"bytes,5,rep,name=nonResourceURLs" json:"nonResourceURLs,omitempty"`
}

type PDBValues struct {
Expand Down
3 changes: 3 additions & 0 deletions hack/compat-matrix/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ func updateTableWithDistro(distroName string, versionMap map[string]string, know

for hostVersion, issueList := range issues {
for vclusterAPI, issueDesc := range issueList {
if issues[hostVersion] == nil {
issues[hostVersion] = make(map[string]string, 0)
}
issues[hostVersion][removeRegistry(vclusterAPI)] = issueDesc
if removeRegistry(vclusterAPI) != vclusterAPI {
// avoids removing valid entries
Expand Down
Loading

0 comments on commit e16b96a

Please sign in to comment.