From c6f29675f7f20afd9e119acd7003188c191b25ad Mon Sep 17 00:00:00 2001 From: dongjiang1989 Date: Wed, 12 Nov 2025 20:00:49 +0800 Subject: [PATCH] update golangci-lint version and add modernize lint Signed-off-by: jiangdong --- .github/workflows/golangci-lint.yml | 2 +- .golangci.yml | 7 + hack/tools/cmd/gomodcheck/main.go | 2 +- pkg/builder/controller.go | 2 +- pkg/builder/controller_test.go | 4 +- pkg/builder/webhook.go | 2 + pkg/cache/cache_test.go | 36 +-- pkg/cache/defaulting_test.go | 8 +- pkg/cache/delegating_by_gvk_cache.go | 6 +- pkg/cache/informer_cache.go | 2 +- pkg/cache/internal/cache_reader.go | 16 +- pkg/cache/internal/informers.go | 6 +- pkg/certwatcher/certwatcher_test.go | 2 +- pkg/client/apiutil/apimachinery.go | 2 +- pkg/client/apiutil/restmapper_test.go | 8 +- pkg/client/client_test.go | 12 +- pkg/client/example_test.go | 24 +- pkg/client/fake/client.go | 41 +--- pkg/client/fake/client_test.go | 54 ++--- pkg/client/namespaced_client_test.go | 6 +- pkg/client/patch.go | 6 +- .../priorityqueue/priorityqueue_test.go | 39 ++- pkg/envtest/komega/equalobject.go | 10 +- pkg/envtest/komega/equalobject_test.go | 222 +++++++++--------- pkg/handler/eventhandler_test.go | 10 +- pkg/internal/controller/controller_test.go | 8 +- pkg/internal/flock/flock_other.go | 2 +- pkg/internal/flock/flock_unix.go | 1 - .../recorder/recorder_integration_test.go | 2 +- pkg/internal/source/event_handler.go | 6 +- pkg/internal/testing/addr/manager.go | 2 +- pkg/internal/testing/certs/tinyca_test.go | 2 +- pkg/internal/testing/process/arguments.go | 4 +- .../testing/process/procattr_other.go | 1 - pkg/internal/testing/process/procattr_unix.go | 1 - pkg/leaderelection/leader_election.go | 5 +- pkg/log/deleg.go | 10 +- pkg/log/log.go | 2 +- pkg/log/log_test.go | 30 +-- pkg/log/null.go | 6 +- pkg/log/zap/zap_test.go | 50 ++-- pkg/manager/runnable_group_test.go | 10 +- pkg/manager/signals/signal_posix.go | 1 - pkg/manager/signals/signal_test.go | 2 +- pkg/scheme/scheme_test.go | 12 +- pkg/source/source_integration_test.go | 8 +- pkg/webhook/admission/decode.go | 2 +- pkg/webhook/admission/decode_test.go | 4 +- pkg/webhook/admission/defaulter_custom.go | 1 + pkg/webhook/admission/validator_custom.go | 2 + pkg/webhook/alias.go | 2 + tools/setup-envtest/env/exit.go | 8 +- 52 files changed, 343 insertions(+), 370 deletions(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 65e849da2d..30c7f7f02a 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -34,6 +34,6 @@ jobs: - name: golangci-lint uses: golangci/golangci-lint-action@0a35821d5c230e903fcfe077583637dea1b27b47 # tag=v9.0.0 with: - version: v2.5.0 + version: v2.6.1 args: --output.text.print-linter-name=true --output.text.colors=true --timeout 10m working-directory: ${{matrix.working-directory}} diff --git a/.golangci.yml b/.golangci.yml index 88fa35359e..591a5224c3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -31,6 +31,7 @@ linters: - iotamixing - makezero - misspell + - modernize - nakedret - nilerr - nolintlint @@ -75,6 +76,9 @@ linters: - pkg: sigs.k8s.io/controller-runtime alias: ctrl no-unaliased: true + modernize: + disable: + - omitzero revive: rules: # The following rules are recommended https://github.com/mgechev/revive#recommended-configuration @@ -125,6 +129,9 @@ linters: - linters: - staticcheck text: 'SA1019: .*The component config package has been deprecated and will be removed in a future release.' + - linters: + - staticcheck + text: 'SA1019: .* is deprecated: .* is deprecated, use .* instead ' # With Go 1.16, the new embed directive can be used with an un-named import, # revive (previously, golint) only allows these to be imported in a main.go, which wouldn't work for us. # This directive allows the embed package to be imported with an underscore everywhere. diff --git a/hack/tools/cmd/gomodcheck/main.go b/hack/tools/cmd/gomodcheck/main.go index 5cbaf377e2..afba18b624 100644 --- a/hack/tools/cmd/gomodcheck/main.go +++ b/hack/tools/cmd/gomodcheck/main.go @@ -162,7 +162,7 @@ func modulesFromUpstreamModGraph(upstreamRefList []string) (map[string]map[strin } modToVersionToUpstreamRef := make(map[string]map[string]string) - for _, line := range strings.Split(graph, "\n") { + for line := range strings.SplitSeq(graph, "\n") { ref := strings.SplitN(line, "@", 2)[0] if _, ok := upstreamRefs[ref]; !ok { diff --git a/pkg/builder/controller.go b/pkg/builder/controller.go index 6d906f6e52..840e27b679 100644 --- a/pkg/builder/controller.go +++ b/pkg/builder/controller.go @@ -312,7 +312,7 @@ func (blder *TypedBuilder[request]) doWatch() error { return err } - if reflect.TypeFor[request]() != reflect.TypeOf(reconcile.Request{}) { + if reflect.TypeFor[request]() != reflect.TypeFor[reconcile.Request]() { return fmt.Errorf("For() can only be used with reconcile.Request, got %T", *new(request)) } diff --git a/pkg/builder/controller_test.go b/pkg/builder/controller_test.go index 46e937d590..1f9729d9f4 100644 --- a/pkg/builder/controller_test.go +++ b/pkg/builder/controller_test.go @@ -61,10 +61,10 @@ func (l *testLogger) Enabled(int) bool { return true } -func (l *testLogger) Info(level int, msg string, keysAndValues ...interface{}) { +func (l *testLogger) Info(level int, msg string, keysAndValues ...any) { } -func (l *testLogger) WithValues(keysAndValues ...interface{}) logr.LogSink { +func (l *testLogger) WithValues(keysAndValues ...any) logr.LogSink { return l } diff --git a/pkg/builder/webhook.go b/pkg/builder/webhook.go index 428100a66c..0d9c8ec4e1 100644 --- a/pkg/builder/webhook.go +++ b/pkg/builder/webhook.go @@ -64,6 +64,7 @@ func WebhookManagedBy[T runtime.Object](m manager.Manager, object T) *WebhookBui // WithCustomDefaulter takes an admission.CustomDefaulter interface, a MutatingWebhook with the provided opts (admission.DefaulterOption) // will be wired for this type. +// // Deprecated: Use WithDefaulter instead. func (blder *WebhookBuilder[T]) WithCustomDefaulter(defaulter admission.CustomDefaulter, opts ...admission.DefaulterOption) *WebhookBuilder[T] { blder.customDefaulter = defaulter @@ -79,6 +80,7 @@ func (blder *WebhookBuilder[T]) WithDefaulter(defaulter admission.Defaulter[T], } // WithCustomValidator takes a admission.CustomValidator interface, a ValidatingWebhook will be wired for this type. +// // Deprecated: Use WithValidator instead. func (blder *WebhookBuilder[T]) WithCustomValidator(validator admission.CustomValidator) *WebhookBuilder[T] { blder.customValidator = validator diff --git a/pkg/cache/cache_test.go b/pkg/cache/cache_test.go index c2dae0978f..a95836b90d 100644 --- a/pkg/cache/cache_test.go +++ b/pkg/cache/cache_test.go @@ -216,7 +216,7 @@ var _ = Describe("Cache with transformers", func() { By("creating the informer cache") informerCache, err = cache.New(cfg, cache.Options{ - DefaultTransform: func(i interface{}) (interface{}, error) { + DefaultTransform: func(i any) (any, error) { obj := i.(runtime.Object) Expect(obj).NotTo(BeNil()) @@ -238,7 +238,7 @@ var _ = Describe("Cache with transformers", func() { }, ByObject: map[client.Object]cache.ByObject{ &corev1.Pod{}: { - Transform: func(i interface{}) (interface{}, error) { + Transform: func(i any) (any, error) { obj := i.(runtime.Object) Expect(obj).NotTo(BeNil()) accessor, err := meta.Accessor(obj) @@ -1103,7 +1103,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(out).To(Equal(uKnownPod2)) By("altering a field in the retrieved pod") - m, _ := out.Object["spec"].(map[string]interface{}) + m, _ := out.Object["spec"].(map[string]any) m["activeDeadlineSeconds"] = 4 By("verifying the pods are no longer equal") @@ -1954,8 +1954,8 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(sii.HasSynced()).To(BeTrue()) By("adding an event handler listening for object creation which sends the object to a channel") - out := make(chan interface{}) - addFunc := func(obj interface{}) { + out := make(chan any) + addFunc := func(obj any) { out <- obj } _, _ = sii.AddEventHandler(kcache.ResourceEventHandlerFuncs{AddFunc: addFunc}) @@ -2014,8 +2014,8 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(sii.HasSynced()).To(BeTrue()) By("adding an event handler listening for object creation which sends the object to a channel") - out := make(chan interface{}) - addFunc := func(obj interface{}) { + out := make(chan any) + addFunc := func(obj any) { out <- obj } _, _ = sii.AddEventHandler(kcache.ResourceEventHandlerFuncs{AddFunc: addFunc}) @@ -2196,9 +2196,9 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca By("getting a shared index informer for a pod") pod := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ - "containers": []map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ + "containers": []map[string]any{ { "name": "nginx", "image": "nginx", @@ -2220,8 +2220,8 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(sii.HasSynced()).To(BeTrue()) By("adding an event handler listening for object creation which sends the object to a channel") - out := make(chan interface{}) - addFunc := func(obj interface{}) { + out := make(chan any) + addFunc := func(obj any) { out <- obj } _, _ = sii.AddEventHandler(kcache.ResourceEventHandlerFuncs{AddFunc: addFunc}) @@ -2239,9 +2239,9 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should be able to stop and restart informers", func(ctx SpecContext) { By("getting a shared index informer for a pod") pod := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ - "containers": []map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ + "containers": []map[string]any{ { "name": "nginx", "image": "nginx", @@ -2294,7 +2294,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca if !ok { return []string{} } - m, ok := s.(map[string]interface{}) + m, ok := s.(map[string]any) if !ok { return []string{} } @@ -2379,8 +2379,8 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(sii.HasSynced()).To(BeTrue()) By("adding an event handler listening for object creation which sends the object to a channel") - out := make(chan interface{}) - addFunc := func(obj interface{}) { + out := make(chan any) + addFunc := func(obj any) { out <- obj } _, _ = sii.AddEventHandler(kcache.ResourceEventHandlerFuncs{AddFunc: addFunc}) diff --git a/pkg/cache/defaulting_test.go b/pkg/cache/defaulting_test.go index 89a0334324..b4b4dd030a 100644 --- a/pkg/cache/defaulting_test.go +++ b/pkg/cache/defaulting_test.go @@ -474,11 +474,9 @@ func TestDefaultOptsRace(t *testing.T) { // Start go routines which re-use the above options struct. wg := sync.WaitGroup{} for range 2 { - wg.Add(1) - go func() { + wg.Go(func() { _, _ = defaultOpts(&rest.Config{}, opts) - wg.Done() - }() + }) } // Wait for the go routines to finish. @@ -509,7 +507,7 @@ func TestDefaultConfigConsidersAllFields(t *testing.T) { }, ) - for i := 0; i < 100; i++ { + for range 100 { fuzzed := Config{} f.Fuzz(&fuzzed) diff --git a/pkg/cache/delegating_by_gvk_cache.go b/pkg/cache/delegating_by_gvk_cache.go index 46bd243c66..adc5d957a4 100644 --- a/pkg/cache/delegating_by_gvk_cache.go +++ b/pkg/cache/delegating_by_gvk_cache.go @@ -81,13 +81,11 @@ func (dbt *delegatingByGVKCache) Start(ctx context.Context) error { errs := make(chan error) for idx := range allCaches { cache := allCaches[idx] - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { if err := cache.Start(ctx); err != nil { errs <- err } - }() + }) } select { diff --git a/pkg/cache/informer_cache.go b/pkg/cache/informer_cache.go index 091667b7fa..5f0d88fdb0 100644 --- a/pkg/cache/informer_cache.go +++ b/pkg/cache/informer_cache.go @@ -221,7 +221,7 @@ func (ic *informerCache) IndexField(ctx context.Context, obj client.Object, fiel } func indexByField(informer Informer, field string, extractValue client.IndexerFunc) error { - indexFunc := func(objRaw interface{}) ([]string, error) { + indexFunc := func(objRaw any) ([]string, error) { // TODO(directxman12): check if this is the correct type? obj, isObj := objRaw.(client.Object) if !isObj { diff --git a/pkg/cache/internal/cache_reader.go b/pkg/cache/internal/cache_reader.go index eb6b544855..624869f590 100644 --- a/pkg/cache/internal/cache_reader.go +++ b/pkg/cache/internal/cache_reader.go @@ -20,6 +20,7 @@ import ( "context" "fmt" "reflect" + "slices" apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" @@ -109,7 +110,7 @@ func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Ob // List lists items out of the indexer and writes them to out. func (c *CacheReader) List(_ context.Context, out client.ObjectList, opts ...client.ListOption) error { - var objs []interface{} + var objs []any var err error listOpts := client.ListOptions{} @@ -186,10 +187,10 @@ func (c *CacheReader) List(_ context.Context, out client.ObjectList, opts ...cli return nil } -func byIndexes(indexer cache.Indexer, requires fields.Requirements, namespace string) ([]interface{}, error) { +func byIndexes(indexer cache.Indexer, requires fields.Requirements, namespace string) ([]any, error) { var ( err error - objs []interface{} + objs []any vals []string ) indexers := indexer.GetIndexers() @@ -213,17 +214,14 @@ func byIndexes(indexer cache.Indexer, requires fields.Requirements, namespace st if !exist { return nil, fmt.Errorf("index with name %s does not exist", indexName) } - filteredObjects := make([]interface{}, 0, len(objs)) + filteredObjects := make([]any, 0, len(objs)) for _, obj := range objs { vals, err = fn(obj) if err != nil { return nil, err } - for _, val := range vals { - if val == indexedValue { - filteredObjects = append(filteredObjects, obj) - break - } + if slices.Contains(vals, indexedValue) { + filteredObjects = append(filteredObjects, obj) } } if len(filteredObjects) == 0 { diff --git a/pkg/cache/internal/informers.go b/pkg/cache/internal/informers.go index f216be0d9e..0f921ef63d 100644 --- a/pkg/cache/internal/informers.go +++ b/pkg/cache/internal/informers.go @@ -242,11 +242,9 @@ func (ip *Informers) startInformerLocked(cacheEntry *Cache) { return } - ip.waitGroup.Add(1) - go func() { - defer ip.waitGroup.Done() + ip.waitGroup.Go(func() { cacheEntry.Start(ip.ctx.Done()) - }() + }) } func (ip *Informers) waitForStarted(ctx context.Context) bool { diff --git a/pkg/certwatcher/certwatcher_test.go b/pkg/certwatcher/certwatcher_test.go index 9737925a6b..ba47afc112 100644 --- a/pkg/certwatcher/certwatcher_test.go +++ b/pkg/certwatcher/certwatcher_test.go @@ -255,7 +255,7 @@ var _ = Describe("CertWatcher", func() { }) func writeCerts(certPath, keyPath, ip string) error { - var priv interface{} + var priv any var err error priv, err = rsa.GenerateKey(rand.Reader, 2048) if err != nil { diff --git a/pkg/client/apiutil/apimachinery.go b/pkg/client/apiutil/apimachinery.go index b132cb2d4d..217990dece 100644 --- a/pkg/client/apiutil/apimachinery.go +++ b/pkg/client/apiutil/apimachinery.go @@ -231,7 +231,7 @@ func (t targetZeroingDecoder) Decode(data []byte, defaults *schema.GroupVersionK } // zero zeros the value of a pointer. -func zero(x interface{}) { +func zero(x any) { if x == nil { return } diff --git a/pkg/client/apiutil/restmapper_test.go b/pkg/client/apiutil/restmapper_test.go index 51807f12de..71fc1681db 100644 --- a/pkg/client/apiutil/restmapper_test.go +++ b/pkg/client/apiutil/restmapper_test.go @@ -746,7 +746,7 @@ func TestLazyRestMapperProvider(t *testing.T) { wg := sync.WaitGroup{} wg.Add(50) - for i := 0; i < 50; i++ { + for range 50 { go func() { defer wg.Done() httpClient, err := rest.HTTPClientFor(restCfg) @@ -811,7 +811,7 @@ type errorMatcher struct { message string } -func (e *errorMatcher) Match(actual interface{}) (success bool, err error) { +func (e *errorMatcher) Match(actual any) (success bool, err error) { if actual == nil { return false, nil } @@ -824,10 +824,10 @@ func (e *errorMatcher) Match(actual interface{}) (success bool, err error) { return e.checkFunc(actualErr), nil } -func (e *errorMatcher) FailureMessage(actual interface{}) (message string) { +func (e *errorMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("to be %s error", e.message)) } -func (e *errorMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (e *errorMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("not to be %s error", e.message)) } diff --git a/pkg/client/client_test.go b/pkg/client/client_test.go index 079458f527..6c040657d7 100644 --- a/pkg/client/client_test.go +++ b/pkg/client/client_test.go @@ -97,7 +97,7 @@ func deleteNamespace(ctx context.Context, ns *corev1.Namespace) { Expect(err).NotTo(HaveOccurred()) WAIT_LOOP: - for i := 0; i < 10; i++ { + for range 10 { ns, err = clientset.CoreV1().Namespaces().Get(ctx, ns.Name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { // success! @@ -1215,7 +1215,7 @@ U5wwSivyi7vmegHKmblOzNVKA5qPO8zWzqBC dep, err := clientset.AppsV1().Deployments(dep.Namespace).Create(ctx, dep, metav1.CreateOptions{}) Expect(err).NotTo(HaveOccurred()) dep.APIVersion = appsv1.SchemeGroupVersion.String() - dep.Kind = reflect.TypeOf(dep).Elem().Name() + dep.Kind = reflect.TypeFor[appsv1.Deployment]().Name() depUnstructured, err := toUnstructured(dep) Expect(err).NotTo(HaveOccurred()) @@ -4133,7 +4133,7 @@ var _ = Describe("Patch", func() { Expect(err).NotTo(HaveOccurred()) By("returning a patch with data only containing the annotation change") - Expect(data).To(Equal([]byte(fmt.Sprintf(`{"metadata":{"annotations":{"%s":"%s"}}}`, annotationKey, annotationValue)))) + Expect(data).To(Equal(fmt.Appendf(nil, `{"metadata":{"annotations":{"%s":"%s"}}}`, annotationKey, annotationValue))) }) It("creates a merge patch with the modifications applied during the mutation, using optimistic locking", func() { @@ -4158,7 +4158,7 @@ var _ = Describe("Patch", func() { Expect(err).NotTo(HaveOccurred()) By("returning a patch with data containing the annotation change and the resourceVersion change") - Expect(data).To(Equal([]byte(fmt.Sprintf(`{"metadata":{"annotations":{"%s":"%s"},"resourceVersion":"%s"}}`, annotationKey, annotationValue, cm.ResourceVersion)))) + Expect(data).To(Equal(fmt.Appendf(nil, `{"metadata":{"annotations":{"%s":"%s"},"resourceVersion":"%s"}}`, annotationKey, annotationValue, cm.ResourceVersion))) }) }) @@ -4234,9 +4234,9 @@ var _ = Describe("Patch", func() { Expect(err).NotTo(HaveOccurred()) By("returning a patch with data containing the image change and the resourceVersion change") - Expect(data).To(Equal([]byte(fmt.Sprintf(`{"metadata":{"resourceVersion":"%s"},`+ + Expect(data).To(Equal(fmt.Appendf(nil, `{"metadata":{"resourceVersion":"%s"},`+ `"spec":{"template":{"spec":{"$setElementOrder/containers":[{"name":"main"},{"name":"sidecar"}],"containers":[{"image":"foo:v2","name":"main"}]}}}}`, - dep.ResourceVersion)))) + dep.ResourceVersion))) }) }) }) diff --git a/pkg/client/example_test.go b/pkg/client/example_test.go index 390dc10143..e98e19df8f 100644 --- a/pkg/client/example_test.go +++ b/pkg/client/example_test.go @@ -122,24 +122,24 @@ func ExampleClient_create() { // Using a unstructured object. u := &unstructured.Unstructured{} - u.Object = map[string]interface{}{ - "metadata": map[string]interface{}{ + u.Object = map[string]any{ + "metadata": map[string]any{ "name": "name", "namespace": "namespace", }, - "spec": map[string]interface{}{ + "spec": map[string]any{ "replicas": 2, - "selector": map[string]interface{}{ - "matchLabels": map[string]interface{}{ + "selector": map[string]any{ + "matchLabels": map[string]any{ "foo": "bar", }, }, - "template": map[string]interface{}{ - "labels": map[string]interface{}{ + "template": map[string]any{ + "labels": map[string]any{ "foo": "bar", }, - "spec": map[string]interface{}{ - "containers": []map[string]interface{}{ + "spec": map[string]any{ + "containers": []map[string]any{ { "name": "nginx", "image": "nginx", @@ -227,8 +227,8 @@ func ExampleClient_apply() { // This example shows how to use the client with typed and unstructured objects to patch objects' status. func ExampleClient_patchStatus() { u := &unstructured.Unstructured{} - u.Object = map[string]interface{}{ - "metadata": map[string]interface{}{ + u.Object = map[string]any{ + "metadata": map[string]any{ "name": "foo", "namespace": "namespace", }, @@ -238,7 +238,7 @@ func ExampleClient_patchStatus() { Version: "v1beta1", Kind: "CronJob", }) - patch := []byte(fmt.Sprintf(`{"status":{"lastScheduleTime":"%s"}}`, time.Now().Format(time.RFC3339))) + patch := fmt.Appendf(nil, `{"status":{"lastScheduleTime":"%s"}}`, time.Now().Format(time.RFC3339)) _ = c.Status().Patch(context.Background(), u, client.RawPatch(types.MergePatchType, patch)) } diff --git a/pkg/client/fake/client.go b/pkg/client/fake/client.go index 05d71bac76..2a07bd40b2 100644 --- a/pkg/client/fake/client.go +++ b/pkg/client/fake/client.go @@ -21,6 +21,7 @@ import ( "errors" "fmt" "reflect" + "slices" "strings" "sync" "time" @@ -588,13 +589,7 @@ func (c *fakeClient) objMatchesFieldSelector(o runtime.Object, extractIndex clie panic(fmt.Errorf("expected object %v to be of type client.Object, but it's not", o)) } - for _, extractedVal := range extractIndex(obj) { - if extractedVal == val { - return true - } - } - - return false + return slices.Contains(extractIndex(obj), val) } func (c *fakeClient) Scheme() *runtime.Scheme { @@ -626,10 +621,8 @@ func (c *fakeClient) Create(ctx context.Context, obj client.Object, opts ...clie createOptions := &client.CreateOptions{} createOptions.ApplyOptions(opts) - for _, dryRunOpt := range createOptions.DryRun { - if dryRunOpt == metav1.DryRunAll { - return nil - } + if slices.Contains(createOptions.DryRun, metav1.DryRunAll) { + return nil } gvr, err := getGVRFromObject(obj, c.scheme) @@ -693,10 +686,8 @@ func (c *fakeClient) Delete(ctx context.Context, obj client.Object, opts ...clie delOptions := client.DeleteOptions{} delOptions.ApplyOptions(opts) - for _, dryRunOpt := range delOptions.DryRun { - if dryRunOpt == metav1.DryRunAll { - return nil - } + if slices.Contains(delOptions.DryRun, metav1.DryRunAll) { + return nil } c.trackerWriteLock.Lock() @@ -742,10 +733,8 @@ func (c *fakeClient) DeleteAllOf(ctx context.Context, obj client.Object, opts .. dcOptions := client.DeleteAllOfOptions{} dcOptions.ApplyOptions(opts) - for _, dryRunOpt := range dcOptions.DryRun { - if dryRunOpt == metav1.DryRunAll { - return nil - } + if slices.Contains(dcOptions.DryRun, metav1.DryRunAll) { + return nil } c.trackerWriteLock.Lock() @@ -793,10 +782,8 @@ func (c *fakeClient) update(obj client.Object, isStatus bool, opts ...client.Upd updateOptions := &client.UpdateOptions{} updateOptions.ApplyOptions(opts) - for _, dryRunOpt := range updateOptions.DryRun { - if dryRunOpt == metav1.DryRunAll { - return nil - } + if slices.Contains(updateOptions.DryRun, metav1.DryRunAll) { + return nil } gvr, err := getGVRFromObject(obj, c.scheme) @@ -908,10 +895,8 @@ func (c *fakeClient) patch(obj client.Object, patch client.Patch, opts ...client c.schemeLock.RLock() defer c.schemeLock.RUnlock() - for _, dryRunOpt := range patchOptions.DryRun { - if dryRunOpt == metav1.DryRunAll { - return nil - } + if slices.Contains(patchOptions.DryRun, metav1.DryRunAll) { + return nil } gvr, err := getGVRFromObject(obj, c.scheme) @@ -1507,7 +1492,7 @@ func inTreeResourcesWithStatus() []schema.GroupVersionKind { } // zero zeros the value of a pointer. -func zero(x interface{}) { +func zero(x any) { if x == nil { return } diff --git a/pkg/client/fake/client_test.go b/pkg/client/fake/client_test.go index 1eed4d5a6d..f85d57b047 100644 --- a/pkg/client/fake/client_test.go +++ b/pkg/client/fake/client_test.go @@ -857,7 +857,7 @@ var _ = Describe("Fake client", func() { }) It("should handle finalizers deleting a collection", func(ctx SpecContext) { - for i := 0; i < 5; i++ { + for i := range 5 { namespacedName := types.NamespacedName{ Name: fmt.Sprintf("test-cm-%d", i), Namespace: "delete-collection-with-finalizers", @@ -992,9 +992,9 @@ var _ = Describe("Fake client", func() { It("should be able to Patch", func(ctx SpecContext) { By("Patching a deployment") - mergePatch, err := json.Marshal(map[string]interface{}{ - "metadata": map[string]interface{}{ - "annotations": map[string]interface{}{ + mergePatch, err := json.Marshal(map[string]any{ + "metadata": map[string]any{ + "annotations": map[string]any{ "foo": "bar", }, }, @@ -1209,8 +1209,8 @@ var _ = Describe("Fake client", func() { Expect(err).ToNot(HaveOccurred()) By("Removing the finalizer") - mergePatch, err := json.Marshal(map[string]interface{}{ - "metadata": map[string]interface{}{ + mergePatch, err := json.Marshal(map[string]any{ + "metadata": map[string]any{ "$deleteFromPrimitiveList/finalizers": []string{ "finalizers.sigs.k8s.io/test", }, @@ -1719,7 +1719,7 @@ var _ = Describe("Fake client", func() { cl := NewClientBuilder().WithObjects(obj).Build() objOriginal := obj.DeepCopy() - patch := []byte(fmt.Sprintf(`{"spec":{"replicas":%d}}`, 2)) + patch := fmt.Appendf(nil, `{"spec":{"replicas":%d}}`, 2) Expect(cl.SubResource("scale").Patch(ctx, obj, client.RawPatch(types.MergePatchType, patch))).NotTo(HaveOccurred()) actual := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: obj.Name}} @@ -2012,7 +2012,7 @@ var _ = Describe("Fake client", func() { Expect(cl.Create(ctx, obj)).To(Succeed()) original := obj.DeepCopy() - err := unstructured.SetNestedField(obj.Object, map[string]interface{}{"count": int64(2)}, "status") + err := unstructured.SetNestedField(obj.Object, map[string]any{"count": int64(2)}, "status") Expect(err).ToNot(HaveOccurred()) Expect(cl.Patch(ctx, obj, client.MergeFrom(original))).To(Succeed()) @@ -3092,12 +3092,12 @@ var _ = Describe("Fake client", func() { }) It("will error out if an object with invalid managedFields is added", func(ctx SpecContext) { - fieldV1Map := map[string]interface{}{ - "f:metadata": map[string]interface{}{ - "f:name": map[string]interface{}{}, - "f:labels": map[string]interface{}{}, - "f:annotations": map[string]interface{}{}, - "f:finalizers": map[string]interface{}{}, + fieldV1Map := map[string]any{ + "f:metadata": map[string]any{ + "f:name": map[string]any{}, + "f:labels": map[string]any{}, + "f:annotations": map[string]any{}, + "f:finalizers": map[string]any{}, }, } fieldV1, err := json.Marshal(fieldV1Map) @@ -3120,12 +3120,12 @@ var _ = Describe("Fake client", func() { }) It("allows adding an object with managedFields", func(ctx SpecContext) { - fieldV1Map := map[string]interface{}{ - "f:metadata": map[string]interface{}{ - "f:name": map[string]interface{}{}, - "f:labels": map[string]interface{}{}, - "f:annotations": map[string]interface{}{}, - "f:finalizers": map[string]interface{}{}, + fieldV1Map := map[string]any{ + "f:metadata": map[string]any{ + "f:name": map[string]any{}, + "f:labels": map[string]any{}, + "f:annotations": map[string]any{}, + "f:finalizers": map[string]any{}, }, } fieldV1, err := json.Marshal(fieldV1Map) @@ -3147,12 +3147,12 @@ var _ = Describe("Fake client", func() { }) It("allows adding an object with invalid managedFields when not using the FieldManagedObjectTracker", func(ctx SpecContext) { - fieldV1Map := map[string]interface{}{ - "f:metadata": map[string]interface{}{ - "f:name": map[string]interface{}{}, - "f:labels": map[string]interface{}{}, - "f:annotations": map[string]interface{}{}, - "f:finalizers": map[string]interface{}{}, + fieldV1Map := map[string]any{ + "f:metadata": map[string]any{ + "f:name": map[string]any{}, + "f:labels": map[string]any{}, + "f:annotations": map[string]any{}, + "f:finalizers": map[string]any{}, }, } fieldV1, err := json.Marshal(fieldV1Map) @@ -3270,7 +3270,7 @@ var _ = Describe("Fake client", func() { } }) -type Schemaless map[string]interface{} +type Schemaless map[string]any type WithSchemalessSpec struct { metav1.TypeMeta `json:",inline"` diff --git a/pkg/client/namespaced_client_test.go b/pkg/client/namespaced_client_test.go index 6e9635474e..d7be6eeee6 100644 --- a/pkg/client/namespaced_client_test.go +++ b/pkg/client/namespaced_client_test.go @@ -706,9 +706,9 @@ var _ = Describe("NamespacedClient", func() { }) func generatePatch() []byte { - mergePatch, err := json.Marshal(map[string]interface{}{ - "metadata": map[string]interface{}{ - "annotations": map[string]interface{}{ + mergePatch, err := json.Marshal(map[string]any{ + "metadata": map[string]any{ + "annotations": map[string]any{ "foo": "bar", }, }, diff --git a/pkg/client/patch.go b/pkg/client/patch.go index 9bd0953fdc..3d914eea22 100644 --- a/pkg/client/patch.go +++ b/pkg/client/patch.go @@ -88,7 +88,7 @@ type MergeFromOptions struct { type mergeFromPatch struct { patchType types.PatchType - createPatch func(originalJSON, modifiedJSON []byte, dataStruct interface{}) ([]byte, error) + createPatch func(originalJSON, modifiedJSON []byte, dataStruct any) ([]byte, error) from Object opts MergeFromOptions } @@ -134,11 +134,11 @@ func (s *mergeFromPatch) Data(obj Object) ([]byte, error) { return data, nil } -func createMergePatch(originalJSON, modifiedJSON []byte, _ interface{}) ([]byte, error) { +func createMergePatch(originalJSON, modifiedJSON []byte, _ any) ([]byte, error) { return jsonpatch.CreateMergePatch(originalJSON, modifiedJSON) } -func createStrategicMergePatch(originalJSON, modifiedJSON []byte, dataStruct interface{}) ([]byte, error) { +func createStrategicMergePatch(originalJSON, modifiedJSON []byte, dataStruct any) ([]byte, error) { return strategicpatch.CreateTwoWayMergePatch(originalJSON, modifiedJSON, dataStruct) } diff --git a/pkg/controller/priorityqueue/priorityqueue_test.go b/pkg/controller/priorityqueue/priorityqueue_test.go index 9c708e982b..40aeccb2e3 100644 --- a/pkg/controller/priorityqueue/priorityqueue_test.go +++ b/pkg/controller/priorityqueue/priorityqueue_test.go @@ -209,14 +209,12 @@ var _ = Describe("Controllerworkqueue", func() { wg := sync.WaitGroup{} for range 100 { // The panic only occurred relatively frequently with a high number of go routines. - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for range 10 { obj, _, _ := q.GetWithPriority() q.Done(obj) } - }() + }) } wg.Wait() @@ -256,9 +254,9 @@ var _ = Describe("Controllerworkqueue", func() { func BenchmarkAddGetDone(b *testing.B) { q := New[int]("") defer q.ShutDown() - b.ResetTimer() - for n := 0; n < b.N; n++ { - for i := 0; i < 1000; i++ { + + for b.Loop() { + for i := range 1000 { q.Add(i) } for range 1000 { @@ -271,9 +269,9 @@ func BenchmarkAddGetDone(b *testing.B) { func BenchmarkAddOnly(b *testing.B) { q := New[int]("") defer q.ShutDown() - b.ResetTimer() - for n := 0; n < b.N; n++ { - for i := 0; i < 1000; i++ { + + for b.Loop() { + for i := range 1000 { q.Add(i) } } @@ -288,9 +286,9 @@ func BenchmarkAddLockContended(b *testing.B) { q.Done(item) } }() - b.ResetTimer() - for n := 0; n < b.N; n++ { - for i := 0; i < 1000; i++ { + + for b.Loop() { + for i := range 1000 { q.Add(i) } } @@ -329,10 +327,7 @@ func TestFuzzPriorityQueue(t *testing.T) { q, metrics := newQueue() for range 10 { - wg.Add(1) - go func() { - defer wg.Done() - + wg.Go(func() { for range 1000 { opts, item := AddOpts{}, "" @@ -354,15 +349,11 @@ func TestFuzzPriorityQueue(t *testing.T) { } }() } - }() + }) } for range 100 { - wg.Add(1) - - go func() { - defer wg.Done() - + wg.Go(func() { for { item, cont := func() (string, bool) { inQueueLock.Lock() @@ -411,7 +402,7 @@ func TestFuzzPriorityQueue(t *testing.T) { q.Done(item) }() } - }() + }) } wg.Wait() diff --git a/pkg/envtest/komega/equalobject.go b/pkg/envtest/komega/equalobject.go index a931c2718a..0295d204ab 100644 --- a/pkg/envtest/komega/equalobject.go +++ b/pkg/envtest/komega/equalobject.go @@ -74,7 +74,7 @@ func EqualObject(original runtime.Object, opts ...EqualObjectOption) types.Gomeg // Match compares the current object to the passed object and returns true if the objects are the same according to // the Matcher and MatchOptions. -func (m *equalObjectMatcher) Match(actual interface{}) (success bool, err error) { +func (m *equalObjectMatcher) Match(actual any) (success bool, err error) { // Nil checks required first here for: // 1) Nil equality which returns true // 2) One object nil which returns an error @@ -93,13 +93,13 @@ func (m *equalObjectMatcher) Match(actual interface{}) (success bool, err error) } // FailureMessage returns a message comparing the full objects after an unexpected failure to match has occurred. -func (m *equalObjectMatcher) FailureMessage(actual interface{}) (message string) { +func (m *equalObjectMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("the following fields were expected to match but did not:\n%v\n%s", m.diffPaths, format.Message(actual, "expected to match", m.original)) } // NegatedFailureMessage returns a string stating that all fields matched, even though that was not expected. -func (m *equalObjectMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *equalObjectMatcher) NegatedFailureMessage(actual any) (message string) { return "it was expected that some fields do not match, but all of them did" } @@ -167,8 +167,8 @@ func (r *diffReporter) PopStep() { // calculateDiff calculates the difference between two objects and returns the // paths of the fields that do not match. -func (m *equalObjectMatcher) calculateDiff(actual interface{}) []diffPath { - var original interface{} = m.original +func (m *equalObjectMatcher) calculateDiff(actual any) []diffPath { + var original any = m.original // Remove the wrapping Object from unstructured.Unstructured to make comparison behave similar to // regular objects. if u, isUnstructured := actual.(runtime.Unstructured); isUnstructured { diff --git a/pkg/envtest/komega/equalobject_test.go b/pkg/envtest/komega/equalobject_test.go index 9fe10d1779..6163610a41 100644 --- a/pkg/envtest/komega/equalobject_test.go +++ b/pkg/envtest/komega/equalobject_test.go @@ -132,16 +132,16 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "works with unstructured.Unstructured", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ + Object: map[string]any{ + "metadata": map[string]any{ "name": "something", "namespace": "test", }, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ + Object: map[string]any{ + "metadata": map[string]any{ "name": "somethingelse", "namespace": "test", }, @@ -159,15 +159,15 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Equal field (spec) both in original and in modified", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "foo": "bar", }, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "foo": "bar", }, }, @@ -178,10 +178,10 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Equal nested field both in original and in modified", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ - "template": map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ + "template": map[string]any{ + "spec": map[string]any{ "A": "A", }, }, @@ -189,10 +189,10 @@ func TestEqualObjectMatcher(t *testing.T) { }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ - "template": map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ + "template": map[string]any{ + "spec": map[string]any{ "A": "A", }, }, @@ -206,15 +206,15 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Unequal field both in original and in modified", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "foo": "bar-changed", }, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "foo": "bar", }, }, @@ -224,10 +224,10 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Unequal nested field both in original and modified", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ - "template": map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ + "template": map[string]any{ + "spec": map[string]any{ "A": "A-Changed", }, }, @@ -235,10 +235,10 @@ func TestEqualObjectMatcher(t *testing.T) { }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ - "template": map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ + "template": map[string]any{ + "spec": map[string]any{ "A": "A", }, }, @@ -251,8 +251,8 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Value of type map with different values", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "map": map[string]string{ "A": "A-changed", "B": "B", @@ -262,8 +262,8 @@ func TestEqualObjectMatcher(t *testing.T) { }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "map": map[string]string{ "A": "A", // B missing @@ -278,8 +278,8 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Value of type Array or Slice with same length but different values", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "slice": []string{ "D", "C", @@ -289,8 +289,8 @@ func TestEqualObjectMatcher(t *testing.T) { }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "slice": []string{ "A", "B", @@ -306,22 +306,22 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Creation timestamp set to empty value on both original and modified", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", }, - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "selfLink": "foo", "creationTimestamp": metav1.Time{}, }, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", }, - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "selfLink": "foo", "creationTimestamp": metav1.Time{}, }, @@ -334,11 +334,11 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Field only in modified", original: &unstructured.Unstructured{ - Object: map[string]interface{}{}, + Object: map[string]any{}, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "foo": "bar", }, }, @@ -348,13 +348,13 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Nested field only in modified", original: &unstructured.Unstructured{ - Object: map[string]interface{}{}, + Object: map[string]any{}, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ - "template": map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ + "template": map[string]any{ + "spec": map[string]any{ "A": "A", }, }, @@ -366,18 +366,18 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Creation timestamp exists on modified but not on original", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", }, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", }, - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "selfLink": "foo", "creationTimestamp": "2021-11-03T11:05:17Z", }, @@ -390,24 +390,24 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Field only in original", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "foo": "bar", }, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{}, + Object: map[string]any{}, }, want: false, }, { name: "Nested field only in original", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ - "template": map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ + "template": map[string]any{ + "spec": map[string]any{ "A": "A", }, }, @@ -415,26 +415,26 @@ func TestEqualObjectMatcher(t *testing.T) { }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{}, + Object: map[string]any{}, }, want: false, }, { name: "Creation timestamp exists on original but not on modified", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", }, - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "selfLink": "foo", "creationTimestamp": "2021-11-03T11:05:17Z", }, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", }, }, @@ -447,18 +447,18 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Unequal Metadata fields computed by the system or in status", original: &unstructured.Unstructured{ - Object: map[string]interface{}{}, + Object: map[string]any{}, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ + Object: map[string]any{ + "metadata": map[string]any{ "selfLink": "foo", "uid": "foo", "resourceVersion": "foo", "generation": "foo", "managedFields": "foo", }, - "status": map[string]interface{}{ + "status": map[string]any{ "foo": "bar", }, }, @@ -468,15 +468,15 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Unequal labels and annotations", original: &unstructured.Unstructured{ - Object: map[string]interface{}{}, + Object: map[string]any{}, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ - "labels": map[string]interface{}{ + Object: map[string]any{ + "metadata": map[string]any{ + "labels": map[string]any{ "foo": "bar", }, - "annotations": map[string]interface{}{ + "annotations": map[string]any{ "foo": "bar", }, }, @@ -489,15 +489,15 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Unequal metadata fields ignored by IgnorePaths MatchOption", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ + Object: map[string]any{ + "metadata": map[string]any{ "name": "test", }, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ + Object: map[string]any{ + "metadata": map[string]any{ "name": "test", "selfLink": "foo", "uid": "foo", @@ -513,20 +513,20 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Unequal labels and annotations ignored by IgnorePaths MatchOption", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ + Object: map[string]any{ + "metadata": map[string]any{ "name": "test", }, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ + Object: map[string]any{ + "metadata": map[string]any{ "name": "test", - "labels": map[string]interface{}{ + "labels": map[string]any{ "foo": "bar", }, - "annotations": map[string]interface{}{ + "annotations": map[string]any{ "foo": "bar", }, }, @@ -538,14 +538,14 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Ignore fields are not compared", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{}, + Object: map[string]any{ + "spec": map[string]any{}, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ - "controlPlaneEndpoint": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ + "controlPlaneEndpoint": map[string]any{ "host": "", "port": 0, }, @@ -558,16 +558,16 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Not-ignored fields are still compared", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ - "annotations": map[string]interface{}{}, + Object: map[string]any{ + "metadata": map[string]any{ + "annotations": map[string]any{}, }, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ - "annotations": map[string]interface{}{ + Object: map[string]any{ + "metadata": map[string]any{ + "annotations": map[string]any{ "ignored": "somevalue", "superflous": "shouldcausefailure", }, @@ -582,18 +582,18 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Unequal metadata fields not compared by setting MatchPaths MatchOption", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", }, }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", }, - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "selfLink": "foo", "uid": "foo", }, @@ -607,8 +607,8 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "No changes", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", "B": "B", "C": "C", // C only in original @@ -616,8 +616,8 @@ func TestEqualObjectMatcher(t *testing.T) { }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", "B": "B", }, @@ -628,8 +628,8 @@ func TestEqualObjectMatcher(t *testing.T) { { name: "Many changes", original: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", // B missing "C": "C", // C only in original @@ -637,8 +637,8 @@ func TestEqualObjectMatcher(t *testing.T) { }, }, modified: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{ + Object: map[string]any{ + "spec": map[string]any{ "A": "A", "B": "B", }, diff --git a/pkg/handler/eventhandler_test.go b/pkg/handler/eventhandler_test.go index 2a7453f761..2023156146 100644 --- a/pkg/handler/eventhandler_test.go +++ b/pkg/handler/eventhandler_test.go @@ -183,7 +183,7 @@ var _ = Describe("Eventhandler", func() { i1, _ := q.Get() i2, _ := q.Get() - Expect([]interface{}{i1, i2}).To(ConsistOf( + Expect([]any{i1, i2}).To(ConsistOf( reconcile.Request{ NamespacedName: types.NamespacedName{Namespace: "foo", Name: "bar"}}, reconcile.Request{ @@ -215,7 +215,7 @@ var _ = Describe("Eventhandler", func() { i1, _ := q.Get() i2, _ := q.Get() - Expect([]interface{}{i1, i2}).To(ConsistOf( + Expect([]any{i1, i2}).To(ConsistOf( reconcile.Request{ NamespacedName: types.NamespacedName{Namespace: "foo", Name: "bar"}}, reconcile.Request{ @@ -280,7 +280,7 @@ var _ = Describe("Eventhandler", func() { i1, _ := q.Get() i2, _ := q.Get() - Expect([]interface{}{i1, i2}).To(ConsistOf( + Expect([]any{i1, i2}).To(ConsistOf( reconcile.Request{ NamespacedName: types.NamespacedName{Namespace: "foo", Name: "bar"}}, reconcile.Request{ @@ -362,7 +362,7 @@ var _ = Describe("Eventhandler", func() { i1, _ := q.Get() i2, _ := q.Get() - Expect([]interface{}{i1, i2}).To(ConsistOf( + Expect([]any{i1, i2}).To(ConsistOf( reconcile.Request{ NamespacedName: types.NamespacedName{Namespace: pod.GetNamespace(), Name: "foo1-parent"}}, reconcile.Request{ @@ -602,7 +602,7 @@ var _ = Describe("Eventhandler", func() { i1, _ := q.Get() i2, _ := q.Get() i3, _ := q.Get() - Expect([]interface{}{i1, i2, i3}).To(ConsistOf( + Expect([]any{i1, i2, i3}).To(ConsistOf( reconcile.Request{ NamespacedName: types.NamespacedName{Namespace: pod.GetNamespace(), Name: "foo1-parent"}}, reconcile.Request{ diff --git a/pkg/internal/controller/controller_test.go b/pkg/internal/controller/controller_test.go index 259f6669e2..0771de9534 100644 --- a/pkg/internal/controller/controller_test.go +++ b/pkg/internal/controller/controller_test.go @@ -637,13 +637,11 @@ var _ = Describe("controller", func() { By("Calling startEventSourcesAndQueueLocked multiple times in parallel") var wg sync.WaitGroup for i := 1; i <= 5; i++ { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { err := ctrl.startEventSourcesAndQueueLocked(ctx) // All calls should return the same nil error Expect(err).NotTo(HaveOccurred()) - }() + }) } wg.Wait() @@ -1625,7 +1623,7 @@ var _ = Describe("controller", func() { } var wg sync.WaitGroup - for i := 0; i < 5; i++ { + for range 5 { wg.Add(1) go func() { defer GinkgoRecover() diff --git a/pkg/internal/flock/flock_other.go b/pkg/internal/flock/flock_other.go index 069a5b3a2c..1def472197 100644 --- a/pkg/internal/flock/flock_other.go +++ b/pkg/internal/flock/flock_other.go @@ -1,4 +1,4 @@ -// +build !linux,!darwin,!freebsd,!openbsd,!netbsd,!dragonfly +//go:build !linux && !darwin && !freebsd && !openbsd && !netbsd && !dragonfly /* Copyright 2016 The Kubernetes Authors. diff --git a/pkg/internal/flock/flock_unix.go b/pkg/internal/flock/flock_unix.go index 71ec576df2..be2a8c2cfd 100644 --- a/pkg/internal/flock/flock_unix.go +++ b/pkg/internal/flock/flock_unix.go @@ -1,5 +1,4 @@ //go:build linux || darwin || freebsd || openbsd || netbsd || dragonfly -// +build linux darwin freebsd openbsd netbsd dragonfly /* Copyright 2016 The Kubernetes Authors. diff --git a/pkg/internal/recorder/recorder_integration_test.go b/pkg/internal/recorder/recorder_integration_test.go index 061070166c..d0201d1cd1 100644 --- a/pkg/internal/recorder/recorder_integration_test.go +++ b/pkg/internal/recorder/recorder_integration_test.go @@ -45,7 +45,7 @@ var _ = Describe("recorder", func() { Expect(err).NotTo(HaveOccurred()) By("Creating the Controller") - deprecatedRecorder := cm.GetEventRecorderFor("test-deprecated-recorder") //nolint:staticcheck + deprecatedRecorder := cm.GetEventRecorderFor("test-deprecated-recorder") recorder := cm.GetEventRecorder("test-recorder") instance, err := controller.New("foo-controller", cm, controller.Options{ Reconciler: reconcile.Func( diff --git a/pkg/internal/source/event_handler.go b/pkg/internal/source/event_handler.go index 7cc8c51555..9d614f34a5 100644 --- a/pkg/internal/source/event_handler.go +++ b/pkg/internal/source/event_handler.go @@ -60,7 +60,7 @@ type EventHandler[object client.Object, request comparable] struct { } // OnAdd creates CreateEvent and calls Create on EventHandler. -func (e *EventHandler[object, request]) OnAdd(obj interface{}, isInInitialList bool) { +func (e *EventHandler[object, request]) OnAdd(obj any, isInInitialList bool) { c := event.TypedCreateEvent[object]{ IsInInitialList: isInInitialList, } @@ -87,7 +87,7 @@ func (e *EventHandler[object, request]) OnAdd(obj interface{}, isInInitialList b } // OnUpdate creates UpdateEvent and calls Update on EventHandler. -func (e *EventHandler[object, request]) OnUpdate(oldObj, newObj interface{}) { +func (e *EventHandler[object, request]) OnUpdate(oldObj, newObj any) { u := event.TypedUpdateEvent[object]{} if o, ok := oldObj.(object); ok { @@ -120,7 +120,7 @@ func (e *EventHandler[object, request]) OnUpdate(oldObj, newObj interface{}) { } // OnDelete creates DeleteEvent and calls Delete on EventHandler. -func (e *EventHandler[object, request]) OnDelete(obj interface{}) { +func (e *EventHandler[object, request]) OnDelete(obj any) { d := event.TypedDeleteEvent[object]{} // Deal with tombstone events by pulling the object out. Tombstone events wrap the object in a diff --git a/pkg/internal/testing/addr/manager.go b/pkg/internal/testing/addr/manager.go index 2e2e41323a..e8f1f10d2a 100644 --- a/pkg/internal/testing/addr/manager.go +++ b/pkg/internal/testing/addr/manager.go @@ -126,7 +126,7 @@ func suggest(listenHost string) (*net.TCPListener, int, string, error) { // It makes sure that new port allocated does not conflict with old ports // allocated within 2 minute. func Suggest(listenHost string) (int, string, error) { - for i := 0; i < portConflictRetry; i++ { + for range portConflictRetry { listener, port, resolvedHost, err := suggest(listenHost) if err != nil { return -1, "", err diff --git a/pkg/internal/testing/certs/tinyca_test.go b/pkg/internal/testing/certs/tinyca_test.go index 9542975565..11207a2930 100644 --- a/pkg/internal/testing/certs/tinyca_test.go +++ b/pkg/internal/testing/certs/tinyca_test.go @@ -120,7 +120,7 @@ var _ = Describe("TinyCA", func() { localhostAddrs, err := net.LookupHost("localhost") Expect(err).NotTo(HaveOccurred(), "should be able to find IPs for localhost") - localhostIPs := make([]interface{}, len(localhostAddrs)) + localhostIPs := make([]any, len(localhostAddrs)) for i, addr := range localhostAddrs { // normalize the elements with To16 so we can compare them to the output of // of ParseIP safely (the alternative is a custom matcher that calls Equal, diff --git a/pkg/internal/testing/process/arguments.go b/pkg/internal/testing/process/arguments.go index 1e556e9980..caa417d2c2 100644 --- a/pkg/internal/testing/process/arguments.go +++ b/pkg/internal/testing/process/arguments.go @@ -26,7 +26,7 @@ import ( // RenderTemplates returns an []string to render the templates // // Deprecated: will be removed in favor of Arguments. -func RenderTemplates(argTemplates []string, data interface{}) (args []string, err error) { +func RenderTemplates(argTemplates []string, data any) (args []string, err error) { var t *template.Template for _, arg := range argTemplates { @@ -82,7 +82,7 @@ func SliceToArguments(sliceArgs []string, args *Arguments) []string { // Deprecated: will be removed when RenderTemplates is removed. type TemplateDefaults struct { // Data will be used to render the template. - Data interface{} + Data any // Defaults will be used to default structured arguments if no template is passed. Defaults map[string][]string // MinimalDefaults will be used to default structured arguments if a template is passed. diff --git a/pkg/internal/testing/process/procattr_other.go b/pkg/internal/testing/process/procattr_other.go index df13b341a4..e65ddc5f40 100644 --- a/pkg/internal/testing/process/procattr_other.go +++ b/pkg/internal/testing/process/procattr_other.go @@ -1,5 +1,4 @@ //go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !zos -// +build !aix,!darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!zos /* Copyright 2016 The Kubernetes Authors. diff --git a/pkg/internal/testing/process/procattr_unix.go b/pkg/internal/testing/process/procattr_unix.go index 83ad509af0..2bdf0c7c47 100644 --- a/pkg/internal/testing/process/procattr_unix.go +++ b/pkg/internal/testing/process/procattr_unix.go @@ -1,5 +1,4 @@ //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos /* Copyright 2023 The Kubernetes Authors. diff --git a/pkg/leaderelection/leader_election.go b/pkg/leaderelection/leader_election.go index 63d875b45a..7f59d82897 100644 --- a/pkg/leaderelection/leader_election.go +++ b/pkg/leaderelection/leader_election.go @@ -103,10 +103,7 @@ func NewResourceLock(config *rest.Config, recorderProvider recorder.Provider, op // RenewDeadline to keep a single hung request from forcing a leader loss. // Setting it to max(time.Second, RenewDeadline/2) as a reasonable heuristic. if options.RenewDeadline != 0 { - timeout := options.RenewDeadline / 2 - if timeout < time.Second { - timeout = time.Second - } + timeout := max(options.RenewDeadline/2, time.Second) config.Timeout = timeout } diff --git a/pkg/log/deleg.go b/pkg/log/deleg.go index 6eb551d3b6..948330b01d 100644 --- a/pkg/log/deleg.go +++ b/pkg/log/deleg.go @@ -30,7 +30,7 @@ type loggerPromise struct { promisesLock sync.Mutex name *string - tags []interface{} + tags []any } func (p *loggerPromise) WithName(l *delegatingLogSink, name string) *loggerPromise { @@ -47,7 +47,7 @@ func (p *loggerPromise) WithName(l *delegatingLogSink, name string) *loggerPromi } // WithValues provides a new Logger with the tags appended. -func (p *loggerPromise) WithValues(l *delegatingLogSink, tags ...interface{}) *loggerPromise { +func (p *loggerPromise) WithValues(l *delegatingLogSink, tags ...any) *loggerPromise { res := &loggerPromise{ logger: l, tags: tags, @@ -120,7 +120,7 @@ func (l *delegatingLogSink) Enabled(level int) bool { // the log line. The key/value pairs can then be used to add additional // variable information. The key/value pairs should alternate string // keys and arbitrary values. -func (l *delegatingLogSink) Info(level int, msg string, keysAndValues ...interface{}) { +func (l *delegatingLogSink) Info(level int, msg string, keysAndValues ...any) { eventuallyFulfillRoot() l.lock.RLock() defer l.lock.RUnlock() @@ -135,7 +135,7 @@ func (l *delegatingLogSink) Info(level int, msg string, keysAndValues ...interfa // The msg field should be used to add context to any underlying error, // while the err field should be used to attach the actual error that // triggered this log line, if present. -func (l *delegatingLogSink) Error(err error, msg string, keysAndValues ...interface{}) { +func (l *delegatingLogSink) Error(err error, msg string, keysAndValues ...any) { eventuallyFulfillRoot() l.lock.RLock() defer l.lock.RUnlock() @@ -164,7 +164,7 @@ func (l *delegatingLogSink) WithName(name string) logr.LogSink { } // WithValues provides a new Logger with the tags appended. -func (l *delegatingLogSink) WithValues(tags ...interface{}) logr.LogSink { +func (l *delegatingLogSink) WithValues(tags ...any) logr.LogSink { eventuallyFulfillRoot() l.lock.RLock() defer l.lock.RUnlock() diff --git a/pkg/log/log.go b/pkg/log/log.go index ade21d6fb5..48a4d490d3 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -88,7 +88,7 @@ var ( ) // FromContext returns a logger with predefined values from a context.Context. -func FromContext(ctx context.Context, keysAndValues ...interface{}) logr.Logger { +func FromContext(ctx context.Context, keysAndValues ...any) logr.Logger { log := Log if ctx != nil { if logger, err := logr.FromContext(ctx); err == nil { diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index 404a859e4d..f56aef3706 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -29,7 +29,7 @@ var _ logr.LogSink = &delegatingLogSink{} // logInfo is the information for a particular fakeLogger message. type logInfo struct { name []string - tags []interface{} + tags []any msg string } @@ -43,7 +43,7 @@ type fakeLoggerRoot struct { // just records the name. type fakeLogger struct { name []string - tags []interface{} + tags []any root *fakeLoggerRoot } @@ -61,8 +61,8 @@ func (f *fakeLogger) WithName(name string) logr.LogSink { } } -func (f *fakeLogger) WithValues(vals ...interface{}) logr.LogSink { - tags := append([]interface{}(nil), f.tags...) +func (f *fakeLogger) WithValues(vals ...any) logr.LogSink { + tags := append([]any(nil), f.tags...) tags = append(tags, vals...) return &fakeLogger{ name: f.name, @@ -71,8 +71,8 @@ func (f *fakeLogger) WithValues(vals ...interface{}) logr.LogSink { } } -func (f *fakeLogger) Error(err error, msg string, vals ...interface{}) { - tags := append([]interface{}(nil), f.tags...) +func (f *fakeLogger) Error(err error, msg string, vals ...any) { + tags := append([]any(nil), f.tags...) tags = append(tags, "error", err) tags = append(tags, vals...) f.root.messages = append(f.root.messages, logInfo{ @@ -82,8 +82,8 @@ func (f *fakeLogger) Error(err error, msg string, vals ...interface{}) { }) } -func (f *fakeLogger) Info(level int, msg string, vals ...interface{}) { - tags := append([]interface{}(nil), f.tags...) +func (f *fakeLogger) Info(level int, msg string, vals ...any) { + tags := append([]any(nil), f.tags...) tags = append(tags, vals...) f.root.messages = append(f.root.messages, logInfo{ name: append([]string(nil), f.name...), @@ -113,8 +113,8 @@ var _ = Describe("logging", func() { By("ensuring that messages after the logger was set were logged") Expect(logger.root.messages).To(ConsistOf( - logInfo{name: []string{"runtimeLog"}, tags: []interface{}{"newtag", "newvalue1"}, msg: "after msg 1"}, - logInfo{name: []string{"runtimeLog"}, tags: []interface{}{"newtag", "newvalue2"}, msg: "after msg 2"}, + logInfo{name: []string{"runtimeLog"}, tags: []any{"newtag", "newvalue1"}, msg: "after msg 1"}, + logInfo{name: []string{"runtimeLog"}, tags: []any{"newtag", "newvalue2"}, msg: "after msg 2"}, )) }) }) @@ -259,10 +259,10 @@ var _ = Describe("logging", func() { By("ensuring that the messages are appropriately named") Expect(root.messages).To(ConsistOf( - logInfo{tags: []interface{}{"tag1", "val1"}, msg: "after 1"}, - logInfo{tags: []interface{}{"tag1", "val1", "tag2", "val2"}, msg: "after 2"}, - logInfo{tags: []interface{}{"tag1", "val1", "tag3", "val3"}, msg: "after 3"}, - logInfo{tags: []interface{}{"tag3", "val3"}, msg: "after 4"}, + logInfo{tags: []any{"tag1", "val1"}, msg: "after 1"}, + logInfo{tags: []any{"tag1", "val1", "tag2", "val2"}, msg: "after 2"}, + logInfo{tags: []any{"tag1", "val1", "tag3", "val3"}, msg: "after 3"}, + logInfo{tags: []any{"tag3", "val3"}, msg: "after 4"}, )) }) @@ -329,7 +329,7 @@ var _ = Describe("logging", func() { gotLog.Info("test message") Expect(root.messages).To(ConsistOf( - logInfo{name: []string{"my-logger"}, tags: []interface{}{"tag1", "value1"}, msg: "test message"}, + logInfo{name: []string{"my-logger"}, tags: []any{"tag1", "value1"}, msg: "test message"}, )) }) }) diff --git a/pkg/log/null.go b/pkg/log/null.go index f3e81074fe..f8dd84ca65 100644 --- a/pkg/log/null.go +++ b/pkg/log/null.go @@ -34,7 +34,7 @@ func (log NullLogSink) Init(logr.RuntimeInfo) { } // Info implements logr.InfoLogger. -func (NullLogSink) Info(_ int, _ string, _ ...interface{}) { +func (NullLogSink) Info(_ int, _ string, _ ...any) { // Do nothing. } @@ -44,7 +44,7 @@ func (NullLogSink) Enabled(level int) bool { } // Error implements logr.Logger. -func (NullLogSink) Error(_ error, _ string, _ ...interface{}) { +func (NullLogSink) Error(_ error, _ string, _ ...any) { // Do nothing. } @@ -54,6 +54,6 @@ func (log NullLogSink) WithName(_ string) logr.LogSink { } // WithValues implements logr.Logger. -func (log NullLogSink) WithValues(_ ...interface{}) logr.LogSink { +func (log NullLogSink) WithValues(_ ...any) logr.LogSink { return log } diff --git a/pkg/log/zap/zap_test.go b/pkg/log/zap/zap_test.go index 3e80113a65..1ff5e902d9 100644 --- a/pkg/log/zap/zap_test.go +++ b/pkg/log/zap/zap_test.go @@ -54,7 +54,7 @@ func (w *fakeSyncWriter) Sync() error { // logInfo is the information for a particular fakeLogger message. type logInfo struct { name []string - tags []interface{} + tags []any msg string } @@ -70,7 +70,7 @@ var _ logr.LogSink = &fakeLogger{} // just records the name. type fakeLogger struct { name []string - tags []interface{} + tags []any root *fakeLoggerRoot } @@ -88,8 +88,8 @@ func (f *fakeLogger) WithName(name string) logr.LogSink { } } -func (f *fakeLogger) WithValues(vals ...interface{}) logr.LogSink { - tags := append([]interface{}(nil), f.tags...) +func (f *fakeLogger) WithValues(vals ...any) logr.LogSink { + tags := append([]any(nil), f.tags...) tags = append(tags, vals...) return &fakeLogger{ name: f.name, @@ -98,8 +98,8 @@ func (f *fakeLogger) WithValues(vals ...interface{}) logr.LogSink { } } -func (f *fakeLogger) Error(err error, msg string, vals ...interface{}) { - tags := append([]interface{}(nil), f.tags...) +func (f *fakeLogger) Error(err error, msg string, vals ...any) { + tags := append([]any(nil), f.tags...) tags = append(tags, "error", err) tags = append(tags, vals...) f.root.messages = append(f.root.messages, logInfo{ @@ -109,8 +109,8 @@ func (f *fakeLogger) Error(err error, msg string, vals ...interface{}) { }) } -func (f *fakeLogger) Info(level int, msg string, vals ...interface{}) { - tags := append([]interface{}(nil), f.tags...) +func (f *fakeLogger) Info(level int, msg string, vals ...any) { + tags := append([]any(nil), f.tags...) tags = append(tags, vals...) f.root.messages = append(f.root.messages, logInfo{ name: append([]string(nil), f.name...), @@ -159,10 +159,10 @@ var _ = Describe("Zap logger setup", func() { logger.Info("here's a kubernetes object", "thing", pod) outRaw := logOut.Bytes() - res := map[string]interface{}{} + res := map[string]any{} Expect(json.Unmarshal(outRaw, &res)).To(Succeed()) - Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{ + Expect(res).To(HaveKeyWithValue("thing", map[string]any{ "name": pod.Name, "namespace": pod.Namespace, })) @@ -171,7 +171,7 @@ var _ = Describe("Zap logger setup", func() { It("should work fine with normal stringers", func() { logger.Info("here's a non-kubernetes stringer", "thing", testStringer{}) outRaw := logOut.Bytes() - res := map[string]interface{}{} + res := map[string]any{} Expect(json.Unmarshal(outRaw, &res)).To(Succeed()) Expect(res).To(HaveKeyWithValue("thing", "value")) @@ -183,10 +183,10 @@ var _ = Describe("Zap logger setup", func() { logger.Info("here's a kubernetes object", "thing", node) outRaw := logOut.Bytes() - res := map[string]interface{}{} + res := map[string]any{} Expect(json.Unmarshal(outRaw, &res)).To(Succeed()) - Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{ + Expect(res).To(HaveKeyWithValue("thing", map[string]any{ "name": node.Name, })) }) @@ -199,10 +199,10 @@ var _ = Describe("Zap logger setup", func() { logger.Info("here's a kubernetes object", "thing", node) outRaw := logOut.Bytes() - res := map[string]interface{}{} + res := map[string]any{} Expect(json.Unmarshal(outRaw, &res)).To(Succeed()) - Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{ + Expect(res).To(HaveKeyWithValue("thing", map[string]any{ "name": node.Name, "apiVersion": "v1", "kind": "Node", @@ -214,18 +214,18 @@ var _ = Describe("Zap logger setup", func() { logger.Info("here's a kubernetes object", "thing", name) outRaw := logOut.Bytes() - res := map[string]interface{}{} + res := map[string]any{} Expect(json.Unmarshal(outRaw, &res)).To(Succeed()) - Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{ + Expect(res).To(HaveKeyWithValue("thing", map[string]any{ "name": name.Name, })) }) It("should log an unstructured Kubernetes object", func() { pod := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ + Object: map[string]any{ + "metadata": map[string]any{ "name": "some-pod", "namespace": "some-ns", }, @@ -234,10 +234,10 @@ var _ = Describe("Zap logger setup", func() { logger.Info("here's a kubernetes object", "thing", pod) outRaw := logOut.Bytes() - res := map[string]interface{}{} + res := map[string]any{} Expect(json.Unmarshal(outRaw, &res)).To(Succeed()) - Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{ + Expect(res).To(HaveKeyWithValue("thing", map[string]any{ "name": "some-pod", "namespace": "some-ns", })) @@ -248,10 +248,10 @@ var _ = Describe("Zap logger setup", func() { logger.Info("here's a kubernetes object", "thing", name) outRaw := logOut.Bytes() - res := map[string]interface{}{} + res := map[string]any{} Expect(json.Unmarshal(outRaw, &res)).To(Succeed()) - Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{ + Expect(res).To(HaveKeyWithValue("thing", map[string]any{ "name": name.Name, "namespace": name.Namespace, })) @@ -550,7 +550,7 @@ var _ = Describe("Zap log level flag options setup", func() { outRaw := logOut.Bytes() - res := map[string]interface{}{} + res := map[string]any{} Expect(json.Unmarshal(outRaw, &res)).To(Succeed()) Expect(res["ts"]).Should(MatchRegexp(iso8601Pattern)) }) @@ -569,7 +569,7 @@ var _ = Describe("Zap log level flag options setup", func() { log.Info("This is a test message") outRaw := logOut.Bytes() // Assert for JSON Encoder - res := map[string]interface{}{} + res := map[string]any{} Expect(json.Unmarshal(outRaw, &res)).To(Succeed()) // Assert for MessageKey Expect(string(outRaw)).Should(ContainSubstring("MillisTimeFormat")) diff --git a/pkg/manager/runnable_group_test.go b/pkg/manager/runnable_group_test.go index e22f2c00d5..9a278a1495 100644 --- a/pkg/manager/runnable_group_test.go +++ b/pkg/manager/runnable_group_test.go @@ -181,7 +181,7 @@ var _ = Describe("runnableGroup", func() { Expect(rg.Start(ctx)).To(Succeed()) }() - for i := 0; i < 20; i++ { + for i := range 20 { go func(i int) { defer GinkgoRecover() @@ -199,7 +199,7 @@ var _ = Describe("runnableGroup", func() { exited := ptr.To(int64(0)) rg := newRunnableGroup(defaultBaseContext, errCh) - for i := 0; i < 10; i++ { + for i := range 10 { Expect(rg.Add(RunnableFunc(func(c context.Context) error { defer atomic.AddInt64(exited, 1) <-ctx.Done() @@ -231,7 +231,7 @@ var _ = Describe("runnableGroup", func() { Expect(rg.Start(ctx)).To(Succeed()) }() - for i := 0; i < 20; i++ { + for i := range 20 { go func(i int) { defer GinkgoRecover() @@ -264,7 +264,7 @@ var _ = Describe("runnableGroup", func() { rg.StopAndWait(ctx) }() - for i := 0; i < 200; i++ { + for i := range 200 { go func(i int) { defer GinkgoRecover() @@ -293,7 +293,7 @@ var _ = Describe("runnableGroup", func() { Expect(rg.Start(ctx)).To(Succeed()) }() - for i := 0; i < 20; i++ { + for i := range 20 { go func(i int) { defer GinkgoRecover() diff --git a/pkg/manager/signals/signal_posix.go b/pkg/manager/signals/signal_posix.go index a0f00a7321..2b24faa428 100644 --- a/pkg/manager/signals/signal_posix.go +++ b/pkg/manager/signals/signal_posix.go @@ -1,5 +1,4 @@ //go:build !windows -// +build !windows /* Copyright 2017 The Kubernetes Authors. diff --git a/pkg/manager/signals/signal_test.go b/pkg/manager/signals/signal_test.go index 134937e012..f2e3c4d02d 100644 --- a/pkg/manager/signals/signal_test.go +++ b/pkg/manager/signals/signal_test.go @@ -69,7 +69,7 @@ func (t *Task) Run(c chan os.Signal) { } func handle() { - for i := 0; i < 5; i++ { + for range 5 { fmt.Print("#") time.Sleep(time.Millisecond * 100) } diff --git a/pkg/scheme/scheme_test.go b/pkg/scheme/scheme_test.go index 37c6766e6f..0f68fb0e2b 100644 --- a/pkg/scheme/scheme_test.go +++ b/pkg/scheme/scheme_test.go @@ -41,8 +41,8 @@ var _ = Describe("Scheme", func() { internalGv := schema.GroupVersion{Group: "core", Version: "__internal"} emptyGv := schema.GroupVersion{Group: "", Version: "v1"} Expect(s.AllKnownTypes()).To(MatchAllKeys(Keys{ - gv.WithKind("Pod"): Equal(reflect.TypeOf(corev1.Pod{})), - gv.WithKind("PodList"): Equal(reflect.TypeOf(corev1.PodList{})), + gv.WithKind("Pod"): Equal(reflect.TypeFor[corev1.Pod]()), + gv.WithKind("PodList"): Equal(reflect.TypeFor[corev1.PodList]()), // Base types gv.WithKind("CreateOptions"): Ignore(), @@ -80,12 +80,12 @@ var _ = Describe("Scheme", func() { emptyGv := schema.GroupVersion{Group: "", Version: "v1"} Expect(s.AllKnownTypes()).To(MatchAllKeys(Keys{ // Types from b1 - gv1.WithKind("Pod"): Equal(reflect.TypeOf(corev1.Pod{})), - gv1.WithKind("PodList"): Equal(reflect.TypeOf(corev1.PodList{})), + gv1.WithKind("Pod"): Equal(reflect.TypeFor[corev1.Pod]()), + gv1.WithKind("PodList"): Equal(reflect.TypeFor[corev1.PodList]()), // Types from b2 - gv2.WithKind("Deployment"): Equal(reflect.TypeOf(appsv1.Deployment{})), - gv2.WithKind("DeploymentList"): Equal(reflect.TypeOf(appsv1.DeploymentList{})), + gv2.WithKind("Deployment"): Equal(reflect.TypeFor[appsv1.Deployment]()), + gv2.WithKind("DeploymentList"): Equal(reflect.TypeFor[appsv1.DeploymentList]()), // Base types gv1.WithKind("CreateOptions"): Ignore(), diff --git a/pkg/source/source_integration_test.go b/pkg/source/source_integration_test.go index cc0ba530ec..afe39c3bcf 100644 --- a/pkg/source/source_integration_test.go +++ b/pkg/source/source_integration_test.go @@ -41,7 +41,7 @@ var _ = Describe("Source", func() { var instance1, instance2 source.Source var obj client.Object var q workqueue.TypedRateLimitingInterface[reconcile.Request] - var c1, c2 chan interface{} + var c1, c2 chan any var ns string count := 0 @@ -59,8 +59,8 @@ var _ = Describe("Source", func() { workqueue.TypedRateLimitingQueueConfig[reconcile.Request]{ Name: "test", }) - c1 = make(chan interface{}) - c2 = make(chan interface{}) + c1 = make(chan any) + c2 = make(chan any) }) AfterEach(func(ctx SpecContext) { @@ -101,7 +101,7 @@ var _ = Describe("Source", func() { } // Create an event handler to verify the events - newHandler := func(c chan interface{}) handler.Funcs { + newHandler := func(c chan any) handler.Funcs { return handler.Funcs{ CreateFunc: func(ctx context.Context, evt event.CreateEvent, rli workqueue.TypedRateLimitingInterface[reconcile.Request]) { defer GinkgoRecover() diff --git a/pkg/webhook/admission/decode.go b/pkg/webhook/admission/decode.go index 55f1cafb5e..576262cf70 100644 --- a/pkg/webhook/admission/decode.go +++ b/pkg/webhook/admission/decode.go @@ -79,7 +79,7 @@ func (d *decoder) DecodeRaw(rawObj runtime.RawExtension, into runtime.Object) er } if unstructuredInto, isUnstructured := into.(runtime.Unstructured); isUnstructured { // unmarshal into unstructured's underlying object to avoid calling the decoder - var object map[string]interface{} + var object map[string]any if err := json.Unmarshal(rawObj.Raw, &object); err != nil { return err } diff --git a/pkg/webhook/admission/decode_test.go b/pkg/webhook/admission/decode_test.go index 130308800f..c8a8208f67 100644 --- a/pkg/webhook/admission/decode_test.go +++ b/pkg/webhook/admission/decode_test.go @@ -139,7 +139,7 @@ var _ = Describe("Admission Webhook Decoder", func() { Expect(decoder.Decode(req, &target)).To(Succeed()) By("sanity-checking the metadata on the output object") - Expect(target.Object["metadata"]).To(Equal(map[string]interface{}{ + Expect(target.Object["metadata"]).To(Equal(map[string]any{ "name": "foo", "namespace": "default", })) @@ -149,7 +149,7 @@ var _ = Describe("Admission Webhook Decoder", func() { Expect(decoder.DecodeRaw(req.Object, &target2)).To(Succeed()) By("sanity-checking the metadata on the output object") - Expect(target2.Object["metadata"]).To(Equal(map[string]interface{}{ + Expect(target2.Object["metadata"]).To(Equal(map[string]any{ "name": "foo", "namespace": "default", })) diff --git a/pkg/webhook/admission/defaulter_custom.go b/pkg/webhook/admission/defaulter_custom.go index 1dc8af10ee..d946966d4e 100644 --- a/pkg/webhook/admission/defaulter_custom.go +++ b/pkg/webhook/admission/defaulter_custom.go @@ -38,6 +38,7 @@ type Defaulter[T runtime.Object] interface { } // CustomDefaulter defines functions for setting defaults on resources. +// // Deprecated: CustomDefaulter is deprecated, use Defaulter instead type CustomDefaulter = Defaulter[runtime.Object] diff --git a/pkg/webhook/admission/validator_custom.go b/pkg/webhook/admission/validator_custom.go index abd68e88bf..f8401571d0 100644 --- a/pkg/webhook/admission/validator_custom.go +++ b/pkg/webhook/admission/validator_custom.go @@ -51,6 +51,7 @@ type Validator[T runtime.Object] interface { } // CustomValidator defines functions for validating an operation. +// // Deprecated: CustomValidator is deprecated, use Validator instead type CustomValidator = Validator[runtime.Object] @@ -73,6 +74,7 @@ func WithValidator[T runtime.Object](scheme *runtime.Scheme, validator Validator } // WithCustomValidator creates a new Webhook for a CustomValidator. +// // Deprecated: WithCustomValidator is deprecated, use WithValidator instead func WithCustomValidator(scheme *runtime.Scheme, obj runtime.Object, validator CustomValidator) *Webhook { return &Webhook{ diff --git a/pkg/webhook/alias.go b/pkg/webhook/alias.go index b4f16a3f5f..8370745a2a 100644 --- a/pkg/webhook/alias.go +++ b/pkg/webhook/alias.go @@ -24,10 +24,12 @@ import ( // define some aliases for common bits of the webhook functionality // CustomDefaulter defines functions for setting defaults on resources. +// // Deprecated: Use admission.Defaulter instead. type CustomDefaulter = admission.CustomDefaulter // CustomValidator defines functions for validating an operation. +// // Deprecated: Use admission.Validator instead. type CustomValidator = admission.CustomValidator diff --git a/tools/setup-envtest/env/exit.go b/tools/setup-envtest/env/exit.go index ae393b593b..640e65a4fc 100644 --- a/tools/setup-envtest/env/exit.go +++ b/tools/setup-envtest/env/exit.go @@ -12,7 +12,7 @@ import ( // Exit exits with the given code and error message. // // Defer HandleExitWithCode in main to catch this and get the right behavior. -func Exit(code int, msg string, args ...interface{}) { +func Exit(code int, msg string, args ...any) { panic(&exitCode{ code: code, err: fmt.Errorf(msg, args...), @@ -23,7 +23,7 @@ func Exit(code int, msg string, args ...interface{}) { // wrapping the underlying error passed as well. // // Defer HandleExitWithCode in main to catch this and get the right behavior. -func ExitCause(code int, err error, msg string, args ...interface{}) { +func ExitCause(code int, err error, msg string, args ...any) { args = append(args, err) panic(&exitCode{ code: code, @@ -48,7 +48,7 @@ func (c *exitCode) Unwrap() error { // asExit checks if the given (panic) value is an exitCode error, // and if so stores it in the given pointer. It's roughly analogous // to errors.As, except it works on recover() values. -func asExit(val interface{}, exit **exitCode) bool { +func asExit(val any, exit **exitCode) bool { if val == nil { return false } @@ -81,7 +81,7 @@ func HandleExitWithCode() { // the cause. // // It's mainly useful for testing, normally you'd use HandleExitWithCode. -func CheckRecover(cause interface{}, cb func(int, error)) bool { +func CheckRecover(cause any, cb func(int, error)) bool { if cause == nil { return false }