Skip to content

Commit b3cded1

Browse files
authored
Integrate golangci-lint to run aggregate linting checks for CI (#2536)
* Introduce golangci-lint support Introduce a root .golangci-lint.yaml file to the repository. This file is responsible for housing the golangci-lint configuration, and the various aggregate linters that are enabled/disabled. Signed-off-by: timflannagan <[email protected]> * .github/workflows: Run the golangci-lint action during the sanity checks Update the sanity workflow and add the golangci-lint action. Signed-off-by: timflannagan <[email protected]> * Fix linting violations outlined by golangci-lint Signed-off-by: timflannagan <[email protected]>
1 parent c6cc1d7 commit b3cded1

File tree

82 files changed

+463
-663
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

82 files changed

+463
-663
lines changed

.github/workflows/sanity.yaml

+7-3
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,11 @@ jobs:
1313
- uses: actions/setup-go@v2
1414
with:
1515
go-version: '~1.16'
16-
- name: Install goimports
17-
run: go install golang.org/x/tools/cmd/goimports@latest
1816
- name: Run sanity checks
19-
run: make vendor && make lint && make diff
17+
run: make vendor && make diff
18+
- name: Run linting checks
19+
uses: "golangci/golangci-lint-action@v2"
20+
with:
21+
version: "v1.43"
22+
skip-go-installation: true
23+
skip-pkg-cache: true

.golangci.yaml

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
run:
2+
timeout: 5m
3+
skip-dirs:
4+
- pkg/lib
5+
- pkg/api
6+
- pkg/fakes
7+
- pkg/package-server/apis
8+
- test/e2e
9+
10+
linters:
11+
enable:
12+
- depguard
13+
- gofmt
14+
- goimports
15+
- importas
16+
- misspell
17+
- stylecheck
18+
- tparallel
19+
- unconvert
20+
- whitespace
21+
disable:
22+
- errcheck
23+
24+
issues:
25+
max-issues-per-linter: 0
26+
max-same-issues: 0
27+
28+
output:
29+
format: tab
30+
sort-results: true

cmd/catalog/main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ var (
6969
tlsCertPath = flag.String(
7070
"tls-cert", "", "Path to use for certificate key (requires tls-key)")
7171

72-
profiling = flag.Bool("profiling", false, "deprecated")
72+
_ = flag.Bool("profiling", false, "deprecated")
7373

7474
clientCAPath = flag.String("client-ca", "", "path to watch for client ca bundle")
7575

cmd/olm/main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ var (
6363
tlsCertPath = pflag.String(
6464
"tls-cert", "", "Path to use for certificate key (requires tls-key)")
6565

66-
profiling = pflag.Bool("profiling", false, "deprecated")
66+
_ = pflag.Bool("profiling", false, "deprecated")
6767

6868
clientCAPath = pflag.String("client-ca", "", "path to watch for client ca bundle")
6969

cmd/olm/manager.go

-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,6 @@ func Manager(ctx context.Context, debug bool) (ctrl.Manager, error) {
118118
if err = adoptionReconciler.SetupWithManager(mgr); err != nil {
119119
return nil, err
120120
}
121-
122121
}
123122
setupLog.Info("manager configured")
124123

pkg/controller/bundle/bundle_unpacker.go

+4-5
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,6 @@ const (
384384
)
385385

386386
func (c *ConfigMapUnpacker) UnpackBundle(lookup *operatorsv1alpha1.BundleLookup, timeout time.Duration) (result *BundleUnpackResult, err error) {
387-
388387
result = newBundleUnpackResult(lookup)
389388

390389
// if bundle lookup failed condition already present, then there is nothing more to do
@@ -523,8 +522,8 @@ func (c *ConfigMapUnpacker) pendingContainerStatusMessages(job *batchv1.Job) (st
523522
podLabel := map[string]string{BundleUnpackPodLabel: job.GetName()}
524523
pods, listErr := c.podLister.Pods(job.GetNamespace()).List(k8slabels.SelectorFromValidatedSet(podLabel))
525524
if listErr != nil {
526-
c.logger.Errorf("Failed to list pods for job(%s): %v", job.GetName(), listErr)
527-
return "", fmt.Errorf("Failed to list pods for job(%s): %v", job.GetName(), listErr)
525+
c.logger.Errorf("failed to list pods for job(%s): %v", job.GetName(), listErr)
526+
return "", fmt.Errorf("failed to list pods for job(%s): %v", job.GetName(), listErr)
528527
}
529528

530529
// Ideally there should be just 1 pod running but inspect all pods in the pending phase
@@ -570,14 +569,14 @@ func (c *ConfigMapUnpacker) ensureConfigmap(csRef *corev1.ObjectReference, name
570569
if err != nil && apierrors.IsAlreadyExists(err) {
571570
cm, err = c.client.CoreV1().ConfigMaps(fresh.GetNamespace()).Get(context.TODO(), fresh.GetName(), metav1.GetOptions{})
572571
if err != nil {
573-
return nil, fmt.Errorf("Failed to retrieve configmap %s: %v", fresh.GetName(), err)
572+
return nil, fmt.Errorf("failed to retrieve configmap %s: %v", fresh.GetName(), err)
574573
}
575574
cm.SetLabels(map[string]string{
576575
install.OLMManagedLabelKey: install.OLMManagedLabelValue,
577576
})
578577
cm, err = c.client.CoreV1().ConfigMaps(cm.GetNamespace()).Update(context.TODO(), cm, metav1.UpdateOptions{})
579578
if err != nil {
580-
return nil, fmt.Errorf("Failed to update configmap %s: %v", cm.GetName(), err)
579+
return nil, fmt.Errorf("failed to update configmap %s: %v", cm.GetName(), err)
581580
}
582581
}
583582
}

pkg/controller/bundle/bundle_unpacker_test.go

+5-6
Large diffs are not rendered by default.

pkg/controller/install/apiservice.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func (i *StrategyDeploymentInstaller) createOrUpdateAPIService(caPEM []byte, des
4343
} else {
4444
csv, ok := i.owner.(*v1alpha1.ClusterServiceVersion)
4545
if !ok {
46-
return fmt.Errorf("APIServices require a CSV Owner.")
46+
return fmt.Errorf("failed to typecast the APIService owner: APIServices require a CSV owner")
4747
}
4848

4949
adoptable, err := IsAPIServiceAdoptable(i.strategyClient.GetOpLister(), csv, apiService)

pkg/controller/install/certresources.go

-1
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,6 @@ func (i *StrategyDeploymentInstaller) installCertRequirementsForDeployment(deplo
315315
logger.Warnf("could not update secret %s", secret.GetName())
316316
return nil, nil, err
317317
}
318-
319318
} else if k8serrors.IsNotFound(err) {
320319
// Create the secret
321320
ownerutil.AddNonBlockingOwner(secret, i.owner)

pkg/controller/install/certresources_test.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func selector(t *testing.T, selector string) *metav1.LabelSelector {
3737
return s
3838
}
3939

40-
var staticCerts *certs.KeyPair = nil
40+
var staticCerts *certs.KeyPair
4141

4242
// staticCertGenerator replaces the CertGenerator to get consistent keys for testing
4343
func staticCertGenerator(notAfter time.Time, organization string, ca *certs.KeyPair, hosts []string) (*certs.KeyPair, error) {
@@ -124,7 +124,6 @@ func TestInstallCertRequirementsForDeployment(t *testing.T) {
124124
assert.NoError(t, err)
125125
caHash := certs.PEMSHA256(caPEM)
126126
type fields struct {
127-
strategyClient wrappers.InstallStrategyDeploymentInterface
128127
owner ownerutil.Owner
129128
previousStrategy Strategy
130129
templateAnnotations map[string]string

pkg/controller/install/deployment.go

+3-25
Original file line numberDiff line numberDiff line change
@@ -179,23 +179,6 @@ func (i *StrategyDeploymentInstaller) deploymentForSpec(name string, spec appsv1
179179
return
180180
}
181181

182-
func (i *StrategyDeploymentInstaller) cleanupPrevious(current *v1alpha1.StrategyDetailsDeployment, previous *v1alpha1.StrategyDetailsDeployment) error {
183-
previousDeploymentsMap := map[string]struct{}{}
184-
for _, d := range previous.DeploymentSpecs {
185-
previousDeploymentsMap[d.Name] = struct{}{}
186-
}
187-
for _, d := range current.DeploymentSpecs {
188-
delete(previousDeploymentsMap, d.Name)
189-
}
190-
log.Debugf("preparing to cleanup: %s", previousDeploymentsMap)
191-
// delete deployments in old strategy but not new
192-
var err error = nil
193-
for name := range previousDeploymentsMap {
194-
err = i.strategyClient.DeleteDeployment(name)
195-
}
196-
return err
197-
}
198-
199182
func (i *StrategyDeploymentInstaller) Install(s Strategy) error {
200183
strategy, ok := s.(*v1alpha1.StrategyDetailsDeployment)
201184
if !ok {
@@ -235,11 +218,6 @@ func (i *StrategyDeploymentInstaller) CheckInstalled(s Strategy) (installed bool
235218
}
236219

237220
func (i *StrategyDeploymentInstaller) checkForDeployments(deploymentSpecs []v1alpha1.StrategyDeploymentSpec) error {
238-
var depNames []string
239-
for _, dep := range deploymentSpecs {
240-
depNames = append(depNames, dep.Name)
241-
}
242-
243221
// Check the owner is a CSV
244222
csv, ok := i.owner.(*v1alpha1.ClusterServiceVersion)
245223
if !ok {
@@ -273,7 +251,7 @@ func (i *StrategyDeploymentInstaller) checkForDeployments(deploymentSpecs []v1al
273251

274252
// check annotations
275253
if len(i.templateAnnotations) > 0 && dep.Spec.Template.Annotations == nil {
276-
return StrategyError{Reason: StrategyErrReasonAnnotationsMissing, Message: fmt.Sprintf("no annotations found on deployment")}
254+
return StrategyError{Reason: StrategyErrReasonAnnotationsMissing, Message: "no annotations found on deployment"}
277255
}
278256
for key, value := range i.templateAnnotations {
279257
if actualValue, ok := dep.Spec.Template.Annotations[key]; !ok {
@@ -286,11 +264,11 @@ func (i *StrategyDeploymentInstaller) checkForDeployments(deploymentSpecs []v1al
286264
// check that the deployment spec hasn't changed since it was created
287265
labels := dep.GetLabels()
288266
if len(labels) == 0 {
289-
return StrategyError{Reason: StrategyErrDeploymentUpdated, Message: fmt.Sprintf("deployment doesn't have a spec hash, update it")}
267+
return StrategyError{Reason: StrategyErrDeploymentUpdated, Message: fmt.Sprintf("deployment %s doesn't have a spec hash, update it", dep.Name)}
290268
}
291269
existingDeploymentSpecHash, ok := labels[DeploymentSpecHashLabelKey]
292270
if !ok {
293-
return StrategyError{Reason: StrategyErrDeploymentUpdated, Message: fmt.Sprintf("deployment doesn't have a spec hash, update it")}
271+
return StrategyError{Reason: StrategyErrDeploymentUpdated, Message: fmt.Sprintf("deployment %s doesn't have a spec hash, update it", dep.Name)}
294272
}
295273

296274
_, calculatedDeploymentHash, err := i.deploymentForSpec(spec.Name, spec.Spec, labels)

pkg/controller/install/rule_checker.go

-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,6 @@ func (c *CSVRuleChecker) RuleSatisfied(sa *corev1.ServiceAccount, namespace stri
6767
if decision == authorizer.DecisionDeny || decision == authorizer.DecisionNoOpinion {
6868
return false, nil
6969
}
70-
7170
}
7271

7372
return true, nil

pkg/controller/install/rule_checker_test.go

-2
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import (
2323
)
2424

2525
func TestRuleSatisfied(t *testing.T) {
26-
2726
csv := &v1alpha1.ClusterServiceVersion{}
2827
csv.SetName("barista-operator")
2928
csv.SetUID(types.UID("barista-operator"))
@@ -606,7 +605,6 @@ func NewFakeCSVRuleChecker(k8sObjs []runtime.Object, csv *v1alpha1.ClusterServic
606605
ruleChecker := NewCSVRuleChecker(roleInformer.Lister(), roleBindingInformer.Lister(), clusterRoleInformer.Lister(), clusterRoleBindingInformer.Lister(), csv)
607606

608607
return ruleChecker, nil
609-
610608
}
611609

612610
func Objs(roles []*rbacv1.Role, roleBindings []*rbacv1.RoleBinding, clusterRoles []*rbacv1.ClusterRole, clusterRoleBindings []*rbacv1.ClusterRoleBinding) []runtime.Object {

pkg/controller/install/webhook.go

+10-11
Original file line numberDiff line numberDiff line change
@@ -24,18 +24,18 @@ func ValidWebhookRules(rules []admissionregistrationv1.RuleWithOperations) error
2424

2525
// protect OLM resources
2626
if contains(apiGroupMap, "*") {
27-
return fmt.Errorf("Webhook rules cannot include all groups")
27+
return fmt.Errorf("webhook rules cannot include all groups")
2828
}
2929

3030
if contains(apiGroupMap, "operators.coreos.com") {
31-
return fmt.Errorf("Webhook rules cannot include the OLM group")
31+
return fmt.Errorf("webhook rules cannot include the OLM group")
3232
}
3333

3434
// protect Admission Webhook resources
3535
if contains(apiGroupMap, "admissionregistration.k8s.io") {
3636
resourceGroupMap := listToMap(rule.Resources)
3737
if contains(resourceGroupMap, "*") || contains(resourceGroupMap, "MutatingWebhookConfiguration") || contains(resourceGroupMap, "ValidatingWebhookConfiguration") {
38-
return fmt.Errorf("Webhook rules cannot include MutatingWebhookConfiguration or ValidatingWebhookConfiguration resources")
38+
return fmt.Errorf("webhook rules cannot include MutatingWebhookConfiguration or ValidatingWebhookConfiguration resources")
3939
}
4040
}
4141
}
@@ -58,7 +58,7 @@ func contains(m map[string]struct{}, tar string) bool {
5858
func (i *StrategyDeploymentInstaller) createOrUpdateWebhook(caPEM []byte, desc v1alpha1.WebhookDescription) error {
5959
operatorGroups, err := i.strategyClient.GetOpLister().OperatorsV1().OperatorGroupLister().OperatorGroups(i.owner.GetNamespace()).List(labels.Everything())
6060
if err != nil || len(operatorGroups) != 1 {
61-
return fmt.Errorf("Error retrieving OperatorGroup info")
61+
return fmt.Errorf("error retrieving OperatorGroup info")
6262
}
6363
ogNamespacelabelSelector, err := operatorGroups[0].NamespaceLabelSelector()
6464
if err != nil {
@@ -188,15 +188,14 @@ func (i *StrategyDeploymentInstaller) createOrUpdateConversionWebhook(caPEM []by
188188
// get a list of owned CRDs
189189
csv, ok := i.owner.(*v1alpha1.ClusterServiceVersion)
190190
if !ok {
191-
return fmt.Errorf("ConversionWebhook owner must be a ClusterServiceVersion")
191+
return fmt.Errorf("unable to manage conversion webhook: conversion webhook owner must be a ClusterServiceVersion")
192192
}
193-
194193
if !isSingletonOperator(*csv) {
195-
return fmt.Errorf("CSVs with conversion webhooks must support only AllNamespaces")
194+
return fmt.Errorf("unable to manage conversion webhook: CSVs with conversion webhooks must support only AllNamespaces")
196195
}
197196

198197
if len(desc.ConversionCRDs) == 0 {
199-
return fmt.Errorf("Conversion Webhook must have at least one CRD specified")
198+
return fmt.Errorf("unable to manager conversion webhook: conversion webhook must have at least one CRD specified")
200199
}
201200

202201
// iterate over all the ConversionCRDs
@@ -205,7 +204,7 @@ func (i *StrategyDeploymentInstaller) createOrUpdateConversionWebhook(caPEM []by
205204
// Get existing CRD on cluster
206205
crd, err := i.strategyClient.GetOpClient().ApiextensionsInterface().ApiextensionsV1().CustomResourceDefinitions().Get(context.TODO(), conversionCRD, metav1.GetOptions{})
207206
if err != nil {
208-
return fmt.Errorf("Unable to get CRD %s specified in Conversion Webhook: %v", conversionCRD, err)
207+
return fmt.Errorf("unable to get CRD %s specified in Conversion Webhook: %v", conversionCRD, err)
209208
}
210209

211210
// check if this CRD is an owned CRD
@@ -217,7 +216,7 @@ func (i *StrategyDeploymentInstaller) createOrUpdateConversionWebhook(caPEM []by
217216
}
218217
}
219218
if !foundCRD {
220-
return fmt.Errorf("CSV %s does not own CRD %s", csv.GetName(), conversionCRD)
219+
return fmt.Errorf("csv %s does not own CRD %s", csv.GetName(), conversionCRD)
221220
}
222221

223222
// crd.Spec.Conversion.Strategy specifies how custom resources are converted between versions.
@@ -230,7 +229,7 @@ func (i *StrategyDeploymentInstaller) createOrUpdateConversionWebhook(caPEM []by
230229
// By default the strategy is none
231230
// Reference:
232231
// - https://v1-15.docs.kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definition-versioning/#specify-multiple-versions
233-
if crd.Spec.PreserveUnknownFields != false {
232+
if crd.Spec.PreserveUnknownFields {
234233
return fmt.Errorf("crd.Spec.PreserveUnknownFields must be false to let API Server call webhook to do the conversion")
235234
}
236235

pkg/controller/operators/adoption_controller.go

+6-7
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ type AdoptionReconciler struct {
3737
client.Client
3838

3939
log logr.Logger
40-
mu sync.RWMutex
4140
factory decorators.OperatorFactory
4241
}
4342

@@ -268,7 +267,7 @@ func (r *AdoptionReconciler) adopt(ctx context.Context, operator *decorators.Ope
268267

269268
cObj, ok := component.(client.Object)
270269
if !ok {
271-
return fmt.Errorf("Unable to typecast runtime.Object to client.Object")
270+
return fmt.Errorf("unable to typecast runtime.Object to client.Object")
272271
}
273272

274273
if err := r.Get(ctx, types.NamespacedName{Namespace: m.GetNamespace(), Name: m.GetName()}, cObj); err != nil {
@@ -290,7 +289,7 @@ func (r *AdoptionReconciler) adopt(ctx context.Context, operator *decorators.Ope
290289
// Only update if freshly adopted
291290
pCObj, ok := candidate.(client.Object)
292291
if !ok {
293-
return fmt.Errorf("Unable to typecast runtime.Object to client.Object")
292+
return fmt.Errorf("unable to typecast runtime.Object to client.Object")
294293
}
295294
return r.Patch(ctx, pCObj, client.MergeFrom(cObj))
296295
}
@@ -301,7 +300,7 @@ func (r *AdoptionReconciler) adopt(ctx context.Context, operator *decorators.Ope
301300
func (r *AdoptionReconciler) disown(ctx context.Context, operator *decorators.Operator, component runtime.Object) error {
302301
cObj, ok := component.(client.Object)
303302
if !ok {
304-
return fmt.Errorf("Unable to typecast runtime.Object to client.Object")
303+
return fmt.Errorf("unable to typecast runtime.Object to client.Object")
305304
}
306305
candidate := component.DeepCopyObject()
307306
disowned, err := operator.DisownComponent(candidate)
@@ -318,15 +317,15 @@ func (r *AdoptionReconciler) disown(ctx context.Context, operator *decorators.Op
318317
r.log.V(1).Info("component disowned", "component", candidate)
319318
uCObj, ok := candidate.(client.Object)
320319
if !ok {
321-
return fmt.Errorf("Unable to typecast runtime.Object to client.Object")
320+
return fmt.Errorf("unable to typecast runtime.Object to client.Object")
322321
}
323322
return r.Patch(ctx, uCObj, client.MergeFrom(cObj))
324323
}
325324

326325
func (r *AdoptionReconciler) disownFromAll(ctx context.Context, component runtime.Object) error {
327326
cObj, ok := component.(client.Object)
328327
if !ok {
329-
return fmt.Errorf("Unable to typecast runtime.Object to client.Object")
328+
return fmt.Errorf("unable to typecast runtime.Object to client.Object")
330329
}
331330
var operators []decorators.Operator
332331
for _, name := range decorators.OperatorNames(cObj.GetLabels()) {
@@ -362,7 +361,7 @@ func (r *AdoptionReconciler) adoptees(ctx context.Context, operator decorators.O
362361
for _, list := range componentLists {
363362
cList, ok := list.(client.ObjectList)
364363
if !ok {
365-
return nil, fmt.Errorf("Unable to typecast runtime.Object to client.ObjectList")
364+
return nil, fmt.Errorf("unable to typecast runtime.Object to client.ObjectList")
366365
}
367366
if err := r.List(ctx, cList, opt); err != nil {
368367
return nil, err

0 commit comments

Comments
 (0)