Skip to content

Commit

Permalink
lint: enable gocritic configuration and fix findings
Browse files Browse the repository at this point in the history
  • Loading branch information
MrDXY committed Sep 5, 2023
1 parent e9b09f6 commit 21f31e0
Show file tree
Hide file tree
Showing 23 changed files with 123 additions and 130 deletions.
42 changes: 21 additions & 21 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -68,27 +68,27 @@ linters-settings:
exclude:
- '^ \+.*'
- '^ ANCHOR.*'
# gocritic:
# enabled-tags:
# - diagnostic
# - experimental
# - performance
# disabled-checks:
# - appendAssign
# - dupImport # https://github.com/go-critic/go-critic/issues/845
# - evalOrder
# - ifElseChain
# - octalLiteral
# - regexpSimplify
# - sloppyReassign
# - truncateCmp
# - typeDefFirst
# - unnamedResult
# - unnecessaryDefer
# - whyNoLint
# - wrapperFunc
# - rangeValCopy
# - hugeParam
gocritic:
enabled-tags:
- diagnostic
- experimental
- performance
disabled-checks:
- appendAssign
- dupImport # https://github.com/go-critic/go-critic/issues/845
- evalOrder
- ifElseChain
- octalLiteral
- regexpSimplify
- sloppyReassign
- truncateCmp
- typeDefFirst
- unnamedResult
- unnecessaryDefer
- whyNoLint
- wrapperFunc
- rangeValCopy
- hugeParam
importas:
no-unaliased: true
alias:
Expand Down
1 change: 0 additions & 1 deletion apis/v1alpha3/cloudprovider_encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,6 @@ func TestUnmarshalINI(t *testing.T) {
},
}

