Skip to content

Commit

Permalink
chore: Linter configuration: gofumpt, goerr113, godox, goconst (#341)
Browse files Browse the repository at this point in the history
* Linter: gofumpt

* Linter: goerr113

* Linter: goconst

* Linter: godox

* golangci/golangci-lint-action@v3

* Refine linters
  • Loading branch information
the1bit authored Feb 28, 2024
1 parent 1242840 commit 5e03864
Show file tree
Hide file tree
Showing 22 changed files with 117 additions and 59 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/codequality.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
cache: false
- uses: actions/checkout@v4
- name: golangci-lint
uses: golangci/golangci-lint-action@v4
uses: golangci/golangci-lint-action@v3
with:
# Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
version: v1.55
Expand Down
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,5 @@ module-config.yaml
.env.dev


.golangci.yaml
.golangci.yaml_old
.golangci.*
lint-report.json
4 changes: 0 additions & 4 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ linters:
- tagalign
- dupword
- gomoddirectives
- gofumpt
- goerr113
- funlen
- testifylint
- bodyclose
Expand All @@ -47,8 +45,6 @@ linters:
- errchkjson
- perfsprint
- noctx
- godox
- goconst

linters-settings:
gomoddirectives:
Expand Down
21 changes: 15 additions & 6 deletions api/v1alpha1/nats_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,11 @@ func (ns *NATSStatus) FindCondition(conditionType ConditionType) *kmetav1.Condit
return nil
}

