Skip to content

Commit

Permalink
chore(lint): updates to latest version (opendatahub-io#1074)
Browse files Browse the repository at this point in the history
Fixes

- removed irrelavant //nolint comments (see config updates below)
- converted unused func params to blank identifier when impl does not
  need it

New linters

perfsprint

- disabled fmt.Sprintf checks for one element
- adjusted errors creation to use errors.New instead of fmt.Errorf when
  no-arg strings are used as messages

Configuration updates

- configured revive to not complain about dot-imports for testing
  libraries
- adjusted configuration yaml due to changes in the structure
  (skip-dirs)
- some deprecated linters were removed from golangci-lint toolchain so they are now gone from the config too
  • Loading branch information
bartoszmajsak authored Jun 24, 2024
1 parent 2993707 commit 9be146f
Show file tree
Hide file tree
Showing 23 changed files with 58 additions and 51 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/linter.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ jobs:
- name: golangci-lint
uses: golangci/golangci-lint-action@v4
with:
version: v1.54.0
version: v1.59.1
skip-cache: true
args: --timeout 5m0s
26 changes: 13 additions & 13 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
run:
deadline: 10m
skip-dirs:
- apis

linters-settings:
gocyclo:
Expand Down Expand Up @@ -30,38 +28,38 @@ linters-settings:
nolintlint:
allow-no-explanation: [ funlen, lll ]
require-specific: true
revive:
rules:
- name: dot-imports
arguments:
- allowedPackages: ["github.com/onsi/ginkgo/v2","github.com/onsi/gomega","github.com/onsi/gomega/gstruct"]
perfsprint:
sprintf1: false
strconcat: false

linters:
enable-all: true
disable:
- containedctx # detects struct contained context.Context field
- deadcode # deprecated
- depguard # [replaced by gomodguard] checks if package imports are in a list of acceptable packages
- exhaustivestruct # Prevents empty struct. We use a lot of these so I think it is safe to disable.
- exhaustruct # Prevents empty struct. We use a lot of these so I think it is safe to disable.c
- forbidigo
- gochecknoglobals # Prevents use of global vars.
- gofumpt
- golint # deprecated
- gomnd # Doesnot allow hardcoded numbers
- gomoddirectives # Doesnot allow replace in go mod file
- ifshort # deprecated
- interfacer
- maligned # deprecated
- mnd
- nestif
- nilnil
- nosnakecase # snakecase is used in a lot of places. Need to check if that is required.
- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test
- scopelint # deprecated
- structcheck # deprecated
- tagliatelle
- varcheck # deprecated
- varnamelen # doesnot allow shorter names like c,k etc. But golang prefers short named vars.
- wsl # [too strict and mostly code is not more readable] whitespace linter forces you to use empty lines
- wrapcheck # check if this is required. Prevents direct return of err.

# Need to check
- nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity
- goerr113 # [too strict] checks the errors handling expressions
- err113 # [too strict] checks the errors handling expressions
- contextcheck # Requires to pass context to all function.

# To be fixed
Expand All @@ -71,6 +69,8 @@ linters:
- godox # https://github.com/opendatahub-io/opendatahub-operator/issues/699

issues:
exclude-dirs:
- apis
exclude-rules:
- path: tests/*/(.+)_test\.go
linters:
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ YQ ?= $(LOCALBIN)/yq
KUSTOMIZE_VERSION ?= v3.8.7
CONTROLLER_GEN_VERSION ?= v0.9.2
OPERATOR_SDK_VERSION ?= v1.31.0
GOLANGCI_LINT_VERSION ?= v1.54.0
GOLANGCI_LINT_VERSION ?= v1.59.1
YQ_VERSION ?= v4.12.2
# ENVTEST_K8S_VERSION refers to the version of kubebuilder assets to be downloaded by envtest binary.
ENVTEST_K8S_VERSION = 1.24.2
Expand Down
5 changes: 3 additions & 2 deletions components/kserve/kserve_config_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package kserve
import (
"context"
"encoding/json"
"errors"
"fmt"

operatorv1 "github.com/openshift/api/operator/v1"
Expand Down Expand Up @@ -36,7 +37,7 @@ func (k *Kserve) setupKserveConfig(ctx context.Context, cli client.Client, dscis
}
case operatorv1.Removed:
if k.DefaultDeploymentMode == Serverless {
return fmt.Errorf("setting defaultdeployment mode as Serverless is incompatible with having Serving 'Removed'")
return errors.New("setting defaultdeployment mode as Serverless is incompatible with having Serving 'Removed'")
}
if k.DefaultDeploymentMode == "" {
fmt.Println("Serving is removed, Kserve will default to rawdeployment")
Expand Down Expand Up @@ -128,7 +129,7 @@ func (k *Kserve) configureServerless(instance *dsciv1.DSCInitializationSpec) err
case operatorv1.Managed: // standard workflow to create CR
switch instance.ServiceMesh.ManagementState {
case operatorv1.Unmanaged, operatorv1.Removed:
return fmt.Errorf("ServiceMesh is need to set to 'Managed' in DSCI CR, it is required by KServe serving field")
return errors.New("ServiceMesh is need to set to 'Managed' in DSCI CR, it is required by KServe serving field")
}

serverlessFeatures := feature.ComponentFeaturesHandler(k.GetComponentName(), instance, k.configureServerlessFeatures())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import (
)

// CertConfigmapGeneratorReconciler holds the controller configuration.
type CertConfigmapGeneratorReconciler struct { //nolint:golint,revive // Readability
type CertConfigmapGeneratorReconciler struct {
Client client.Client
Scheme *runtime.Scheme
Log logr.Logger
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package datasciencecluster

import (
"context"
"errors"
"fmt"
"strings"
"time"
Expand Down Expand Up @@ -60,7 +61,7 @@ import (
)

// DataScienceClusterReconciler reconciles a DataScienceCluster object.
type DataScienceClusterReconciler struct { //nolint:golint,revive
type DataScienceClusterReconciler struct {
client.Client
Scheme *runtime.Scheme
Log logr.Logger
Expand All @@ -70,7 +71,7 @@ type DataScienceClusterReconciler struct { //nolint:golint,revive
}

// DataScienceClusterConfig passing Spec of DSCI for reconcile DataScienceCluster.
type DataScienceClusterConfig struct { //nolint:golint,revive
type DataScienceClusterConfig struct {
DSCISpec *dsci.DSCInitializationSpec
}

Expand Down Expand Up @@ -511,7 +512,7 @@ func (r *DataScienceClusterReconciler) getRequestName() (string, error) {
case len(instanceList.Items) == 0:
return "default-dsc", nil
default:
return "", fmt.Errorf("multiple DataScienceCluster instances found")
return "", errors.New("multiple DataScienceCluster instances found")
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const (
var managementStateChangeTrustedCA = false

// DSCInitializationReconciler reconciles a DSCInitialization object.
type DSCInitializationReconciler struct { //nolint:golint,revive // Readability
type DSCInitializationReconciler struct {
client.Client
Scheme *runtime.Scheme
Log logr.Logger
Expand Down
2 changes: 1 addition & 1 deletion controllers/secretgenerator/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
annotation "github.com/opendatahub-io/opendatahub-operator/v2/pkg/metadata/annotations"
)

//nolint:golint,revive,stylecheck //CAPS is preferred for const
//nolint:golint,stylecheck //CAPS is preferred for const
const (
SECRET_DEFAULT_COMPLEXITY = 16

Expand Down
2 changes: 1 addition & 1 deletion controllers/secretgenerator/secretgenerator_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const (
)

// SecretGeneratorReconciler holds the controller configuration.
type SecretGeneratorReconciler struct { //nolint:golint,revive // Readability
type SecretGeneratorReconciler struct {
Client client.Client
Scheme *runtime.Scheme
Log logr.Logger
Expand Down
4 changes: 2 additions & 2 deletions controllers/status/reporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package status

import (
"context"
"fmt"
"errors"

"k8s.io/client-go/util/retry"
"sigs.k8s.io/controller-runtime/pkg/client"
Expand Down Expand Up @@ -43,7 +43,7 @@ type SaveStatusFunc[T client.Object] func(saved T)
func UpdateWithRetry[T client.Object](ctx context.Context, cli client.Client, original T, update SaveStatusFunc[T]) (T, error) {
saved, ok := original.DeepCopyObject().(T)
if !ok {
return *new(T), fmt.Errorf("failed to deep copy object")
return *new(T), errors.New("failed to deep copy object")
}
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
if err := cli.Get(ctx, client.ObjectKeyFromObject(original), saved); err != nil {
Expand Down
3 changes: 2 additions & 1 deletion pkg/cluster/resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cluster

import (
"context"
"errors"
"fmt"
"time"

Expand Down Expand Up @@ -89,7 +90,7 @@ func CreateSecret(ctx context.Context, cli client.Client, name, namespace string
// ConfigMap.ObjectMeta.Name and ConfigMap.ObjectMeta.Namespace are both required, it returns an error otherwise.
func CreateOrUpdateConfigMap(ctx context.Context, c client.Client, desiredCfgMap *corev1.ConfigMap, metaOptions ...MetaOptions) error {
if desiredCfgMap.GetName() == "" || desiredCfgMap.GetNamespace() == "" {
return fmt.Errorf("configmap name and namespace must be set")
return errors.New("configmap name and namespace must be set")
}

existingCfgMap := &corev1.ConfigMap{}
Expand Down
2 changes: 1 addition & 1 deletion pkg/deploy/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ func DownloadManifests(componentName string, manifestConfig components.Manifests
return err
}

func DeployManifestsFromPath(cli client.Client, owner metav1.Object, manifestPath string, namespace string, componentName string, componentEnabled bool) error { //nolint:golint,revive,lll
func DeployManifestsFromPath(cli client.Client, owner metav1.Object, manifestPath string, namespace string, componentName string, componentEnabled bool) error {
// Render the Kustomize manifests
k := krusty.MakeKustomizer(krusty.MakeDefaultOptions())
fs := filesys.MakeFsOnDisk()
Expand Down
2 changes: 1 addition & 1 deletion pkg/feature/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ type featureBuilder struct {
}

// CreateFeature creates a new feature builder with the given name.
func CreateFeature(name string) *usingFeaturesHandler { //nolint:golint,revive //No need to export featureBuilder.
func CreateFeature(name string) *usingFeaturesHandler {
return &usingFeaturesHandler{
name: name,
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/feature/feature_tracker_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func (f *Feature) ensureGVKSet(obj runtime.Object) error {
return fmt.Errorf("failed to get group, version, & kinds for object: %w", err)
}
if unversioned {
return fmt.Errorf("object is unversioned")
return errors.New("object is unversioned")
}
// Update the target object back with one of the discovered GVKs.
obj.GetObjectKind().SetGroupVersionKind(gvks[0])
Expand Down
4 changes: 2 additions & 2 deletions pkg/feature/manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func loadManifestsFrom(fsys fs.FS, path string) ([]Manifest, error) {
return manifests, nil
}

func CreateRawManifestFrom(fsys fs.FS, path string) *rawManifest { //nolint:golint,revive //No need to export rawManifest.
func CreateRawManifestFrom(fsys fs.FS, path string) *rawManifest {
basePath := filepath.Base(path)

return &rawManifest{
Expand All @@ -154,7 +154,7 @@ func CreateRawManifestFrom(fsys fs.FS, path string) *rawManifest { //nolint:goli
}
}

func CreateTemplateManifestFrom(fsys fs.FS, path string) *templateManifest { //nolint:golint,revive //No need to export templateManifest.
func CreateTemplateManifestFrom(fsys fs.FS, path string) *templateManifest {
basePath := filepath.Base(path)

return &templateManifest{
Expand Down
5 changes: 3 additions & 2 deletions pkg/feature/serverless/conditions.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package serverless

import (
"context"
"errors"
"fmt"

"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
Expand All @@ -28,7 +29,7 @@ func EnsureServerlessAbsent(f *feature.Feature) error {
}

if len(list.Items) > 1 {
return fmt.Errorf("multiple KNativeServing resources found, which is an unsupported state")
return errors.New("multiple KNativeServing resources found, which is an unsupported state")
}

servingOwners := list.Items[0].GetOwnerReferences()
Expand All @@ -42,7 +43,7 @@ func EnsureServerlessAbsent(f *feature.Feature) error {
}
}

return fmt.Errorf("existing KNativeServing resource was found; integrating to an existing installation is not supported")
return errors.New("existing KNativeServing resource was found; integrating to an existing installation is not supported")
}

func EnsureServerlessOperatorInstalled(f *feature.Feature) error {
Expand Down
2 changes: 1 addition & 1 deletion tests/e2e/controller_setup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ type testContext struct {
ctx context.Context
}

func NewTestContext() (*testContext, error) { //nolint:golint,revive // Only used in tests
func NewTestContext() (*testContext, error) {
// GetConfig(): If KUBECONFIG env variable is set, it is used to create
// the client, else the inClusterConfig() is used.
// Lastly if none of them are set, it uses $HOME/.kube/config to create the client.
Expand Down
3 changes: 2 additions & 1 deletion tests/e2e/dsc_cfmap_deletion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package e2e_test

import (
"context"
"errors"
"fmt"
"testing"

Expand Down Expand Up @@ -63,7 +64,7 @@ func (tc *testContext) testOwnedNamespacesAllExist() error {
return fmt.Errorf("failed getting owned namespaces %w", err)
}
if len(namespaces.Items) == 0 {
return fmt.Errorf("all namespaces are gone")
return errors.New("all namespaces are gone")
}

return nil
Expand Down
13 changes: 7 additions & 6 deletions tests/e2e/dsc_creation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package e2e_test

import (
"context"
"errors"
"fmt"
"log"
"reflect"
Expand All @@ -12,7 +13,7 @@ import (
operatorv1 "github.com/openshift/api/operator/v1"
"github.com/stretchr/testify/require"
autoscalingv1 "k8s.io/api/autoscaling/v1"
"k8s.io/apimachinery/pkg/api/errors"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
Expand Down Expand Up @@ -103,7 +104,7 @@ func (tc *testContext) testDSCICreation() error {
// create one for you
err = tc.customClient.Get(tc.ctx, dscLookupKey, createdDSCI)
if err != nil {
if errors.IsNotFound(err) {
if k8serrors.IsNotFound(err) {
nberr := wait.PollUntilContextTimeout(tc.ctx, tc.resourceRetryInterval, tc.resourceCreationTimeout, false, func(ctx context.Context) (bool, error) {
creationErr := tc.customClient.Create(tc.ctx, tc.testDSCI)
if creationErr != nil {
Expand Down Expand Up @@ -163,7 +164,7 @@ func (tc *testContext) testDSCCreation() error {

err = tc.customClient.Get(tc.ctx, dscLookupKey, createdDSC)
if err != nil {
if errors.IsNotFound(err) {
if k8serrors.IsNotFound(err) {
nberr := wait.PollUntilContextTimeout(tc.ctx, tc.resourceRetryInterval, tc.resourceCreationTimeout, false, func(ctx context.Context) (bool, error) {
creationErr := tc.customClient.Create(tc.ctx, tc.testDsc)
if creationErr != nil {
Expand Down Expand Up @@ -193,7 +194,7 @@ func (tc *testContext) requireInstalled(t *testing.T, gvk schema.GroupVersionKin
err := tc.customClient.List(tc.ctx, list)
require.NoErrorf(t, err, "Could not get %s list", gvk.Kind)

require.Greaterf(t, len(list.Items), 0, "%s has not been installed", gvk.Kind)
require.NotEmptyf(t, len(list.Items), "%s has not been installed", gvk.Kind)
}

func (tc *testContext) testDuplication(t *testing.T, gvk schema.GroupVersionKind, o any) {
Expand Down Expand Up @@ -480,7 +481,7 @@ func (tc *testContext) testUpdateDSCComponentEnabled() error {
}
}
} else {
return fmt.Errorf("dashboard spec should be in 'enabled: true' state in order to perform test")
return errors.New("dashboard spec should be in 'enabled: true' state in order to perform test")
}

// Disable component Dashboard
Expand Down Expand Up @@ -511,7 +512,7 @@ func (tc *testContext) testUpdateDSCComponentEnabled() error {
time.Sleep(4 * tc.resourceRetryInterval)
_, err = tc.kubeClient.AppsV1().Deployments(tc.applicationsNamespace).Get(context.TODO(), dashboardDeploymentName, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
if k8serrors.IsNotFound(err) {
return nil // correct result: should not find deployment after we disable it already
}

Expand Down
2 changes: 1 addition & 1 deletion tests/envtestutil/cleaner.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"

. "github.com/onsi/gomega" //nolint:revive,golint,stylecheck // This is the standard for ginkgo and gomega.
. "github.com/onsi/gomega" //nolint:stylecheck // This is the standard for ginkgo and gomega.
)

// Cleaner is a struct to perform deletion of resources,
Expand Down
4 changes: 2 additions & 2 deletions tests/envtestutil/utils.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package envtestutil

import (
"fmt"
"errors"
"os"
"path/filepath"
)
Expand All @@ -25,5 +25,5 @@ func FindProjectRoot() (string, error) {
currentDir = parentDir
}

return "", fmt.Errorf("project root not found")
return "", errors.New("project root not found")
}
Loading

0 comments on commit 9be146f

Please sign in to comment.