From 8535fcc248ae6713535ca27e72bc8fca95201265 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Tue, 25 Jun 2024 03:27:07 -0400 Subject: [PATCH] gofumpt the repo (#3067) * gofumpt the repo * don't prefix numbers with 0 - otherwise they're octal --- apiextensions/storageversion/migrator_test.go | 87 +++++------ apis/condition_set.go | 3 +- apis/condition_set_impl_test.go | 8 +- apis/condition_types_test.go | 5 +- apis/convert.go | 2 - apis/convert_test.go | 3 - apis/deprecated_test.go | 3 - apis/duck/enqueue_test.go | 1 + apis/duck/patch_test.go | 7 +- apis/duck/unstructured_test.go | 9 +- apis/duck/v1/addressable_types.go | 6 +- apis/duck/v1/kresource_type.go | 2 +- apis/duck/v1/source_types.go | 2 +- apis/duck/v1beta1/destination.go | 1 + apis/duck/v1beta1/source_types.go | 2 +- apis/duck/v1beta1/status_types.go | 2 +- apis/duck/verify.go | 6 +- apis/duck/verify_test.go | 64 +++++--- apis/field_error_test.go | 1 - apis/kind2resource_test.go | 1 - apis/metadata_validation_test.go | 6 +- apis/test/example/v1alpha1/fiz_types.go | 10 +- apis/test/example/v1alpha1/foo_types.go | 10 +- apis/test/pub/v1alpha1/bar_types.go | 10 +- apis/testing/roundtrip/roundtrip.go | 2 - apis/url_test.go | 63 ++++---- changeset/commit_test.go | 1 - configmap/example.go | 6 +- configmap/filter_test.go | 8 +- configmap/hash-gen/main.go | 2 +- configmap/load_test.go | 4 +- configmap/store.go | 4 +- controller/controller.go | 14 +- controller/controller_test.go | 3 +- controller/stats_reporter.go | 1 - depcheck/depcheck_test.go | 1 - depcheck/heavy.go | 20 ++- environment/client_config.go | 1 - injection/sharedmain/main.go | 5 +- kmap/lookup_test.go | 1 - kmeta/names_test.go | 67 ++++---- kmeta/ownerrefable_accessor_test.go | 3 +- kmp/diff_test.go | 1 - kmp/reporters_test.go | 1 - kvstore/kvstore_cm.go | 5 +- leaderelection/config_test.go | 1 - leaderelection/context.go | 3 +- logging/config.go | 3 +- logging/config_test.go | 1 - metrics/config.go | 8 +- metrics/e2e_test.go | 4 +- metrics/exporter.go | 3 +- metrics/exporter_test.go | 3 +- metrics/metrics.go | 4 +- metrics/metricstest/metricstest.go | 1 - metrics/metricstest/resource_metrics.go | 3 +- metrics/metricstest/resource_metrics_test.go | 1 - metrics/prometheus_exporter.go | 2 +- metrics/resource_view.go | 25 +-- metrics/resource_view_test.go | 7 +- network/h2c.go | 2 +- profiling/server.go | 2 +- reconciler/testing/actions_test.go | 1 - .../testing/generate_name_reactor_test.go | 1 - reconciler/testing/reactions_test.go | 4 +- reconciler/testing/table.go | 3 +- resolver/addressable_resolver_test.go | 104 +++++++------ source/source_labels_test.go | 1 - test/cleanup_test.go | 1 - test/clients.go | 3 +- test/e2e_flags.go | 10 +- test/helpers/dir.go | 2 +- test/logstream/interface.go | 1 - test/request.go | 11 +- test/spoof/spoof.go | 13 +- test/spoof/spoof_test.go | 3 +- test/upgrade/functions.go | 3 +- test/upgrade/shell/executor.go | 2 +- test/vegeta/pacers/combined_pacer.go | 2 +- testing/duck/testbindable.go | 6 +- testing/inner_default_resource.go | 6 +- testing/resource.go | 8 +- tracker/interface.go | 1 - webhook/admission.go | 2 +- webhook/certificates/certificates.go | 6 +- webhook/certificates/controller.go | 1 - webhook/certificates/resources/certs.go | 4 +- webhook/configmaps/configmaps.go | 10 +- webhook/configmaps/configmaps_test.go | 3 +- webhook/configmaps/controller.go | 1 - webhook/configmaps/table_test.go | 15 +- webhook/conversion.go | 2 +- webhook/helper.go | 8 +- webhook/helper_test.go | 9 +- webhook/json/decode.go | 2 +- webhook/psbinding/controller.go | 1 - webhook/psbinding/psbinding.go | 17 ++- webhook/psbinding/reconciler.go | 7 +- webhook/psbinding/table_test.go | 143 ++++++++++-------- .../conversion/controller.go | 1 - .../conversion/conversion.go | 1 - .../conversion/conversion_test.go | 2 - .../conversion/reconciler.go | 8 +- .../defaulting/controller.go | 1 - .../defaulting/defaulting.go | 10 +- .../defaulting/defaulting_test.go | 6 +- .../defaulting/table_test.go | 18 ++- .../defaulting/user_info_test.go | 1 - .../validation/controller.go | 2 - .../validation/reconcile_config.go | 10 +- .../validation/reconcile_config_test.go | 25 +-- .../validation/validation_admit.go | 4 +- .../validation/validation_admit_test.go | 4 +- .../validation/validation_deprecated_test.go | 1 - webhook/stats_reporter.go | 6 +- webhook/testing/factory.go | 3 +- webhook/webhook.go | 5 +- webhook/webhook_test.go | 3 +- websocket/connection_test.go | 2 - 119 files changed, 551 insertions(+), 516 deletions(-) diff --git a/apiextensions/storageversion/migrator_test.go b/apiextensions/storageversion/migrator_test.go index f5b50c3340..95a48930a1 100644 --- a/apiextensions/storageversion/migrator_test.go +++ b/apiextensions/storageversion/migrator_test.go @@ -136,50 +136,51 @@ func TestMigrate_Errors(t *testing.T) { crd func(*k8stesting.Fake) dyn func(*k8stesting.Fake) pass bool - }{{ - name: "failed to fetch CRD", - crd: func(fake *k8stesting.Fake) { - fake.PrependReactor("get", "*", - func(k8stesting.Action) (bool, runtime.Object, error) { - return true, nil, errors.New("failed to get crd") - }) - }, - }, { - name: "listing fails", - dyn: func(fake *k8stesting.Fake) { - fake.PrependReactor("list", "*", - func(k8stesting.Action) (bool, runtime.Object, error) { - return true, nil, errors.New("failed to list resources") - }) - }, - }, { - name: "patching resource fails", - dyn: func(fake *k8stesting.Fake) { - fake.PrependReactor("patch", "*", - func(k8stesting.Action) (bool, runtime.Object, error) { - return true, nil, errors.New("failed to patch resources") - }) - }, - }, { - name: "patching definition fails", - crd: func(fake *k8stesting.Fake) { - fake.PrependReactor("patch", "*", - func(k8stesting.Action) (bool, runtime.Object, error) { - return true, nil, errors.New("failed to patch definition") - }) - }, - }, { - name: "patching unexisting resource", - dyn: func(fake *k8stesting.Fake) { - fake.PrependReactor("patch", "*", - func(k8stesting.Action) (bool, runtime.Object, error) { - return true, nil, apierrs.NewNotFound(fakeGR, "resource-removed") - }) + }{ + { + name: "failed to fetch CRD", + crd: func(fake *k8stesting.Fake) { + fake.PrependReactor("get", "*", + func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, errors.New("failed to get crd") + }) + }, + }, { + name: "listing fails", + dyn: func(fake *k8stesting.Fake) { + fake.PrependReactor("list", "*", + func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, errors.New("failed to list resources") + }) + }, + }, { + name: "patching resource fails", + dyn: func(fake *k8stesting.Fake) { + fake.PrependReactor("patch", "*", + func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, errors.New("failed to patch resources") + }) + }, + }, { + name: "patching definition fails", + crd: func(fake *k8stesting.Fake) { + fake.PrependReactor("patch", "*", + func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, errors.New("failed to patch definition") + }) + }, + }, { + name: "patching unexisting resource", + dyn: func(fake *k8stesting.Fake) { + fake.PrependReactor("patch", "*", + func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, apierrs.NewNotFound(fakeGR, "resource-removed") + }) + }, + // Resouce not found error should not block the storage migration. + pass: true, }, - // Resouce not found error should not block the storage migration. - pass: true, - }, - // todo paging fails + // todo paging fails } for _, test := range tests { diff --git a/apis/condition_set.go b/apis/condition_set.go index 1b110475ff..9ad14902e7 100644 --- a/apis/condition_set.go +++ b/apis/condition_set.go @@ -17,12 +17,11 @@ limitations under the License. package apis import ( + "fmt" "reflect" "sort" "time" - "fmt" - corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) diff --git a/apis/condition_set_impl_test.go b/apis/condition_set_impl_test.go index 63e4265c1e..ea829f4ef5 100644 --- a/apis/condition_set_impl_test.go +++ b/apis/condition_set_impl_test.go @@ -40,9 +40,7 @@ func (t *TestStatus) SetConditions(conditions Conditions) { t.c = conditions } -var ( - ignoreFields = cmpopts.IgnoreFields(Condition{}, "LastTransitionTime", "Severity") -) +var ignoreFields = cmpopts.IgnoreFields(Condition{}, "LastTransitionTime", "Severity") func TestGetCondition(t *testing.T) { condSet := NewLivingConditionSet() @@ -318,7 +316,6 @@ func TestUpdateLastTransitionTime(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - conds := &TestStatus{c: tc.conditions} was := condSet.Manage(conds).GetCondition(tc.condition.Type) @@ -821,7 +818,6 @@ type ConditionMarkFalseTest struct { func doTestMarkFalseAccessor(t *testing.T, cases []ConditionMarkFalseTest) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - condSet := NewLivingConditionSet(getTypes(tc.conditions)...) status := &TestStatus{c: tc.conditions} condSet.Manage(status).InitializeConditions() @@ -933,7 +929,6 @@ type ConditionMarkUnknownTest struct { func doTestMarkUnknownAccessor(t *testing.T, cases []ConditionMarkUnknownTest) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - condSet := NewLivingConditionSet(getTypes(tc.conditions)...) status := &TestStatus{c: tc.conditions} @@ -1171,5 +1166,4 @@ func TestClearConditionWithNilManager(t *testing.T) { if err != nil { t.Error("ClearCondition() expected to return nil if status is nil, got", err) } - } diff --git a/apis/condition_types_test.go b/apis/condition_types_test.go index a55bdebea6..bf476837e1 100644 --- a/apis/condition_types_test.go +++ b/apis/condition_types_test.go @@ -237,7 +237,7 @@ func TestJSON(t *testing.T) { name: "LastTransitionTime", raw: `{"lastTransitionTime":"1984-02-28T18:52:00Z"}`, condition: &Condition{ - LastTransitionTime: VolatileTime{Inner: metav1.NewTime(time.Date(1984, 02, 28, 18, 52, 00, 00, time.UTC))}, + LastTransitionTime: VolatileTime{Inner: metav1.NewTime(time.Date(1984, 2, 28, 18, 52, 0, 0, time.UTC))}, }, }, { name: "Reason", @@ -263,7 +263,7 @@ func TestJSON(t *testing.T) { condition: &Condition{ Type: "Foo", Status: corev1.ConditionTrue, - LastTransitionTime: VolatileTime{Inner: metav1.NewTime(time.Date(1984, 02, 28, 18, 52, 00, 00, time.UTC))}, + LastTransitionTime: VolatileTime{Inner: metav1.NewTime(time.Date(1984, 2, 28, 18, 52, 0, 0, time.UTC))}, Reason: "DatTest", Message: "this is just a test", }, @@ -278,7 +278,6 @@ func TestJSON(t *testing.T) { if diff := cmp.Diff(tc.condition, cond); diff != "" { t.Errorf("%q unexpected diff (-want +got): %s", tc.name, diff) } - }) } } diff --git a/apis/convert.go b/apis/convert.go index d6a28a0727..72e9b67618 100644 --- a/apis/convert.go +++ b/apis/convert.go @@ -24,7 +24,6 @@ func ConvertToViaProxy( ctx context.Context, source, proxy, sink Convertible, ) error { - if err := source.ConvertTo(ctx, proxy); err != nil { return err } @@ -38,7 +37,6 @@ func ConvertFromViaProxy( ctx context.Context, source, proxy, sink Convertible, ) error { - if err := proxy.ConvertFrom(ctx, source); err != nil { return err } diff --git a/apis/convert_test.go b/apis/convert_test.go index c6f35415e9..a0b03c6510 100644 --- a/apis/convert_test.go +++ b/apis/convert_test.go @@ -28,7 +28,6 @@ func TestConvertToViaProxy(t *testing.T) { source := &testResource{proxy: proxy} err := ConvertToViaProxy(context.Background(), source, proxy, sink) - if err != nil { t.Error("ConvertToViaProxy returned unexpected err:", err) } @@ -81,7 +80,6 @@ func TestConvertFromViaProxy(t *testing.T) { source := &testResource{} err := ConvertFromViaProxy(context.Background(), source, proxy, sink) - if err != nil { t.Error("ConvertFromViaProxy returned unexpected err:", err) } @@ -115,7 +113,6 @@ func TestConvertFromViaProxyError(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - err := ConvertFromViaProxy(context.Background(), nil, /* source */ &test.proxy, diff --git a/apis/deprecated_test.go b/apis/deprecated_test.go index 930c89b31f..dbac49d9b5 100644 --- a/apis/deprecated_test.go +++ b/apis/deprecated_test.go @@ -27,7 +27,6 @@ import ( ) func TestCheckDeprecated(t *testing.T) { - testCases := map[string]struct { strict bool obj interface{} @@ -226,7 +225,6 @@ func TestCheckDeprecated(t *testing.T) { // It comes in on obj.InlinedStruct.InlinedPtrStruct.DeprecatedField and // obj.InlinedPtrStruct.DeprecatedField. func TestCheckDeprecated_Dedupe(t *testing.T) { - obj := &InnerDefaultSubSpec{ InlinedStruct: InlinedStruct{ DeprecatedField: "fail", @@ -250,7 +248,6 @@ func TestCheckDeprecated_Dedupe(t *testing.T) { } func TestCheckDeprecatedUpdate(t *testing.T) { - testCases := map[string]struct { strict bool obj interface{} diff --git a/apis/duck/enqueue_test.go b/apis/duck/enqueue_test.go index 908d7e2b28..33022ab4b6 100644 --- a/apis/duck/enqueue_test.go +++ b/apis/duck/enqueue_test.go @@ -183,6 +183,7 @@ func (fsii *fakeSharedIndexInformer) IsStopped() bool { fsii.t.Fatalf("NYI: IsStopped") return false } + func (fsii *fakeSharedIndexInformer) RemoveEventHandler(handler cache.ResourceEventHandlerRegistration) error { fsii.t.Fatalf("NYI: RemoveEventHandler") return nil diff --git a/apis/duck/patch_test.go b/apis/duck/patch_test.go index 5ade803736..2ea2f5601d 100644 --- a/apis/duck/patch_test.go +++ b/apis/duck/patch_test.go @@ -333,7 +333,6 @@ func TestCreatePatch(t *testing.T) { if diff := cmp.Diff(want, got); diff != "" { t.Error("CreateBytePatch (-want, +got) =", diff) } - }) t.Run(test.name, func(t *testing.T) { got, err := CreatePatch(test.before, test.after) @@ -398,8 +397,10 @@ type PatchSpec struct { Patchable *Patchable `json:"patchable,omitempty"` } -var _ Implementable = (*Patchable)(nil) -var _ Populatable = (*Patch)(nil) +var ( + _ Implementable = (*Patchable)(nil) + _ Populatable = (*Patch)(nil) +) func (*Patch) GetObjectKind() schema.ObjectKind { return nil // not used diff --git a/apis/duck/unstructured_test.go b/apis/duck/unstructured_test.go index 25aacd07e0..8eadf8a82f 100644 --- a/apis/duck/unstructured_test.go +++ b/apis/duck/unstructured_test.go @@ -17,11 +17,10 @@ limitations under the License. package duck import ( + "encoding/json" "errors" "testing" - "encoding/json" - "github.com/google/go-cmp/cmp" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -48,7 +47,8 @@ func TestFromUnstructuredFooable(t *testing.T) { "field2": "bar", }, }, - }}, + }, + }, want: FooStatus{&Fooable{ Field1: "foo", Field2: "bar", @@ -64,7 +64,8 @@ func TestFromUnstructuredFooable(t *testing.T) { "status": map[string]interface{}{ "extra": "fields", }, - }}, + }, + }, want: FooStatus{}, wantError: nil, }, { diff --git a/apis/duck/v1/addressable_types.go b/apis/duck/v1/addressable_types.go index a855c38571..3877683c30 100644 --- a/apis/duck/v1/addressable_types.go +++ b/apis/duck/v1/addressable_types.go @@ -54,10 +54,8 @@ type Addressable struct { Audience *string `json:"audience,omitempty"` } -var ( - // Addressable is a Convertible type. - _ apis.Convertible = (*Addressable)(nil) -) +// Addressable is a Convertible type. +var _ apis.Convertible = (*Addressable)(nil) // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object diff --git a/apis/duck/v1/kresource_type.go b/apis/duck/v1/kresource_type.go index 1f6ee8264e..9229ba9306 100644 --- a/apis/duck/v1/kresource_type.go +++ b/apis/duck/v1/kresource_type.go @@ -68,7 +68,7 @@ func (t *KResource) Populate() { // Populate ALL fields Type: "Birthday", Status: corev1.ConditionTrue, - LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Date(1984, 02, 28, 18, 52, 00, 00, time.UTC))}, + LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Date(1984, 2, 28, 18, 52, 0, 0, time.UTC))}, Reason: "Celebrate", Message: "n3wScott, find your party hat :tada:", }} diff --git a/apis/duck/v1/source_types.go b/apis/duck/v1/source_types.go index 95b7d1417d..284ab318dd 100644 --- a/apis/duck/v1/source_types.go +++ b/apis/duck/v1/source_types.go @@ -158,7 +158,7 @@ func (s *Source) Populate() { // Populate ALL fields Type: SourceConditionSinkProvided, Status: corev1.ConditionTrue, - LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Date(1984, 02, 28, 18, 52, 00, 00, time.UTC))}, + LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Date(1984, 2, 28, 18, 52, 0, 0, time.UTC))}, }} s.Status.SinkURI = &apis.URL{ Scheme: "https", diff --git a/apis/duck/v1beta1/destination.go b/apis/duck/v1beta1/destination.go index ba83f1d4ee..41c7702df1 100644 --- a/apis/duck/v1beta1/destination.go +++ b/apis/duck/v1beta1/destination.go @@ -167,6 +167,7 @@ func validateDestinationRef(ref corev1.ObjectReference) *apis.FieldError { return errs } + func validateCACerts(CACert *string) *apis.FieldError { // Check the object. var errs *apis.FieldError diff --git a/apis/duck/v1beta1/source_types.go b/apis/duck/v1beta1/source_types.go index 60a502041a..e1056cf828 100644 --- a/apis/duck/v1beta1/source_types.go +++ b/apis/duck/v1beta1/source_types.go @@ -129,7 +129,7 @@ func (s *Source) Populate() { // Populate ALL fields Type: SourceConditionSinkProvided, Status: corev1.ConditionTrue, - LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Date(1984, 02, 28, 18, 52, 00, 00, time.UTC))}, + LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Date(1984, 2, 28, 18, 52, 0, 0, time.UTC))}, }} s.Status.SinkURI = &apis.URL{ Scheme: "https", diff --git a/apis/duck/v1beta1/status_types.go b/apis/duck/v1beta1/status_types.go index e1ae875eb4..30f4354ac4 100644 --- a/apis/duck/v1beta1/status_types.go +++ b/apis/duck/v1beta1/status_types.go @@ -129,7 +129,7 @@ func (t *KResource) Populate() { // Populate ALL fields Type: "Birthday", Status: corev1.ConditionTrue, - LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Date(1984, 02, 28, 18, 52, 00, 00, time.UTC))}, + LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Date(1984, 2, 28, 18, 52, 0, 0, time.UTC))}, Reason: "Celebrate", Message: "n3wScott, find your party hat :tada:", }} diff --git a/apis/duck/verify.go b/apis/duck/verify.go index 48675f93a4..4e33e65972 100644 --- a/apis/duck/verify.go +++ b/apis/duck/verify.go @@ -24,8 +24,10 @@ import ( "knative.dev/pkg/kmp" ) -type Implementable = ducktypes.Implementable -type Populatable = ducktypes.Populatable +type ( + Implementable = ducktypes.Implementable + Populatable = ducktypes.Populatable +) // VerifyType verifies that a particular concrete resource properly implements // the provided Implementable duck type. It is expected that under the resource diff --git a/apis/duck/verify_test.go b/apis/duck/verify_test.go index ec737d1180..8dd7e23795 100644 --- a/apis/duck/verify_test.go +++ b/apis/duck/verify_test.go @@ -106,7 +106,6 @@ func TestMatches(t *testing.T) { } ok, err := ConformsToType(test.instance, test.iface) - if err != nil { t.Error(err) } @@ -160,7 +159,6 @@ func TestMismatches(t *testing.T) { } ok, err := ConformsToType(test.instance, test.iface) - if err != nil { t.Error(err) } @@ -224,8 +222,10 @@ type FooStatus struct { Fooable *Fooable `json:"fooable,omitempty"` } -var _ Implementable = (*Fooable)(nil) -var _ Populatable = (*Foo)(nil) +var ( + _ Implementable = (*Fooable)(nil) + _ Populatable = (*Foo)(nil) +) func (*Foo) GetObjectKind() schema.ObjectKind { return nil // not used @@ -263,8 +263,10 @@ type BarStatus struct { Barable *Barable `json:"barable,omitempty"` } -var _ Implementable = (*Barable)(nil) -var _ Populatable = (*Bar)(nil) +var ( + _ Implementable = (*Barable)(nil) + _ Populatable = (*Bar)(nil) +) func (*Bar) GetObjectKind() schema.ObjectKind { return nil // not used @@ -294,16 +296,20 @@ func (f *Bar) Populate() { type AStruct struct { Field string `json:"field,omitempty"` } -type Sliceable []AStruct -type Slice struct { - Status SliceStatus `json:"status"` -} +type ( + Sliceable []AStruct + Slice struct { + Status SliceStatus `json:"status"` + } +) type SliceStatus struct { Sliceable *Sliceable `json:"sliceable,omitempty"` } -var _ Implementable = (*Sliceable)(nil) -var _ Populatable = (*Slice)(nil) +var ( + _ Implementable = (*Sliceable)(nil) + _ Populatable = (*Slice)(nil) +) func (*Slice) GetObjectKind() schema.ObjectKind { return nil // not used @@ -326,16 +332,20 @@ func (f *Slice) Populate() { } // Define a "Stringable" duck type. -type Stringable string -type String struct { - Status StringStatus `json:"status"` -} +type ( + Stringable string + String struct { + Status StringStatus `json:"status"` + } +) type StringStatus struct { Stringable Stringable `json:"stringable,omitempty"` } -var _ Implementable = (*Stringable)(nil) -var _ Populatable = (*String)(nil) +var ( + _ Implementable = (*Stringable)(nil) + _ Populatable = (*String)(nil) +) func (*String) GetObjectKind() schema.ObjectKind { return nil // not used @@ -364,8 +374,10 @@ var emptyStringable Stringable // and 'Populatable' type UnableToMarshal struct{} -var _ Implementable = (*UnableToMarshal)(nil) -var _ Populatable = (*UnableToMarshal)(nil) +var ( + _ Implementable = (*UnableToMarshal)(nil) + _ Populatable = (*UnableToMarshal)(nil) +) func (*UnableToMarshal) GetObjectKind() schema.ObjectKind { return nil // not used @@ -394,8 +406,10 @@ func (*UnableToMarshal) MarshalJSON() ([]byte, error) { // and 'Populatable' type UnableToUnmarshal struct{} -var _ Implementable = (*UnableToUnmarshal)(nil) -var _ Populatable = (*UnableToUnmarshal)(nil) +var ( + _ Implementable = (*UnableToUnmarshal)(nil) + _ Populatable = (*UnableToUnmarshal)(nil) +) func (*UnableToUnmarshal) GetObjectKind() schema.ObjectKind { return nil // not used @@ -426,8 +440,10 @@ type UnexportedFields struct { a string } -var _ Implementable = (*UnexportedFields)(nil) -var _ Populatable = (*UnexportedFields)(nil) +var ( + _ Implementable = (*UnexportedFields)(nil) + _ Populatable = (*UnexportedFields)(nil) +) func (*UnexportedFields) GetObjectKind() schema.ObjectKind { return nil // not used diff --git a/apis/field_error_test.go b/apis/field_error_test.go index a52fb9e6af..4a3828dca1 100644 --- a/apis/field_error_test.go +++ b/apis/field_error_test.go @@ -510,7 +510,6 @@ can not use @, do not try`, }, { name: "manual multiple index", err: func() *FieldError { - err := &FieldError{ Message: "invalid field(s)", Paths: []string{"foo"}, diff --git a/apis/kind2resource_test.go b/apis/kind2resource_test.go index 94fb8b3003..c7f96d26c7 100644 --- a/apis/kind2resource_test.go +++ b/apis/kind2resource_test.go @@ -24,7 +24,6 @@ import ( ) func TestGVK2GVR(t *testing.T) { - tests := []struct { name string input schema.GroupVersionKind diff --git a/apis/metadata_validation_test.go b/apis/metadata_validation_test.go index 3b46442f61..4a1d7b11f6 100644 --- a/apis/metadata_validation_test.go +++ b/apis/metadata_validation_test.go @@ -145,8 +145,10 @@ func TestServiceAnnotationUpdate(t *testing.T) { this: nil, oldAnnotation: getAnnotation(groupName, CreatorAnnotationSuffix, u1), newAnnotation: getAnnotation(groupName, CreatorAnnotationSuffix, u2), - want: &FieldError{Message: "annotation value is immutable", - Paths: []string{groupName + CreatorAnnotationSuffix}}, + want: &FieldError{ + Message: "annotation value is immutable", + Paths: []string{groupName + CreatorAnnotationSuffix}, + }, }, { name: "update lastModifier without spec changes", prev: nil, diff --git a/apis/test/example/v1alpha1/fiz_types.go b/apis/test/example/v1alpha1/fiz_types.go index 8b0fbe472c..58a45844e3 100644 --- a/apis/test/example/v1alpha1/fiz_types.go +++ b/apis/test/example/v1alpha1/fiz_types.go @@ -47,10 +47,12 @@ type ClusterFiz struct { } // Check that ClusterFiz can be validated and defaulted. -var _ apis.Validatable = (*ClusterFiz)(nil) -var _ apis.Defaultable = (*ClusterFiz)(nil) -var _ kmeta.OwnerRefable = (*ClusterFiz)(nil) -var _ duckv1.KRShaped = (*ClusterFiz)(nil) +var ( + _ apis.Validatable = (*ClusterFiz)(nil) + _ apis.Defaultable = (*ClusterFiz)(nil) + _ kmeta.OwnerRefable = (*ClusterFiz)(nil) + _ duckv1.KRShaped = (*ClusterFiz)(nil) +) // ClusterFizSpec holds the desired state of the ClusterFiz (from the client). type ClusterFizSpec struct{} diff --git a/apis/test/example/v1alpha1/foo_types.go b/apis/test/example/v1alpha1/foo_types.go index e971637551..884de268a7 100644 --- a/apis/test/example/v1alpha1/foo_types.go +++ b/apis/test/example/v1alpha1/foo_types.go @@ -46,10 +46,12 @@ type Foo struct { } // Check that Foo can be validated and defaulted. -var _ apis.Validatable = (*Foo)(nil) -var _ apis.Defaultable = (*Foo)(nil) -var _ kmeta.OwnerRefable = (*Foo)(nil) -var _ duckv1.KRShaped = (*Foo)(nil) +var ( + _ apis.Validatable = (*Foo)(nil) + _ apis.Defaultable = (*Foo)(nil) + _ kmeta.OwnerRefable = (*Foo)(nil) + _ duckv1.KRShaped = (*Foo)(nil) +) // FooSpec holds the desired state of the Foo (from the client). type FooSpec struct{} diff --git a/apis/test/pub/v1alpha1/bar_types.go b/apis/test/pub/v1alpha1/bar_types.go index 4af6f8928c..8ce0649d7b 100644 --- a/apis/test/pub/v1alpha1/bar_types.go +++ b/apis/test/pub/v1alpha1/bar_types.go @@ -46,10 +46,12 @@ type Bar struct { } // Check that Bar can be validated and defaulted. -var _ apis.Validatable = (*Bar)(nil) -var _ apis.Defaultable = (*Bar)(nil) -var _ kmeta.OwnerRefable = (*Bar)(nil) -var _ duckv1.KRShaped = (*Bar)(nil) +var ( + _ apis.Validatable = (*Bar)(nil) + _ apis.Defaultable = (*Bar)(nil) + _ kmeta.OwnerRefable = (*Bar)(nil) + _ duckv1.KRShaped = (*Bar)(nil) +) // BarSpec holds the desired state of the Bar (from the client). type BarSpec struct{} diff --git a/apis/testing/roundtrip/roundtrip.go b/apis/testing/roundtrip/roundtrip.go index afb4bee493..bdf33349f1 100644 --- a/apis/testing/roundtrip/roundtrip.go +++ b/apis/testing/roundtrip/roundtrip.go @@ -203,7 +203,6 @@ func objForGVK(t *testing.T, gvk schema.GroupVersionKind, scheme *runtime.Scheme, ) convertibleObject { - t.Helper() obj, err := scheme.New(gvk) @@ -235,7 +234,6 @@ func hubInstanceForGK(t *testing.T, hubs *runtime.Scheme, gk schema.GroupKind, ) (apis.Convertible, schema.GroupVersionKind) { - t.Helper() for hubGVK := range hubs.AllKnownTypes() { diff --git a/apis/url_test.go b/apis/url_test.go index ed3aa2aa84..e7a20b7c2e 100644 --- a/apis/url_test.go +++ b/apis/url_test.go @@ -67,7 +67,6 @@ func TestParseURL(t *testing.T) { }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - got, err := ParseURL(tc.t) if err != nil { if !tc.wantErr { @@ -157,7 +156,6 @@ func TestJSONUnmarshalURL(t *testing.T) { } for n, tc := range testCases { t.Run(n, func(t *testing.T) { - got := &URL{} err := got.UnmarshalJSON(tc.b) @@ -215,7 +213,6 @@ func TestJSONMarshalURLAsMember(t *testing.T) { } for n, tc := range testCases { t.Run(n, func(t *testing.T) { - got, err := json.Marshal(tc.obj) if tc.wantErr != "" || err != nil { @@ -273,7 +270,6 @@ func TestJSONMarshalURLAsPointerMember(t *testing.T) { } for n, tc := range testCases { t.Run(n, func(t *testing.T) { - got, err := json.Marshal(tc.obj) if tc.wantErr != "" || err != nil { @@ -334,7 +330,6 @@ func TestJSONUnmarshalURLAsMember(t *testing.T) { } for n, tc := range testCases { t.Run(n, func(t *testing.T) { - got := &objectType{} err := json.Unmarshal(tc.b, got) @@ -365,38 +360,38 @@ func TestJSONUnmarshalURLAsMemberPointer(t *testing.T) { b []byte want *objectType wantErr string - }{{ - name: "zero", - wantErr: "unexpected end of JSON input", - }, { - name: "empty", - b: []byte(`{}`), - want: &objectType{}, - }, { - name: "invalid format", - b: []byte(`{"url":"%"}`), - wantErr: `invalid URL escape "%"`, - }, { - name: "relative", - b: []byte(`{"url":"/path/to/something"}`), - want: &objectType{URL: &URL{Path: "/path/to/something"}}, - }, { - name: "url", - b: []byte(`{"url":"http://path/to/something"}`), - want: &objectType{URL: &URL{ - Scheme: "http", - Host: "path", - Path: "/to/something", - }}, - }, { - name: "empty url", - b: []byte(`{"url":""}`), - want: &objectType{URL: &URL{}}, - }, + }{ + { + name: "zero", + wantErr: "unexpected end of JSON input", + }, { + name: "empty", + b: []byte(`{}`), + want: &objectType{}, + }, { + name: "invalid format", + b: []byte(`{"url":"%"}`), + wantErr: `invalid URL escape "%"`, + }, { + name: "relative", + b: []byte(`{"url":"/path/to/something"}`), + want: &objectType{URL: &URL{Path: "/path/to/something"}}, + }, { + name: "url", + b: []byte(`{"url":"http://path/to/something"}`), + want: &objectType{URL: &URL{ + Scheme: "http", + Host: "path", + Path: "/to/something", + }}, + }, { + name: "empty url", + b: []byte(`{"url":""}`), + want: &objectType{URL: &URL{}}, + }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - got := &objectType{} err := json.Unmarshal(tc.b, got) diff --git a/changeset/commit_test.go b/changeset/commit_test.go index a764d18651..e880efa091 100644 --- a/changeset/commit_test.go +++ b/changeset/commit_test.go @@ -25,7 +25,6 @@ import ( ) func TestGet(t *testing.T) { - cases := []struct { name string info *debug.BuildInfo diff --git a/configmap/example.go b/configmap/example.go index f14a6e6ff5..82aaf93980 100644 --- a/configmap/example.go +++ b/configmap/example.go @@ -31,10 +31,8 @@ const ( ExampleChecksumAnnotation = "knative.dev/example-checksum" ) -var ( - // Allows for normalizing by collapsing newlines. - sequentialNewlines = regexp.MustCompile("(?:\r?\n)+") -) +// Allows for normalizing by collapsing newlines. +var sequentialNewlines = regexp.MustCompile("(?:\r?\n)+") // Checksum generates a checksum for the example value to be compared against // a respective annotation. diff --git a/configmap/filter_test.go b/configmap/filter_test.go index 4d054f48a6..6e65eea919 100644 --- a/configmap/filter_test.go +++ b/configmap/filter_test.go @@ -18,13 +18,15 @@ package configmap import "testing" -type foo struct{} -type bar struct{} +type ( + foo struct{} + bar struct{} +) func TestTypeFilter(t *testing.T) { count := 0 - var f = func(name string, value interface{}) { + f := func(name string, value interface{}) { count++ } diff --git a/configmap/hash-gen/main.go b/configmap/hash-gen/main.go index a2b154d92d..6703677aef 100644 --- a/configmap/hash-gen/main.go +++ b/configmap/hash-gen/main.go @@ -49,7 +49,7 @@ func processFile(fileName string) error { } //nolint:gosec // This is not security critical so open permissions are fine. - if err := os.WriteFile(fileName, out, 0644); err != nil { + if err := os.WriteFile(fileName, out, 0o644); err != nil { return fmt.Errorf("failed to write file: %w", err) } return nil diff --git a/configmap/load_test.go b/configmap/load_test.go index 0516b437e4..8321da49dd 100644 --- a/configmap/load_test.go +++ b/configmap/load_test.go @@ -48,7 +48,7 @@ func TestLoad(t *testing.T) { nowUnix := time.Now().Unix() tsPart := fmt.Sprintf("..%d", nowUnix) tsDir := path.Join(tmpdir, tsPart) - if err := os.Mkdir(tsDir, 0755); err != nil { + if err := os.Mkdir(tsDir, 0o755); err != nil { t.Fatal("Mkdir() =", err) } dataLink := path.Join(tmpdir, "..data") @@ -59,7 +59,7 @@ func TestLoad(t *testing.T) { // Write out the files as they should be loaded. for k, v := range want { // Write the actual file to $/.{timestamp}/key - if err := os.WriteFile(path.Join(tsDir, k), []byte(v), 0644); err != nil { + if err := os.WriteFile(path.Join(tsDir, k), []byte(v), 0o644); err != nil { t.Fatalf("WriteFile(..{ts}/%s) = %v", k, err) } // Symlink $/key => $/..data/key diff --git a/configmap/store.go b/configmap/store.go index 375a474c26..e265802190 100644 --- a/configmap/store.go +++ b/configmap/store.go @@ -81,8 +81,8 @@ func NewUntypedStore( name string, logger Logger, constructors Constructors, - onAfterStore ...func(name string, value interface{})) *UntypedStore { - + onAfterStore ...func(name string, value interface{}), +) *UntypedStore { store := &UntypedStore{ name: name, logger: logger, diff --git a/controller/controller.go b/controller/controller.go index 9fdb0a9d58..bc7c4be495 100644 --- a/controller/controller.go +++ b/controller/controller.go @@ -54,14 +54,12 @@ const ( DefaultResyncPeriod = 10 * time.Hour ) -var ( - // DefaultThreadsPerController is the number of threads to use - // when processing the controller's workqueue. Controller binaries - // may adjust this process-wide default. For finer control, invoke - // Run on the controller directly. - // TODO rename the const to Concurrency and deprecated this - DefaultThreadsPerController = 2 -) +// DefaultThreadsPerController is the number of threads to use +// when processing the controller's workqueue. Controller binaries +// may adjust this process-wide default. For finer control, invoke +// Run on the controller directly. +// TODO rename the const to Concurrency and deprecated this +var DefaultThreadsPerController = 2 // Reconciler is the interface that controller implementations are expected // to implement, so that the shared controller.Impl can drive work through it. diff --git a/controller/controller_test.go b/controller/controller_test.go index 19b5e70fba..0c29fafedd 100644 --- a/controller/controller_test.go +++ b/controller/controller_test.go @@ -699,7 +699,8 @@ func TestEnqueue(t *testing.T) { ObjectMeta: metav1.ObjectMeta{ Name: "foo", Namespace: "bar", - }}) + }, + }) }, wantQueue: []types.NamespacedName{{Name: "bar"}}, }, { diff --git a/controller/stats_reporter.go b/controller/stats_reporter.go index 6735285db4..99386f91b2 100644 --- a/controller/stats_reporter.go +++ b/controller/stats_reporter.go @@ -194,7 +194,6 @@ func (r *reporter) ReportReconcile(duration time.Duration, success string, key t tag.Insert(successTagKey, success), tag.Insert(NamespaceTagKey, key.Namespace), ) - if err != nil { return err } diff --git a/depcheck/depcheck_test.go b/depcheck/depcheck_test.go index e54ca2c4de..03e6c3cc26 100644 --- a/depcheck/depcheck_test.go +++ b/depcheck/depcheck_test.go @@ -29,7 +29,6 @@ import ( // TestExample doesn't follow the Go Example style because it isn't well // suited for libraries needing *testing.T func TestExample(t *testing.T) { - // For larger packages, it can make the most sense to simply avoid // known "heavy" packages, which pull in large amount of code or data. depcheck.AssertNoDependency(t, map[string][]string{ diff --git a/depcheck/heavy.go b/depcheck/heavy.go index d984ed998a..18498fa147 100644 --- a/depcheck/heavy.go +++ b/depcheck/heavy.go @@ -16,15 +16,13 @@ limitations under the License. package depcheck -var ( - // KnownHeavyDependencies is a list of dependencies that are known to increase the - // binary's size by a lot. - KnownHeavyDependencies = []string{ - "k8s.io/apimachinery/pkg/api/apitesting/fuzzer", +// KnownHeavyDependencies is a list of dependencies that are known to increase the +// binary's size by a lot. +var KnownHeavyDependencies = []string{ + "k8s.io/apimachinery/pkg/api/apitesting/fuzzer", - // As of 2020/10/27 this adds about 13MB to overall binary size. - "k8s.io/client-go/kubernetes", - // As of 2020/10/27 this adds about 7MB to overall binary size. - "contrib.go.opencensus.io/exporter/stackdriver", - } -) + // As of 2020/10/27 this adds about 13MB to overall binary size. + "k8s.io/client-go/kubernetes", + // As of 2020/10/27 this adds about 7MB to overall binary size. + "contrib.go.opencensus.io/exporter/stackdriver", +} diff --git a/environment/client_config.go b/environment/client_config.go index aef33927ef..9f1883d236 100644 --- a/environment/client_config.go +++ b/environment/client_config.go @@ -86,7 +86,6 @@ func (c *ClientConfig) GetRESTConfig() (*rest.Config, error) { loadingRules, overrides, ).ClientConfig() - if err != nil { return nil, fmt.Errorf("failed to create client config: %w", err) } diff --git a/injection/sharedmain/main.go b/injection/sharedmain/main.go index 348599f096..86bb1e3409 100644 --- a/injection/sharedmain/main.go +++ b/injection/sharedmain/main.go @@ -151,7 +151,6 @@ var ( // In addition to the MainWithConfig flow, it defines a `disabled-controllers` flag that allows disabling controllers // by name. func MainNamed(ctx context.Context, component string, ctors ...injection.NamedControllerConstructor) { - disabledControllers := flag.String("disable-controllers", "", "Comma-separated list of disabled controllers.") // HACK: This parses flags, so the above should be set once this runs. @@ -456,8 +455,8 @@ func SecretFetcher(ctx context.Context) metrics.SecretFetcher { // of the webhooks created from the given constructors. func ControllersAndWebhooksFromCtors(ctx context.Context, cmw *cminformer.InformedWatcher, - ctors ...injection.ControllerConstructor) ([]*controller.Impl, []interface{}) { - + ctors ...injection.ControllerConstructor, +) ([]*controller.Impl, []interface{}) { // Check whether the context has been infused with a leader elector builder. // If it has, then every reconciler we plan to start MUST implement LeaderAware. leEnabled := leaderelection.HasLeaderElection(ctx) diff --git a/kmap/lookup_test.go b/kmap/lookup_test.go index 0018ff94f7..58fe963849 100644 --- a/kmap/lookup_test.go +++ b/kmap/lookup_test.go @@ -121,7 +121,6 @@ func TestUpdateKeys(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - out := UpdateKeys(tc.in, tc.ols...) if diff := cmp.Diff(tc.out, out); diff != "" { t.Error("Migrate diff (-want,+got):", diff) diff --git a/kmeta/names_test.go b/kmeta/names_test.go index df757e67b1..0df0923019 100644 --- a/kmeta/names_test.go +++ b/kmeta/names_test.go @@ -30,39 +30,40 @@ func TestChildName(t *testing.T) { parent string suffix string want string - }{{ - parent: "asdf", - suffix: "-deployment", - want: "asdf-deployment", - }, { - parent: strings.Repeat("f", 63), - suffix: "-deployment", - want: "ffffffffffffffffffff105d7597f637e83cc711605ac3ea4957-deployment", - }, { - parent: strings.Repeat("f", 63), - suffix: "-deploy", - want: "ffffffffffffffffffffffff105d7597f637e83cc711605ac3ea4957-deploy", - }, { - parent: strings.Repeat("f", 63), - suffix: strings.Repeat("f", 63), - want: "fffffffffffffffffffffffffffffff0502661254f13c89973cb3a83e0cbec0", - }, { - parent: "a", - suffix: strings.Repeat("f", 63), - want: "ab5cfd486935decbc0d305799f4ce4414ffffffffffffffffffffffffffffff", - }, { - parent: strings.Repeat("b", 32), - suffix: strings.Repeat("f", 32), - want: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb329c7c81b9ab3ba71aa139066aa5625d", - }, { - parent: "aaaa", - suffix: strings.Repeat("b---a", 20), - want: "aaaa7a3f7966594e3f0849720eced8212c18b---ab---ab---ab---ab---ab", - }, { - parent: strings.Repeat("a", 17), - suffix: "a.-.-.-.-.-.-.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - want: "aaaaaaaaaaaaaaaaaa1eb10dc911444f8434af83b7225442da", - }, + }{ + { + parent: "asdf", + suffix: "-deployment", + want: "asdf-deployment", + }, { + parent: strings.Repeat("f", 63), + suffix: "-deployment", + want: "ffffffffffffffffffff105d7597f637e83cc711605ac3ea4957-deployment", + }, { + parent: strings.Repeat("f", 63), + suffix: "-deploy", + want: "ffffffffffffffffffffffff105d7597f637e83cc711605ac3ea4957-deploy", + }, { + parent: strings.Repeat("f", 63), + suffix: strings.Repeat("f", 63), + want: "fffffffffffffffffffffffffffffff0502661254f13c89973cb3a83e0cbec0", + }, { + parent: "a", + suffix: strings.Repeat("f", 63), + want: "ab5cfd486935decbc0d305799f4ce4414ffffffffffffffffffffffffffffff", + }, { + parent: strings.Repeat("b", 32), + suffix: strings.Repeat("f", 32), + want: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb329c7c81b9ab3ba71aa139066aa5625d", + }, { + parent: "aaaa", + suffix: strings.Repeat("b---a", 20), + want: "aaaa7a3f7966594e3f0849720eced8212c18b---ab---ab---ab---ab---ab", + }, { + parent: strings.Repeat("a", 17), + suffix: "a.-.-.-.-.-.-.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + want: "aaaaaaaaaaaaaaaaaa1eb10dc911444f8434af83b7225442da", + }, } for _, test := range tests { diff --git a/kmeta/ownerrefable_accessor_test.go b/kmeta/ownerrefable_accessor_test.go index 774f6c704b..4771dd46b1 100644 --- a/kmeta/ownerrefable_accessor_test.go +++ b/kmeta/ownerrefable_accessor_test.go @@ -50,7 +50,8 @@ func TestNewControllerRef_OwnerRefableAccessor(t *testing.T) { ObjectMeta: metav1.ObjectMeta{ Name: "foo", UID: "42", - }}, + }, + }, } blockOwnerDeletion := true diff --git a/kmp/diff_test.go b/kmp/diff_test.go index 4fddd48bf2..cda64ee39c 100644 --- a/kmp/diff_test.go +++ b/kmp/diff_test.go @@ -92,7 +92,6 @@ func TestFieldDiff(t *testing.T) { } else if !cmp.Equal(got, want) { t.Errorf("FieldDiff() = %v, want: %s", got, want) } - } func TestImmutableDiff(t *testing.T) { diff --git a/kmp/reporters_test.go b/kmp/reporters_test.go index c76160ce99..0596ba5fae 100644 --- a/kmp/reporters_test.go +++ b/kmp/reporters_test.go @@ -45,7 +45,6 @@ type privateStruct struct { } func TestFieldListReporter(t *testing.T) { - tests := []struct { name string x interface{} diff --git a/kvstore/kvstore_cm.go b/kvstore/kvstore_cm.go index de6c4eab38..76254d448c 100644 --- a/kvstore/kvstore_cm.go +++ b/kvstore/kvstore_cm.go @@ -39,12 +39,9 @@ type configMapKVStore struct { data map[string]string } -var ( - _ Interface = (*configMapKVStore)(nil) -) +var _ Interface = (*configMapKVStore)(nil) func NewConfigMapKVStore(ctx context.Context, name string, namespace string, clientset v1.CoreV1Interface) Interface { - return &configMapKVStore{name: name, namespace: namespace, cmClient: clientset.ConfigMaps(namespace)} } diff --git a/leaderelection/config_test.go b/leaderelection/config_test.go index fcb699eb8b..32c58dc87a 100644 --- a/leaderelection/config_test.go +++ b/leaderelection/config_test.go @@ -169,7 +169,6 @@ func TestNewConfigMapFromData(t *testing.T) { } func TestNewConfigFromMap(t *testing.T) { - tt := []struct { name string data map[string]string diff --git a/leaderelection/context.go b/leaderelection/context.go index b0122b84a0..4cd6830639 100644 --- a/leaderelection/context.go +++ b/leaderelection/context.go @@ -117,7 +117,8 @@ type standardBuilder struct { } func (b *standardBuilder) buildElector(ctx context.Context, la reconciler.LeaderAware, - queueName string, enq func(reconciler.Bucket, types.NamespacedName)) (Elector, error) { + queueName string, enq func(reconciler.Bucket, types.NamespacedName), +) (Elector, error) { logger := logging.FromContext(ctx) id := b.lec.Identity diff --git a/logging/config.go b/logging/config.go index a95dfe8fa5..1898ac34f9 100644 --- a/logging/config.go +++ b/logging/config.go @@ -197,7 +197,8 @@ func levelFromString(level string) (*zapcore.Level, error) { // UpdateLevelFromConfigMap returns a helper func that can be used to update the logging level // when a config map is updated func UpdateLevelFromConfigMap(logger *zap.SugaredLogger, atomicLevel zap.AtomicLevel, - levelKey string) func(configMap *corev1.ConfigMap) { + levelKey string, +) func(configMap *corev1.ConfigMap) { return func(configMap *corev1.ConfigMap) { config, err := NewConfigFromConfigMap(configMap) if err != nil { diff --git a/logging/config_test.go b/logging/config_test.go index dac48ae2ab..c02ada2101 100644 --- a/logging/config_test.go +++ b/logging/config_test.go @@ -346,7 +346,6 @@ func TestUpdateLevelFromConfigMap(t *testing.T) { updateFn func(*corev1.ConfigMap) wantLevel zapcore.Level }{{ - // Component deleted, level set to global value updateFn: func(cm *corev1.ConfigMap) { delete(cm.Data, componentLogKey) diff --git a/metrics/config.go b/metrics/config.go index ce5e7f875f..9ed17ef678 100644 --- a/metrics/config.go +++ b/metrics/config.go @@ -58,11 +58,9 @@ const ( prometheusHostEnvName = "METRICS_PROMETHEUS_HOST" ) -var ( - // TestOverrideBundleCount is a variable for testing to reduce the size (number of metrics) buffered before - // OpenCensus will send a bundled metric report. Only applies if non-zero. - TestOverrideBundleCount = 0 -) +// TestOverrideBundleCount is a variable for testing to reduce the size (number of metrics) buffered before +// OpenCensus will send a bundled metric report. Only applies if non-zero. +var TestOverrideBundleCount = 0 // Metrics backend "enum". const ( diff --git a/metrics/e2e_test.go b/metrics/e2e_test.go index b776ca6227..57ded9f1f8 100644 --- a/metrics/e2e_test.go +++ b/metrics/e2e_test.go @@ -45,9 +45,7 @@ import ( "knative.dev/pkg/metrics/metricstest" ) -var ( - NamespaceTagKey = tag.MustNewKey(metricskey.LabelNamespaceName) -) +var NamespaceTagKey = tag.MustNewKey(metricskey.LabelNamespaceName) type metricExtract struct { Name string diff --git a/metrics/exporter.go b/metrics/exporter.go index a4c8373488..95e0f5b2f3 100644 --- a/metrics/exporter.go +++ b/metrics/exporter.go @@ -271,8 +271,7 @@ func flushGivenExporter(e view.Exporter) bool { return false } -type noneExporter struct { -} +type noneExporter struct{} // NoneExporter implements view.Exporter in the nil case. func (*noneExporter) ExportView(*view.Data) { diff --git a/metrics/exporter_test.go b/metrics/exporter_test.go index a163549fa0..61986b9d99 100644 --- a/metrics/exporter_test.go +++ b/metrics/exporter_test.go @@ -111,7 +111,8 @@ func TestInterleavedExporters(t *testing.T) { domain: metricsDomain, component: testComponent, backendDestination: prometheus, - prometheusPort: 9090}, TestLogger(t)) + prometheusPort: 9090, + }, TestLogger(t)) if err != nil { t.Error(err) } diff --git a/metrics/metrics.go b/metrics/metrics.go index b65f470cce..a0c64343b6 100644 --- a/metrics/metrics.go +++ b/metrics/metrics.go @@ -125,9 +125,7 @@ type resultMetric struct { measure *stats.Int64Measure } -var ( - _ metrics.ResultMetric = (*resultMetric)(nil) -) +var _ metrics.ResultMetric = (*resultMetric)(nil) // Increment implements ResultMetric func (m resultMetric) Increment(ctx context.Context, code, method, host string) { diff --git a/metrics/metricstest/metricstest.go b/metrics/metricstest/metricstest.go index 3d054a1830..106c864522 100644 --- a/metrics/metricstest/metricstest.go +++ b/metrics/metricstest/metricstest.go @@ -119,7 +119,6 @@ func CheckDistributionCount(t ti, name string, wantTags map[string]string, expec } else if s.Count != expectedCount { t.Error("reporter count wrong", "metric", name, "got", s.Count, "want", expectedCount) } - } // GetLastValueData returns the last value for the given metric, verifying tags. diff --git a/metrics/metricstest/resource_metrics.go b/metrics/metricstest/resource_metrics.go index 10e2e4c94a..619d536846 100644 --- a/metrics/metricstest/resource_metrics.go +++ b/metrics/metricstest/resource_metrics.go @@ -168,7 +168,8 @@ func DistributionCountOnlyMetric(name string, count int64, tags map[string]strin Values: []Value{{ Distribution: &metricdata.Distribution{Count: count}, Tags: tags, - VerifyDistributionCountOnly: true}}, + VerifyDistributionCountOnly: true, + }}, } } diff --git a/metrics/metricstest/resource_metrics_test.go b/metrics/metricstest/resource_metrics_test.go index dfc4d0def3..140025e8a0 100644 --- a/metrics/metricstest/resource_metrics_test.go +++ b/metrics/metricstest/resource_metrics_test.go @@ -446,5 +446,4 @@ func TestMetricFetch(t *testing.T) { if diff := cmp.Diff(want, m[0]); diff != "" { t.Error("Incorrect received metrics (-want +got):", diff) } - } diff --git a/metrics/prometheus_exporter.go b/metrics/prometheus_exporter.go index 5f11c12e8d..cb5238476f 100644 --- a/metrics/prometheus_exporter.go +++ b/metrics/prometheus_exporter.go @@ -86,7 +86,7 @@ func startNewPromSrv(e *prom.Exporter, host string, port int) *http.Server { curPromSrv = &http.Server{ Addr: host + ":" + strconv.Itoa(port), Handler: sm, - ReadHeaderTimeout: time.Minute, //https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 + ReadHeaderTimeout: time.Minute, // https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 } return curPromSrv } diff --git a/metrics/resource_view.go b/metrics/resource_view.go index 69e4ab435d..930b389319 100644 --- a/metrics/resource_view.go +++ b/metrics/resource_view.go @@ -48,15 +48,17 @@ type meterExporter struct { // for each observed Resource. This is needed because OpenCensus support for // Resources is a bit tacked-on rather than being a first-class component like // Tags are. -type ResourceExporterFactory func(*resource.Resource) (view.Exporter, error) -type meters struct { - meters map[string]*meterExporter - factory ResourceExporterFactory - lock sync.Mutex - clock clock.WithTicker - ticker clock.Ticker - tickerStopChan chan struct{} -} +type ( + ResourceExporterFactory func(*resource.Resource) (view.Exporter, error) + meters struct { + meters map[string]*meterExporter + factory ResourceExporterFactory + lock sync.Mutex + clock clock.WithTicker + ticker clock.Ticker + tickerStopChan chan struct{} + } +) // Lock regime: lock allMeters before resourceViews. The critical path is in // optionForResource, which must lock allMeters, but only needs to lock @@ -421,15 +423,19 @@ func (*defaultMeterImpl) Find(name string) *view.View { func (*defaultMeterImpl) Register(views ...*view.View) error { return view.Register(views...) } + func (*defaultMeterImpl) Unregister(views ...*view.View) { view.Unregister(views...) } + func (*defaultMeterImpl) SetReportingPeriod(t time.Duration) { view.SetReportingPeriod(t) } + func (*defaultMeterImpl) RegisterExporter(e view.Exporter) { view.RegisterExporter(e) } + func (*defaultMeterImpl) UnregisterExporter(e view.Exporter) { view.UnregisterExporter(e) } @@ -438,6 +444,7 @@ func (*defaultMeterImpl) Stop() {} func (*defaultMeterImpl) RetrieveData(viewName string) ([]*view.Row, error) { return view.RetrieveData(viewName) } + func (*defaultMeterImpl) SetResource(*resource.Resource) { } diff --git a/metrics/resource_view_test.go b/metrics/resource_view_test.go index f64c96a7a4..9529edb0d4 100644 --- a/metrics/resource_view_test.go +++ b/metrics/resource_view_test.go @@ -29,9 +29,7 @@ import ( testingclock "k8s.io/utils/clock/testing" ) -var ( - r = resource.Resource{Labels: map[string]string{"foo": "bar"}} -) +var r = resource.Resource{Labels: map[string]string{"foo": "bar"}} func TestRegisterResourceView(t *testing.T) { meter := meterExporterForResource(&r).m @@ -162,7 +160,7 @@ func TestAllMetersExpiration(t *testing.T) { // (123=1.5m, 456=0m) // Warm up the older entry - fakeClock.Step(90 * time.Second) //t+3m + fakeClock.Step(90 * time.Second) // t+3m // (123=4.5m, 456=3m) // Refresh the first entry @@ -268,7 +266,6 @@ func TestResourceAsString(t *testing.T) { // Test 5 time since the iteration could be random. for i := 0; i < 5; i++ { - if s1, s2 := resourceToKey(r1), resourceToKey(r2); s1 != s2 { t.Errorf("Expect same resources, but got %q and %q", s1, s2) } diff --git a/network/h2c.go b/network/h2c.go index e1671233dc..d0608be722 100644 --- a/network/h2c.go +++ b/network/h2c.go @@ -32,7 +32,7 @@ func NewServer(addr string, h http.Handler) *http.Server { h1s := &http.Server{ Addr: addr, Handler: h2c.NewHandler(h, &http2.Server{}), - ReadHeaderTimeout: time.Minute, //https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 + ReadHeaderTimeout: time.Minute, // https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 } return h1s diff --git a/profiling/server.go b/profiling/server.go index f362f36fa4..9eceef51cb 100644 --- a/profiling/server.go +++ b/profiling/server.go @@ -117,6 +117,6 @@ func NewServer(handler http.Handler) *http.Server { return &http.Server{ Addr: ":" + port, Handler: handler, - ReadHeaderTimeout: time.Minute, //https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 + ReadHeaderTimeout: time.Minute, // https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 } } diff --git a/reconciler/testing/actions_test.go b/reconciler/testing/actions_test.go index a12d9c8ecb..12364a400d 100644 --- a/reconciler/testing/actions_test.go +++ b/reconciler/testing/actions_test.go @@ -50,7 +50,6 @@ func TestActionsByVerb(t *testing.T) { } actions, err := list.ActionsByVerb() - if err != nil { t.Error("Unexpected error sorting actions by verb", err) } diff --git a/reconciler/testing/generate_name_reactor_test.go b/reconciler/testing/generate_name_reactor_test.go index 5c7711808e..9bd7b75e3b 100644 --- a/reconciler/testing/generate_name_reactor_test.go +++ b/reconciler/testing/generate_name_reactor_test.go @@ -67,7 +67,6 @@ func TestGenerateNameReactor(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - lastHandlerInvoked := false fake := &clientgotesting.Fake{} diff --git a/reconciler/testing/reactions_test.go b/reconciler/testing/reactions_test.go index ec0b66ba53..e7a6cb93fd 100644 --- a/reconciler/testing/reactions_test.go +++ b/reconciler/testing/reactions_test.go @@ -17,11 +17,11 @@ limitations under the License. package testing import ( + "testing" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" clientgotesting "k8s.io/client-go/testing" - - "testing" ) var ( diff --git a/reconciler/testing/table.go b/reconciler/testing/table.go index d36c49b89a..18a83a2bb5 100644 --- a/reconciler/testing/table.go +++ b/reconciler/testing/table.go @@ -363,7 +363,8 @@ func (r *TableRow) Test(t *testing.T, factory Factory) { func filterUpdatesWithSubresource( subresource string, - actions []clientgotesting.UpdateAction) (result []clientgotesting.UpdateAction) { + actions []clientgotesting.UpdateAction, +) (result []clientgotesting.UpdateAction) { for _, action := range actions { if action.GetSubresource() == subresource { result = append(result, action) diff --git a/resolver/addressable_resolver_test.go b/resolver/addressable_resolver_test.go index 589a036806..6bd2d1561f 100644 --- a/resolver/addressable_resolver_test.go +++ b/resolver/addressable_resolver_test.go @@ -110,37 +110,39 @@ func TestGetURIDestinationV1Beta1(t *testing.T) { dest duckv1beta1.Destination wantURI string wantErr string - }{"nil everything": { - wantErr: "destination missing Ref and URI, expected at least one", - }, "Happy URI with path": { - dest: duckv1beta1.Destination{ - URI: &apis.URL{ - Scheme: "http", - Host: "example.com", - Path: "/foo", + }{ + "nil everything": { + wantErr: "destination missing Ref and URI, expected at least one", + }, "Happy URI with path": { + dest: duckv1beta1.Destination{ + URI: &apis.URL{ + Scheme: "http", + Host: "example.com", + Path: "/foo", + }, }, - }, - wantURI: "http://example.com/foo", - }, "URI is not absolute URL": { - dest: duckv1beta1.Destination{ - URI: &apis.URL{ - Host: "example.com", + wantURI: "http://example.com/foo", + }, "URI is not absolute URL": { + dest: duckv1beta1.Destination{ + URI: &apis.URL{ + Host: "example.com", + }, }, - }, - wantErr: fmt.Sprintf("URI is not absolute (both scheme and host should be non-empty): %q", "//example.com"), - }, "URI with no host": { - dest: duckv1beta1.Destination{ - URI: &apis.URL{ - Scheme: "http", + wantErr: fmt.Sprintf("URI is not absolute (both scheme and host should be non-empty): %q", "//example.com"), + }, "URI with no host": { + dest: duckv1beta1.Destination{ + URI: &apis.URL{ + Scheme: "http", + }, }, + wantErr: fmt.Sprintf("URI is not absolute (both scheme and host should be non-empty): %q", "http:"), }, - wantErr: fmt.Sprintf("URI is not absolute (both scheme and host should be non-empty): %q", "http:"), - }, "Ref and [apiVersion, kind, name] both exists": { objects: []runtime.Object{ getAddressable(), }, - dest: duckv1beta1.Destination{Ref: addressableRef(), + dest: duckv1beta1.Destination{ + Ref: addressableRef(), DeprecatedKind: addressableKind, DeprecatedName: addressableName, DeprecatedAPIVersion: addressableAPIVersion, @@ -242,7 +244,8 @@ func TestGetURIDestinationV1Beta1(t *testing.T) { DeprecatedKind: addressableKind, DeprecatedName: addressableName, DeprecatedAPIVersion: addressableAPIVersion, - DeprecatedNamespace: testNS}, + DeprecatedNamespace: testNS, + }, wantURI: addressableDNS, }, "[apiVersion, kind, name] with relative uri": { @@ -374,7 +377,8 @@ func TestGetURIDestinationV1Beta1(t *testing.T) { }, "notFound": { dest: duckv1beta1.Destination{Ref: unaddressableRef()}, wantErr: fmt.Sprintf("failed to get object %s/%s: %s %q not found", testNS, unaddressableName, unaddressableResource, unaddressableName), - }} + }, + } for n, tc := range tests { t.Run(n, func(t *testing.T) { @@ -411,32 +415,33 @@ func TestGetURIDestinationV1(t *testing.T) { customResolvers []resolver.RefResolverFunc wantURI string wantErr string - }{"nil everything": { - wantErr: "destination missing Ref and URI, expected at least one", - }, "Happy URI with path": { - dest: duckv1.Destination{ - URI: &apis.URL{ - Scheme: "http", - Host: "example.com", - Path: "/foo", + }{ + "nil everything": { + wantErr: "destination missing Ref and URI, expected at least one", + }, "Happy URI with path": { + dest: duckv1.Destination{ + URI: &apis.URL{ + Scheme: "http", + Host: "example.com", + Path: "/foo", + }, }, - }, - wantURI: "http://example.com/foo", - }, "URI is not absolute URL": { - dest: duckv1.Destination{ - URI: &apis.URL{ - Host: "example.com", + wantURI: "http://example.com/foo", + }, "URI is not absolute URL": { + dest: duckv1.Destination{ + URI: &apis.URL{ + Host: "example.com", + }, }, - }, - wantErr: fmt.Sprintf("URI is not absolute (both scheme and host should be non-empty): %q", "//example.com"), - }, "URI with no host": { - dest: duckv1.Destination{ - URI: &apis.URL{ - Scheme: "http", + wantErr: fmt.Sprintf("URI is not absolute (both scheme and host should be non-empty): %q", "//example.com"), + }, "URI with no host": { + dest: duckv1.Destination{ + URI: &apis.URL{ + Scheme: "http", + }, }, + wantErr: fmt.Sprintf("URI is not absolute (both scheme and host should be non-empty): %q", "http:"), }, - wantErr: fmt.Sprintf("URI is not absolute (both scheme and host should be non-empty): %q", "http:"), - }, "happy ref": { objects: []runtime.Object{ getAddressable(), @@ -583,7 +588,8 @@ func TestGetURIDestinationV1(t *testing.T) { dest: duckv1.Destination{Ref: k8sServiceRef()}, customResolvers: []resolver.RefResolverFunc{noopURIResolver, sampleURIResolver}, wantURI: "ref://" + addressableName + ".Service.v1", - }} + }, + } for n, tc := range tests { t.Run(n, func(t *testing.T) { @@ -1081,7 +1087,6 @@ func invalidObjectRef() *corev1.ObjectReference { APIVersion: addressableAPIVersion, Namespace: "-bad", } - } func k8sServiceRef() *duckv1.KReference { @@ -1091,7 +1096,6 @@ func k8sServiceRef() *duckv1.KReference { APIVersion: "v1", Namespace: testNS, } - } func addressableKnativeRef() *duckv1.KReference { diff --git a/source/source_labels_test.go b/source/source_labels_test.go index 14c839994a..695ded3b2c 100644 --- a/source/source_labels_test.go +++ b/source/source_labels_test.go @@ -23,7 +23,6 @@ import ( ) func TestLabels(t *testing.T) { - sourceLabels := Labels("foo", "foo-source-controller") wantTags := map[string]string{ diff --git a/test/cleanup_test.go b/test/cleanup_test.go index 145e56bccb..3674737285 100644 --- a/test/cleanup_test.go +++ b/test/cleanup_test.go @@ -74,7 +74,6 @@ func TestCleanupOnInterrupt(t *testing.T) { } return false, err }) - if err != nil { t.Fatal("Test subprocess never became ready", err) } diff --git a/test/clients.go b/test/clients.go index 88530c36b7..44234100bc 100644 --- a/test/clients.go +++ b/test/clients.go @@ -34,7 +34,8 @@ import ( // NewSpoofingClient returns a spoofing client to make requests func NewSpoofingClient(ctx context.Context, client kubernetes.Interface, logf logging.FormatLogger, - domain string, resolvable bool, opts ...spoof.TransportOption) (*spoof.SpoofingClient, error) { + domain string, resolvable bool, opts ...spoof.TransportOption, +) (*spoof.SpoofingClient, error) { return spoof.New(ctx, client, logf, domain, resolvable, Flags.IngressEndpoint, Flags.SpoofRequestInterval, Flags.SpoofRequestTimeout, opts...) } diff --git a/test/e2e_flags.go b/test/e2e_flags.go index ef9b5519e7..3860dff942 100644 --- a/test/e2e_flags.go +++ b/test/e2e_flags.go @@ -29,12 +29,10 @@ import ( "knative.dev/pkg/test/logging" ) -var ( - // Flags holds the command line flags or defaults for settings in the user's environment. - // See EnvironmentFlags for a list of supported fields. - // Deprecated: use test/flags.Flags() - Flags = initializeFlags() -) +// Flags holds the command line flags or defaults for settings in the user's environment. +// See EnvironmentFlags for a list of supported fields. +// Deprecated: use test/flags.Flags() +var Flags = initializeFlags() // EnvironmentFlags define the flags that are needed to run the e2e tests. // Deprecated: use test/flags.Flags() or injection.Flags() diff --git a/test/helpers/dir.go b/test/helpers/dir.go index e6df61121d..e5085f009b 100644 --- a/test/helpers/dir.go +++ b/test/helpers/dir.go @@ -23,7 +23,7 @@ import ( "strings" ) -const allUsersFullPermission = 0777 +const allUsersFullPermission = 0o777 // CreateDir creates dir if does not exist. // The created dir will have the permission bits as 0777, which means everyone can read/write/execute it. diff --git a/test/logstream/interface.go b/test/logstream/interface.go index a1b39aabda..c9c95459ce 100644 --- a/test/logstream/interface.go +++ b/test/logstream/interface.go @@ -95,7 +95,6 @@ type shim struct { func (s *shim) Start(t ti) Canceler { name := helpers.ObjectPrefixForTest(t) canceler, err := s.StartStream(name, t.Logf) - if err != nil { t.Error("Failed to start logstream", "error", err) } diff --git a/test/request.go b/test/request.go index a22542e29b..46c7d6857f 100644 --- a/test/request.go +++ b/test/request.go @@ -83,7 +83,8 @@ func WaitForEndpointState( inState spoof.ResponseChecker, desc string, resolvable bool, - opts ...interface{}) (*spoof.Response, error) { + opts ...interface{}, +) (*spoof.Response, error) { return WaitForEndpointStateWithTimeout(ctx, kubeClient, logf, url, inState, desc, resolvable, Flags.SpoofRequestTimeout, opts...) } @@ -103,8 +104,8 @@ func WaitForEndpointStateWithTimeout( desc string, resolvable bool, timeout time.Duration, - opts ...interface{}) (*spoof.Response, error) { - + opts ...interface{}, +) (*spoof.Response, error) { client, rOpts, err := makeSpoofClient(ctx, kubeClient, logf, url, resolvable, timeout, opts...) if err != nil { return nil, err @@ -119,8 +120,8 @@ func makeSpoofClient( url *url.URL, resolvable bool, timeout time.Duration, - opts ...interface{}) (*spoof.SpoofingClient, []spoof.RequestOption, error) { - + opts ...interface{}, +) (*spoof.SpoofingClient, []spoof.RequestOption, error) { var tOpts []spoof.TransportOption var rOpts []spoof.RequestOption diff --git a/test/spoof/spoof.go b/test/spoof/spoof.go index 716e5d83db..ac1c23e7dc 100644 --- a/test/spoof/spoof.go +++ b/test/spoof/spoof.go @@ -100,7 +100,8 @@ func New( resolvable bool, endpointOverride string, requestInterval, requestTimeout time.Duration, - opts ...TransportOption) (*SpoofingClient, error) { + opts ...TransportOption, +) (*SpoofingClient, error) { endpoint, mapper, err := ResolveEndpoint(ctx, kubeClientset, domain, resolvable, endpointOverride) if err != nil { return nil, fmt.Errorf("failed to get the cluster endpoint: %w", err) @@ -288,8 +289,8 @@ func (sc *SpoofingClient) WaitForEndpointState( url *url.URL, inState ResponseChecker, desc string, - opts ...RequestOption) (*Response, error) { - + opts ...RequestOption, +) (*Response, error) { return sc.endpointState( ctx, url, @@ -307,7 +308,8 @@ func (sc *SpoofingClient) endpointState( desc string, f func(*http.Request, ResponseChecker) (*Response, error), logName string, - opts ...RequestOption) (*Response, error) { + opts ...RequestOption, +) (*Response, error) { defer logging.GetEmitableSpan(ctx, logName+"/"+desc).End() if url.Scheme == "" || url.Host == "" { @@ -348,7 +350,8 @@ func (sc *SpoofingClient) CheckEndpointState( url *url.URL, inState ResponseChecker, desc string, - opts ...RequestOption) (*Response, error) { + opts ...RequestOption, +) (*Response, error) { return sc.endpointState( ctx, url, diff --git a/test/spoof/spoof_test.go b/test/spoof/spoof_test.go index df07f40947..10dc64367d 100644 --- a/test/spoof/spoof_test.go +++ b/test/spoof/spoof_test.go @@ -25,9 +25,8 @@ import ( "net/http" "net/url" "sync/atomic" - "time" - "testing" + "time" ) var ( diff --git a/test/upgrade/functions.go b/test/upgrade/functions.go index fe4965d809..e988c5bf81 100644 --- a/test/upgrade/functions.go +++ b/test/upgrade/functions.go @@ -77,7 +77,8 @@ func NewBackgroundVerification(name string, setup func(c Context), verify func(c // NewBackgroundOperation creates a new background operation or test that can be // notified to stop its operation. func NewBackgroundOperation(name string, setup func(c Context), - handler func(bc BackgroundContext)) BackgroundOperation { + handler func(bc BackgroundContext), +) BackgroundOperation { return &simpleBackgroundOperation{ name: name, setup: setup, diff --git a/test/upgrade/shell/executor.go b/test/upgrade/shell/executor.go index 020f0d3edd..866b814149 100644 --- a/test/upgrade/shell/executor.go +++ b/test/upgrade/shell/executor.go @@ -28,7 +28,7 @@ import ( const ( defaultLabelOut = "[OUT]" defaultLabelErr = "[ERR]" - executeMode = 0700 + executeMode = 0o700 ) // NewExecutor creates a new executor. diff --git a/test/vegeta/pacers/combined_pacer.go b/test/vegeta/pacers/combined_pacer.go index 5b0aa3ed48..2340acc670 100644 --- a/test/vegeta/pacers/combined_pacer.go +++ b/test/vegeta/pacers/combined_pacer.go @@ -51,7 +51,7 @@ func NewCombined(pacers []vegeta.Pacer, durations []time.Duration) (vegeta.Pacer } var totalDuration uint64 - var stepDurations = make([]uint64, len(pacers)) + stepDurations := make([]uint64, len(pacers)) for i, duration := range durations { if duration < 1*time.Second { return nil, errors.New("duration for each pacer must be longer than 1 second") diff --git a/testing/duck/testbindable.go b/testing/duck/testbindable.go index 272ea580b7..346a45208e 100644 --- a/testing/duck/testbindable.go +++ b/testing/duck/testbindable.go @@ -42,8 +42,10 @@ type TestBindable struct { } // Check that TestBindable may be validated and defaulted. -var _ apis.Listable = (*TestBindable)(nil) -var _ duck.Bindable = (*TestBindable)(nil) +var ( + _ apis.Listable = (*TestBindable)(nil) + _ duck.Bindable = (*TestBindable)(nil) +) // TestBindableSpec represents test resource spec. type TestBindableSpec struct { diff --git a/testing/inner_default_resource.go b/testing/inner_default_resource.go index 9506858b18..d0b32fdb41 100644 --- a/testing/inner_default_resource.go +++ b/testing/inner_default_resource.go @@ -114,8 +114,10 @@ type InnerDefaultStatus struct { } // Check that ImmutableDefaultResource may be validated and defaulted. -var _ apis.Validatable = (*InnerDefaultResource)(nil) -var _ apis.Defaultable = (*InnerDefaultResource)(nil) +var ( + _ apis.Validatable = (*InnerDefaultResource)(nil) + _ apis.Defaultable = (*InnerDefaultResource)(nil) +) // SetDefaults sets default values. func (i *InnerDefaultResource) SetDefaults(ctx context.Context) { diff --git a/testing/resource.go b/testing/resource.go index 97d424b3b2..cb95ac60a9 100644 --- a/testing/resource.go +++ b/testing/resource.go @@ -38,9 +38,11 @@ type Resource struct { } // Check that Resource may be validated and defaulted. -var _ apis.Validatable = (*Resource)(nil) -var _ apis.Defaultable = (*Resource)(nil) -var _ apis.Listable = (*Resource)(nil) +var ( + _ apis.Validatable = (*Resource)(nil) + _ apis.Defaultable = (*Resource)(nil) + _ apis.Listable = (*Resource)(nil) +) // ResourceSpec represents test resource spec. type ResourceSpec struct { diff --git a/tracker/interface.go b/tracker/interface.go index 5e580b34cf..58bc941d8e 100644 --- a/tracker/interface.go +++ b/tracker/interface.go @@ -177,5 +177,4 @@ func (ref *Reference) Validate(ctx context.Context) *apis.FieldError { } return errs - } diff --git a/webhook/admission.go b/webhook/admission.go index db131b902b..9e14eae89b 100644 --- a/webhook/admission.go +++ b/webhook/admission.go @@ -88,7 +88,7 @@ func admissionHandler(rootLogger *zap.SugaredLogger, stats StatsReporter, c Admi <-synced } - var ttStart = time.Now() + ttStart := time.Now() logger := rootLogger logger.Infof("Webhook ServeHTTP request=%#v", r) diff --git a/webhook/certificates/certificates.go b/webhook/certificates/certificates.go index 5239279e52..21c6bdec6a 100644 --- a/webhook/certificates/certificates.go +++ b/webhook/certificates/certificates.go @@ -48,8 +48,10 @@ type reconciler struct { serviceName string } -var _ controller.Reconciler = (*reconciler)(nil) -var _ pkgreconciler.LeaderAware = (*reconciler)(nil) +var ( + _ controller.Reconciler = (*reconciler)(nil) + _ pkgreconciler.LeaderAware = (*reconciler)(nil) +) // Reconcile implements controller.Reconciler func (r *reconciler) Reconcile(ctx context.Context, key string) error { diff --git a/webhook/certificates/controller.go b/webhook/certificates/controller.go index 1932e28c25..b076bd6612 100644 --- a/webhook/certificates/controller.go +++ b/webhook/certificates/controller.go @@ -41,7 +41,6 @@ func NewController( ctx context.Context, cmw configmap.Watcher, ) *controller.Impl { - client := kubeclient.Get(ctx) secretInformer := secretinformer.Get(ctx) options := webhook.GetOptions(ctx) diff --git a/webhook/certificates/resources/certs.go b/webhook/certificates/resources/certs.go index 811eb569c2..cb56c8cef9 100644 --- a/webhook/certificates/resources/certs.go +++ b/webhook/certificates/resources/certs.go @@ -98,8 +98,8 @@ func createServerCertTemplate(name, namespace string, notAfter time.Time) (*x509 // Actually sign the cert and return things in a form that we can use later on func createCert(template, parent *x509.Certificate, pub, parentPriv interface{}) ( - cert *x509.Certificate, certPEM []byte, err error) { - + cert *x509.Certificate, certPEM []byte, err error, +) { certDER, err := x509.CreateCertificate(rand.Reader, template, parent, pub, parentPriv) if err != nil { return diff --git a/webhook/configmaps/configmaps.go b/webhook/configmaps/configmaps.go index 5a4c4d8888..d7d37b8ec4 100644 --- a/webhook/configmaps/configmaps.go +++ b/webhook/configmaps/configmaps.go @@ -61,10 +61,12 @@ type reconciler struct { secretName string } -var _ controller.Reconciler = (*reconciler)(nil) -var _ pkgreconciler.LeaderAware = (*reconciler)(nil) -var _ webhook.AdmissionController = (*reconciler)(nil) -var _ webhook.StatelessAdmissionController = (*reconciler)(nil) +var ( + _ controller.Reconciler = (*reconciler)(nil) + _ pkgreconciler.LeaderAware = (*reconciler)(nil) + _ webhook.AdmissionController = (*reconciler)(nil) + _ webhook.StatelessAdmissionController = (*reconciler)(nil) +) // Reconcile implements controller.Reconciler func (ac *reconciler) Reconcile(ctx context.Context, key string) error { diff --git a/webhook/configmaps/configmaps_test.go b/webhook/configmaps/configmaps_test.go index 709ba3c553..ae37d4fa76 100644 --- a/webhook/configmaps/configmaps_test.go +++ b/webhook/configmaps/configmaps_test.go @@ -79,7 +79,8 @@ var ( func newNonRunningTestConfigValidationController(t *testing.T) ( kubeClient *fakekubeclientset.Clientset, - ac *reconciler) { + ac *reconciler, +) { t.Helper() // Create fake clients kubeClient = fakekubeclientset.NewSimpleClientset(initialConfigWebhook) diff --git a/webhook/configmaps/controller.go b/webhook/configmaps/controller.go index c2d71eb039..9c2aae4952 100644 --- a/webhook/configmaps/controller.go +++ b/webhook/configmaps/controller.go @@ -41,7 +41,6 @@ func NewAdmissionController( name, path string, constructors configmap.Constructors, ) *controller.Impl { - client := kubeclient.Get(ctx) vwhInformer := vwhinformer.Get(ctx) secretInformer := secretinformer.Get(ctx) diff --git a/webhook/configmaps/table_test.go b/webhook/configmaps/table_test.go index 1b0c51c0fe..ef9157a08f 100644 --- a/webhook/configmaps/table_test.go +++ b/webhook/configmaps/table_test.go @@ -112,7 +112,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and VWH exist, missing service reference", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -126,7 +127,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and VWH exist, missing other stuff", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -168,7 +170,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and VWH exist, added fields are incorrect", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -227,7 +230,8 @@ func TestReconcile(t *testing.T) { WithReactors: []clientgotesting.ReactionFunc{ InduceFailure("update", "validatingwebhookconfigurations"), }, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -282,7 +286,8 @@ func TestReconcile(t *testing.T) { }, { Name: ":fire: everything is fine :fire:", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, diff --git a/webhook/conversion.go b/webhook/conversion.go index 2e876c14f5..fa3c76a702 100644 --- a/webhook/conversion.go +++ b/webhook/conversion.go @@ -40,7 +40,7 @@ type ConversionController interface { func conversionHandler(rootLogger *zap.SugaredLogger, stats StatsReporter, c ConversionController) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var ttStart = time.Now() + ttStart := time.Now() logger := rootLogger logger.Infof("Webhook ServeHTTP request=%#v", r) diff --git a/webhook/helper.go b/webhook/helper.go index a3647ac742..a9ff91fe25 100644 --- a/webhook/helper.go +++ b/webhook/helper.go @@ -29,8 +29,8 @@ import ( // adds all knative-keys not yet there. func EnsureLabelSelectorExpressions( current *metav1.LabelSelector, - want *metav1.LabelSelector) *metav1.LabelSelector { - + want *metav1.LabelSelector, +) *metav1.LabelSelector { if current == nil { return want } @@ -56,8 +56,8 @@ func EnsureLabelSelectorExpressions( func ensureLabelSelectorRequirements( current []metav1.LabelSelectorRequirement, - want []metav1.LabelSelectorRequirement) []metav1.LabelSelectorRequirement { - + want []metav1.LabelSelectorRequirement, +) []metav1.LabelSelectorRequirement { nonKnative := make([]metav1.LabelSelectorRequirement, 0, len(current)) for _, r := range current { if !strings.Contains(r.Key, "knative.dev") { diff --git a/webhook/helper_test.go b/webhook/helper_test.go index 4a34626307..830fb48dc5 100644 --- a/webhook/helper_test.go +++ b/webhook/helper_test.go @@ -99,7 +99,8 @@ func TestEnsureLabelSelectorExpressions(t *testing.T) { }, expect: &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ - knativeExpression, fooExpression}, + knativeExpression, fooExpression, + }, }, }, { name: "remove obsolete", @@ -114,7 +115,8 @@ func TestEnsureLabelSelectorExpressions(t *testing.T) { }, expect: &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ - knativeExpression, fooExpression}, + knativeExpression, fooExpression, + }, }, }} @@ -127,9 +129,10 @@ func TestEnsureLabelSelectorExpressions(t *testing.T) { }) } } + func waitForNonTLSServerAvailable(t *testing.T, serverURL string, timeout time.Duration) error { t.Helper() - var interval = 100 * time.Millisecond + interval := 100 * time.Millisecond conditionFunc := func(ctx context.Context) (done bool, err error) { var conn net.Conn diff --git a/webhook/json/decode.go b/webhook/json/decode.go index b62caec612..c8e5707907 100644 --- a/webhook/json/decode.go +++ b/webhook/json/decode.go @@ -32,7 +32,7 @@ var ( // Unmarshal is an alias for json.Unmarshal Unmarshal = json.Unmarshal - //Marshal is an alias for json.Marshal + // Marshal is an alias for json.Marshal Marshal = json.Marshal ) diff --git a/webhook/psbinding/controller.go b/webhook/psbinding/controller.go index bceffcb4f7..f799847214 100644 --- a/webhook/psbinding/controller.go +++ b/webhook/psbinding/controller.go @@ -78,7 +78,6 @@ func NewAdmissionController( withContext BindableContext, reconcilerOptions ...ReconcilerOption, ) *controller.Impl { - // Extract the assorted things from our context. client := kubeclient.Get(ctx) mwhInformer := mwhinformer.Get(ctx) diff --git a/webhook/psbinding/psbinding.go b/webhook/psbinding/psbinding.go index ee1d66a822..2236cadc64 100644 --- a/webhook/psbinding/psbinding.go +++ b/webhook/psbinding/psbinding.go @@ -118,9 +118,11 @@ type Reconciler struct { index index } -var _ controller.Reconciler = (*Reconciler)(nil) -var _ pkgreconciler.LeaderAware = (*Reconciler)(nil) -var _ webhook.AdmissionController = (*Reconciler)(nil) +var ( + _ controller.Reconciler = (*Reconciler)(nil) + _ pkgreconciler.LeaderAware = (*Reconciler)(nil) + _ webhook.AdmissionController = (*Reconciler)(nil) +) // We need to specifically exclude our deployment(s) from consideration, but this provides a way // of excluding other things as well. @@ -186,7 +188,8 @@ func (ac *Reconciler) Admit(ctx context.Context, request *admissionv1.AdmissionR Group: request.Kind.Group, Kind: request.Kind.Kind, Namespace: request.Namespace, - Name: orig.Name}, + Name: orig.Name, + }, labels.Set(orig.Labels)) if len(fbs) == 0 { // This doesn't apply! @@ -269,7 +272,8 @@ func (ac *Reconciler) reconcileMutatingWebhook(ctx context.Context, caCert []byt Group: gk.Group, Kind: gk.Kind, Namespace: ref.Namespace, - Name: ref.Name}, + Name: ref.Name, + }, fb) } else { selector, err := metav1.LabelSelectorAsSelector(ref.Selector) @@ -279,7 +283,8 @@ func (ac *Reconciler) reconcileMutatingWebhook(ctx context.Context, caCert []byt ib.associateSelection(inexactKey{ Group: gk.Group, Kind: gk.Kind, - Namespace: ref.Namespace}, + Namespace: ref.Namespace, + }, selector, fb) } } diff --git a/webhook/psbinding/reconciler.go b/webhook/psbinding/reconciler.go index 3d156fdca2..233af0d389 100644 --- a/webhook/psbinding/reconciler.go +++ b/webhook/psbinding/reconciler.go @@ -102,8 +102,10 @@ type BaseReconciler struct { } // Check that our Reconciler implements controller.Reconciler -var _ controller.Reconciler = (*BaseReconciler)(nil) -var _ pkgreconciler.LeaderAware = (*BaseReconciler)(nil) +var ( + _ controller.Reconciler = (*BaseReconciler)(nil) + _ pkgreconciler.LeaderAware = (*BaseReconciler)(nil) +) // Reconcile implements controller.Reconciler func (r *BaseReconciler) Reconcile(ctx context.Context, key string) error { @@ -275,7 +277,6 @@ func (r *BaseReconciler) RemoveFinalizer(ctx context.Context, fb kmeta.Accessor) } func (r *BaseReconciler) labelNamespace(ctx context.Context, subject tracker.Reference) error { - namespaceObject, err := r.NamespaceLister.Get(subject.Namespace) if apierrs.IsNotFound(err) { logging.FromContext(ctx).Info("Error getting namespace (not found): ", err) diff --git a/webhook/psbinding/table_test.go b/webhook/psbinding/table_test.go index c2fab50912..3ec1d51865 100644 --- a/webhook/psbinding/table_test.go +++ b/webhook/psbinding/table_test.go @@ -310,7 +310,8 @@ func TestWebhookReconcile(t *testing.T) { }, { Name: "secret and MWH exist, missing service reference", Key: key, - Objects: []runtime.Object{secret, + Objects: []runtime.Object{ + secret, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -324,7 +325,8 @@ func TestWebhookReconcile(t *testing.T) { }, { Name: "secret and MWH exist, missing other stuff", Key: key, - Objects: []runtime.Object{secret, + Objects: []runtime.Object{ + secret, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -371,7 +373,8 @@ func TestWebhookReconcile(t *testing.T) { }, { Name: "secret and MWH exist, added fields are incorrect", Key: key, - Objects: []runtime.Object{secret, + Objects: []runtime.Object{ + secret, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -437,7 +440,8 @@ func TestWebhookReconcile(t *testing.T) { WithReactors: []clientgotesting.ReactionFunc{ InduceFailure("update", "mutatingwebhookconfigurations"), }, - Objects: []runtime.Object{secret, + Objects: []runtime.Object{ + secret, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -497,7 +501,8 @@ func TestWebhookReconcile(t *testing.T) { }, { Name: ":fire: everything is fine :fire:", Key: key, - Objects: []runtime.Object{secret, + Objects: []runtime.Object{ + secret, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -528,7 +533,8 @@ func TestWebhookReconcile(t *testing.T) { }, { Name: "a new binding has entered the match", Key: key, - Objects: []runtime.Object{secret, + Objects: []runtime.Object{ + secret, &TestBindable{ ObjectMeta: metav1.ObjectMeta{ Namespace: "foo", @@ -605,7 +611,8 @@ func TestWebhookReconcile(t *testing.T) { }, { Name: "steady state direct bindings", Key: key, - Objects: []runtime.Object{secret, + Objects: []runtime.Object{ + secret, &TestBindable{ ObjectMeta: metav1.ObjectMeta{ Namespace: "foo", @@ -687,7 +694,8 @@ func TestWebhookReconcile(t *testing.T) { }, { Name: "steady state selector", Key: key, - Objects: []runtime.Object{secret, + Objects: []runtime.Object{ + secret, &TestBindable{ ObjectMeta: metav1.ObjectMeta{ Namespace: "foo", @@ -776,7 +784,8 @@ func TestWebhookReconcile(t *testing.T) { }, { Name: "tombstoned binding undoes patch", Key: key, - Objects: []runtime.Object{secret, + Objects: []runtime.Object{ + secret, &TestBindable{ ObjectMeta: metav1.ObjectMeta{ Namespace: "foo", @@ -838,7 +847,8 @@ func TestWebhookReconcile(t *testing.T) { }, { Name: "multiple new bindings have entered the match", Key: key, - Objects: []runtime.Object{secret, + Objects: []runtime.Object{ + secret, &TestBindable{ ObjectMeta: metav1.ObjectMeta{ Namespace: "foo", @@ -938,7 +948,8 @@ func TestWebhookReconcile(t *testing.T) { }, { Name: "a new selector-based binding has entered the match", Key: key, - Objects: []runtime.Object{secret, + Objects: []runtime.Object{ + secret, &TestBindable{ ObjectMeta: metav1.ObjectMeta{ Namespace: "foo", @@ -2023,73 +2034,74 @@ func TestBaseReconcile(t *testing.T) { } func TestBaseReconcileWithSubResourcesReconciler(t *testing.T) { - table := TableTest{{ - Name: "create new subresource", - Key: "foo/bar", - Objects: []runtime.Object{ - &TestBindable{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "foo", - Name: "bar", - Finalizers: []string{"testbindables.duck.knative.dev"}, - }, - Spec: TestBindableSpec{ - BindingSpec: duckv1alpha1.BindingSpec{ - Subject: tracker.Reference{ - APIVersion: "apps/v1", - Kind: "Deployment", - Namespace: "foo", - Name: "on-it", + table := TableTest{ + { + Name: "create new subresource", + Key: "foo/bar", + Objects: []runtime.Object{ + &TestBindable{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "foo", + Name: "bar", + Finalizers: []string{"testbindables.duck.knative.dev"}, + }, + Spec: TestBindableSpec{ + BindingSpec: duckv1alpha1.BindingSpec{ + Subject: tracker.Reference{ + APIVersion: "apps/v1", + Kind: "Deployment", + Namespace: "foo", + Name: "on-it", + }, }, + Foo: "asdfasdfasdfasdf", }, - Foo: "asdfasdfasdfasdf", - }, - Status: TestBindableStatus{ - Status: duckv1.Status{ - Conditions: []apis.Condition{{ - Type: "Ready", - Status: "True", - }}, + Status: TestBindableStatus{ + Status: duckv1.Status{ + Conditions: []apis.Condition{{ + Type: "Ready", + Status: "True", + }}, + }, }, }, - }, - &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "foo", - Name: "on-it", - }, - Spec: appsv1.DeploymentSpec{ - Template: corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "foo", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "FOO", - Value: "asdfasdfasdfasdf", + &appsv1.Deployment{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "foo", + Name: "on-it", + }, + Spec: appsv1.DeploymentSpec{ + Template: corev1.PodTemplateSpec{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{{ + Name: "foo", + Image: "busybox", + Env: []corev1.EnvVar{{ + Name: "FOO", + Value: "asdfasdfasdfasdf", + }}, }}, - }}, + }, }, }, }, - }, - &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", + &corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{ + Name: "foo", + }, }, }, - }, - WantPatches: []clientgotesting.PatchActionImpl{ - patchAddLabel("foo"), - }, - WantCreates: []runtime.Object{ - &corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: "bar", + WantPatches: []clientgotesting.PatchActionImpl{ + patchAddLabel("foo"), + }, + WantCreates: []runtime.Object{ + &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{ + Name: "bar", + }, }, }, }, - }, { Name: "delete resource and subresource", Key: "foo/bar", @@ -2233,6 +2245,7 @@ func patchAddLabel(namespace string) clientgotesting.PatchActionImpl { action.Patch = patch return action } + func patchAddFinalizer(namespace, name, resourceVersion string) clientgotesting.PatchActionImpl { action := clientgotesting.PatchActionImpl{} action.Name = name diff --git a/webhook/resourcesemantics/conversion/controller.go b/webhook/resourcesemantics/conversion/controller.go index 45e2eef4e6..8f200d3c23 100644 --- a/webhook/resourcesemantics/conversion/controller.go +++ b/webhook/resourcesemantics/conversion/controller.go @@ -89,7 +89,6 @@ func NewConversionController( kinds map[schema.GroupKind]GroupKindConversion, withContext func(context.Context) context.Context, ) *controller.Impl { - opts := []OptionFunc{ WithPath(path), WithWrapContext(withContext), diff --git a/webhook/resourcesemantics/conversion/conversion.go b/webhook/resourcesemantics/conversion/conversion.go index d8dcde744c..29830a8751 100644 --- a/webhook/resourcesemantics/conversion/conversion.go +++ b/webhook/resourcesemantics/conversion/conversion.go @@ -39,7 +39,6 @@ func (r *reconciler) Convert( ctx context.Context, req *apixv1.ConversionRequest, ) *apixv1.ConversionResponse { - if r.withContext != nil { ctx = r.withContext(ctx) } diff --git a/webhook/resourcesemantics/conversion/conversion_test.go b/webhook/resourcesemantics/conversion/conversion_test.go index de7b586224..d995ee0d81 100644 --- a/webhook/resourcesemantics/conversion/conversion_test.go +++ b/webhook/resourcesemantics/conversion/conversion_test.go @@ -459,7 +459,6 @@ func TestConversionFailureToConvert(t *testing.T) { } }) } - } func TestConversionFailureInvalidDesiredAPIVersion(t *testing.T) { @@ -621,7 +620,6 @@ func newConversionWithKinds( context.Context, webhook.ConversionController, ) { - ctx, _ := SetupFakeContext(t) ctx = webhook.WithOptions(ctx, webhook.Options{ SecretName: "webhook-secret", diff --git a/webhook/resourcesemantics/conversion/reconciler.go b/webhook/resourcesemantics/conversion/reconciler.go index 103e6a5eba..f23b055872 100644 --- a/webhook/resourcesemantics/conversion/reconciler.go +++ b/webhook/resourcesemantics/conversion/reconciler.go @@ -51,9 +51,11 @@ type reconciler struct { client apixclient.Interface } -var _ webhook.ConversionController = (*reconciler)(nil) -var _ controller.Reconciler = (*reconciler)(nil) -var _ pkgreconciler.LeaderAware = (*reconciler)(nil) +var ( + _ webhook.ConversionController = (*reconciler)(nil) + _ controller.Reconciler = (*reconciler)(nil) + _ pkgreconciler.LeaderAware = (*reconciler)(nil) +) // Path implements webhook.ConversionController func (r *reconciler) Path() string { diff --git a/webhook/resourcesemantics/defaulting/controller.go b/webhook/resourcesemantics/defaulting/controller.go index ba50005d79..c7f9bb139e 100644 --- a/webhook/resourcesemantics/defaulting/controller.go +++ b/webhook/resourcesemantics/defaulting/controller.go @@ -45,7 +45,6 @@ func NewAdmissionController( disallowUnknownFields bool, callbacks ...map[schema.GroupVersionKind]Callback, ) *controller.Impl { - // This not ideal, we are using a variadic argument to effectively make callbacks optional // This allows this addition to be non-breaking to consumers of /pkg // TODO: once all sub-repos have adopted this, we might move this back to a traditional param. diff --git a/webhook/resourcesemantics/defaulting/defaulting.go b/webhook/resourcesemantics/defaulting/defaulting.go index 90f9ec8c96..4140ec7192 100644 --- a/webhook/resourcesemantics/defaulting/defaulting.go +++ b/webhook/resourcesemantics/defaulting/defaulting.go @@ -104,10 +104,12 @@ func NewCallback(function func(context.Context, *unstructured.Unstructured) erro return Callback{function: function, supportedVerbs: m} } -var _ controller.Reconciler = (*reconciler)(nil) -var _ pkgreconciler.LeaderAware = (*reconciler)(nil) -var _ webhook.AdmissionController = (*reconciler)(nil) -var _ webhook.StatelessAdmissionController = (*reconciler)(nil) +var ( + _ controller.Reconciler = (*reconciler)(nil) + _ pkgreconciler.LeaderAware = (*reconciler)(nil) + _ webhook.AdmissionController = (*reconciler)(nil) + _ webhook.StatelessAdmissionController = (*reconciler)(nil) +) // Reconcile implements controller.Reconciler func (ac *reconciler) Reconcile(ctx context.Context, key string) error { diff --git a/webhook/resourcesemantics/defaulting/defaulting_test.go b/webhook/resourcesemantics/defaulting/defaulting_test.go index 3b3c6d86c5..4f88c6b84a 100644 --- a/webhook/resourcesemantics/defaulting/defaulting_test.go +++ b/webhook/resourcesemantics/defaulting/defaulting_test.go @@ -132,8 +132,8 @@ var ( func newNonRunningTestResourceAdmissionController(t *testing.T) ( kubeClient *fakekubeclientset.Clientset, - ac webhook.AdmissionController) { - + ac webhook.AdmissionController, +) { t.Helper() // Create fake clients kubeClient = fakekubeclientset.NewSimpleClientset(initialResourceWebhook) @@ -611,7 +611,6 @@ func TestAdmitUpdatesCallback(t *testing.T) { Path: "/spec/fieldForCallbackDefaulting", Value: "I'm a default", }, { - Operation: "replace", Path: "/metadata/annotations/pkg.knative.dev~1lastModifier", Value: user2, @@ -688,7 +687,6 @@ func TestAdmitUpdatesCallback(t *testing.T) { Path: "/spec/fieldForCallbackDefaulting", Value: "I'm a default", }, { - Operation: "replace", Path: "/metadata/annotations/pkg.knative.dev~1lastModifier", Value: user2, diff --git a/webhook/resourcesemantics/defaulting/table_test.go b/webhook/resourcesemantics/defaulting/table_test.go index 2f946073da..0468d4f10a 100644 --- a/webhook/resourcesemantics/defaulting/table_test.go +++ b/webhook/resourcesemantics/defaulting/table_test.go @@ -160,7 +160,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and MWH exist, missing service reference", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -174,7 +175,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and MWH exist, missing other stuff", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -218,7 +220,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and MWH exist, added fields are incorrect", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -281,7 +284,8 @@ func TestReconcile(t *testing.T) { WithReactors: []clientgotesting.ReactionFunc{ InduceFailure("update", "mutatingwebhookconfigurations"), }, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -338,7 +342,8 @@ func TestReconcile(t *testing.T) { }, { Name: ":fire: everything is fine :fire:", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -375,7 +380,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and MWH exist, correcting namespaceSelector", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, diff --git a/webhook/resourcesemantics/defaulting/user_info_test.go b/webhook/resourcesemantics/defaulting/user_info_test.go index 8c217beb45..c5e744748c 100644 --- a/webhook/resourcesemantics/defaulting/user_info_test.go +++ b/webhook/resourcesemantics/defaulting/user_info_test.go @@ -88,7 +88,6 @@ func TestSetUserInfoAnnotationsWhenWithinCreate(t *testing.T) { } t.Fatalf("Annotations don't match") } - }) } } diff --git a/webhook/resourcesemantics/validation/controller.go b/webhook/resourcesemantics/validation/controller.go index eee6105b45..f24b36792a 100644 --- a/webhook/resourcesemantics/validation/controller.go +++ b/webhook/resourcesemantics/validation/controller.go @@ -45,7 +45,6 @@ func NewAdmissionControllerWithConfig( disallowUnknownFields bool, callbacks map[schema.GroupVersionKind]Callback, ) *controller.Impl { - opts := []OptionFunc{ WithPath(path), WithTypes(handlers), @@ -122,7 +121,6 @@ func newController(ctx context.Context, name string, optsFunc ...OptionFunc) *co }) return c - } // NewAdmissionController constructs a reconciler diff --git a/webhook/resourcesemantics/validation/reconcile_config.go b/webhook/resourcesemantics/validation/reconcile_config.go index dfc3619910..afbc45c051 100644 --- a/webhook/resourcesemantics/validation/reconcile_config.go +++ b/webhook/resourcesemantics/validation/reconcile_config.go @@ -64,10 +64,12 @@ type reconciler struct { secretName string } -var _ controller.Reconciler = (*reconciler)(nil) -var _ pkgreconciler.LeaderAware = (*reconciler)(nil) -var _ webhook.AdmissionController = (*reconciler)(nil) -var _ webhook.StatelessAdmissionController = (*reconciler)(nil) +var ( + _ controller.Reconciler = (*reconciler)(nil) + _ pkgreconciler.LeaderAware = (*reconciler)(nil) + _ webhook.AdmissionController = (*reconciler)(nil) + _ webhook.StatelessAdmissionController = (*reconciler)(nil) +) // Path implements AdmissionController func (ac *reconciler) Path() string { diff --git a/webhook/resourcesemantics/validation/reconcile_config_test.go b/webhook/resourcesemantics/validation/reconcile_config_test.go index 5663225889..668a2db5c0 100644 --- a/webhook/resourcesemantics/validation/reconcile_config_test.go +++ b/webhook/resourcesemantics/validation/reconcile_config_test.go @@ -147,7 +147,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and VWH exist, missing service reference", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -161,7 +162,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and VWH exist, missing other stuff", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -204,7 +206,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and VWH exist, added fields are incorrect", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -264,7 +267,8 @@ func TestReconcile(t *testing.T) { WithReactors: []clientgotesting.ReactionFunc{ InduceFailure("update", "validatingwebhookconfigurations"), }, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -320,7 +324,8 @@ func TestReconcile(t *testing.T) { }, { Name: ":fire: everything is fine :fire:", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -356,7 +361,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and VWH exist, correcting namespaceSelector", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -422,7 +428,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and VWH exist, correcting namespaceSelector, preserving matchLabels", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -494,7 +501,8 @@ func TestReconcile(t *testing.T) { }, { Name: "secret and VWH exist, correcting namespaceSelector without existing matchExpressions, preserving matchLabels", Key: key, - Objects: []runtime.Object{secret, ns, + Objects: []runtime.Object{ + secret, ns, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -606,5 +614,4 @@ func TestNew(t *testing.T) { }) != nil { t.Error("Queue length was never 1") } - } diff --git a/webhook/resourcesemantics/validation/validation_admit.go b/webhook/resourcesemantics/validation/validation_admit.go index e601890afc..ed5b834920 100644 --- a/webhook/resourcesemantics/validation/validation_admit.go +++ b/webhook/resourcesemantics/validation/validation_admit.go @@ -106,8 +106,8 @@ func (ac *reconciler) Admit(ctx context.Context, request *admissionv1.AdmissionR func (ac *reconciler) decodeRequestAndPrepareContext( ctx context.Context, req *admissionv1.AdmissionRequest, - gvk schema.GroupVersionKind) (context.Context, resourcesemantics.GenericCRD, error) { - + gvk schema.GroupVersionKind, +) (context.Context, resourcesemantics.GenericCRD, error) { logger := logging.FromContext(ctx) handler, ok := ac.handlers[gvk] if !ok { diff --git a/webhook/resourcesemantics/validation/validation_admit_test.go b/webhook/resourcesemantics/validation/validation_admit_test.go index 784c15e918..f67199f137 100644 --- a/webhook/resourcesemantics/validation/validation_admit_test.go +++ b/webhook/resourcesemantics/validation/validation_admit_test.go @@ -121,8 +121,8 @@ var ( func newNonRunningTestResourceAdmissionController(t *testing.T) ( kubeClient *fakekubeclientset.Clientset, - ac webhook.AdmissionController) { - + ac webhook.AdmissionController, +) { t.Helper() // Create fake clients kubeClient = fakekubeclientset.NewSimpleClientset(initialResourceWebhook) diff --git a/webhook/resourcesemantics/validation/validation_deprecated_test.go b/webhook/resourcesemantics/validation/validation_deprecated_test.go index c973e20f07..01509071b0 100644 --- a/webhook/resourcesemantics/validation/validation_deprecated_test.go +++ b/webhook/resourcesemantics/validation/validation_deprecated_test.go @@ -31,7 +31,6 @@ import ( // In strict mode, you are not allowed to set a deprecated field when doing a Create. func TestStrictValidation(t *testing.T) { - newCreateReq := func(new []byte) *admissionv1.AdmissionRequest { req := &admissionv1.AdmissionRequest{ Operation: admissionv1.Create, diff --git a/webhook/stats_reporter.go b/webhook/stats_reporter.go index 3f05d4a91c..bc62820b98 100644 --- a/webhook/stats_reporter.go +++ b/webhook/stats_reporter.go @@ -66,8 +66,10 @@ var ( resultCodeKey = tag.MustNewKey("result_code") ) -type admissionToValue func(*admissionv1.AdmissionRequest, *admissionv1.AdmissionResponse) string -type conversionToValue func(*apixv1.ConversionRequest, *apixv1.ConversionResponse) string +type ( + admissionToValue func(*admissionv1.AdmissionRequest, *admissionv1.AdmissionResponse) string + conversionToValue func(*apixv1.ConversionRequest, *apixv1.ConversionResponse) string +) var ( allAdmissionTags = map[tag.Key]admissionToValue{ diff --git a/webhook/testing/factory.go b/webhook/testing/factory.go index 1e8d215c53..b35d955da4 100644 --- a/webhook/testing/factory.go +++ b/webhook/testing/factory.go @@ -50,7 +50,8 @@ type Ctor func(context.Context, *Listers, configmap.Watcher) controller.Reconcil // MakeFactory creates a reconciler factory with fake clients and controller created by `ctor`. func MakeFactory(ctor Ctor) rtesting.Factory { return func(t *testing.T, r *rtesting.TableRow) ( - controller.Reconciler, rtesting.ActionRecorderList, rtesting.EventList) { + controller.Reconciler, rtesting.ActionRecorderList, rtesting.EventList, + ) { ls := NewListers(r.Objects) ctx := r.Ctx diff --git a/webhook/webhook.go b/webhook/webhook.go index d8842df35a..e91262db2c 100644 --- a/webhook/webhook.go +++ b/webhook/webhook.go @@ -132,7 +132,6 @@ func New( ctx context.Context, controllers []interface{}, ) (webhook *Webhook, err error) { - // ServeMux.Handle panics on duplicate paths defer func() { if r := recover(); r != nil { @@ -270,11 +269,11 @@ func (wh *Webhook) Run(stop <-chan struct{}) error { Handler: drainer, Addr: fmt.Sprint(":", wh.Options.Port), TLSConfig: wh.tlsConfig, - ReadHeaderTimeout: time.Minute, //https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 + ReadHeaderTimeout: time.Minute, // https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 TLSNextProto: nextProto, } - var serve = server.ListenAndServe + serve := server.ListenAndServe if server.TLSConfig != nil && wh.testListener != nil { serve = func() error { diff --git a/webhook/webhook_test.go b/webhook/webhook_test.go index 7d0e596acd..2f0e3d1078 100644 --- a/webhook/webhook_test.go +++ b/webhook/webhook_test.go @@ -55,7 +55,8 @@ const ( ) func newNonRunningTestWebhook(t *testing.T, options Options, acs ...interface{}) ( - ctx context.Context, ac *Webhook, cancel context.CancelFunc) { + ctx context.Context, ac *Webhook, cancel context.CancelFunc, +) { t.Helper() // override the grace period so it drains quickly diff --git a/websocket/connection_test.go b/websocket/connection_test.go index f57cb6c7d4..5caab95caa 100644 --- a/websocket/connection_test.go +++ b/websocket/connection_test.go @@ -368,7 +368,6 @@ func TestDurableConnectionWhenConnectionBreaksDown(t *testing.T) { } return true, nil }) - if err != nil { t.Error("Timed out trying to send a message:", err) } @@ -458,5 +457,4 @@ func TestNewDurableSendingConnectionGuaranteed(t *testing.T) { // Message successfully sent, instruct the server to drop the connection. reconnectChan <- struct{}{} - }