func (ns *NATSStatus) UpdateConditionStatefulSet(status kmetav1.ConditionStatus, reason ConditionReason,
message string) {
func (ns *NATSStatus) UpdateConditionStatefulSet(
status kmetav1.ConditionStatus,
reason ConditionReason,
message string,
) {
condition := kmetav1.Condition{
Type: string(ConditionStatefulSet),
Status: status,
Expand All @@ -40,8 +43,11 @@ func (ns *NATSStatus) UpdateConditionStatefulSet(status kmetav1.ConditionStatus,
meta.SetStatusCondition(&ns.Conditions, condition)
}

func (ns *NATSStatus) UpdateConditionAvailable(status kmetav1.ConditionStatus, reason ConditionReason,
message string) {
func (ns *NATSStatus) UpdateConditionAvailable(
status kmetav1.ConditionStatus,
reason ConditionReason,
message string,
) {
condition := kmetav1.Condition{
Type: string(ConditionAvailable),
Status: status,
Expand Down Expand Up @@ -84,8 +90,11 @@ func (ns *NATSStatus) SetStateDeleting() {
ns.State = StateDeleting
}

func (ns *NATSStatus) UpdateConditionDeletion(status kmetav1.ConditionStatus, reason ConditionReason,
message string) {
func (ns *NATSStatus) UpdateConditionDeletion(
status kmetav1.ConditionStatus,
reason ConditionReason,
message string,
) {
condition := kmetav1.Condition{
Type: string(ConditionDeleted),
Status: status,
Expand Down
7 changes: 5 additions & 2 deletions internal/controller/nats/deprovisioner.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ const (
)

func (r *Reconciler) handleNATSDeletion(ctx context.Context, nats *nmapiv1alpha1.NATS,
log *zap.SugaredLogger) (kcontrollerruntime.Result, error) {
log *zap.SugaredLogger,
) (kcontrollerruntime.Result, error) {
// skip reconciliation for deletion if the finalizer is not set.
if !r.containsFinalizer(nats) {
log.Debugf("skipped reconciliation for deletion as finalizer is not set.")
Expand Down Expand Up @@ -116,8 +117,10 @@ func (r *Reconciler) createAndConnectNatsClient(nats *nmapiv1alpha1.NATS) error
}

func (r *Reconciler) deletePVCsAndRemoveFinalizer(ctx context.Context,
nats *nmapiv1alpha1.NATS, log *zap.SugaredLogger) (kcontrollerruntime.Result, error) {
nats *nmapiv1alpha1.NATS, log *zap.SugaredLogger,
) (kcontrollerruntime.Result, error) {
labelValue := nats.Name
//nolint: godox
// TODO: delete the following logic after migrating to modular Kyma
if nats.Name == "eventing-nats" {
labelValue = "eventing"
Expand Down
22 changes: 14 additions & 8 deletions internal/controller/nats/deprovisioner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ import (
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)

var (
ErrConnectionErrorMsg = errors.New("connection cannot be established")
ErrUnexpectedErrorMsg = errors.New("unexpected error")
ErrInitErrorMsg = errors.New("init error")
ErrDeleteErrorMsg = errors.New("delete error")
)

func Test_handleNATSDeletion(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -54,7 +61,7 @@ func Test_handleNATSDeletion(t *testing.T) {
givenWithNATSCreated: true,
mockNatsClientFunc: func() nmnats.Client {
natsClient := new(mocks.Client)
natsClient.On("Init").Return(errors.New("connection cannot be established"))
natsClient.On("Init").Return(ErrConnectionErrorMsg)
natsClient.On("Close").Return()
return natsClient
},
Expand All @@ -69,7 +76,7 @@ func Test_handleNATSDeletion(t *testing.T) {
mockNatsClientFunc: func() nmnats.Client {
natsClient := new(mocks.Client)
natsClient.On("Init").Return(nil)
natsClient.On("GetStreams").Return(nil, errors.New("unexpected error"))
natsClient.On("GetStreams").Return(nil, ErrUnexpectedErrorMsg)
natsClient.On("Close").Return()
return natsClient
},
Expand All @@ -90,7 +97,7 @@ func Test_handleNATSDeletion(t *testing.T) {
},
},
}, nil)
natsClient.On("ConsumersExist", mock.Anything).Return(false, errors.New("unexpected error"))
natsClient.On("ConsumersExist", mock.Anything).Return(false, ErrUnexpectedErrorMsg)
natsClient.On("Close").Return()
return natsClient
},
Expand Down Expand Up @@ -311,9 +318,9 @@ func Test_DeletePVCsAndRemoveFinalizer(t *testing.T) {
testutils.WithNATSCRFinalizer(NATSFinalizerName),
),
labelValue: "test-nats",
deleteErr: errors.New("delete error"),
deleteErr: ErrDeleteErrorMsg,
expectedResult: kcontrollerruntime.Result{},
expectedErr: errors.New("delete error"),
expectedErr: ErrDeleteErrorMsg,
},
}

Expand Down Expand Up @@ -370,8 +377,8 @@ func Test_CreateAndConnectNatsClient(t *testing.T) {
testutils.WithNATSCRName("test-nats"),
testutils.WithNATSCRNamespace("test-namespace"),
),
initErr: errors.New("init error"),
expectedErr: errors.New("init error"),
initErr: ErrInitErrorMsg,
expectedErr: ErrInitErrorMsg,
},
}

Expand All @@ -383,7 +390,6 @@ func Test_CreateAndConnectNatsClient(t *testing.T) {
r.getNatsClient(tt.nats).(*mocks.Client).On("Init").Return(tt.initErr)

err := r.createAndConnectNatsClient(tt.nats)

if err != nil {
require.Equal(t, tt.expectedErr.Error(), err.Error())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -630,7 +630,8 @@ func makeStatefulSetReady(t *testing.T, name, namespace string) {
type deletionFunc func(env integration.TestEnvironment, natsName, namespace string) error

func ensureK8sResourceDeletion(
t *testing.T, env integration.TestEnvironment, natsName, namespace string, fs ...deletionFunc) {
t *testing.T, env integration.TestEnvironment, natsName, namespace string, fs ...deletionFunc,
) {
for _, f := range fs {
require.NoError(t, f(env, natsName, namespace))
}
Expand Down
6 changes: 4 additions & 2 deletions internal/controller/nats/provisioner.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ import (
const RequeueTimeForStatusCheck = 10

func (r *Reconciler) handleNATSReconcile(ctx context.Context,
nats *nmapiv1alpha1.NATS, log *zap.SugaredLogger) (kcontrollerruntime.Result, error) {
nats *nmapiv1alpha1.NATS, log *zap.SugaredLogger,
) (kcontrollerruntime.Result, error) {
log.Info("handling NATS reconciliation...")

// set status to processing
Expand Down Expand Up @@ -66,7 +67,8 @@ func (r *Reconciler) handleNATSReconcile(ctx context.Context,
// handleNATSState checks if NATS resources are ready.
// It also syncs the NATS CR status.
func (r *Reconciler) handleNATSState(ctx context.Context, nats *nmapiv1alpha1.NATS, instance *chart.ReleaseInstance,
log *zap.SugaredLogger) (kcontrollerruntime.Result, error) {
log *zap.SugaredLogger,
) (kcontrollerruntime.Result, error) {
// Clear the url until the StatefulSet is ready.
nats.Status.ClearURL()

Expand Down
4 changes: 3 additions & 1 deletion internal/controller/nats/provisioner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)

var ErrDeployErrorMsg = errors.New("deploy error")

func Test_handleNATSState(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -158,7 +160,7 @@ func Test_handleNATSReconcile(t *testing.T) {
testutils.WithNATSCRNamespace("kyma-system"),
testutils.WithNATSCRFinalizer(NATSFinalizerName),
),
givenDeployError: errors.New("deploy error"),
givenDeployError: ErrDeployErrorMsg,
wantState: nmapiv1alpha1.StateError,
wantConditions: []kmetav1.Condition{
{
Expand Down
9 changes: 6 additions & 3 deletions internal/controller/nats/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ import (
// syncNATSStatus syncs NATS status.
// Returns the relevant error.
func (r *Reconciler) syncNATSStatusWithErr(ctx context.Context,
nats *nmapiv1alpha1.NATS, err error, log *zap.SugaredLogger) error {
nats *nmapiv1alpha1.NATS, err error, log *zap.SugaredLogger,
) error {
// set error state in status
nats.Status.SetStateError()
nats.Status.UpdateConditionAvailable(kmetav1.ConditionFalse, nmapiv1alpha1.ConditionReasonProcessingError, err.Error())
Expand All @@ -30,7 +31,8 @@ func (r *Reconciler) syncNATSStatusWithErr(ctx context.Context,

// syncNATSStatus syncs NATS status.
func (r *Reconciler) syncNATSStatus(ctx context.Context,
nats *nmapiv1alpha1.NATS, log *zap.SugaredLogger) error {
nats *nmapiv1alpha1.NATS, log *zap.SugaredLogger,
) error {
namespacedName := &ktypes.NamespacedName{
Name: nats.Name,
Namespace: nats.Namespace,
Expand All @@ -52,7 +54,8 @@ func (r *Reconciler) syncNATSStatus(ctx context.Context,

// updateStatus updates the status to k8s if modified.
func (r *Reconciler) updateStatus(ctx context.Context, oldNATS, newNATS *nmapiv1alpha1.NATS,
logger *zap.SugaredLogger) error {
logger *zap.SugaredLogger,
) error {
// compare the status taking into consideration lastTransitionTime in conditions
if oldNATS.Status.IsEqual(newNATS.Status) {
return nil
Expand Down
4 changes: 3 additions & 1 deletion internal/controller/nats/status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import (
kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var ErrTestErrorMsg = errors.New("test error")

func Test_syncNATSStatus(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -97,7 +99,7 @@ func Test_syncNATSStatusWithErr(t *testing.T) {
testutils.WithNATSCRStatusInitialized(),
testutils.WithNATSStateProcessing(),
),
givenError: errors.New("test error"),
givenError: ErrTestErrorMsg,
wantNATSStatus: nmapiv1alpha1.NATSStatus{
State: nmapiv1alpha1.StateError,
Conditions: []kmetav1.Condition{
Expand Down
6 changes: 4 additions & 2 deletions pkg/events/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import (

// Normal records a normal event for an API object.
func Normal(recorder record.EventRecorder, obj runtime.Object, rn nmapiv1alpha1.ConditionReason, msgFmt string,
args ...interface{}) {
args ...interface{},
) {
recorder.Eventf(obj, kcorev1.EventTypeNormal, string(rn), msgFmt, args...)
}

// Warn records a warning event for an API object.
func Warn(recorder record.EventRecorder, obj runtime.Object, rn nmapiv1alpha1.ConditionReason, msgFmt string,
args ...interface{}) {
args ...interface{},
) {
recorder.Eventf(obj, kcorev1.EventTypeWarning, string(rn), msgFmt, args...)
}
2 changes: 1 addition & 1 deletion pkg/k8s/chart/helmrenderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type HelmRenderer struct {

func NewHelmRenderer(chartPath string, logger *zap.SugaredLogger) (Renderer, error) {
if !file.DirExists(chartPath) {
return nil, fmt.Errorf("HELM chart directory '%s' not found", chartPath)
return nil, fmt.Errorf("HELM chart directory '%s' not found", chartPath) //nolint: goerr113 // reason: This is the only place where we use dynamic error message
}

// load chart into memory
Expand Down
4 changes: 3 additions & 1 deletion pkg/k8s/chart/releaseinstance.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"dario.cat/mergo"
)

var ErrFailedToConvertToNestedMap = errors.New("failed to convert to nestedMap to map[string]interface{}")

func NewReleaseInstance(name, namespace string, istioEnabled bool,
configuration map[string]interface{},
) *ReleaseInstance {
Expand Down Expand Up @@ -71,7 +73,7 @@ func (c *ReleaseInstance) convertToNestedMap(key string, value interface{}) (map
var ok bool
lastNestedMap, ok = lastNestedMap[token].(map[string]interface{})
if !ok {
return result, errors.New("failed to convert to nestedMap to map[string]interface{}")
return result, ErrFailedToConvertToNestedMap
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion pkg/k8s/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ func (c *KubeClient) DestinationRuleCRDExists(ctx context.Context) (bool, error)
}

func (c *KubeClient) DeletePVCsWithLabel(ctx context.Context, labelSelector string,
mustHaveNamePrefix, namespace string) error {
mustHaveNamePrefix, namespace string,
) error {
// create a new labels.Selector object for the label selector
selector, err := labels.Parse(labelSelector)
if err != nil {
Expand Down
7 changes: 5 additions & 2 deletions pkg/manager/nats.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"github.com/kyma-project/nats-manager/pkg/k8s/chart"
)

var ErrNATSStatefulSetNotFound = fmt.Errorf("NATS StatefulSet not found in manifests")

type NatsConfig struct {
ClusterSize int
}
Expand Down Expand Up @@ -42,7 +44,8 @@ func NewNATSManger(kubeClient k8s.Client, chartRenderer chart.Renderer, logger *
}

func (m NATSManager) GenerateNATSResources(instance *chart.ReleaseInstance,
opts ...Option) (*chart.ManifestResources, error) {
opts ...Option,
) (*chart.ManifestResources, error) {
manifests, err := m.chartRenderer.RenderManifestAsUnstructured(instance)
if err == nil {
// apply options
Expand Down Expand Up @@ -80,7 +83,7 @@ func (m NATSManager) IsNATSStatefulSetReady(ctx context.Context, instance *chart
// get statefulSets from rendered manifests
statefulSets := instance.GetStatefulSets()
if len(statefulSets) == 0 {
return false, fmt.Errorf("NATS StatefulSet not found in manifests")
return false, ErrNATSStatefulSetNotFound
}

// fetch statefulSets from cluster and check if they are ready
Expand Down
12 changes: 9 additions & 3 deletions pkg/manager/nats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ import (
"k8s.io/apimachinery/pkg/runtime"
)

var (
ErrNATSStatefulSetNotFoundMsg = errors.New("NATS StatefulSet not found in manifests")
ErrFailedToDeployMsg = errors.New("failed to deploy")
ErrFailedToDeleteMsg = errors.New("failed to delete")
)

func Test_GenerateNATSResources(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -106,7 +112,7 @@ func Test_DeployInstance(t *testing.T) {
},
{
name: "should fail when k8s fails to deploy resource",
wantError: errors.New("failed to deploy"),
wantError: ErrFailedToDeployMsg,
},
}

Expand Down Expand Up @@ -171,7 +177,7 @@ func Test_DeleteInstance(t *testing.T) {
},
{
name: "should fail when k8s fails to delete resource",
wantError: errors.New("failed to delete"),
wantError: ErrFailedToDeleteMsg,
},
}

Expand Down Expand Up @@ -235,7 +241,7 @@ func Test_IsNATSStatefulSetReady(t *testing.T) {
{
name: "should return error if no StatefulSet exists in manifests",
givenStatefulSet: nil,
wantError: errors.New("NATS StatefulSet not found in manifests"),
wantError: ErrNATSStatefulSetNotFoundMsg,
},
{
name: "should return not ready when CurrentReplicas is not as needed",
Expand Down
Loading

0 comments on commit 5e03864

Please sign in to comment.