//nolint:gocritic
testCases := append(
testcases,
deprecatedTestCases...,
Expand Down
2 changes: 1 addition & 1 deletion apis/v1alpha3/cloudprovider_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ limitations under the License.
//
// The "gopkg.in/go-ini/ini.v1" package was investigated, but it does not
// support reflecting a struct with a field of type "map[string]TYPE" to INI.
//nolint:gocritic,godot

package v1alpha3

// CPIConfig is the vSphere cloud provider's configuration.
Expand Down
1 change: 0 additions & 1 deletion apis/v1alpha3/haproxyloadbalancer_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

//nolint:gocritic,godot
package v1alpha3

import (
Expand Down
1 change: 0 additions & 1 deletion apis/v1alpha3/vspherecluster_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

//nolint:gocritic,godot
package v1alpha3

import (
Expand Down
3 changes: 2 additions & 1 deletion apis/v1alpha4/vspheremachinetemplate_conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import (
infrav1 "sigs.k8s.io/cluster-api-provider-vsphere/apis/v1beta1"
)

// ConvertTo.
// ConvertTo converts this VSphereMachineTemplate to the Hub version (v1beta1).
func (src *VSphereMachineTemplate) ConvertTo(dstRaw conversion.Hub) error {
dst := dstRaw.(*infrav1.VSphereMachineTemplate)
if err := Convert_v1alpha4_VSphereMachineTemplate_To_v1beta1_VSphereMachineTemplate(src, dst, nil); err != nil {
Expand All @@ -51,6 +51,7 @@ func (src *VSphereMachineTemplate) ConvertTo(dstRaw conversion.Hub) error {
return nil
}

// ConvertFrom converts from the Hub version (v1beta1) to this VSphereMachineTemplate.
func (dst *VSphereMachineTemplate) ConvertFrom(srcRaw conversion.Hub) error {
src := srcRaw.(*infrav1.VSphereMachineTemplate)
if err := Convert_v1beta1_VSphereMachineTemplate_To_v1alpha4_VSphereMachineTemplate(src, dst, nil); err != nil {
Expand Down
4 changes: 1 addition & 3 deletions controllers/controllers_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,7 @@ var (

func TestMain(m *testing.M) {
setup()
defer func() {
teardown()
}()
defer teardown()
code := m.Run()
os.Exit(code) //nolint:gocritic
}
Expand Down
2 changes: 1 addition & 1 deletion controllers/servicediscovery_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ func getSupervisorAPIServerURLWithFIP(client client.Client) (string, error) {
// tryParseClusterInfoFromConfigMap tries to parse a kubeconfig file from a ConfigMap key.
func tryParseClusterInfoFromConfigMap(cm *corev1.ConfigMap) (*clientcmdapi.Config, error) {
kubeConfigString, ok := cm.Data[bootstrapapi.KubeConfigKey]
if !ok || len(kubeConfigString) == 0 {
if !ok || kubeConfigString == "" {
return nil, errors.Errorf("no %s key in ConfigMap %s/%s", bootstrapapi.KubeConfigKey, cm.Namespace, cm.Name)
}
parsedKubeConfig, err := clientcmd.Load([]byte(kubeConfigString))
Expand Down
2 changes: 1 addition & 1 deletion controllers/vmware/test/controllers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ func getManager(cfg *rest.Config, networkProvider string) manager.Manager {
Expect(err).NotTo(HaveOccurred())

content := fmt.Sprintf(contentFmt, cfg.Username, cfg.Password)
_, err = tmpFile.Write([]byte(content))
_, err = tmpFile.WriteString(content)
Expect(err).NotTo(HaveOccurred())

opts := manager.Options{
Expand Down
25 changes: 13 additions & 12 deletions controllers/vspherecluster_reconciler.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,18 +153,19 @@ func (r clusterReconciler) reconcileDelete(ctx *context.ClusterContext) (reconci
// If the VSphereMachine is not owned by the CAPI Machine object because the machine object was deleted
// before setting the owner references, then proceed with the deletion of the VSphereMachine object.
// This is required until CAPI has a solution for https://github.com/kubernetes-sigs/cluster-api/issues/5483
if clusterutilv1.IsOwnedByObject(vsphereMachine, ctx.VSphereCluster) && len(vsphereMachine.OwnerReferences) == 1 {
machineDeletionCount++
// Remove the finalizer since VM creation wouldn't proceed
r.Logger.Info("Removing finalizer from VSphereMachine", "namespace", vsphereMachine.Namespace, "name", vsphereMachine.Name)
ctrlutil.RemoveFinalizer(vsphereMachine, infrav1.MachineFinalizer)
if err := r.Client.Update(ctx, vsphereMachine); err != nil {
return reconcile.Result{}, err
}
if err := r.Client.Delete(ctx, vsphereMachine); err != nil && !apierrors.IsNotFound(err) {
ctx.Logger.Error(err, "Failed to delete for VSphereMachine", "namespace", vsphereMachine.Namespace, "name", vsphereMachine.Name)
deletionErrors = append(deletionErrors, err)
}
if !clusterutilv1.IsOwnedByObject(vsphereMachine, ctx.VSphereCluster) || len(vsphereMachine.OwnerReferences) != 1 {
continue
}
machineDeletionCount++
// Remove the finalizer since VM creation wouldn't proceed
r.Logger.Info("Removing finalizer from VSphereMachine", "namespace", vsphereMachine.Namespace, "name", vsphereMachine.Name)
ctrlutil.RemoveFinalizer(vsphereMachine, infrav1.MachineFinalizer)
if err := r.Client.Update(ctx, vsphereMachine); err != nil {
return reconcile.Result{}, err
}
if err := r.Client.Delete(ctx, vsphereMachine); err != nil && !apierrors.IsNotFound(err) {
ctx.Logger.Error(err, "Failed to delete for VSphereMachine", "namespace", vsphereMachine.Namespace, "name", vsphereMachine.Name)
deletionErrors = append(deletionErrors, err)
}
}
if len(deletionErrors) > 0 {
Expand Down
27 changes: 14 additions & 13 deletions controllers/vspheredeploymentzone_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,20 +243,21 @@ func (r vsphereDeploymentZoneReconciler) getVCenterSession(ctx *context.VSphereD
}

for _, vsphereCluster := range clusterList.Items {
if ctx.VSphereDeploymentZone.Spec.Server == vsphereCluster.Spec.Server && vsphereCluster.Spec.IdentityRef != nil {
logger := ctx.Logger.WithValues("cluster", vsphereCluster.Name)
params = params.WithThumbprint(vsphereCluster.Spec.Thumbprint)
clust := vsphereCluster
creds, err := identity.GetCredentials(ctx, r.Client, &clust, r.Namespace)
if err != nil {
logger.Error(err, "error retrieving credentials from IdentityRef")
continue
}
logger.Info("using server credentials to create the authenticated session")
params = params.WithUserInfo(creds.Username, creds.Password)
return session.GetOrCreate(r.Context,
params)
if ctx.VSphereDeploymentZone.Spec.Server != vsphereCluster.Spec.Server || vsphereCluster.Spec.IdentityRef == nil {
continue
}
logger := ctx.Logger.WithValues("cluster", vsphereCluster.Name)
params = params.WithThumbprint(vsphereCluster.Spec.Thumbprint)
clust := vsphereCluster
creds, err := identity.GetCredentials(ctx, r.Client, &clust, r.Namespace)
if err != nil {
logger.Error(err, "error retrieving credentials from IdentityRef")
continue
}
logger.Info("using server credentials to create the authenticated session")
params = params.WithUserInfo(creds.Username, creds.Password)
return session.GetOrCreate(r.Context,
params)
}

// Fallback to using credentials provided to the manager
Expand Down
10 changes: 2 additions & 8 deletions controllers/vspheredeploymentzone_controller_domain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,7 @@ import (
"sigs.k8s.io/cluster-api-provider-vsphere/test/helpers/vcsim"
)

//nolint:paralleltest
func TestVsphereDeploymentZoneReconciler_Reconcile_VerifyFailureDomain(t *testing.T) {
t.Run("for Compute Cluster Zone Failure Domain", ForComputeClusterZone)
t.Run("for Host Group Zone Failure Domain", ForHostGroupZone)
}

func ForComputeClusterZone(t *testing.T) {
func TestVsphereDeploymentZoneReconciler_Reconcile_VerifyFailureDomain_ComputeClusterZone(t *testing.T) {
g := NewWithT(t)

model := simulator.VPX()
Expand Down Expand Up @@ -120,7 +114,7 @@ func ForComputeClusterZone(t *testing.T) {
g.Expect(reconciler.verifyFailureDomain(deploymentZoneCtx, vsphereFailureDomain.Spec.Zone)).To(HaveOccurred())
}

func ForHostGroupZone(t *testing.T) {
func TestVsphereDeploymentZoneReconciler_Reconcile_VerifyFailureDomain_HostGroupZone(t *testing.T) {
g := NewWithT(t)

model := simulator.VPX()
Expand Down
45 changes: 23 additions & 22 deletions controllers/vspherevm_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -710,31 +710,32 @@ func createMachineOwnerHierarchy(machine *clusterv1.Machine) []client.Object {
clusterName, _ = machine.Labels[clusterv1.ClusterNameLabel]
)

objs = append(objs, &clusterv1.MachineSet{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-ms", machine.Name),
Namespace: machine.Namespace,
Labels: map[string]string{
clusterv1.ClusterNameLabel: clusterName,
},
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: clusterv1.GroupVersion.String(),
Kind: "MachineDeployment",
Name: fmt.Sprintf("%s-md", machine.Name),
objs = append(
objs,
&clusterv1.MachineSet{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-ms", machine.Name),
Namespace: machine.Namespace,
Labels: map[string]string{
clusterv1.ClusterNameLabel: clusterName,
},
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: clusterv1.GroupVersion.String(),
Kind: "MachineDeployment",
Name: fmt.Sprintf("%s-md", machine.Name),
},
},
},
},
})

objs = append(objs, &clusterv1.MachineDeployment{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-md", machine.Name),
Namespace: machine.Namespace,
Labels: map[string]string{
clusterv1.ClusterNameLabel: clusterName,
&clusterv1.MachineDeployment{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-md", machine.Name),
Namespace: machine.Namespace,
Labels: map[string]string{
clusterv1.ClusterNameLabel: clusterName,
},
},
},
})
})
return objs
}
4 changes: 2 additions & 2 deletions pkg/manager/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ password: '%s'

// Update the file and wait for watch to detect the change
content := fmt.Sprintf(contentFmt, updatedUsername, updatedPassword)
_, err = tmpFile.Write([]byte(content))
_, err = tmpFile.WriteString(content)
g.Expect(err).ToNot(HaveOccurred())

g.Eventually(func() bool {
Expand Down Expand Up @@ -98,7 +98,7 @@ password: '%s'

// Update the file and wait for watch to detect the change
content := fmt.Sprintf(contentFmt, updatedUsername, updatedPassword)
if _, err := tmpFile.Write([]byte(content)); err != nil {
if _, err := tmpFile.WriteString(content); err != nil {
fmt.Printf("failed to update credentials in the file err:%s", err.Error())
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/manager/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ password: '%s'
}
t.Cleanup(func() { os.Remove(tmpFile.Name()) })

if _, err := tmpFile.Write([]byte(content)); err != nil {
if _, err := tmpFile.WriteString(content); err != nil {
t.Fatal(err)
}
if err := tmpFile.Close(); err != nil {
Expand Down
16 changes: 9 additions & 7 deletions pkg/services/govmomi/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ func waitForMacAddresses(ctx *virtualMachineContext) error {
func getMacAddresses(ctx *virtualMachineContext) ([]string, map[string]int, map[int]string, error) {
var (
vm mo.VirtualMachine
macAddresses []string
macAddresses = make([]string, 0, len(vm.Config.Hardware.Device))
macToDeviceSpecIndex = map[string]int{}
deviceSpecIndexToMac = map[int]string{}
)
Expand All @@ -375,13 +375,15 @@ func getMacAddresses(ctx *virtualMachineContext) ([]string, map[string]int, map[
}
i := 0
for _, device := range vm.Config.Hardware.Device {
if nic, ok := device.(types.BaseVirtualEthernetCard); ok {
mac := nic.GetVirtualEthernetCard().MacAddress
macAddresses = append(macAddresses, mac)
macToDeviceSpecIndex[mac] = i
deviceSpecIndexToMac[i] = mac
i++
nic, ok := device.(types.BaseVirtualEthernetCard)
if !ok {
continue
}
mac := nic.GetVirtualEthernetCard().MacAddress
macAddresses = append(macAddresses, mac)
macToDeviceSpecIndex[mac] = i
deviceSpecIndexToMac[i] = mac
i++
}
return macAddresses, macToDeviceSpecIndex, deviceSpecIndexToMac, nil
}
Expand Down
7 changes: 1 addition & 6 deletions pkg/services/govmomi/vcenter/clone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,7 @@ func TestGetDiskSpec(t *testing.T) {
}
vmContext := &context.VMContext{VSphereVM: vsphereVM}
devices, err := getDiskSpec(vmContext, tc.disks)
switch {
case tc.err != "" && err == nil:
fallthrough
case tc.err == "" && err != nil:
fallthrough
case err != nil && tc.err != err.Error():
if (tc.err != "" && err == nil) || (tc.err == "" && err != nil) || (err != nil && tc.err != err.Error()) {
t.Fatalf("Expected to get '%v' error from getDiskSpec, got: '%v'", tc.err, err)
}
if deviceFound := len(devices) != 0; tc.expectDevice != deviceFound {
Expand Down
9 changes: 2 additions & 7 deletions pkg/util/label_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,7 @@ import (
"github.com/onsi/gomega"
)

func TestSanitizeHostInfoLabel(t *testing.T) {
t.Run("for IP addresses", testIPAddressLogic)
t.Run("for DNS entries", testDNSLogic)
}

func testIPAddressLogic(t *testing.T) {
func TestSanitizeIPHostInfoLabel(t *testing.T) {
tests := []struct {
name, input, expected string
}{
Expand Down Expand Up @@ -61,7 +56,7 @@ func testIPAddressLogic(t *testing.T) {
}
}

func testDNSLogic(t *testing.T) {
func TestSanitizeDNSHostInfoLabel(t *testing.T) {
tests := []struct {
name, input, expected string
}{
Expand Down
Loading

0 comments on commit 21f31e0

Please sign in to comment.