diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 25fa17c854..988ca82966 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -32,8 +32,8 @@ jobs: with: go-version: ${{ steps.vars.outputs.go_version }} - name: golangci-lint - uses: golangci/golangci-lint-action@4696ba8babb6127d732c3c6dde519db15edab9ea # tag=v6.5.1 + uses: golangci/golangci-lint-action@1481404843c368bc19ca9406f87d6e0fc97bdcfd # tag=v7.0.0 with: - version: v1.64.6 - args: --out-format=colored-line-number + version: v2.0.2 + args: --output.text.print-linter-name=true --output.text.colors=true working-directory: ${{matrix.working-directory}} diff --git a/.golangci.yml b/.golangci.yml index cc00a1903b..16736bfa36 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,9 @@ +version: "2" +run: + go: "1.24" + allow-parallel-runners: true linters: - disable-all: true + default: none enable: - asasalint - asciicheck @@ -16,10 +20,7 @@ linters: - goconst - gocritic - gocyclo - - gofmt - - goimports - goprintffuncname - - gosimple - govet - importas - ineffassign @@ -31,150 +32,154 @@ linters: - prealloc - revive - staticcheck - - stylecheck - tagliatelle - - typecheck - unconvert - unparam - unused - whitespace - -linters-settings: - govet: - enable-all: true - disable: - - fieldalignment - - shadow - importas: - no-unaliased: true - alias: - # Kubernetes - - pkg: k8s.io/api/core/v1 - alias: corev1 - - pkg: k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 - alias: apiextensionsv1 - - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 - alias: metav1 - - pkg: k8s.io/apimachinery/pkg/api/errors - alias: apierrors - - pkg: k8s.io/apimachinery/pkg/util/errors - alias: kerrors - # Controller Runtime - - pkg: sigs.k8s.io/controller-runtime - alias: ctrl - revive: + settings: + govet: + disable: + - fieldalignment + - shadow + enable-all: true + importas: + alias: + - pkg: k8s.io/api/core/v1 + alias: corev1 + - pkg: k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 + alias: apiextensionsv1 + - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 + alias: metav1 + - pkg: k8s.io/apimachinery/pkg/api/errors + alias: apierrors + - pkg: k8s.io/apimachinery/pkg/util/errors + alias: kerrors + - pkg: sigs.k8s.io/controller-runtime + alias: ctrl + no-unaliased: true + revive: + rules: + # The following rules are recommended https://github.com/mgechev/revive#recommended-configuration + - name: blank-imports + - name: context-as-argument + - name: context-keys-type + - name: dot-imports + - name: error-return + - name: error-strings + - name: error-naming + - name: exported + - name: if-return + - name: increment-decrement + - name: var-naming + - name: var-declaration + - name: range + - name: receiver-naming + - name: time-naming + - name: unexported-return + - name: indent-error-flow + - name: errorf + - name: superfluous-else + - name: unreachable-code + - name: redefines-builtin-id + # + # Rules in addition to the recommended configuration above. + # + - name: bool-literal-in-expr + - name: constant-logical-expr + exclusions: + generated: lax rules: - # The following rules are recommended https://github.com/mgechev/revive#recommended-configuration - - name: blank-imports - - name: context-as-argument - - name: context-keys-type - - name: dot-imports - - name: error-return - - name: error-strings - - name: error-naming - - name: exported - - name: if-return - - name: increment-decrement - - name: var-naming - - name: var-declaration - - name: range - - name: receiver-naming - - name: time-naming - - name: unexported-return - - name: indent-error-flow - - name: errorf - - name: superfluous-else - - name: unreachable-code - - name: redefines-builtin-id - # - # Rules in addition to the recommended configuration above. - # - - name: bool-literal-in-expr - - name: constant-logical-expr - + - linters: + - gosec + text: 'G108: Profiling endpoint is automatically exposed on /debug/pprof' + - linters: + - revive + text: 'exported: exported method .*\.(Reconcile|SetupWithManager|SetupWebhookWithManager) should have comment or be unexported' + - linters: + - errcheck + text: Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*print(f|ln)?|os\.(Un)?Setenv). is not checked + - linters: + - staticcheck + text: 'SA1019: .*The component config package has been deprecated and will be removed in a future release.' + # 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. + - linters: + - revive + source: _ "embed" + # Exclude some packages or code to require comments, for example test code, or fake clients. + - linters: + - revive + text: exported (method|function|type|const) (.+) should have comment or be unexported + source: (func|type).*Fake.* + - linters: + - revive + path: fake_\.go + text: exported (method|function|type|const) (.+) should have comment or be unexported + # Disable unparam "always receives" which might not be really + # useful when building libraries. + - linters: + - unparam + text: always receives + # Dot imports for gomega and ginkgo are allowed + # within test files. + - path: _test\.go + text: should not use dot imports + - path: _test\.go + text: cyclomatic complexity + - path: _test\.go + text: 'G107: Potential HTTP request made with variable url' + # Append should be able to assign to a different var/slice. + - linters: + - gocritic + text: 'appendAssign: append result not assigned to the same slice' + - linters: + - gocritic + text: 'singleCaseSwitch: should rewrite switch statement to if statement' + # It considers all file access to a filename that comes from a variable problematic, + # which is naiv at best. + - linters: + - gosec + text: 'G304: Potential file inclusion via variable' + - linters: + - dupl + path: _test\.go + - linters: + - revive + path: .*/internal/.* + - linters: + - unused + # Seems to incorrectly trigger on the two implementations that are only + # used through an interface and not directly..? + # Likely same issue as https://github.com/dominikh/go-tools/issues/1616 + path: pkg/controller/priorityqueue/metrics\.go + # The following are being worked on to remove their exclusion. This list should be reduced or go away all together over time. + # If it is decided they will not be addressed they should be moved above this comment. + - path: (.+)\.go$ + text: Subprocess launch(ed with variable|ing should be audited) + - path: (.+)\.go$ + text: (G204|G104|G307) + - path: (.+)\.go$ + text: 'ST1000: at least one file in a package should have a package comment' + paths: + - zz_generated.*\.go$ + - .*conversion.*\.go$ + - third_party$ + - builtin$ + - examples$ issues: - max-same-issues: 0 max-issues-per-linter: 0 - # We are disabling default golangci exclusions because we want to help reviewers to focus on reviewing the most relevant - # changes in PRs and avoid nitpicking. - exclude-use-default: false - # List of regexps of issue texts to exclude, empty list by default. - exclude: - # The following are being worked on to remove their exclusion. This list should be reduced or go away all together over time. - # If it is decided they will not be addressed they should be moved above this comment. - - Subprocess launch(ed with variable|ing should be audited) - - (G204|G104|G307) - - "ST1000: at least one file in a package should have a package comment" - exclude-files: - - "zz_generated.*\\.go$" - - ".*conversion.*\\.go$" - exclude-rules: - - linters: - - gosec - text: "G108: Profiling endpoint is automatically exposed on /debug/pprof" - - linters: - - revive - text: "exported: exported method .*\\.(Reconcile|SetupWithManager|SetupWebhookWithManager) should have comment or be unexported" - - linters: - - errcheck - text: Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*print(f|ln)?|os\.(Un)?Setenv). is not checked - - linters: - - staticcheck - text: "SA1019: .*The component config package has been deprecated and will be removed in a future release." - # 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. - - linters: - - revive - source: _ "embed" - # Exclude some packages or code to require comments, for example test code, or fake clients. - - linters: - - revive - text: exported (method|function|type|const) (.+) should have comment or be unexported - source: (func|type).*Fake.* - - linters: - - revive - text: exported (method|function|type|const) (.+) should have comment or be unexported - path: fake_\.go - # Disable unparam "always receives" which might not be really - # useful when building libraries. - - linters: - - unparam - text: always receives - # Dot imports for gomega and ginkgo are allowed - # within test files. - - path: _test\.go - text: should not use dot imports - - path: _test\.go - text: cyclomatic complexity - - path: _test\.go - text: "G107: Potential HTTP request made with variable url" - # Append should be able to assign to a different var/slice. - - linters: - - gocritic - text: "appendAssign: append result not assigned to the same slice" - - linters: - - gocritic - text: "singleCaseSwitch: should rewrite switch statement to if statement" - # It considers all file access to a filename that comes from a variable problematic, - # which is naiv at best. - - linters: - - gosec - text: "G304: Potential file inclusion via variable" - - linters: - - dupl - path: _test\.go - - linters: - - revive - path: .*/internal/.* - - linters: - - unused - # Seems to incorrectly trigger on the two implementations that are only - # used through an interface and not directly..? - # Likely same issue as https://github.com/dominikh/go-tools/issues/1616 - path: pkg/controller/priorityqueue/metrics\.go - -run: - go: "1.24" - timeout: 10m - allow-parallel-runners: true + max-same-issues: 0 +formatters: + enable: + - gofmt + - goimports + exclusions: + generated: lax + paths: + - zz_generated.*\.go$ + - .*conversion.*\.go$ + - third_party$ + - builtin$ + - examples$ diff --git a/Makefile b/Makefile index b656fa0175..b8e9cfa877 100644 --- a/Makefile +++ b/Makefile @@ -99,7 +99,7 @@ $(CONTROLLER_GEN): # Build controller-gen from tools folder. GOLANGCI_LINT_BIN := golangci-lint GOLANGCI_LINT_VER := $(shell cat .github/workflows/golangci-lint.yml | grep [[:space:]]version: | sed 's/.*version: //') GOLANGCI_LINT := $(abspath $(TOOLS_BIN_DIR)/$(GOLANGCI_LINT_BIN)-$(GOLANGCI_LINT_VER)) -GOLANGCI_LINT_PKG := github.com/golangci/golangci-lint/cmd/golangci-lint +GOLANGCI_LINT_PKG := github.com/golangci/golangci-lint/v2/cmd/golangci-lint $(GOLANGCI_LINT): # Build golangci-lint from tools folder. GOBIN=$(TOOLS_BIN_DIR) $(GO_INSTALL) $(GOLANGCI_LINT_PKG) $(GOLANGCI_LINT_BIN) $(GOLANGCI_LINT_VER) diff --git a/examples/builtins/controller.go b/examples/builtins/controller.go index 6c8c5d935f..443283140a 100644 --- a/examples/builtins/controller.go +++ b/examples/builtins/controller.go @@ -21,7 +21,7 @@ import ( "fmt" appsv1 "k8s.io/api/apps/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/reconcile" @@ -43,13 +43,13 @@ func (r *reconcileReplicaSet) Reconcile(ctx context.Context, request reconcile.R // Fetch the ReplicaSet from the cache rs := &appsv1.ReplicaSet{} err := r.client.Get(ctx, request.NamespacedName, rs) - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { log.Error(nil, "Could not find ReplicaSet") return reconcile.Result{}, nil } if err != nil { - return reconcile.Result{}, fmt.Errorf("could not fetch ReplicaSet: %+v", err) + return reconcile.Result{}, fmt.Errorf("could not fetch ReplicaSet: %+w", err) } // Print the ReplicaSet @@ -67,7 +67,7 @@ func (r *reconcileReplicaSet) Reconcile(ctx context.Context, request reconcile.R rs.Labels["hello"] = "world" err = r.client.Update(ctx, rs) if err != nil { - return reconcile.Result{}, fmt.Errorf("could not write ReplicaSet: %+v", err) + return reconcile.Result{}, fmt.Errorf("could not write ReplicaSet: %+w", err) } return reconcile.Result{}, nil diff --git a/examples/crd/main.go b/examples/crd/main.go index 1f6cd5fac2..0bf65c9890 100644 --- a/examples/crd/main.go +++ b/examples/crd/main.go @@ -65,7 +65,7 @@ func (r *reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu if podFound { shouldStop := chaospod.Spec.NextStop.Time.Before(time.Now()) if !shouldStop { - return ctrl.Result{RequeueAfter: chaospod.Spec.NextStop.Sub(time.Now()) + 1*time.Second}, nil + return ctrl.Result{RequeueAfter: time.Until(chaospod.Spec.NextStop.Time) + 1*time.Second}, nil } if err := r.Delete(ctx, &pod); err != nil { diff --git a/examples/crd/pkg/groupversion_info.go b/examples/crd/pkg/groupversion_info.go index 04953dd939..31dfbbc779 100644 --- a/examples/crd/pkg/groupversion_info.go +++ b/examples/crd/pkg/groupversion_info.go @@ -20,13 +20,10 @@ package pkg import ( "k8s.io/apimachinery/pkg/runtime/schema" - logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/scheme" ) var ( - log = logf.Log.WithName("chaospod-resource") - // SchemeGroupVersion is group version used to register these objects SchemeGroupVersion = schema.GroupVersion{Group: "chaosapps.metamagical.io", Version: "v1"} diff --git a/pkg/cache/cache_test.go b/pkg/cache/cache_test.go index 9efd04877c..64cf207570 100644 --- a/pkg/cache/cache_test.go +++ b/pkg/cache/cache_test.go @@ -1917,7 +1917,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should error when starting the cache a second time", func() { err := informerCache.Start(context.Background()) Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("Informer already started")) + Expect(err.Error()).To(ContainSubstring("informer already started")) }) Context("with structured objects", func() { diff --git a/pkg/cache/informer_cache.go b/pkg/cache/informer_cache.go index 091667b7fa..214af14140 100644 --- a/pkg/cache/informer_cache.go +++ b/pkg/cache/informer_cache.go @@ -180,7 +180,7 @@ func (ic *informerCache) GetInformer(ctx context.Context, obj client.Object, opt func (ic *informerCache) getInformerForKind(ctx context.Context, gvk schema.GroupVersionKind, obj runtime.Object) (bool, *internal.Cache, error) { if ic.readerFailOnMissingInformer { - cache, started, ok := ic.Informers.Peek(gvk, obj) + cache, started, ok := ic.Peek(gvk, obj) if !ok { return false, nil, &ErrResourceNotCached{GVK: gvk} } @@ -197,7 +197,7 @@ func (ic *informerCache) RemoveInformer(_ context.Context, obj client.Object) er return err } - ic.Informers.Remove(gvk, obj) + ic.Remove(gvk, obj) return nil } diff --git a/pkg/cache/internal/informers.go b/pkg/cache/internal/informers.go index b21a9c6345..4bf832b2d9 100644 --- a/pkg/cache/internal/informers.go +++ b/pkg/cache/internal/informers.go @@ -201,7 +201,7 @@ func (ip *Informers) Start(ctx context.Context) error { defer ip.mu.Unlock() if ip.started { - return errors.New("Informer already started") //nolint:stylecheck + return errors.New("informer already started") //nolint:stylecheck } // Set the context so it can be passed to informers that are added later diff --git a/pkg/client/apiutil/restmapper_wb_test.go b/pkg/client/apiutil/restmapper_wb_test.go index 73c4236724..2b24d9f0fa 100644 --- a/pkg/client/apiutil/restmapper_wb_test.go +++ b/pkg/client/apiutil/restmapper_wb_test.go @@ -209,6 +209,6 @@ type fakeAggregatedDiscoveryClient struct { } func (f *fakeAggregatedDiscoveryClient) GroupsAndMaybeResources() (*metav1.APIGroupList, map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error, error) { - groupList, err := f.DiscoveryInterface.ServerGroups() + groupList, err := f.ServerGroups() return groupList, nil, nil, err } diff --git a/pkg/client/client.go b/pkg/client/client.go index 50b0ebf338..725d7368c7 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -450,7 +450,7 @@ type SubResourceUpdateOptions struct { // ApplyToSubResourceUpdate updates the configuration on the given create options func (uo *SubResourceUpdateOptions) ApplyToSubResourceUpdate(o *SubResourceUpdateOptions) { - uo.UpdateOptions.ApplyToUpdate(&o.UpdateOptions) + uo.ApplyToUpdate(&o.UpdateOptions) if uo.SubResourceBody != nil { o.SubResourceBody = uo.SubResourceBody } @@ -507,7 +507,7 @@ func (co *SubResourceCreateOptions) ApplyOptions(opts []SubResourceCreateOption) // ApplyToSubResourceCreate applies the the configuration on the given create options. func (co *SubResourceCreateOptions) ApplyToSubResourceCreate(o *SubResourceCreateOptions) { - co.CreateOptions.ApplyToCreate(&co.CreateOptions) + co.ApplyToCreate(&co.CreateOptions) } // SubResourcePatchOptions holds all possible configurations for a subresource patch @@ -528,7 +528,7 @@ func (po *SubResourcePatchOptions) ApplyOptions(opts []SubResourcePatchOption) * // ApplyToSubResourcePatch applies the configuration on the given patch options. func (po *SubResourcePatchOptions) ApplyToSubResourcePatch(o *SubResourcePatchOptions) { - po.PatchOptions.ApplyToPatch(&o.PatchOptions) + po.ApplyToPatch(&o.PatchOptions) if po.SubResourceBody != nil { o.SubResourceBody = po.SubResourceBody } diff --git a/pkg/client/client_test.go b/pkg/client/client_test.go index ff014e7321..78ff58bae6 100644 --- a/pkg/client/client_test.go +++ b/pkg/client/client_test.go @@ -1698,7 +1698,7 @@ U5wwSivyi7vmegHKmblOzNVKA5qPO8zWzqBC dep2Name := dep2.Name By("deleting Deployments") - err = cl.DeleteAllOf(context.TODO(), dep, client.InNamespace(ns), client.MatchingLabels(dep.ObjectMeta.Labels)) + err = cl.DeleteAllOf(context.TODO(), dep, client.InNamespace(ns), client.MatchingLabels(dep.Labels)) Expect(err).NotTo(HaveOccurred()) By("validating the Deployment no longer exists") @@ -1804,7 +1804,7 @@ U5wwSivyi7vmegHKmblOzNVKA5qPO8zWzqBC Kind: "Deployment", Version: "v1", }) - err = cl.DeleteAllOf(context.TODO(), u, client.InNamespace(ns), client.MatchingLabels(dep.ObjectMeta.Labels)) + err = cl.DeleteAllOf(context.TODO(), u, client.InNamespace(ns), client.MatchingLabels(dep.Labels)) Expect(err).NotTo(HaveOccurred()) By("validating the Deployment no longer exists") @@ -1884,7 +1884,7 @@ U5wwSivyi7vmegHKmblOzNVKA5qPO8zWzqBC By("deleting Deployments") metaObj := metaOnlyFromObj(dep, scheme) - err = cl.DeleteAllOf(context.TODO(), metaObj, client.InNamespace(ns), client.MatchingLabels(dep.ObjectMeta.Labels)) + err = cl.DeleteAllOf(context.TODO(), metaObj, client.InNamespace(ns), client.MatchingLabels(dep.Labels)) Expect(err).NotTo(HaveOccurred()) By("validating the Deployment no longer exists") diff --git a/pkg/client/config/config_test.go b/pkg/client/config/config_test.go index 76d42b318f..bbaeb2e2bd 100644 --- a/pkg/client/config/config_test.go +++ b/pkg/client/config/config_test.go @@ -52,7 +52,7 @@ var _ = Describe("Config", func() { }) AfterEach(func() { - os.Unsetenv(clientcmd.RecommendedConfigPathEnvVar) + _ = os.Unsetenv(clientcmd.RecommendedConfigPathEnvVar) kubeconfig = "" clientcmd.RecommendedHomeFile = origRecommendedHomeFile diff --git a/pkg/client/fake/client.go b/pkg/client/fake/client.go index 99124e2f03..09634ac969 100644 --- a/pkg/client/fake/client.go +++ b/pkg/client/fake/client.go @@ -411,12 +411,9 @@ func (t versionedTracker) Patch(gvr schema.GroupVersionResource, obj runtime.Obj return err } - isStatus := false + isStatus := bytes.Contains(debug.Stack(), []byte("sigs.k8s.io/controller-runtime/pkg/client/fake.(*fakeSubResourceClient).statusPatch")) // We apply patches using a client-go reaction that ends up calling the trackers Patch. As we can't change // that reaction, we use the callstack to figure out if this originated from the status client. - if bytes.Contains(debug.Stack(), []byte("sigs.k8s.io/controller-runtime/pkg/client/fake.(*fakeSubResourceClient).statusPatch")) { - isStatus = true - } obj, err = t.updateObject(gvr, obj, ns, isStatus, false, patchOptions.DryRun) if err != nil { @@ -447,7 +444,7 @@ func (t versionedTracker) updateObject(gvr schema.GroupVersionResource, obj runt return nil, err } - oldObject, err := t.ObjectTracker.Get(gvr, ns, accessor.GetName()) + oldObject, err := t.Get(gvr, ns, accessor.GetName()) if err != nil { // If the resource is not found and the resource allows create on update, issue a // create instead. @@ -518,7 +515,7 @@ func (t versionedTracker) updateObject(gvr schema.GroupVersionResource, obj runt } if !accessor.GetDeletionTimestamp().IsZero() && len(accessor.GetFinalizers()) == 0 { - return nil, t.ObjectTracker.Delete(gvr, accessor.GetNamespace(), accessor.GetName(), metav1.DeleteOptions{DryRun: dryRun}) + return nil, t.Delete(gvr, accessor.GetNamespace(), accessor.GetName(), metav1.DeleteOptions{DryRun: dryRun}) } return convertFromUnstructuredIfNecessary(t.scheme, obj) } diff --git a/pkg/client/metadata_client.go b/pkg/client/metadata_client.go index d0c6b8e13a..962c91a275 100644 --- a/pkg/client/metadata_client.go +++ b/pkg/client/metadata_client.go @@ -77,7 +77,7 @@ func (mc *metadataClient) DeleteAllOf(ctx context.Context, obj Object, opts ...D deleteAllOfOpts := DeleteAllOfOptions{} deleteAllOfOpts.ApplyOptions(opts) - resInt, err := mc.getResourceInterface(metadata.GroupVersionKind(), deleteAllOfOpts.ListOptions.Namespace) + resInt, err := mc.getResourceInterface(metadata.GroupVersionKind(), deleteAllOfOpts.Namespace) if err != nil { return err } diff --git a/pkg/client/watch.go b/pkg/client/watch.go index 181b22a673..71a1d53e6b 100644 --- a/pkg/client/watch.go +++ b/pkg/client/watch.go @@ -67,7 +67,7 @@ func (w *watchingClient) metadataWatch(ctx context.Context, obj *metav1.PartialO listOpts := w.listOpts(opts...) - resInt, err := w.client.metadataClient.getResourceInterface(gvk, listOpts.Namespace) + resInt, err := w.metadataClient.getResourceInterface(gvk, listOpts.Namespace) if err != nil { return nil, err } @@ -76,7 +76,7 @@ func (w *watchingClient) metadataWatch(ctx context.Context, obj *metav1.PartialO } func (w *watchingClient) unstructuredWatch(ctx context.Context, obj runtime.Unstructured, opts ...ListOption) (watch.Interface, error) { - r, err := w.client.unstructuredClient.resources.getResource(obj) + r, err := w.unstructuredClient.resources.getResource(obj) if err != nil { return nil, err } @@ -91,7 +91,7 @@ func (w *watchingClient) unstructuredWatch(ctx context.Context, obj runtime.Unst } func (w *watchingClient) typedWatch(ctx context.Context, obj ObjectList, opts ...ListOption) (watch.Interface, error) { - r, err := w.client.typedClient.resources.getResource(obj) + r, err := w.typedClient.resources.getResource(obj) if err != nil { return nil, err } diff --git a/pkg/controller/controllerutil/example_test.go b/pkg/controller/controllerutil/example_test.go index b2d6f71a5c..1e35ae2547 100644 --- a/pkg/controller/controllerutil/example_test.go +++ b/pkg/controller/controllerutil/example_test.go @@ -41,7 +41,7 @@ func ExampleCreateOrUpdate() { op, err := controllerutil.CreateOrUpdate(context.TODO(), c, deploy, func() error { // Deployment selector is immutable so we set this value only if // a new object is going to be created - if deploy.ObjectMeta.CreationTimestamp.IsZero() { + if deploy.CreationTimestamp.IsZero() { deploy.Spec.Selector = &metav1.LabelSelector{ MatchLabels: map[string]string{"foo": "bar"}, } diff --git a/pkg/envtest/komega/default_test.go b/pkg/envtest/komega/default_test.go index 1a1de72cf3..8f8b3df8c1 100644 --- a/pkg/envtest/komega/default_test.go +++ b/pkg/envtest/komega/default_test.go @@ -38,8 +38,8 @@ func TestDefaultList(t *testing.T) { g.Expect(list.Items).To(HaveLen(1)) depl := exampleDeployment() g.Expect(list.Items[0]).To(And( - HaveField("ObjectMeta.Name", Equal(depl.ObjectMeta.Name)), - HaveField("ObjectMeta.Namespace", Equal(depl.ObjectMeta.Namespace)), + HaveField("ObjectMeta.Name", Equal(depl.Name)), + HaveField("ObjectMeta.Namespace", Equal(depl.Namespace)), )) } diff --git a/pkg/envtest/komega/komega_test.go b/pkg/envtest/komega/komega_test.go index 8867ac239a..4d98a03029 100644 --- a/pkg/envtest/komega/komega_test.go +++ b/pkg/envtest/komega/komega_test.go @@ -60,8 +60,8 @@ func TestList(t *testing.T) { g.Expect(list.Items).To(HaveLen(1)) depl := exampleDeployment() g.Expect(list.Items[0]).To(And( - HaveField("ObjectMeta.Name", Equal(depl.ObjectMeta.Name)), - HaveField("ObjectMeta.Namespace", Equal(depl.ObjectMeta.Namespace)), + HaveField("ObjectMeta.Name", Equal(depl.Name)), + HaveField("ObjectMeta.Namespace", Equal(depl.Namespace)), )) } diff --git a/pkg/envtest/webhook.go b/pkg/envtest/webhook.go index f6bfe95cc6..a6961bf7c6 100644 --- a/pkg/envtest/webhook.go +++ b/pkg/envtest/webhook.go @@ -419,8 +419,8 @@ func readWebhooks(path string) ([]*admissionv1.MutatingWebhookConfiguration, []* const ( admissionregv1 = "admissionregistration.k8s.io/v1" ) - switch { - case generic.Kind == "MutatingWebhookConfiguration": + switch generic.Kind { + case "MutatingWebhookConfiguration": if generic.APIVersion != admissionregv1 { return nil, nil, fmt.Errorf("only v1 is supported right now for MutatingWebhookConfiguration (name: %s)", generic.Name) } @@ -429,7 +429,7 @@ func readWebhooks(path string) ([]*admissionv1.MutatingWebhookConfiguration, []* return nil, nil, err } mutHooks = append(mutHooks, hook) - case generic.Kind == "ValidatingWebhookConfiguration": + case "ValidatingWebhookConfiguration": if generic.APIVersion != admissionregv1 { return nil, nil, fmt.Errorf("only v1 is supported right now for ValidatingWebhookConfiguration (name: %s)", generic.Name) } diff --git a/pkg/internal/controller/controller.go b/pkg/internal/controller/controller.go index 8bef660003..b13b46af7c 100644 --- a/pkg/internal/controller/controller.go +++ b/pkg/internal/controller/controller.go @@ -403,16 +403,16 @@ func (p *priorityQueueWrapper[request]) AddWithOpts(opts priorityqueue.AddOpts, for _, item := range items { switch { case opts.RateLimited: - p.TypedRateLimitingInterface.AddRateLimited(item) + p.AddRateLimited(item) case opts.After > 0: - p.TypedRateLimitingInterface.AddAfter(item, opts.After) + p.AddAfter(item, opts.After) default: - p.TypedRateLimitingInterface.Add(item) + p.Add(item) } } } func (p *priorityQueueWrapper[request]) GetWithPriority() (request, int, bool) { - item, shutdown := p.TypedRateLimitingInterface.Get() + item, shutdown := p.Get() return item, 0, shutdown } diff --git a/pkg/internal/testing/controlplane/apiserver.go b/pkg/internal/testing/controlplane/apiserver.go index bbd2eff64b..19f82476f9 100644 --- a/pkg/internal/testing/controlplane/apiserver.go +++ b/pkg/internal/testing/controlplane/apiserver.go @@ -200,23 +200,23 @@ func (s *APIServer) configurePorts() error { // Secure: SecurePort, SecureServing if s.SecurePort != 0 { - s.SecureServing.Port = strconv.Itoa(s.SecurePort) + s.Port = strconv.Itoa(s.SecurePort) // if we don't have an address, try the insecure address, and otherwise // default to loopback. - if s.SecureServing.Address == "" { + if s.Address == "" { if s.InsecureServing != nil { - s.SecureServing.Address = s.InsecureServing.Address + s.Address = s.InsecureServing.Address } else { - s.SecureServing.Address = "127.0.0.1" + s.Address = "127.0.0.1" } } - } else if s.SecureServing.Port == "" || s.SecureServing.Address == "" { + } else if s.Port == "" || s.Address == "" { port, host, err := addr.Suggest("") if err != nil { return fmt.Errorf("unable to provision unused secure port: %w", err) } - s.SecureServing.Port = strconv.Itoa(port) - s.SecureServing.Address = host + s.Port = strconv.Itoa(port) + s.Address = host s.SecurePort = port } @@ -260,12 +260,12 @@ func (s *APIServer) setProcessState() error { return err } - if s.SecureServing.Authn == nil { + if s.Authn == nil { authn, err := NewCertAuthn() if err != nil { return err } - s.SecureServing.Authn = authn + s.Authn = authn } if err := s.Authn.Configure(s.CertDir, s.Configure()); err != nil { @@ -337,11 +337,11 @@ func (s *APIServer) defaultArgs() map[string][]string { "disable-admission-plugins": {"ServiceAccount"}, "cert-dir": {s.CertDir}, "authorization-mode": {"RBAC"}, - "secure-port": {s.SecureServing.Port}, + "secure-port": {s.Port}, // NB(directxman12): previously we didn't set the bind address for the secure // port. It *shouldn't* make a difference unless people are doing something really // funky, but if you start to get bug reports look here ;-) - "bind-address": {s.SecureServing.Address}, + "bind-address": {s.Address}, // required on 1.20+, fine to leave on for <1.20 "service-account-issuer": {s.SecureServing.URL("https", "/").String()}, @@ -391,7 +391,7 @@ func (s *APIServer) populateAPIServerCerts() error { return err } - s.SecureServing.CA = ca.CA.CertBytes() + s.CA = ca.CA.CertBytes() // service account signing files too saCA, err := certs.NewTinyCA() diff --git a/pkg/internal/testing/controlplane/plane.go b/pkg/internal/testing/controlplane/plane.go index 456183a7a3..e7122aeaf9 100644 --- a/pkg/internal/testing/controlplane/plane.go +++ b/pkg/internal/testing/controlplane/plane.go @@ -168,11 +168,11 @@ func (u *AuthenticatedUser) Config() *rest.Config { if u.cfgIsComplete { return u.cfg } - if len(u.plane.APIServer.SecureServing.CA) == 0 { + if len(u.plane.APIServer.CA) == 0 { panic("the API server has not yet been started, please do that before accessing connection details") } - u.cfg.CAData = u.plane.APIServer.SecureServing.CA + u.cfg.CAData = u.plane.APIServer.CA u.cfg.Host = u.plane.APIServer.SecureServing.URL("https", "/").String() u.cfgIsComplete = true return u.cfg @@ -232,14 +232,14 @@ func (u *AuthenticatedUser) Kubectl() (*KubeCtl, error) { // guaranteed to be callable both before and after Start has been called (but, as noted in the // AuthenticatedUser docs, the given user objects are only valid after Start has been called). func (f *ControlPlane) AddUser(user User, baseConfig *rest.Config) (*AuthenticatedUser, error) { - if f.GetAPIServer().SecureServing.Authn == nil { + if f.GetAPIServer().Authn == nil { return nil, fmt.Errorf("no API server authentication is configured yet. The API server defaults one when Start is called, did you mean to use that?") } if baseConfig == nil { baseConfig = &rest.Config{} } - cfg, err := f.GetAPIServer().SecureServing.AddUser(user, baseConfig) + cfg, err := f.GetAPIServer().AddUser(user, baseConfig) if err != nil { return nil, err } diff --git a/pkg/webhook/admission/response.go b/pkg/webhook/admission/response.go index ec1c88c989..e901ae2595 100644 --- a/pkg/webhook/admission/response.go +++ b/pkg/webhook/admission/response.go @@ -119,6 +119,6 @@ func validationResponseFromStatus(allowed bool, status metav1.Status) Response { // WithWarnings adds the given warnings to the Response. // If any warnings were already given, they will not be overwritten. func (r Response) WithWarnings(warnings ...string) Response { - r.AdmissionResponse.Warnings = append(r.AdmissionResponse.Warnings, warnings...) + r.Warnings = append(r.Warnings, warnings...) return r } diff --git a/pkg/webhook/authentication/response.go b/pkg/webhook/authentication/response.go index 3e1d362049..c84044ab9b 100644 --- a/pkg/webhook/authentication/response.go +++ b/pkg/webhook/authentication/response.go @@ -57,7 +57,7 @@ func ReviewResponse(authenticated bool, user authenticationv1.UserInfo, err stri }, } if len(err) > 0 { - resp.TokenReview.Status.Error = err + resp.Status.Error = err } return resp } diff --git a/tools/setup-envtest/env/env.go b/tools/setup-envtest/env/env.go index 6168739eb6..153e926255 100644 --- a/tools/setup-envtest/env/env.go +++ b/tools/setup-envtest/env/env.go @@ -366,7 +366,7 @@ func (e *Env) PrintInfo(printFmt PrintFormat) { fmt.Fprintf(e.Out, "Version: %s\n", e.Version) fmt.Fprintf(e.Out, "OS/Arch: %s\n", e.Platform) if e.Platform.Hash != nil { - fmt.Fprintf(e.Out, "%s: %s\n", e.Platform.Hash.Type, e.Platform.Hash.Value) + fmt.Fprintf(e.Out, "%s: %s\n", e.Platform.Type, e.Platform.Value) } fmt.Fprintf(e.Out, "Path: %s\n", path) case PrintPath: diff --git a/tools/setup-envtest/remote/read_body.go b/tools/setup-envtest/remote/read_body.go index 1c71102897..b74de9ea37 100644 --- a/tools/setup-envtest/remote/read_body.go +++ b/tools/setup-envtest/remote/read_body.go @@ -23,13 +23,13 @@ func readBody(resp *http.Response, out io.Writer, archiveName string, platform v // memory to avoid causing issues with big files. buf := make([]byte, 32*1024) // 32KiB, same as io.Copy var hasher hash.Hash - switch platform.Hash.Type { + switch platform.Type { case versions.SHA512HashType: hasher = sha512.New() case versions.MD5HashType: hasher = md5.New() default: - return fmt.Errorf("hash type %s not implemented", platform.Hash.Type) + return fmt.Errorf("hash type %s not implemented", platform.Type) } for cont := true; cont; { amt, err := resp.Body.Read(buf) @@ -47,16 +47,16 @@ func readBody(resp *http.Response, out io.Writer, archiveName string, platform v } var sum string - switch platform.Hash.Encoding { + switch platform.Encoding { case versions.Base64HashEncoding: sum = base64.StdEncoding.EncodeToString(hasher.Sum(nil)) case versions.HexHashEncoding: sum = hex.EncodeToString(hasher.Sum(nil)) default: - return fmt.Errorf("hash encoding %s not implemented", platform.Hash.Encoding) + return fmt.Errorf("hash encoding %s not implemented", platform.Encoding) } - if sum != platform.Hash.Value { - return fmt.Errorf("checksum mismatch for %s: %s (computed) != %s (reported)", archiveName, sum, platform.Hash.Value) + if sum != platform.Value { + return fmt.Errorf("checksum mismatch for %s: %s (computed) != %s (reported)", archiveName, sum, platform.Value) } } else if _, err := io.Copy(out, resp.Body); err != nil { return fmt.Errorf("unable to download %s: %w", archiveName, err)