From 7864b3706a8f6a5b2c4eafc187cab70ab445d8a6 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Sat, 21 Dec 2024 01:01:38 +0100 Subject: [PATCH] chore: enable use-any from revive Signed-off-by: Matthieu MOREL --- .golangci.yaml | 64 +++ .../applicationset_controller_test.go | 2 +- .../controllers/requeue_after_test.go | 14 +- .../controllers/template/template.go | 4 +- .../controllers/template/template_test.go | 14 +- applicationset/generators/cluster.go | 14 +- applicationset/generators/cluster_test.go | 64 +-- applicationset/generators/duck_type.go | 18 +- applicationset/generators/duck_type_test.go | 96 ++-- .../generators/generator_spec_processor.go | 12 +- .../generator_spec_processor_test.go | 44 +- applicationset/generators/git.go | 36 +- applicationset/generators/git_test.go | 170 +++---- applicationset/generators/interface.go | 2 +- applicationset/generators/list.go | 12 +- applicationset/generators/list_test.go | 12 +- applicationset/generators/matrix.go | 8 +- applicationset/generators/matrix_test.go | 76 +-- applicationset/generators/merge.go | 18 +- applicationset/generators/merge_test.go | 60 +-- applicationset/generators/plugin.go | 10 +- applicationset/generators/plugin_test.go | 52 +- applicationset/generators/pull_request.go | 6 +- .../generators/pull_request_test.go | 12 +- applicationset/generators/scm_provider.go | 6 +- .../generators/scm_provider_test.go | 6 +- .../generators/value_interpolation.go | 6 +- .../generators/value_interpolation_test.go | 32 +- .../services/internal/http/client.go | 6 +- .../services/internal/http/client_test.go | 12 +- .../services/plugin/plugin_service.go | 2 +- .../services/pull_request/bitbucket_cloud.go | 4 +- .../services/pull_request/bitbucket_server.go | 2 +- .../services/scm_provider/bitbucket_cloud.go | 4 +- .../services/scm_provider/bitbucket_server.go | 6 +- applicationset/services/scm_provider/types.go | 2 +- applicationset/utils/createOrUpdate.go | 2 +- applicationset/utils/map.go | 10 +- applicationset/utils/map_test.go | 16 +- applicationset/utils/template_functions.go | 14 +- applicationset/utils/utils.go | 26 +- applicationset/utils/utils_test.go | 120 ++--- applicationset/webhook/webhook.go | 14 +- applicationset/webhook/webhook_test.go | 4 +- cmd/argocd-dex/commands/argocd_dex.go | 14 +- cmd/argocd/commands/admin/admin_test.go | 18 +- cmd/argocd/commands/admin/app.go | 8 +- .../commands/admin/generatespec_utils.go | 10 +- cmd/argocd/commands/app.go | 8 +- cmd/argocd/commands/app_resources.go | 2 +- cmd/argocd/commands/app_test.go | 16 +- cmd/argocd/commands/applicationset.go | 6 +- cmd/argocd/commands/common.go | 4 +- cmd/argocd/commands/headless/headless.go | 2 +- cmd/argocd/commands/projectwindows.go | 4 +- cmd/argocd/commands/version.go | 2 +- cmpserver/plugin/plugin.go | 4 +- cmpserver/plugin/plugin_test.go | 4 +- cmpserver/server.go | 4 +- controller/appcontroller.go | 38 +- controller/appcontroller_test.go | 60 +-- controller/cache/cache.go | 4 +- controller/cache/info.go | 16 +- controller/cache/info_test.go | 2 +- controller/metrics/metrics.go | 8 +- controller/metrics/metrics_test.go | 2 +- controller/sync.go | 2 +- controller/sync_test.go | 52 +- hack/dev-mounter/main.go | 4 +- hack/gen-crd-spec/main.go | 6 +- hack/gen-docs/main.go | 18 +- hack/known_types/main.go | 2 +- .../controller/controller_test.go | 30 +- .../application/forwarder_overwrite.go | 46 +- .../application/forwarder_overwrite_test.go | 12 +- pkg/apiclient/grpcproxy.go | 6 +- .../application/v1alpha1/openapi_generated.go | 262 +++++----- pkg/apis/application/v1alpha1/types.go | 2 +- pkg/apis/application/v1alpha1/values.go | 4 +- pkg/ratelimiter/ratelimiter.go | 4 +- reposerver/cache/cache_test.go | 4 +- reposerver/repository/repository.go | 4 +- reposerver/repository/repository_test.go | 8 +- server/account/account_test.go | 6 +- server/application/application.go | 22 +- server/application/application_test.go | 18 +- server/application/broadcaster.go | 12 +- server/application/websocket_test.go | 4 +- server/cluster/cluster_test.go | 2 +- server/deeplinks/deeplinks.go | 6 +- server/extension/extension.go | 4 +- server/project/project.go | 2 +- server/project/project_test.go | 2 +- server/rbacpolicy/rbacpolicy.go | 12 +- server/repository/repository_test.go | 2 +- server/server.go | 6 +- server/server_test.go | 8 +- test/e2e/cli_test.go | 4 +- test/e2e/clusterdecisiongenerator_e2e_test.go | 30 +- test/e2e/fixture/admin/utils/backup.go | 2 +- test/e2e/fixture/app/actions.go | 2 +- test/e2e/fixture/applicationsets/actions.go | 10 +- .../fixture/applicationsets/utils/errrors.go | 6 +- .../fixture/applicationsets/utils/fixture.go | 6 +- test/e2e/fixture/fixture.go | 2 +- test/e2e/fixture/http.go | 2 +- test/e2e/fixture/tmpl.go | 2 +- test/e2e/merge_e2e_test.go | 2 +- test/testutil.go | 8 +- util/argo/argo.go | 8 +- util/argo/managedfields/managed_fields.go | 4 +- .../argo/managedfields/managed_fields_test.go | 2 +- util/argo/normalizers/corev1_known_types.go | 462 +++++++++--------- util/argo/normalizers/diff_normalizer.go | 2 +- util/argo/normalizers/diff_normalizer_test.go | 8 +- .../argo/normalizers/knowntypes_normalizer.go | 20 +- .../normalizers/knowntypes_normalizer_test.go | 4 +- util/cache/appstate/cache.go | 4 +- util/cache/cache.go | 4 +- util/cache/client.go | 4 +- util/cache/inmemory.go | 10 +- util/cache/mocks/cacheclient.go | 2 +- util/cache/redis.go | 6 +- util/cache/twolevelclient.go | 2 +- util/clusterauth/clusterauth.go | 18 +- util/config/reader.go | 12 +- util/db/secrets.go | 6 +- util/dex/config.go | 38 +- util/dex/dex_test.go | 42 +- util/errors/errors.go | 6 +- util/gpg/gpg.go | 2 +- util/grpc/errors.go | 8 +- util/grpc/grpc.go | 12 +- util/grpc/json.go | 6 +- util/grpc/logging.go | 12 +- util/grpc/logging_test.go | 8 +- util/grpc/sanitizer.go | 2 +- util/grpc/sanitizer_test.go | 2 +- util/grpc/useragent.go | 4 +- util/helm/helm.go | 8 +- util/helm/helm_test.go | 6 +- util/jwt/jwt.go | 4 +- util/kube/kube.go | 8 +- util/kustomize/kustomize.go | 22 +- util/kustomize/kustomize_test.go | 6 +- util/log/logrus.go | 2 +- util/lua/custom_actions_test.go | 8 +- util/lua/health_test.go | 2 +- util/lua/lua.go | 38 +- util/lua/lua_test.go | 2 +- util/notification/expression/expr.go | 10 +- util/notification/expression/repo/repo.go | 8 +- .../expression/strings/strings.go | 4 +- util/notification/expression/time/time.go | 4 +- .../notification/expression/time/time_test.go | 2 +- util/notification/settings/legacy.go | 2 +- util/notification/settings/settings.go | 8 +- util/notification/settings/settings_test.go | 4 +- util/oidc/oidc_test.go | 4 +- util/oidc/templates.go | 2 +- util/rbac/rbac.go | 28 +- util/rbac/rbac_test.go | 10 +- util/session/sessionmanager.go | 2 +- util/settings/settings.go | 40 +- util/tls/tls.go | 4 +- util/webhook/webhook.go | 14 +- util/webhook/webhook_test.go | 4 +- 167 files changed, 1519 insertions(+), 1455 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index ad92622481dbc6..5b8ba1d19dda85 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -21,6 +21,7 @@ linters: - ineffassign - misspell - perfsprint + - revive - staticcheck - testifylint - thelper @@ -63,6 +64,69 @@ linters-settings: sprintf1: true # Optimizes into strings concatenation. strconcat: true + revive: + rules: + # Blank import should be only in a main or test package, or have a comment justifying it. + - name: blank-imports + disabled: true + # context.Context() should be the first parameter of a function when provided as argument. + - name: context-as-argument + disabled: true + # Basic types should not be used as a key in `context.WithValue` + - name: context-keys-type + disabled: true + # Importing with `.` makes the programs much harder to understand + - name: dot-imports + disabled: true + # Empty blocks make code less readable and could be a symptom of a bug or unfinished refactoring. + - name: empty-block + disabled: true + # for better readability, variables of type `error` must be named with the prefix `err`. + - name: error-naming + disabled: true + # for better readability, the errors should be last in the list of returned values by a function. + - name: error-return + # for better readability, error messages should not be capitalized or end with punctuation or a newline. + - name: error-strings + disabled: true + # report when replacing `errors.New(fmt.Sprintf())` with `fmt.Errorf()` is possible + - name: errorf + # incrementing an integer variable by 1 is recommended to be done using the `++` operator + - name: increment-decrement + disabled: true + # highlights redundant else-blocks that can be eliminated from the code + - name: indent-error-flow + disabled: true + # This rule suggests a shorter way of writing ranges that do not use the second value. + - name: range + # receiver names in a method should reflect the struct name (p for Person, for example) + - name: receiver-naming + disabled: true + # redefining built in names (true, false, append, make) can lead to bugs very difficult to detect. + - name: redefines-builtin-id + disabled: true + # redundant else-blocks that can be eliminated from the code. + - name: superfluous-else + disabled: true + # prevent confusing name for variables when using `time` package + - name: time-naming + disabled: true + # warns when an exported function or method returns a value of an un-exported type. + - name: unexported-return + disabled: true + # spots and proposes to remove unreachable code. also helps to spot errors + - name: unreachable-code + # Functions or methods with unused parameters can be a symptom of an unfinished refactoring or a bug. + - name: unused-parameter + disabled: true + # Since Go 1.18, interface{} has an alias: any. This rule proposes to replace instances of interface{} with any. + - name: use-any + # report when a variable declaration can be simplified + - name: var-declaration + disabled: true + # warns when initialism, variable or package naming conventions are not followed. + - name: var-naming + disabled: true testifylint: enable-all: true disable: diff --git a/applicationset/controllers/applicationset_controller_test.go b/applicationset/controllers/applicationset_controller_test.go index 28c534ad5fd111..480222b8dd1f28 100644 --- a/applicationset/controllers/applicationset_controller_test.go +++ b/applicationset/controllers/applicationset_controller_test.go @@ -1865,7 +1865,7 @@ func TestRequeueGeneratorFails(t *testing.T) { generatorMock.On("GetTemplate", &generator). Return(&v1alpha1.ApplicationSetTemplate{}) generatorMock.On("GenerateParams", &generator, mock.AnythingOfType("*v1alpha1.ApplicationSet"), mock.Anything). - Return([]map[string]interface{}{}, errors.New("Simulated error generating params that could be related to an external service/API call")) + Return([]map[string]any{}, errors.New("Simulated error generating params that could be related to an external service/API call")) metrics := appsetmetrics.NewFakeAppsetMetrics(client) diff --git a/applicationset/controllers/requeue_after_test.go b/applicationset/controllers/requeue_after_test.go index c0c039b88faca9..7ee01e9d73e12e 100644 --- a/applicationset/controllers/requeue_after_test.go +++ b/applicationset/controllers/requeue_after_test.go @@ -36,20 +36,20 @@ func TestRequeueAfter(t *testing.T) { appClientset := kubefake.NewSimpleClientset() k8sClient := fake.NewClientBuilder().Build() duckType := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "v2quack", "kind": "Duck", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "mightyduck", "namespace": "namespace", - "labels": map[string]interface{}{"duck": "all-species"}, + "labels": map[string]any{"duck": "all-species"}, }, - "status": map[string]interface{}{ - "decisions": []interface{}{ - map[string]interface{}{ + "status": map[string]any{ + "decisions": []any{ + map[string]any{ "clusterName": "staging-01", }, - map[string]interface{}{ + map[string]any{ "clusterName": "production-01", }, }, diff --git a/applicationset/controllers/template/template.go b/applicationset/controllers/template/template.go index 616b7ef9a7e744..cd8e38837f1864 100644 --- a/applicationset/controllers/template/template.go +++ b/applicationset/controllers/template/template.go @@ -20,7 +20,7 @@ func GenerateApplications(logCtx *log.Entry, applicationSetInfo argov1alpha1.App var applicationSetReason argov1alpha1.ApplicationSetReasonType for _, requestedGenerator := range applicationSetInfo.Spec.Generators { - t, err := generators.Transform(requestedGenerator, g, applicationSetInfo.Spec.Template, &applicationSetInfo, map[string]interface{}{}, client) + t, err := generators.Transform(requestedGenerator, g, applicationSetInfo.Spec.Template, &applicationSetInfo, map[string]any{}, client) if err != nil { logCtx.WithError(err).WithField("generator", requestedGenerator). Error("error generating application from params") @@ -79,7 +79,7 @@ func GenerateApplications(logCtx *log.Entry, applicationSetInfo argov1alpha1.App return res, applicationSetReason, firstError } -func renderTemplatePatch(r utils.Renderer, app *argov1alpha1.Application, applicationSetInfo argov1alpha1.ApplicationSet, params map[string]interface{}) (*argov1alpha1.Application, error) { +func renderTemplatePatch(r utils.Renderer, app *argov1alpha1.Application, applicationSetInfo argov1alpha1.ApplicationSet, params map[string]any) (*argov1alpha1.Application, error) { replacedTemplate, err := r.Replace(*applicationSetInfo.Spec.TemplatePatch, params, applicationSetInfo.Spec.GoTemplate, applicationSetInfo.Spec.GoTemplateOptions) if err != nil { return nil, fmt.Errorf("error replacing values in templatePatch: %w", err) diff --git a/applicationset/controllers/template/template_test.go b/applicationset/controllers/template/template_test.go index 1df037c13a566a..09bfab4a523cfe 100644 --- a/applicationset/controllers/template/template_test.go +++ b/applicationset/controllers/template/template_test.go @@ -31,7 +31,7 @@ func TestGenerateApplications(t *testing.T) { for _, c := range []struct { name string - params []map[string]interface{} + params []map[string]any template v1alpha1.ApplicationSetTemplate generateParamsError error rendererError error @@ -40,7 +40,7 @@ func TestGenerateApplications(t *testing.T) { }{ { name: "Generate two applications", - params: []map[string]interface{}{{"name": "app1"}, {"name": "app2"}}, + params: []map[string]any{{"name": "app1"}, {"name": "app2"}}, template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{ Name: "name", @@ -59,7 +59,7 @@ func TestGenerateApplications(t *testing.T) { }, { name: "Handles error from the render", - params: []map[string]interface{}{{"name": "app1"}, {"name": "app2"}}, + params: []map[string]any{{"name": "app1"}, {"name": "app2"}}, template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{ Name: "name", @@ -153,7 +153,7 @@ func TestGenerateApplications(t *testing.T) { func TestMergeTemplateApplications(t *testing.T) { for _, c := range []struct { name string - params []map[string]interface{} + params []map[string]any template v1alpha1.ApplicationSetTemplate overrideTemplate v1alpha1.ApplicationSetTemplate expectedMerged v1alpha1.ApplicationSetTemplate @@ -161,7 +161,7 @@ func TestMergeTemplateApplications(t *testing.T) { }{ { name: "Generate app", - params: []map[string]interface{}{{"name": "app1"}}, + params: []map[string]any{{"name": "app1"}}, template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{ Name: "name", @@ -245,13 +245,13 @@ func TestMergeTemplateApplications(t *testing.T) { func TestGenerateAppsUsingPullRequestGenerator(t *testing.T) { for _, cases := range []struct { name string - params []map[string]interface{} + params []map[string]any template v1alpha1.ApplicationSetTemplate expectedApp []v1alpha1.Application }{ { name: "Generate an application from a go template application set manifest using a pull request generator", - params: []map[string]interface{}{ + params: []map[string]any{ { "number": "1", "title": "title1", diff --git a/applicationset/generators/cluster.go b/applicationset/generators/cluster.go index d7b35d18154542..bcc5c55f8473f2 100644 --- a/applicationset/generators/cluster.go +++ b/applicationset/generators/cluster.go @@ -56,7 +56,7 @@ func (g *ClusterGenerator) GetTemplate(appSetGenerator *argoappsetv1alpha1.Appli return &appSetGenerator.Clusters.Template } -func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.ApplicationSetGenerator, appSet *argoappsetv1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) { +func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.ApplicationSetGenerator, appSet *argoappsetv1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) { logCtx := log.WithField("applicationset", appSet.GetName()).WithField("namespace", appSet.GetNamespace()) if appSetGenerator == nil { return nil, EmptyAppSetGeneratorError @@ -85,13 +85,13 @@ func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.Ap return nil, fmt.Errorf("error getting cluster secrets: %w", err) } - res := []map[string]interface{}{} + res := []map[string]any{} secretsFound := []corev1.Secret{} isFlatMode := appSetGenerator.Clusters.FlatList logCtx.Debugf("Using flat mode = %t for cluster generator", isFlatMode) - clustersParams := make([]map[string]interface{}, 0) + clustersParams := make([]map[string]any, 0) for _, cluster := range clustersFromArgoCD.Items { // If there is a secret for this cluster, then it's a non-local cluster, so it will be @@ -100,7 +100,7 @@ func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.Ap secretsFound = append(secretsFound, secretForCluster) } else if !ignoreLocalClusters { // If there is no secret for the cluster, it's the local cluster, so handle it here. - params := map[string]interface{}{} + params := map[string]any{} params["name"] = cluster.Name params["nameNormalized"] = cluster.Name params["server"] = cluster.Server @@ -123,7 +123,7 @@ func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.Ap // For each matching cluster secret (non-local clusters only) for _, cluster := range secretsFound { - params := map[string]interface{}{} + params := map[string]any{} params["name"] = string(cluster.Data["name"]) params["nameNormalized"] = utils.SanitizeName(string(cluster.Data["name"])) @@ -137,7 +137,7 @@ func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.Ap } if appSet.Spec.GoTemplate { - meta := map[string]interface{}{} + meta := map[string]any{} if len(cluster.ObjectMeta.Annotations) > 0 { meta["annotations"] = cluster.ObjectMeta.Annotations @@ -172,7 +172,7 @@ func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.Ap } if isFlatMode { - res = append(res, map[string]interface{}{ + res = append(res, map[string]any{ "clusters": clustersParams, }) } diff --git a/applicationset/generators/cluster_test.go b/applicationset/generators/cluster_test.go index 57aefe847604cc..10c114f39dcae6 100644 --- a/applicationset/generators/cluster_test.go +++ b/applicationset/generators/cluster_test.go @@ -89,7 +89,7 @@ func TestGenerateParams(t *testing.T) { selector metav1.LabelSelector isFlatMode bool values map[string]string - expected []map[string]interface{} + expected []map[string]any // clientError is true if a k8s client error should be simulated clientError bool expectedError error @@ -106,7 +106,7 @@ func TestGenerateParams(t *testing.T) { "bat": "{{ metadata.labels.environment }}", "aaa": "{{ server }}", "no-op": "{{ this-does-not-exist }}", - }, expected: []map[string]interface{}{ + }, expected: []map[string]any{ {"values.lol1": "lol", "values.lol2": "{{values.lol1}}{{values.lol1}}", "values.lol3": "{{values.lol2}}{{values.lol2}}{{values.lol2}}", "values.foo": "bar", "values.bar": "{{ metadata.annotations.foo.argoproj.io }}", "values.no-op": "{{ this-does-not-exist }}", "values.bat": "{{ metadata.labels.environment }}", "values.aaa": "https://kubernetes.default.svc", "nameNormalized": "in-cluster", "name": "in-cluster", "server": "https://kubernetes.default.svc", "project": ""}, { "values.lol1": "lol", "values.lol2": "{{values.lol1}}{{values.lol1}}", "values.lol3": "{{values.lol2}}{{values.lol2}}{{values.lol2}}", "values.foo": "bar", "values.bar": "production", "values.no-op": "{{ this-does-not-exist }}", "values.bat": "production", "values.aaa": "https://production-01.example.com", "name": "production_01/west", "nameNormalized": "production-01-west", "server": "https://production-01.example.com", "metadata.labels.environment": "production", "metadata.labels.org": "bar", @@ -129,7 +129,7 @@ func TestGenerateParams(t *testing.T) { }, }, values: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "name": "production_01/west", "nameNormalized": "production-01-west", "server": "https://production-01.example.com", "metadata.labels.environment": "production", "metadata.labels.org": "bar", "metadata.labels.argocd.argoproj.io/secret-type": "cluster", "metadata.annotations.foo.argoproj.io": "production", "project": "prod-project", @@ -153,7 +153,7 @@ func TestGenerateParams(t *testing.T) { values: map[string]string{ "foo": "bar", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "values.foo": "bar", "name": "production_01/west", "nameNormalized": "production-01-west", "server": "https://production-01.example.com", "metadata.labels.environment": "production", "metadata.labels.org": "bar", "metadata.labels.argocd.argoproj.io/secret-type": "cluster", "metadata.annotations.foo.argoproj.io": "production", "project": "prod-project", @@ -179,7 +179,7 @@ func TestGenerateParams(t *testing.T) { values: map[string]string{ "foo": "bar", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "values.foo": "bar", "name": "staging-01", "nameNormalized": "staging-01", "server": "https://staging-01.example.com", "metadata.labels.environment": "staging", "metadata.labels.org": "foo", "metadata.labels.argocd.argoproj.io/secret-type": "cluster", "metadata.annotations.foo.argoproj.io": "staging", "project": "", @@ -212,7 +212,7 @@ func TestGenerateParams(t *testing.T) { values: map[string]string{ "name": "baz", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "values.name": "baz", "name": "staging-01", "nameNormalized": "staging-01", "server": "https://staging-01.example.com", "metadata.labels.environment": "staging", "metadata.labels.org": "foo", "metadata.labels.argocd.argoproj.io/secret-type": "cluster", "metadata.annotations.foo.argoproj.io": "staging", "project": "", @@ -242,9 +242,9 @@ func TestGenerateParams(t *testing.T) { "aaa": "{{ server }}", "no-op": "{{ this-does-not-exist }}", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "clusters": []map[string]interface{}{ + "clusters": []map[string]any{ {"values.lol1": "lol", "values.lol2": "{{values.lol1}}{{values.lol1}}", "values.lol3": "{{values.lol2}}{{values.lol2}}{{values.lol2}}", "values.foo": "bar", "values.bar": "{{ metadata.annotations.foo.argoproj.io }}", "values.no-op": "{{ this-does-not-exist }}", "values.bat": "{{ metadata.labels.environment }}", "values.aaa": "https://kubernetes.default.svc", "nameNormalized": "in-cluster", "name": "in-cluster", "server": "https://kubernetes.default.svc", "project": ""}, { "values.lol1": "lol", "values.lol2": "{{values.lol1}}{{values.lol1}}", "values.lol3": "{{values.lol2}}{{values.lol2}}{{values.lol2}}", "values.foo": "bar", "values.bar": "production", "values.no-op": "{{ this-does-not-exist }}", "values.bat": "production", "values.aaa": "https://production-01.example.com", "name": "production_01/west", "nameNormalized": "production-01-west", "server": "https://production-01.example.com", "metadata.labels.environment": "production", "metadata.labels.org": "bar", @@ -280,9 +280,9 @@ func TestGenerateParams(t *testing.T) { values: map[string]string{ "foo": "bar", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "clusters": []map[string]interface{}{ + "clusters": []map[string]any{ { "values.foo": "bar", "name": "production_01/west", "nameNormalized": "production-01-west", "server": "https://production-01.example.com", "metadata.labels.environment": "production", "metadata.labels.org": "bar", "metadata.labels.argocd.argoproj.io/secret-type": "cluster", "metadata.annotations.foo.argoproj.io": "production", "project": "prod-project", @@ -398,7 +398,7 @@ func TestGenerateParamsGoTemplate(t *testing.T) { selector metav1.LabelSelector values map[string]string isFlatMode bool - expected []map[string]interface{} + expected []map[string]any // clientError is true if a k8s client error should be simulated clientError bool expectedError error @@ -415,13 +415,13 @@ func TestGenerateParamsGoTemplate(t *testing.T) { "bat": "{{ if not (empty .metadata) }}{{.metadata.labels.environment}}{{ end }}", "aaa": "{{ .server }}", "no-op": "{{ .thisDoesNotExist }}", - }, expected: []map[string]interface{}{ + }, expected: []map[string]any{ { "name": "production_01/west", "nameNormalized": "production-01-west", "server": "https://production-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "production", @@ -447,7 +447,7 @@ func TestGenerateParamsGoTemplate(t *testing.T) { "nameNormalized": "staging-01", "server": "https://staging-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "staging", @@ -496,13 +496,13 @@ func TestGenerateParamsGoTemplate(t *testing.T) { }, }, values: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "name": "production_01/west", "nameNormalized": "production-01-west", "server": "https://production-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "production", @@ -518,7 +518,7 @@ func TestGenerateParamsGoTemplate(t *testing.T) { "nameNormalized": "staging-01", "server": "https://staging-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "staging", @@ -543,13 +543,13 @@ func TestGenerateParamsGoTemplate(t *testing.T) { values: map[string]string{ "foo": "bar", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "name": "production_01/west", "nameNormalized": "production-01-west", "server": "https://production-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "production", @@ -584,13 +584,13 @@ func TestGenerateParamsGoTemplate(t *testing.T) { values: map[string]string{ "foo": "bar", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "name": "production_01/west", "nameNormalized": "production-01-west", "server": "https://production-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "production", @@ -609,7 +609,7 @@ func TestGenerateParamsGoTemplate(t *testing.T) { "nameNormalized": "staging-01", "server": "https://staging-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "staging", @@ -647,13 +647,13 @@ func TestGenerateParamsGoTemplate(t *testing.T) { values: map[string]string{ "name": "baz", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "name": "staging-01", "nameNormalized": "staging-01", "server": "https://staging-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "staging", @@ -693,9 +693,9 @@ func TestGenerateParamsGoTemplate(t *testing.T) { "aaa": "{{ .server }}", "no-op": "{{ .thisDoesNotExist }}", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "clusters": []map[string]interface{}{ + "clusters": []map[string]any{ { "nameNormalized": "in-cluster", "name": "in-cluster", @@ -717,7 +717,7 @@ func TestGenerateParamsGoTemplate(t *testing.T) { "nameNormalized": "production-01-west", "server": "https://production-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "production", @@ -743,7 +743,7 @@ func TestGenerateParamsGoTemplate(t *testing.T) { "nameNormalized": "staging-01", "server": "https://staging-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "staging", @@ -788,15 +788,15 @@ func TestGenerateParamsGoTemplate(t *testing.T) { values: map[string]string{ "foo": "bar", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "clusters": []map[string]interface{}{ + "clusters": []map[string]any{ { "name": "production_01/west", "nameNormalized": "production-01-west", "server": "https://production-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "production", @@ -815,7 +815,7 @@ func TestGenerateParamsGoTemplate(t *testing.T) { "nameNormalized": "staging-01", "server": "https://staging-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "argocd.argoproj.io/secret-type": "cluster", "environment": "staging", diff --git a/applicationset/generators/duck_type.go b/applicationset/generators/duck_type.go index 4d9d95f9cf4b8e..31bbd7cc5d92b8 100644 --- a/applicationset/generators/duck_type.go +++ b/applicationset/generators/duck_type.go @@ -60,7 +60,7 @@ func (g *DuckTypeGenerator) GetTemplate(appSetGenerator *argoprojiov1alpha1.Appl return &appSetGenerator.ClusterDecisionResource.Template } -func (g *DuckTypeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) { +func (g *DuckTypeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) { if appSetGenerator == nil { return nil, EmptyAppSetGeneratorError } @@ -147,21 +147,21 @@ func (g *DuckTypeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.A return nil, nil } - res := []map[string]interface{}{} - clusterDecisions := []interface{}{} + res := []map[string]any{} + clusterDecisions := []any{} // Build the decision slice for _, duckResource := range duckResources.Items { log.WithField("duckResourceName", duckResource.GetName()).Debug("found resource") - if duckResource.Object["status"] == nil || len(duckResource.Object["status"].(map[string]interface{})) == 0 { + if duckResource.Object["status"] == nil || len(duckResource.Object["status"].(map[string]any)) == 0 { log.Warningf("clusterDecisionResource: %s, has no status", duckResource.GetName()) continue } log.WithField("duckResourceStatus", duckResource.Object["status"]).Debug("found resource") - clusterDecisions = append(clusterDecisions, duckResource.Object["status"].(map[string]interface{})[statusListKey].([]interface{})...) + clusterDecisions = append(clusterDecisions, duckResource.Object["status"].(map[string]any)[statusListKey].([]any)...) } log.Infof("Number of decisions found: %v", len(clusterDecisions)) @@ -171,12 +171,12 @@ func (g *DuckTypeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.A if len(clusterDecisions) > 0 { for _, cluster := range clusterDecisions { // generated instance of cluster params - params := map[string]interface{}{} + params := map[string]any{} log.Infof("cluster: %v", cluster) - matchValue := cluster.(map[string]interface{})[matchKey] + matchValue := cluster.(map[string]any)[matchKey] if matchValue == nil || matchValue.(string) == "" { - log.Warningf("matchKey=%v not found in \"%v\" list: %v\n", matchKey, statusListKey, cluster.(map[string]interface{})) + log.Warningf("matchKey=%v not found in \"%v\" list: %v\n", matchKey, statusListKey, cluster.(map[string]any)) continue } @@ -201,7 +201,7 @@ func (g *DuckTypeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.A continue } - for key, value := range cluster.(map[string]interface{}) { + for key, value := range cluster.(map[string]any) { params[key] = value.(string) } diff --git a/applicationset/generators/duck_type_test.go b/applicationset/generators/duck_type_test.go index 4ac24f094edd25..7cec658cf06c39 100644 --- a/applicationset/generators/duck_type_test.go +++ b/applicationset/generators/duck_type_test.go @@ -78,20 +78,20 @@ func TestGenerateParamsForDuckType(t *testing.T) { } duckType := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": resourceApiVersion, "kind": "Duck", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": resourceName, "namespace": "namespace", - "labels": map[string]interface{}{"duck": "all-species"}, + "labels": map[string]any{"duck": "all-species"}, }, - "status": map[string]interface{}{ - "decisions": []interface{}{ - map[string]interface{}{ + "status": map[string]any{ + "decisions": []any{ + map[string]any{ "clusterName": "staging-01", }, - map[string]interface{}{ + map[string]any{ "clusterName": "production-01", }, }, @@ -100,17 +100,17 @@ func TestGenerateParamsForDuckType(t *testing.T) { } duckTypeProdOnly := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": resourceApiVersion, "kind": "Duck", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": resourceName, "namespace": "namespace", - "labels": map[string]interface{}{"duck": "spotted"}, + "labels": map[string]any{"duck": "spotted"}, }, - "status": map[string]interface{}{ - "decisions": []interface{}{ - map[string]interface{}{ + "status": map[string]any{ + "decisions": []any{ + map[string]any{ "clusterName": "production-01", }, }, @@ -119,15 +119,15 @@ func TestGenerateParamsForDuckType(t *testing.T) { } duckTypeEmpty := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": resourceApiVersion, "kind": "Duck", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": resourceName, "namespace": "namespace", - "labels": map[string]interface{}{"duck": "canvasback"}, + "labels": map[string]any{"duck": "canvasback"}, }, - "status": map[string]interface{}{}, + "status": map[string]any{}, }, } @@ -151,7 +151,7 @@ func TestGenerateParamsForDuckType(t *testing.T) { labelSelector metav1.LabelSelector resource *unstructured.Unstructured values map[string]string - expected []map[string]interface{} + expected []map[string]any expectedError error }{ { @@ -159,7 +159,7 @@ func TestGenerateParamsForDuckType(t *testing.T) { resourceName: "", resource: duckType, values: nil, - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: errors.New("There is a problem with the definition of the ClusterDecisionResource generator"), }, /*** This does not work with the FAKE runtime client, fieldSelectors are broken. @@ -177,7 +177,7 @@ func TestGenerateParamsForDuckType(t *testing.T) { resourceName: resourceName, resource: duckType, values: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"}, {"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"}, @@ -191,7 +191,7 @@ func TestGenerateParamsForDuckType(t *testing.T) { values: map[string]string{ "foo": "bar", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"clusterName": "production-01", "values.foo": "bar", "name": "production-01", "server": "https://production-01.example.com"}, }, expectedError: nil, @@ -219,7 +219,7 @@ func TestGenerateParamsForDuckType(t *testing.T) { labelSelector: metav1.LabelSelector{MatchLabels: map[string]string{"duck": "all-species"}}, resource: duckType, values: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"}, {"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"}, @@ -234,7 +234,7 @@ func TestGenerateParamsForDuckType(t *testing.T) { values: map[string]string{ "foo": "bar", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"clusterName": "production-01", "values.foo": "bar", "name": "production-01", "server": "https://production-01.example.com"}, }, expectedError: nil, @@ -251,7 +251,7 @@ func TestGenerateParamsForDuckType(t *testing.T) { }}, resource: duckType, values: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"}, {"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"}, @@ -374,20 +374,20 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) { } duckType := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": resourceApiVersion, "kind": "Duck", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": resourceName, "namespace": "namespace", - "labels": map[string]interface{}{"duck": "all-species"}, + "labels": map[string]any{"duck": "all-species"}, }, - "status": map[string]interface{}{ - "decisions": []interface{}{ - map[string]interface{}{ + "status": map[string]any{ + "decisions": []any{ + map[string]any{ "clusterName": "staging-01", }, - map[string]interface{}{ + map[string]any{ "clusterName": "production-01", }, }, @@ -396,17 +396,17 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) { } duckTypeProdOnly := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": resourceApiVersion, "kind": "Duck", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": resourceName, "namespace": "namespace", - "labels": map[string]interface{}{"duck": "spotted"}, + "labels": map[string]any{"duck": "spotted"}, }, - "status": map[string]interface{}{ - "decisions": []interface{}{ - map[string]interface{}{ + "status": map[string]any{ + "decisions": []any{ + map[string]any{ "clusterName": "production-01", }, }, @@ -415,15 +415,15 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) { } duckTypeEmpty := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": resourceApiVersion, "kind": "Duck", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": resourceName, "namespace": "namespace", - "labels": map[string]interface{}{"duck": "canvasback"}, + "labels": map[string]any{"duck": "canvasback"}, }, - "status": map[string]interface{}{}, + "status": map[string]any{}, }, } @@ -447,7 +447,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) { labelSelector metav1.LabelSelector resource *unstructured.Unstructured values map[string]string - expected []map[string]interface{} + expected []map[string]any expectedError error }{ { @@ -455,7 +455,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) { resourceName: "", resource: duckType, values: nil, - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: errors.New("There is a problem with the definition of the ClusterDecisionResource generator"), }, /*** This does not work with the FAKE runtime client, fieldSelectors are broken. @@ -473,7 +473,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) { resourceName: resourceName, resource: duckType, values: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"}, {"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"}, @@ -487,7 +487,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) { values: map[string]string{ "foo": "bar", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"clusterName": "production-01", "values": map[string]string{"foo": "bar"}, "name": "production-01", "server": "https://production-01.example.com"}, }, expectedError: nil, @@ -515,7 +515,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) { labelSelector: metav1.LabelSelector{MatchLabels: map[string]string{"duck": "all-species"}}, resource: duckType, values: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"}, {"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"}, @@ -530,7 +530,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) { values: map[string]string{ "foo": "bar", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"clusterName": "production-01", "values": map[string]string{"foo": "bar"}, "name": "production-01", "server": "https://production-01.example.com"}, }, expectedError: nil, @@ -547,7 +547,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) { }}, resource: duckType, values: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"}, {"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"}, diff --git a/applicationset/generators/generator_spec_processor.go b/applicationset/generators/generator_spec_processor.go index 25e6b138da7491..6a94890eb92ebf 100644 --- a/applicationset/generators/generator_spec_processor.go +++ b/applicationset/generators/generator_spec_processor.go @@ -22,12 +22,12 @@ const ( ) type TransformResult struct { - Params []map[string]interface{} + Params []map[string]any Template argoprojiov1alpha1.ApplicationSetTemplate } // Transform a spec generator to list of paramSets and a template -func Transform(requestedGenerator argoprojiov1alpha1.ApplicationSetGenerator, allGenerators map[string]Generator, baseTemplate argoprojiov1alpha1.ApplicationSetTemplate, appSet *argoprojiov1alpha1.ApplicationSet, genParams map[string]interface{}, client client.Client) ([]TransformResult, error) { +func Transform(requestedGenerator argoprojiov1alpha1.ApplicationSetGenerator, allGenerators map[string]Generator, baseTemplate argoprojiov1alpha1.ApplicationSetTemplate, appSet *argoprojiov1alpha1.ApplicationSet, genParams map[string]any, client client.Client) ([]TransformResult, error) { // This is a custom version of the `LabelSelectorAsSelector` that is in k8s.io/apimachinery. This has been copied // verbatim from that package, with the difference that we do not have any restrictions on label values. This is done // so that, among other things, we can match on cluster urls. @@ -52,7 +52,7 @@ func Transform(requestedGenerator argoprojiov1alpha1.ApplicationSetGenerator, al } continue } - var params []map[string]interface{} + var params []map[string]any if len(genParams) != 0 { tempInterpolatedGenerator, err := InterpolateGenerator(&requestedGenerator, genParams, appSet.Spec.GoTemplate, appSet.Spec.GoTemplateOptions) interpolatedGenerator = &tempInterpolatedGenerator @@ -74,7 +74,7 @@ func Transform(requestedGenerator argoprojiov1alpha1.ApplicationSetGenerator, al } continue } - var filterParams []map[string]interface{} + var filterParams []map[string]any for _, param := range params { flatParam, err := flattenParameters(param) if err != nil { @@ -123,7 +123,7 @@ func GetRelevantGenerators(requestedGenerator *argoprojiov1alpha1.ApplicationSet return res } -func flattenParameters(in map[string]interface{}) (map[string]string, error) { +func flattenParameters(in map[string]any) (map[string]string, error) { flat, err := flatten.Flatten(in, "", flatten.DotStyle) if err != nil { return nil, fmt.Errorf("error flatenning parameters: %w", err) @@ -149,7 +149,7 @@ func mergeGeneratorTemplate(g Generator, requestedGenerator *argoprojiov1alpha1. // InterpolateGenerator allows interpolating the matrix's 2nd child generator with values from the 1st child generator // "params" parameter is an array, where each index corresponds to a generator. Each index contains a map w/ that generator's parameters. -func InterpolateGenerator(requestedGenerator *argoprojiov1alpha1.ApplicationSetGenerator, params map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (argoprojiov1alpha1.ApplicationSetGenerator, error) { +func InterpolateGenerator(requestedGenerator *argoprojiov1alpha1.ApplicationSetGenerator, params map[string]any, useGoTemplate bool, goTemplateOptions []string) (argoprojiov1alpha1.ApplicationSetGenerator, error) { render := utils.Render{} interpolatedGenerator, err := render.RenderGeneratorParams(requestedGenerator, params, useGoTemplate, goTemplateOptions) if err != nil { diff --git a/applicationset/generators/generator_spec_processor_test.go b/applicationset/generators/generator_spec_processor_test.go index 2c55fecad54034..a208e5781f2648 100644 --- a/applicationset/generators/generator_spec_processor_test.go +++ b/applicationset/generators/generator_spec_processor_test.go @@ -27,19 +27,19 @@ func TestMatchValues(t *testing.T) { name string elements []apiextensionsv1.JSON selector *metav1.LabelSelector - expected []map[string]interface{} + expected []map[string]any }{ { name: "no filter", elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}}, selector: &metav1.LabelSelector{}, - expected: []map[string]interface{}{{"cluster": "cluster", "url": "url"}}, + expected: []map[string]any{{"cluster": "cluster", "url": "url"}}, }, { name: "nil", elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}}, selector: nil, - expected: []map[string]interface{}{{"cluster": "cluster", "url": "url"}}, + expected: []map[string]any{{"cluster": "cluster", "url": "url"}}, }, { name: "values.foo should be foo but is ignore element", @@ -49,7 +49,7 @@ func TestMatchValues(t *testing.T) { "values.foo": "foo", }, }, - expected: []map[string]interface{}{}, + expected: []map[string]any{}, }, { name: "values.foo should be bar", @@ -59,7 +59,7 @@ func TestMatchValues(t *testing.T) { "values.foo": "bar", }, }, - expected: []map[string]interface{}{{"cluster": "cluster", "url": "url", "values.foo": "bar"}}, + expected: []map[string]any{{"cluster": "cluster", "url": "url", "values.foo": "bar"}}, }, } @@ -101,19 +101,19 @@ func TestMatchValuesGoTemplate(t *testing.T) { name string elements []apiextensionsv1.JSON selector *metav1.LabelSelector - expected []map[string]interface{} + expected []map[string]any }{ { name: "no filter", elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}}, selector: &metav1.LabelSelector{}, - expected: []map[string]interface{}{{"cluster": "cluster", "url": "url"}}, + expected: []map[string]any{{"cluster": "cluster", "url": "url"}}, }, { name: "nil", elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}}, selector: nil, - expected: []map[string]interface{}{{"cluster": "cluster", "url": "url"}}, + expected: []map[string]any{{"cluster": "cluster", "url": "url"}}, }, { name: "values.foo should be foo but is ignore element", @@ -123,7 +123,7 @@ func TestMatchValuesGoTemplate(t *testing.T) { "values.foo": "foo", }, }, - expected: []map[string]interface{}{}, + expected: []map[string]any{}, }, { name: "values.foo should be bar", @@ -133,7 +133,7 @@ func TestMatchValuesGoTemplate(t *testing.T) { "values.foo": "bar", }, }, - expected: []map[string]interface{}{{"cluster": "cluster", "url": "url", "values": map[string]interface{}{"foo": "bar"}}}, + expected: []map[string]any{{"cluster": "cluster", "url": "url", "values": map[string]any{"foo": "bar"}}}, }, { name: "values.0 should be bar", @@ -143,7 +143,7 @@ func TestMatchValuesGoTemplate(t *testing.T) { "values.0": "bar", }, }, - expected: []map[string]interface{}{{"cluster": "cluster", "url": "url", "values": []interface{}{"bar"}}}, + expected: []map[string]any{{"cluster": "cluster", "url": "url", "values": []any{"bar"}}}, }, } @@ -184,14 +184,14 @@ func TestTransForm(t *testing.T) { testCases := []struct { name string selector *metav1.LabelSelector - expected []map[string]interface{} + expected []map[string]any }{ { name: "server filter", selector: &metav1.LabelSelector{ MatchLabels: map[string]string{"server": "https://production-01.example.com"}, }, - expected: []map[string]interface{}{{ + expected: []map[string]any{{ "metadata.annotations.foo.argoproj.io": "production", "metadata.labels.argocd.argoproj.io/secret-type": "cluster", "metadata.labels.environment": "production", @@ -207,7 +207,7 @@ func TestTransForm(t *testing.T) { selector: &metav1.LabelSelector{ MatchLabels: map[string]string{"server": "https://some-really-long-url-that-will-exceed-63-characters.com"}, }, - expected: []map[string]interface{}{{ + expected: []map[string]any{{ "metadata.annotations.foo.argoproj.io": "production", "metadata.labels.argocd.argoproj.io/secret-type": "cluster", "metadata.labels.environment": "production", @@ -413,7 +413,7 @@ func TestInterpolateGenerator(t *testing.T) { }, }, } - gitGeneratorParams := map[string]interface{}{ + gitGeneratorParams := map[string]any{ "path": "p1/p2/app3", "path.basename": "app3", "path[0]": "p1", @@ -442,7 +442,7 @@ func TestInterpolateGenerator(t *testing.T) { Template: argov1alpha1.ApplicationSetTemplate{}, }, } - clusterGeneratorParams := map[string]interface{}{ + clusterGeneratorParams := map[string]any{ "name": "production_01/west", "server": "https://production-01.example.com", } interpolatedGenerator, err = InterpolateGenerator(requestedGenerator, clusterGeneratorParams, false, nil) @@ -468,8 +468,8 @@ func TestInterpolateGenerator_go(t *testing.T) { }, }, } - gitGeneratorParams := map[string]interface{}{ - "path": map[string]interface{}{ + gitGeneratorParams := map[string]any{ + "path": map[string]any{ "path": "p1/p2/app3", "segments": []string{"p1", "p2", "app3"}, }, @@ -497,7 +497,7 @@ func TestInterpolateGenerator_go(t *testing.T) { Template: argov1alpha1.ApplicationSetTemplate{}, }, } - clusterGeneratorParams := map[string]interface{}{ + clusterGeneratorParams := map[string]any{ "name": "production_01/west", "server": "https://production-01.example.com", } interpolatedGenerator, err = InterpolateGenerator(requestedGenerator, clusterGeneratorParams, true, nil) @@ -512,7 +512,7 @@ func TestInterpolateGenerator_go(t *testing.T) { func TestInterpolateGeneratorError(t *testing.T) { type args struct { requestedGenerator *argov1alpha1.ApplicationSetGenerator - params map[string]interface{} + params map[string]any useGoTemplate bool goTemplateOptions []string } @@ -530,7 +530,7 @@ func TestInterpolateGeneratorError(t *testing.T) { }, want: argov1alpha1.ApplicationSetGenerator{}, expectedErrStr: "generator is empty"}, {name: "No Params", args: args{ requestedGenerator: &argov1alpha1.ApplicationSetGenerator{}, - params: map[string]interface{}{}, + params: map[string]any{}, useGoTemplate: false, goTemplateOptions: nil, }, want: argov1alpha1.ApplicationSetGenerator{}, expectedErrStr: ""}, @@ -545,7 +545,7 @@ func TestInterpolateGeneratorError(t *testing.T) { "resolved": "{{ index .rmap (default .override .test) }}", }, }}, - params: map[string]interface{}{ + params: map[string]any{ "name": "in-cluster", "override": "foo", }, diff --git a/applicationset/generators/git.go b/applicationset/generators/git.go index d119824f401747..e2440980cfaedd 100644 --- a/applicationset/generators/git.go +++ b/applicationset/generators/git.go @@ -51,7 +51,7 @@ func (g *GitGenerator) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.Appli return getDefaultRequeueAfter() } -func (g *GitGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, error) { +func (g *GitGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]any, error) { if appSetGenerator == nil { return nil, EmptyAppSetGeneratorError } @@ -82,7 +82,7 @@ func (g *GitGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Applic } var err error - var res []map[string]interface{} + var res []map[string]any if len(appSetGenerator.Git.Directories) != 0 { res, err = g.generateParamsForGitDirectories(appSetGenerator, noRevisionCache, verifyCommit, appSet.Spec.GoTemplate, appSet.Spec.GoTemplateOptions) } else if len(appSetGenerator.Git.Files) != 0 { @@ -97,7 +97,7 @@ func (g *GitGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Applic return res, nil } -func (g *GitGenerator) generateParamsForGitDirectories(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, noRevisionCache, verifyCommit bool, useGoTemplate bool, goTemplateOptions []string) ([]map[string]interface{}, error) { +func (g *GitGenerator) generateParamsForGitDirectories(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, noRevisionCache, verifyCommit bool, useGoTemplate bool, goTemplateOptions []string) ([]map[string]any, error) { // Directories, not files allPaths, err := g.repos.GetDirectories(context.TODO(), appSetGenerator.Git.RepoURL, appSetGenerator.Git.Revision, noRevisionCache, verifyCommit) if err != nil { @@ -122,7 +122,7 @@ func (g *GitGenerator) generateParamsForGitDirectories(appSetGenerator *argoproj return res, nil } -func (g *GitGenerator) generateParamsForGitFiles(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, noRevisionCache, verifyCommit bool, useGoTemplate bool, goTemplateOptions []string) ([]map[string]interface{}, error) { +func (g *GitGenerator) generateParamsForGitFiles(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, noRevisionCache, verifyCommit bool, useGoTemplate bool, goTemplateOptions []string) ([]map[string]any, error) { // Get all files that match the requested path string, removing duplicates allFiles := make(map[string][]byte) for _, requestedPath := range appSetGenerator.Git.Files { @@ -144,7 +144,7 @@ func (g *GitGenerator) generateParamsForGitFiles(appSetGenerator *argoprojiov1al sort.Strings(allPaths) // Generate params from each path, and return - res := []map[string]interface{}{} + res := []map[string]any{} for _, path := range allPaths { // A JSON / YAML file path can contain multiple sets of parameters (ie it is an array) paramsArray, err := g.generateParamsFromGitFile(path, allFiles[path], appSetGenerator.Git.Values, useGoTemplate, goTemplateOptions, appSetGenerator.Git.PathParamPrefix) @@ -157,14 +157,14 @@ func (g *GitGenerator) generateParamsForGitFiles(appSetGenerator *argoprojiov1al return res, nil } -func (g *GitGenerator) generateParamsFromGitFile(filePath string, fileContent []byte, values map[string]string, useGoTemplate bool, goTemplateOptions []string, pathParamPrefix string) ([]map[string]interface{}, error) { - objectsFound := []map[string]interface{}{} +func (g *GitGenerator) generateParamsFromGitFile(filePath string, fileContent []byte, values map[string]string, useGoTemplate bool, goTemplateOptions []string, pathParamPrefix string) ([]map[string]any, error) { + objectsFound := []map[string]any{} // First, we attempt to parse as an array err := yaml.Unmarshal(fileContent, &objectsFound) if err != nil { // If unable to parse as an array, attempt to parse as a single object - singleObj := make(map[string]interface{}) + singleObj := make(map[string]any) err = yaml.Unmarshal(fileContent, &singleObj) if err != nil { return nil, fmt.Errorf("unable to parse file: %w", err) @@ -172,20 +172,20 @@ func (g *GitGenerator) generateParamsFromGitFile(filePath string, fileContent [] objectsFound = append(objectsFound, singleObj) } else if len(objectsFound) == 0 { // If file is valid but empty, add a default empty item - objectsFound = append(objectsFound, map[string]interface{}{}) + objectsFound = append(objectsFound, map[string]any{}) } - res := []map[string]interface{}{} + res := []map[string]any{} for _, objectFound := range objectsFound { - params := map[string]interface{}{} + params := map[string]any{} if useGoTemplate { for k, v := range objectFound { params[k] = v } - paramPath := map[string]interface{}{} + paramPath := map[string]any{} paramPath["path"] = path.Dir(filePath) paramPath["basename"] = path.Base(paramPath["path"].(string)) @@ -194,7 +194,7 @@ func (g *GitGenerator) generateParamsFromGitFile(filePath string, fileContent [] paramPath["filenameNormalized"] = utils.SanitizeName(path.Base(paramPath["filename"].(string))) paramPath["segments"] = strings.Split(paramPath["path"].(string), "/") if pathParamPrefix != "" { - params[pathParamPrefix] = map[string]interface{}{"path": paramPath} + params[pathParamPrefix] = map[string]any{"path": paramPath} } else { params["path"] = paramPath } @@ -261,19 +261,19 @@ func (g *GitGenerator) filterApps(directories []argoprojiov1alpha1.GitDirectoryG return res } -func (g *GitGenerator) generateParamsFromApps(requestedApps []string, appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, useGoTemplate bool, goTemplateOptions []string) ([]map[string]interface{}, error) { - res := make([]map[string]interface{}, len(requestedApps)) +func (g *GitGenerator) generateParamsFromApps(requestedApps []string, appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, useGoTemplate bool, goTemplateOptions []string) ([]map[string]any, error) { + res := make([]map[string]any, len(requestedApps)) for i, a := range requestedApps { - params := make(map[string]interface{}, 5) + params := make(map[string]any, 5) if useGoTemplate { - paramPath := map[string]interface{}{} + paramPath := map[string]any{} paramPath["path"] = a paramPath["basename"] = path.Base(a) paramPath["basenameNormalized"] = utils.SanitizeName(path.Base(a)) paramPath["segments"] = strings.Split(paramPath["path"].(string), "/") if appSetGenerator.Git.PathParamPrefix != "" { - params[appSetGenerator.Git.PathParamPrefix] = map[string]interface{}{"path": paramPath} + params[appSetGenerator.Git.PathParamPrefix] = map[string]any{"path": paramPath} } else { params["path"] = paramPath } diff --git a/applicationset/generators/git_test.go b/applicationset/generators/git_test.go index cb7389ac6b0cfc..50bb7536a1e8a9 100644 --- a/applicationset/generators/git_test.go +++ b/applicationset/generators/git_test.go @@ -33,7 +33,7 @@ foo: tests := []struct { name string args args - want []map[string]interface{} + want []map[string]any wantErr bool }{ { @@ -44,7 +44,7 @@ foo: values: map[string]string{}, useGoTemplate: false, }, - want: []map[string]interface{}{ + want: []map[string]any{ { "path": "path/dir", "path.basename": "dir", @@ -74,7 +74,7 @@ foo: values: map[string]string{}, useGoTemplate: false, }, - want: []map[string]interface{}{ + want: []map[string]any{ { "foo.bar": "baz", "path": "path/dir", @@ -96,7 +96,7 @@ foo: useGoTemplate: false, pathParamPrefix: "myRepo", }, - want: []map[string]interface{}{ + want: []map[string]any{ { "foo.bar": "baz", "myRepo.path": "path/dir", @@ -117,12 +117,12 @@ foo: values: map[string]string{}, useGoTemplate: true, }, - want: []map[string]interface{}{ + want: []map[string]any{ { - "foo": map[string]interface{}{ + "foo": map[string]any{ "bar": "baz", }, - "path": map[string]interface{}{ + "path": map[string]any{ "path": "path/dir", "basename": "dir", "filename": "file_name.yaml", @@ -145,13 +145,13 @@ foo: useGoTemplate: true, pathParamPrefix: "myRepo", }, - want: []map[string]interface{}{ + want: []map[string]any{ { - "foo": map[string]interface{}{ + "foo": map[string]any{ "bar": "baz", }, - "myRepo": map[string]interface{}{ - "path": map[string]interface{}{ + "myRepo": map[string]any{ + "path": map[string]any{ "path": "path/dir", "basename": "dir", "filename": "file_name.yaml", @@ -187,7 +187,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { repoApps []string repoError error values map[string]string - expected []map[string]interface{} + expected []map[string]any expectedError error }{ { @@ -200,7 +200,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { "p1/app4", }, repoError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"path": "app1", "path.basename": "app1", "path.basenameNormalized": "app1", "path[0]": "app1"}, {"path": "app2", "path.basename": "app2", "path.basenameNormalized": "app2", "path[0]": "app2"}, {"path": "app_3", "path.basename": "app_3", "path.basenameNormalized": "app-3", "path[0]": "app_3"}, @@ -218,7 +218,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { "p1/app4", }, repoError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"myRepo.path": "app1", "myRepo.path.basename": "app1", "myRepo.path.basenameNormalized": "app1", "myRepo.path[0]": "app1"}, {"myRepo.path": "app2", "myRepo.path.basename": "app2", "myRepo.path.basenameNormalized": "app2", "myRepo.path[0]": "app2"}, {"myRepo.path": "app_3", "myRepo.path.basename": "app_3", "myRepo.path.basenameNormalized": "app-3", "myRepo.path[0]": "app_3"}, @@ -235,7 +235,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { "p1/p2/p3/app4", }, repoError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"path": "p1/app2", "path.basename": "app2", "path[0]": "p1", "path[1]": "app2", "path.basenameNormalized": "app2"}, {"path": "p1/p2/app3", "path.basename": "app3", "path[0]": "p1", "path[1]": "p2", "path[2]": "app3", "path.basenameNormalized": "app3"}, }, @@ -252,7 +252,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { "p2/app3", }, repoError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"path": "app1", "path.basename": "app1", "path[0]": "app1", "path.basenameNormalized": "app1"}, {"path": "app2", "path.basename": "app2", "path[0]": "app2", "path.basenameNormalized": "app2"}, {"path": "p2/app3", "path.basename": "app3", "path[0]": "p2", "path[1]": "app3", "path.basenameNormalized": "app3"}, @@ -270,7 +270,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { "p2/app3", }, repoError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"path": "app1", "path.basename": "app1", "path[0]": "app1", "path.basenameNormalized": "app1"}, {"path": "app2", "path.basename": "app2", "path[0]": "app2", "path.basenameNormalized": "app2"}, {"path": "p2/app3", "path.basename": "app3", "path[0]": "p2", "path[1]": "app3", "path.basenameNormalized": "app3"}, @@ -290,7 +290,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { "aaa": "{{ path[0] }}", "no-op": "{{ this-does-not-exist }}", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"values.foo": "bar", "values.no-op": "{{ this-does-not-exist }}", "values.aaa": "app1", "path": "app1", "path.basename": "app1", "path[0]": "app1", "path.basenameNormalized": "app1"}, {"values.foo": "bar", "values.no-op": "{{ this-does-not-exist }}", "values.aaa": "p1", "path": "p1/app2", "path.basename": "app2", "path[0]": "p1", "path[1]": "app2", "path.basenameNormalized": "app2"}, }, @@ -301,7 +301,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, repoApps: []string{}, repoError: nil, - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: nil, }, { @@ -309,7 +309,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, repoApps: []string{}, repoError: errors.New("error"), - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: errors.New("error generating params from git: error getting directories from repo: error"), }, } @@ -370,7 +370,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { pathParamPrefix string repoApps []string repoError error - expected []map[string]interface{} + expected []map[string]any expectedError error }{ { @@ -383,9 +383,9 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { "p1/app4", }, repoError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "path": map[string]interface{}{ + "path": map[string]any{ "path": "app1", "basename": "app1", "basenameNormalized": "app1", @@ -395,7 +395,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, }, { - "path": map[string]interface{}{ + "path": map[string]any{ "path": "app2", "basename": "app2", "basenameNormalized": "app2", @@ -405,7 +405,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, }, { - "path": map[string]interface{}{ + "path": map[string]any{ "path": "app_3", "basename": "app_3", "basenameNormalized": "app-3", @@ -428,10 +428,10 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { "p1/app4", }, repoError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "myRepo": map[string]interface{}{ - "path": map[string]interface{}{ + "myRepo": map[string]any{ + "path": map[string]any{ "path": "app1", "basename": "app1", "basenameNormalized": "app1", @@ -442,8 +442,8 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, }, { - "myRepo": map[string]interface{}{ - "path": map[string]interface{}{ + "myRepo": map[string]any{ + "path": map[string]any{ "path": "app2", "basename": "app2", "basenameNormalized": "app2", @@ -454,8 +454,8 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, }, { - "myRepo": map[string]interface{}{ - "path": map[string]interface{}{ + "myRepo": map[string]any{ + "path": map[string]any{ "path": "app_3", "basename": "app_3", "basenameNormalized": "app-3", @@ -478,9 +478,9 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { "p1/p2/p3/app4", }, repoError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "path": map[string]interface{}{ + "path": map[string]any{ "path": "p1/app2", "basename": "app2", "basenameNormalized": "app2", @@ -491,7 +491,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, }, { - "path": map[string]interface{}{ + "path": map[string]any{ "path": "p1/p2/app3", "basename": "app3", "basenameNormalized": "app3", @@ -516,9 +516,9 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { "p2/app3", }, repoError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "path": map[string]interface{}{ + "path": map[string]any{ "path": "app1", "basename": "app1", "basenameNormalized": "app1", @@ -528,7 +528,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, }, { - "path": map[string]interface{}{ + "path": map[string]any{ "path": "app2", "basename": "app2", "basenameNormalized": "app2", @@ -538,7 +538,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, }, { - "path": map[string]interface{}{ + "path": map[string]any{ "path": "p2/app3", "basename": "app3", "basenameNormalized": "app3", @@ -562,9 +562,9 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { "p2/app3", }, repoError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "path": map[string]interface{}{ + "path": map[string]any{ "path": "app1", "basename": "app1", "basenameNormalized": "app1", @@ -574,7 +574,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, }, { - "path": map[string]interface{}{ + "path": map[string]any{ "path": "app2", "basename": "app2", "basenameNormalized": "app2", @@ -584,7 +584,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, }, { - "path": map[string]interface{}{ + "path": map[string]any{ "path": "p2/app3", "basename": "app3", "basenameNormalized": "app3", @@ -602,7 +602,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, repoApps: []string{}, repoError: nil, - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: nil, }, { @@ -610,7 +610,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, repoApps: []string{}, repoError: errors.New("error"), - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: errors.New("error generating params from git: error getting directories from repo: error"), }, } @@ -674,7 +674,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { // if repoPathsError is non-nil, the call to GetPaths(...) will return this error value repoPathsError error values map[string]string - expected []map[string]interface{} + expected []map[string]any expectedError error }{ { @@ -705,7 +705,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { }`), }, repoPathsError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "cluster.owner": "john.doe@example.com", "cluster.name": "production", @@ -769,7 +769,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { "aaa": "{{ cluster.owner }}", "no-op": "{{ this-does-not-exist }}", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "cluster.owner": "john.doe@example.com", "cluster.name": "production", @@ -810,7 +810,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, repoFileContents: map[string][]byte{}, repoPathsError: errors.New("paths error"), - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: errors.New("error generating params from git: paths error"), }, { @@ -820,7 +820,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { "cluster-config/production/config.json": []byte(`invalid json file`), }, repoPathsError: nil, - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: errors.New("error generating params from git: unable to process file 'cluster-config/production/config.json': unable to parse file: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go value of type map[string]interface {}"), }, { @@ -849,7 +849,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { ]`), }, repoPathsError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "cluster.owner": "john.doe@example.com", "cluster.name": "production", @@ -901,7 +901,7 @@ cluster: `), }, repoPathsError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "cluster.owner": "john.doe@example.com", "cluster.name": "production", @@ -949,7 +949,7 @@ cluster: address: https://kubernetes.default.svc`), }, repoPathsError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "cluster.owner": "john.doe@example.com", "cluster.name": "production", @@ -1038,7 +1038,7 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { repoFileContents map[string][]byte // if repoPathsError is non-nil, the call to GetPaths(...) will return this error value repoPathsError error - expected []map[string]interface{} + expected []map[string]any expectedError error }{ { @@ -1069,22 +1069,22 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { }`), }, repoPathsError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "cluster": map[string]interface{}{ + "cluster": map[string]any{ "owner": "john.doe@example.com", "name": "production", "address": "https://kubernetes.default.svc", }, "key1": "val1", - "key2": map[string]interface{}{ + "key2": map[string]any{ "key2_1": "val2_1", - "key2_2": map[string]interface{}{ + "key2_2": map[string]any{ "key2_2_1": "val2_2_1", }, }, "key3": float64(123), - "path": map[string]interface{}{ + "path": map[string]any{ "path": "cluster-config/production", "basename": "production", "filename": "config.json", @@ -1097,12 +1097,12 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { }, }, { - "cluster": map[string]interface{}{ + "cluster": map[string]any{ "owner": "foo.bar@example.com", "name": "staging", "address": "https://kubernetes.default.svc", }, - "path": map[string]interface{}{ + "path": map[string]any{ "path": "cluster-config/staging", "basename": "staging", "filename": "config.json", @@ -1122,7 +1122,7 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, repoFileContents: map[string][]byte{}, repoPathsError: errors.New("paths error"), - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: errors.New("error generating params from git: paths error"), }, { @@ -1132,7 +1132,7 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { "cluster-config/production/config.json": []byte(`invalid json file`), }, repoPathsError: nil, - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: errors.New("error generating params from git: unable to process file 'cluster-config/production/config.json': unable to parse file: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go value of type map[string]interface {}"), }, { @@ -1161,17 +1161,17 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { ]`), }, repoPathsError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "cluster": map[string]interface{}{ + "cluster": map[string]any{ "owner": "john.doe@example.com", "name": "production", "address": "https://kubernetes.default.svc", - "inner": map[string]interface{}{ + "inner": map[string]any{ "one": "two", }, }, - "path": map[string]interface{}{ + "path": map[string]any{ "path": "cluster-config/production", "basename": "production", "filename": "config.json", @@ -1184,12 +1184,12 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { }, }, { - "cluster": map[string]interface{}{ + "cluster": map[string]any{ "owner": "john.doe@example.com", "name": "staging", "address": "https://kubernetes.default.svc", }, - "path": map[string]interface{}{ + "path": map[string]any{ "path": "cluster-config/production", "basename": "production", "filename": "config.json", @@ -1227,21 +1227,21 @@ cluster: `), }, repoPathsError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "cluster": map[string]interface{}{ + "cluster": map[string]any{ "owner": "john.doe@example.com", "name": "production", "address": "https://kubernetes.default.svc", }, "key1": "val1", - "key2": map[string]interface{}{ + "key2": map[string]any{ "key2_1": "val2_1", - "key2_2": map[string]interface{}{ + "key2_2": map[string]any{ "key2_2_1": "val2_2_1", }, }, - "path": map[string]interface{}{ + "path": map[string]any{ "path": "cluster-config/production", "basename": "production", "filename": "config.yaml", @@ -1254,12 +1254,12 @@ cluster: }, }, { - "cluster": map[string]interface{}{ + "cluster": map[string]any{ "owner": "foo.bar@example.com", "name": "staging", "address": "https://kubernetes.default.svc", }, - "path": map[string]interface{}{ + "path": map[string]any{ "path": "cluster-config/staging", "basename": "staging", "filename": "config.yaml", @@ -1291,17 +1291,17 @@ cluster: address: https://kubernetes.default.svc`), }, repoPathsError: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { - "cluster": map[string]interface{}{ + "cluster": map[string]any{ "owner": "john.doe@example.com", "name": "production", "address": "https://kubernetes.default.svc", - "inner": map[string]interface{}{ + "inner": map[string]any{ "one": "two", }, }, - "path": map[string]interface{}{ + "path": map[string]any{ "path": "cluster-config/production", "basename": "production", "filename": "config.yaml", @@ -1314,12 +1314,12 @@ cluster: }, }, { - "cluster": map[string]interface{}{ + "cluster": map[string]any{ "owner": "john.doe@example.com", "name": "staging", "address": "https://kubernetes.default.svc", }, - "path": map[string]interface{}{ + "path": map[string]any{ "path": "cluster-config/production", "basename": "production", "filename": "config.yaml", @@ -1394,7 +1394,7 @@ func TestGitGenerator_GenerateParams(t *testing.T) { repoPathsError error repoFileContents map[string][]byte values map[string]string - expected []map[string]interface{} + expected []map[string]any expectedError error appset argoprojiov1alpha1.ApplicationSet callGetDirectories bool @@ -1430,7 +1430,7 @@ func TestGitGenerator_GenerateParams(t *testing.T) { }, }, callGetDirectories: true, - expected: []map[string]interface{}{{"path": "app1", "path.basename": "app1", "path.basenameNormalized": "app1", "path[0]": "app1", "values.foo": "bar"}}, + expected: []map[string]any{{"path": "app1", "path.basename": "app1", "path.basenameNormalized": "app1", "path[0]": "app1", "values.foo": "bar"}}, expectedError: nil, }, { @@ -1464,7 +1464,7 @@ func TestGitGenerator_GenerateParams(t *testing.T) { }, }, callGetDirectories: false, - expected: []map[string]interface{}{{"path": "app1", "path.basename": "app1", "path.basenameNormalized": "app1", "path[0]": "app1", "values.foo": "bar"}}, + expected: []map[string]any{{"path": "app1", "path.basename": "app1", "path.basenameNormalized": "app1", "path[0]": "app1", "values.foo": "bar"}}, expectedError: errors.New("error getting project project: appprojects.argoproj.io \"project\" not found"), }, } diff --git a/applicationset/generators/interface.go b/applicationset/generators/interface.go index a43e3e9b8222fa..6e56be37b2ace2 100644 --- a/applicationset/generators/interface.go +++ b/applicationset/generators/interface.go @@ -15,7 +15,7 @@ type Generator interface { // GenerateParams interprets the ApplicationSet and generates all relevant parameters for the application template. // The expected / desired list of parameters is returned, it then will be render and reconciled // against the current state of the Applications in the cluster. - GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, error) + GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]any, error) // GetRequeueAfter is the generator can controller the next reconciled loop // In case there is more then one generator the time will be the minimum of the times. diff --git a/applicationset/generators/list.go b/applicationset/generators/list.go index 83f364c1a2cb23..7ef4c73ce2a0d5 100644 --- a/applicationset/generators/list.go +++ b/applicationset/generators/list.go @@ -29,7 +29,7 @@ func (g *ListGenerator) GetTemplate(appSetGenerator *argoprojiov1alpha1.Applicat return &appSetGenerator.List.Template } -func (g *ListGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) { +func (g *ListGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) { if appSetGenerator == nil { return nil, EmptyAppSetGeneratorError } @@ -38,11 +38,11 @@ func (g *ListGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Appli return nil, EmptyAppSetGeneratorError } - res := make([]map[string]interface{}, len(appSetGenerator.List.Elements)) + res := make([]map[string]any, len(appSetGenerator.List.Elements)) for i, tmpItem := range appSetGenerator.List.Elements { - params := map[string]interface{}{} - var element map[string]interface{} + params := map[string]any{} + var element map[string]any err := json.Unmarshal(tmpItem.Raw, &element) if err != nil { return nil, fmt.Errorf("error unmarshling list element %w", err) @@ -53,7 +53,7 @@ func (g *ListGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Appli } else { for key, value := range element { if key == "values" { - values, ok := (value).(map[string]interface{}) + values, ok := (value).(map[string]any) if !ok { return nil, errors.New("error parsing values map") } @@ -78,7 +78,7 @@ func (g *ListGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Appli // Append elements from ElementsYaml to the response if len(appSetGenerator.List.ElementsYaml) > 0 { - var yamlElements []map[string]interface{} + var yamlElements []map[string]any err := yaml.Unmarshal([]byte(appSetGenerator.List.ElementsYaml), &yamlElements) if err != nil { return nil, fmt.Errorf("error unmarshling decoded ElementsYaml %w", err) diff --git a/applicationset/generators/list_test.go b/applicationset/generators/list_test.go index 5a3b1d88dd4f40..0869f3ea4dee67 100644 --- a/applicationset/generators/list_test.go +++ b/applicationset/generators/list_test.go @@ -14,14 +14,14 @@ import ( func TestGenerateListParams(t *testing.T) { testCases := []struct { elements []apiextensionsv1.JSON - expected []map[string]interface{} + expected []map[string]any }{ { elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}}, - expected: []map[string]interface{}{{"cluster": "cluster", "url": "url"}}, + expected: []map[string]any{{"cluster": "cluster", "url": "url"}}, }, { elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url","values":{"foo":"bar"}}`)}}, - expected: []map[string]interface{}{{"cluster": "cluster", "url": "url", "values.foo": "bar"}}, + expected: []map[string]any{{"cluster": "cluster", "url": "url", "values.foo": "bar"}}, }, } @@ -49,14 +49,14 @@ func TestGenerateListParams(t *testing.T) { func TestGenerateListParamsGoTemplate(t *testing.T) { testCases := []struct { elements []apiextensionsv1.JSON - expected []map[string]interface{} + expected []map[string]any }{ { elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}}, - expected: []map[string]interface{}{{"cluster": "cluster", "url": "url"}}, + expected: []map[string]any{{"cluster": "cluster", "url": "url"}}, }, { elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url","values":{"foo":"bar"}}`)}}, - expected: []map[string]interface{}{{"cluster": "cluster", "url": "url", "values": map[string]interface{}{"foo": "bar"}}}, + expected: []map[string]any{{"cluster": "cluster", "url": "url", "values": map[string]any{"foo": "bar"}}}, }, } diff --git a/applicationset/generators/matrix.go b/applicationset/generators/matrix.go index 80b0d8a7fc0525..d3edc0558a962e 100644 --- a/applicationset/generators/matrix.go +++ b/applicationset/generators/matrix.go @@ -34,7 +34,7 @@ func NewMatrixGenerator(supportedGenerators map[string]Generator) Generator { return m } -func (m *MatrixGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, error) { +func (m *MatrixGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]any, error) { if appSetGenerator.Matrix == nil { return nil, EmptyAppSetGeneratorError } @@ -47,7 +47,7 @@ func (m *MatrixGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.App return nil, ErrMoreThanTwoGenerators } - res := []map[string]interface{}{} + res := []map[string]any{} g0, err := m.getParams(appSetGenerator.Matrix.Generators[0], appSet, nil, client) if err != nil { @@ -60,7 +60,7 @@ func (m *MatrixGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.App } for _, b := range g1 { if appSet.Spec.GoTemplate { - tmp := map[string]interface{}{} + tmp := map[string]any{} if err := mergo.Merge(&tmp, b, mergo.WithOverride); err != nil { return nil, fmt.Errorf("failed to merge params from the second generator in the matrix generator with temp map: %w", err) } @@ -81,7 +81,7 @@ func (m *MatrixGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.App return res, nil } -func (m *MatrixGenerator) getParams(appSetBaseGenerator argoprojiov1alpha1.ApplicationSetNestedGenerator, appSet *argoprojiov1alpha1.ApplicationSet, params map[string]interface{}, client client.Client) ([]map[string]interface{}, error) { +func (m *MatrixGenerator) getParams(appSetBaseGenerator argoprojiov1alpha1.ApplicationSetNestedGenerator, appSet *argoprojiov1alpha1.ApplicationSet, params map[string]any, client client.Client) ([]map[string]any, error) { matrixGen, err := getMatrixGenerator(appSetBaseGenerator) if err != nil { return nil, err diff --git a/applicationset/generators/matrix_test.go b/applicationset/generators/matrix_test.go index dec0ab96b45c9d..88187705d4c331 100644 --- a/applicationset/generators/matrix_test.go +++ b/applicationset/generators/matrix_test.go @@ -38,7 +38,7 @@ func TestMatrixGenerate(t *testing.T) { name string baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator expectedErr error - expected []map[string]interface{} + expected []map[string]any }{ { name: "happy flow - generate params", @@ -50,7 +50,7 @@ func TestMatrixGenerate(t *testing.T) { List: listGenerator, }, }, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"path": "app1", "path.basename": "app1", "path.basenameNormalized": "app1", "cluster": "Cluster", "url": "Url", "templated": "test-app1"}, {"path": "app2", "path.basename": "app2", "path.basenameNormalized": "app2", "cluster": "Cluster", "url": "Url", "templated": "test-app2"}, }, @@ -75,7 +75,7 @@ func TestMatrixGenerate(t *testing.T) { }, }, }, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"a": "1", "b": "1"}, {"a": "1", "b": "2"}, {"a": "2", "b": "1"}, @@ -151,7 +151,7 @@ func TestMatrixGenerate(t *testing.T) { Git: g.Git, List: g.List, } - genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet, mock.Anything).Return([]map[string]interface{}{ + genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet, mock.Anything).Return([]map[string]any{ { "path": "app1", "path.basename": "app1", @@ -207,7 +207,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { name string baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator expectedErr error - expected []map[string]interface{} + expected []map[string]any }{ { name: "happy flow - generate params", @@ -219,7 +219,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { List: listGenerator, }, }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "path": map[string]string{ "path": "app1", @@ -260,7 +260,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { }, }, }, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"a": "1", "b": "1"}, {"a": "1", "b": "2"}, {"a": "2", "b": "1"}, @@ -285,7 +285,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { }, }, }, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"booleanFalse": false, "booleanTrue": true, "stringFalse": "false", "stringTrue": "true"}, }, }, @@ -360,7 +360,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { Git: g.Git, List: g.List, } - genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet, mock.Anything).Return([]map[string]interface{}{ + genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet, mock.Anything).Return([]map[string]any{ { "path": map[string]string{ "path": "app1", @@ -564,7 +564,7 @@ func TestInterpolatedMatrixGenerate(t *testing.T) { name string baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator expectedErr error - expected []map[string]interface{} + expected []map[string]any clientError bool }{ { @@ -577,7 +577,7 @@ func TestInterpolatedMatrixGenerate(t *testing.T) { Clusters: interpolatedClusterGenerator, }, }, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"path": "examples/git-generator-files-discovery/cluster-config/dev/config.json", "path.basename": "dev", "path.basenameNormalized": "dev", "name": "dev-01", "nameNormalized": "dev-01", "server": "https://dev-01.example.com", "metadata.labels.environment": "dev", "metadata.labels.argocd.argoproj.io/secret-type": "cluster", "project": ""}, {"path": "examples/git-generator-files-discovery/cluster-config/prod/config.json", "path.basename": "prod", "path.basenameNormalized": "prod", "name": "prod-01", "nameNormalized": "prod-01", "server": "https://prod-01.example.com", "metadata.labels.environment": "prod", "metadata.labels.argocd.argoproj.io/secret-type": "cluster", "project": ""}, }, @@ -652,7 +652,7 @@ func TestInterpolatedMatrixGenerate(t *testing.T) { Git: g.Git, Clusters: g.Clusters, } - genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet).Return([]map[string]interface{}{ + genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet).Return([]map[string]any{ { "path": "examples/git-generator-files-discovery/cluster-config/dev/config.json", "path.basename": "dev", @@ -711,7 +711,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { name string baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator expectedErr error - expected []map[string]interface{} + expected []map[string]any clientError bool }{ { @@ -724,7 +724,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { Clusters: interpolatedClusterGenerator, }, }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "path": map[string]string{ "path": "examples/git-generator-files-discovery/cluster-config/dev/config.json", @@ -735,7 +735,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { "nameNormalized": "dev-01", "server": "https://dev-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "environment": "dev", "argocd.argoproj.io/secret-type": "cluster", @@ -752,7 +752,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { "nameNormalized": "prod-01", "server": "https://prod-01.example.com", "project": "", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "labels": map[string]string{ "environment": "prod", "argocd.argoproj.io/secret-type": "cluster", @@ -835,7 +835,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { Git: g.Git, Clusters: g.Clusters, } - genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet).Return([]map[string]interface{}{ + genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet).Return([]map[string]any{ { "path": map[string]string{ "path": "examples/git-generator-files-discovery/cluster-config/dev/config.json", @@ -896,7 +896,7 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) { name string baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator expectedErr error - expected []map[string]interface{} + expected []map[string]any }{ { name: "happy flow - generate params", @@ -908,23 +908,23 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) { List: listGenerator, }, }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "chart": "a", "version": "1", - "foo": map[string]interface{}{ - "bar": []interface{}{ - map[string]interface{}{ + "foo": map[string]any{ + "bar": []any{ + map[string]any{ "chart": "a", "version": "1", }, - map[string]interface{}{ + map[string]any{ "chart": "b", "version": "2", }, }, }, - "path": map[string]interface{}{ + "path": map[string]any{ "basename": "dir", "basenameNormalized": "dir", "filename": "file_name.yaml", @@ -939,19 +939,19 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) { { "chart": "b", "version": "2", - "foo": map[string]interface{}{ - "bar": []interface{}{ - map[string]interface{}{ + "foo": map[string]any{ + "bar": []any{ + map[string]any{ "chart": "a", "version": "1", }, - map[string]interface{}{ + map[string]any{ "chart": "b", "version": "2", }, }, }, - "path": map[string]interface{}{ + "path": map[string]any{ "basename": "dir", "basenameNormalized": "dir", "filename": "file_name.yaml", @@ -987,19 +987,19 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) { List: g.List, } genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet).Return([]map[string]any{{ - "foo": map[string]interface{}{ - "bar": []interface{}{ - map[string]interface{}{ + "foo": map[string]any{ + "bar": []any{ + map[string]any{ "chart": "a", "version": "1", }, - map[string]interface{}{ + map[string]any{ "chart": "b", "version": "2", }, }, }, - "path": map[string]interface{}{ + "path": map[string]any{ "basename": "dir", "basenameNormalized": "dir", "filename": "file_name.yaml", @@ -1049,10 +1049,10 @@ func (g *generatorMock) GetTemplate(appSetGenerator *argoprojiov1alpha1.Applicat return args.Get(0).(*argoprojiov1alpha1.ApplicationSetTemplate) } -func (g *generatorMock) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) { +func (g *generatorMock) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) { args := g.Called(appSetGenerator, appSet) - return args.Get(0).([]map[string]interface{}), args.Error(1) + return args.Get(0).([]map[string]any), args.Error(1) } func (g *generatorMock) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) time.Duration { @@ -1075,7 +1075,7 @@ func TestGitGenerator_GenerateParams_list_x_git_matrix_generator(t *testing.T) { // of that bug. listGeneratorMock := &generatorMock{} - listGeneratorMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), mock.AnythingOfType("*v1alpha1.ApplicationSet"), mock.Anything).Return([]map[string]interface{}{ + listGeneratorMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), mock.AnythingOfType("*v1alpha1.ApplicationSet"), mock.Anything).Return([]map[string]any{ {"some": "value"}, }, nil) listGeneratorMock.On("GetTemplate", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator")).Return(&argoprojiov1alpha1.ApplicationSetTemplate{}) @@ -1126,7 +1126,7 @@ func TestGitGenerator_GenerateParams_list_x_git_matrix_generator(t *testing.T) { Matrix: matrixGeneratorSpec, }, &argoprojiov1alpha1.ApplicationSet{}, client) require.NoError(t, err) - assert.Equal(t, []map[string]interface{}{{ + assert.Equal(t, []map[string]any{{ "path": "some", "path.basename": "some", "path.basenameNormalized": "some", diff --git a/applicationset/generators/merge.go b/applicationset/generators/merge.go index a7de3a1f6ab4a9..2138d3599dc24d 100644 --- a/applicationset/generators/merge.go +++ b/applicationset/generators/merge.go @@ -38,8 +38,8 @@ func NewMergeGenerator(supportedGenerators map[string]Generator) Generator { // getParamSetsForAllGenerators generates params for each child generator in a MergeGenerator. Param sets are returned // in slices ordered according to the order of the given generators. -func (m *MergeGenerator) getParamSetsForAllGenerators(generators []argoprojiov1alpha1.ApplicationSetNestedGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([][]map[string]interface{}, error) { - var paramSets [][]map[string]interface{} +func (m *MergeGenerator) getParamSetsForAllGenerators(generators []argoprojiov1alpha1.ApplicationSetNestedGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([][]map[string]any, error) { + var paramSets [][]map[string]any for i, generator := range generators { generatorParamSets, err := m.getParams(generator, appSet, client) if err != nil { @@ -52,7 +52,7 @@ func (m *MergeGenerator) getParamSetsForAllGenerators(generators []argoprojiov1a } // GenerateParams gets the params produced by the MergeGenerator. -func (m *MergeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, error) { +func (m *MergeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]any, error) { if appSetGenerator.Merge == nil { return nil, EmptyAppSetGeneratorError } @@ -95,7 +95,7 @@ func (m *MergeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Appl } } - mergedParamSets := make([]map[string]interface{}, len(baseParamSetsByMergeKey)) + mergedParamSets := make([]map[string]any, len(baseParamSetsByMergeKey)) i := 0 for _, mergedParamSet := range baseParamSetsByMergeKey { mergedParamSets[i] = mergedParamSet @@ -108,7 +108,7 @@ func (m *MergeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Appl // getParamSetsByMergeKey converts the given list of parameter sets to a map of parameter sets where the key is the // unique key of the parameter set as determined by the given mergeKeys. If any two parameter sets share the same merge // key, getParamSetsByMergeKey will throw NonUniqueParamSets. -func getParamSetsByMergeKey(mergeKeys []string, paramSets []map[string]interface{}) (map[string]map[string]interface{}, error) { +func getParamSetsByMergeKey(mergeKeys []string, paramSets []map[string]any) (map[string]map[string]any, error) { if len(mergeKeys) < 1 { return nil, ErrNoMergeKeys } @@ -118,9 +118,9 @@ func getParamSetsByMergeKey(mergeKeys []string, paramSets []map[string]interface deDuplicatedMergeKeys[mergeKey] = false } - paramSetsByMergeKey := make(map[string]map[string]interface{}, len(paramSets)) + paramSetsByMergeKey := make(map[string]map[string]any, len(paramSets)) for _, paramSet := range paramSets { - paramSetKey := make(map[string]interface{}) + paramSetKey := make(map[string]any) for mergeKey := range deDuplicatedMergeKeys { paramSetKey[mergeKey] = paramSet[mergeKey] } @@ -139,7 +139,7 @@ func getParamSetsByMergeKey(mergeKeys []string, paramSets []map[string]interface } // getParams get the parameters generated by this generator. -func (m *MergeGenerator) getParams(appSetBaseGenerator argoprojiov1alpha1.ApplicationSetNestedGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, error) { +func (m *MergeGenerator) getParams(appSetBaseGenerator argoprojiov1alpha1.ApplicationSetNestedGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]any, error) { matrixGen, err := getMatrixGenerator(appSetBaseGenerator) if err != nil { return nil, err @@ -177,7 +177,7 @@ func (m *MergeGenerator) getParams(appSetBaseGenerator argoprojiov1alpha1.Applic m.supportedGenerators, argoprojiov1alpha1.ApplicationSetTemplate{}, appSet, - map[string]interface{}{}, client) + map[string]any{}, client) if err != nil { return nil, fmt.Errorf("child generator returned an error on parameter generation: %w", err) } diff --git a/applicationset/generators/merge_test.go b/applicationset/generators/merge_test.go index ad54debb37dce8..1b76d7ca2857e9 100644 --- a/applicationset/generators/merge_test.go +++ b/applicationset/generators/merge_test.go @@ -36,7 +36,7 @@ func getTerminalListGeneratorMultiple(jsons []string) argoprojiov1alpha1.Applica return generator } -func listOfMapsToSet(maps []map[string]interface{}) (map[string]bool, error) { +func listOfMapsToSet(maps []map[string]any) (map[string]bool, error) { set := make(map[string]bool, len(maps)) for _, paramMap := range maps { paramMapAsJson, err := json.Marshal(paramMap) @@ -55,7 +55,7 @@ func TestMergeGenerate(t *testing.T) { baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator mergeKeys []string expectedErr error - expected []map[string]interface{} + expected []map[string]any }{ { name: "no generators", @@ -79,7 +79,7 @@ func TestMergeGenerate(t *testing.T) { *getNestedListGenerator(`{"a": "3_1","b": "different","c": "3_3"}`), // gets ignored because its merge key value isn't in the base params set }, mergeKeys: []string{"b"}, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"a": "2_1", "b": "same", "c": "1_3"}, }, }, @@ -90,7 +90,7 @@ func TestMergeGenerate(t *testing.T) { *getNestedListGenerator(`{"a": "a"}`), }, mergeKeys: []string{"b"}, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"a": "a"}, }, }, @@ -101,7 +101,7 @@ func TestMergeGenerate(t *testing.T) { *getNestedListGenerator(`{"b": "b"}`), }, mergeKeys: []string{"b"}, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"a": "a"}, }, }, @@ -119,7 +119,7 @@ func TestMergeGenerate(t *testing.T) { *getNestedListGenerator(`{"a": "1", "b": "1", "c": "added"}`), }, mergeKeys: []string{"a", "b"}, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"a": "1", "b": "1", "c": "added"}, {"a": "1", "b": "2"}, {"a": "2", "b": "1"}, @@ -141,7 +141,7 @@ func TestMergeGenerate(t *testing.T) { *getNestedListGenerator(`{"a": "1", "b": "3", "d": "added"}`), }, mergeKeys: []string{"a", "b"}, - expected: []map[string]interface{}{ + expected: []map[string]any{ {"a": "1", "b": "3", "c": "added", "d": "added"}, {"a": "2", "b": "2"}, }, @@ -196,7 +196,7 @@ func TestMergeGenerate(t *testing.T) { } } -func toAPIExtensionsJSON(t *testing.T, g interface{}) *apiextensionsv1.JSON { +func toAPIExtensionsJSON(t *testing.T, g any) *apiextensionsv1.JSON { t.Helper() resVal, err := json.Marshal(g) if err != nil { @@ -213,9 +213,9 @@ func TestParamSetsAreUniqueByMergeKeys(t *testing.T) { testCases := []struct { name string mergeKeys []string - paramSets []map[string]interface{} + paramSets []map[string]any expectedErr error - expected map[string]map[string]interface{} + expected map[string]map[string]any }{ { name: "no merge keys", @@ -225,13 +225,13 @@ func TestParamSetsAreUniqueByMergeKeys(t *testing.T) { { name: "no paramSets", mergeKeys: []string{"key"}, - expected: make(map[string]map[string]interface{}), + expected: make(map[string]map[string]any), }, { name: "simple key, unique paramSets", mergeKeys: []string{"key"}, - paramSets: []map[string]interface{}{{"key": "a"}, {"key": "b"}}, - expected: map[string]map[string]interface{}{ + paramSets: []map[string]any{{"key": "a"}, {"key": "b"}}, + expected: map[string]map[string]any{ `{"key":"a"}`: {"key": "a"}, `{"key":"b"}`: {"key": "b"}, }, @@ -239,23 +239,23 @@ func TestParamSetsAreUniqueByMergeKeys(t *testing.T) { { name: "simple key object, unique paramSets", mergeKeys: []string{"key"}, - paramSets: []map[string]interface{}{{"key": map[string]interface{}{"hello": "world"}}, {"key": "b"}}, - expected: map[string]map[string]interface{}{ - `{"key":{"hello":"world"}}`: {"key": map[string]interface{}{"hello": "world"}}, + paramSets: []map[string]any{{"key": map[string]any{"hello": "world"}}, {"key": "b"}}, + expected: map[string]map[string]any{ + `{"key":{"hello":"world"}}`: {"key": map[string]any{"hello": "world"}}, `{"key":"b"}`: {"key": "b"}, }, }, { name: "simple key, non-unique paramSets", mergeKeys: []string{"key"}, - paramSets: []map[string]interface{}{{"key": "a"}, {"key": "b"}, {"key": "b"}}, + paramSets: []map[string]any{{"key": "a"}, {"key": "b"}, {"key": "b"}}, expectedErr: fmt.Errorf("%w. Duplicate key was %s", ErrNonUniqueParamSets, `{"key":"b"}`), }, { name: "simple key, duplicated key name, unique paramSets", mergeKeys: []string{"key", "key"}, - paramSets: []map[string]interface{}{{"key": "a"}, {"key": "b"}}, - expected: map[string]map[string]interface{}{ + paramSets: []map[string]any{{"key": "a"}, {"key": "b"}}, + expected: map[string]map[string]any{ `{"key":"a"}`: {"key": "a"}, `{"key":"b"}`: {"key": "b"}, }, @@ -263,18 +263,18 @@ func TestParamSetsAreUniqueByMergeKeys(t *testing.T) { { name: "simple key, duplicated key name, non-unique paramSets", mergeKeys: []string{"key", "key"}, - paramSets: []map[string]interface{}{{"key": "a"}, {"key": "b"}, {"key": "b"}}, + paramSets: []map[string]any{{"key": "a"}, {"key": "b"}, {"key": "b"}}, expectedErr: fmt.Errorf("%w. Duplicate key was %s", ErrNonUniqueParamSets, `{"key":"b"}`), }, { name: "compound key, unique paramSets", mergeKeys: []string{"key1", "key2"}, - paramSets: []map[string]interface{}{ + paramSets: []map[string]any{ {"key1": "a", "key2": "a"}, {"key1": "a", "key2": "b"}, {"key1": "b", "key2": "a"}, }, - expected: map[string]map[string]interface{}{ + expected: map[string]map[string]any{ `{"key1":"a","key2":"a"}`: {"key1": "a", "key2": "a"}, `{"key1":"a","key2":"b"}`: {"key1": "a", "key2": "b"}, `{"key1":"b","key2":"a"}`: {"key1": "b", "key2": "a"}, @@ -283,13 +283,13 @@ func TestParamSetsAreUniqueByMergeKeys(t *testing.T) { { name: "compound key object, unique paramSets", mergeKeys: []string{"key1", "key2"}, - paramSets: []map[string]interface{}{ - {"key1": "a", "key2": map[string]interface{}{"hello": "world"}}, + paramSets: []map[string]any{ + {"key1": "a", "key2": map[string]any{"hello": "world"}}, {"key1": "a", "key2": "b"}, {"key1": "b", "key2": "a"}, }, - expected: map[string]map[string]interface{}{ - `{"key1":"a","key2":{"hello":"world"}}`: {"key1": "a", "key2": map[string]interface{}{"hello": "world"}}, + expected: map[string]map[string]any{ + `{"key1":"a","key2":{"hello":"world"}}`: {"key1": "a", "key2": map[string]any{"hello": "world"}}, `{"key1":"a","key2":"b"}`: {"key1": "a", "key2": "b"}, `{"key1":"b","key2":"a"}`: {"key1": "b", "key2": "a"}, }, @@ -297,12 +297,12 @@ func TestParamSetsAreUniqueByMergeKeys(t *testing.T) { { name: "compound key, duplicate key names, unique paramSets", mergeKeys: []string{"key1", "key1", "key2"}, - paramSets: []map[string]interface{}{ + paramSets: []map[string]any{ {"key1": "a", "key2": "a"}, {"key1": "a", "key2": "b"}, {"key1": "b", "key2": "a"}, }, - expected: map[string]map[string]interface{}{ + expected: map[string]map[string]any{ `{"key1":"a","key2":"a"}`: {"key1": "a", "key2": "a"}, `{"key1":"a","key2":"b"}`: {"key1": "a", "key2": "b"}, `{"key1":"b","key2":"a"}`: {"key1": "b", "key2": "a"}, @@ -311,7 +311,7 @@ func TestParamSetsAreUniqueByMergeKeys(t *testing.T) { { name: "compound key, non-unique paramSets", mergeKeys: []string{"key1", "key2"}, - paramSets: []map[string]interface{}{ + paramSets: []map[string]any{ {"key1": "a", "key2": "a"}, {"key1": "a", "key2": "a"}, {"key1": "b", "key2": "a"}, @@ -321,7 +321,7 @@ func TestParamSetsAreUniqueByMergeKeys(t *testing.T) { { name: "compound key, duplicate key names, non-unique paramSets", mergeKeys: []string{"key1", "key1", "key2"}, - paramSets: []map[string]interface{}{ + paramSets: []map[string]any{ {"key1": "a", "key2": "a"}, {"key1": "a", "key2": "a"}, {"key1": "b", "key2": "a"}, diff --git a/applicationset/generators/plugin.go b/applicationset/generators/plugin.go index f2c7f1d4a97810..4bebfbd88eb07d 100644 --- a/applicationset/generators/plugin.go +++ b/applicationset/generators/plugin.go @@ -56,7 +56,7 @@ func (g *PluginGenerator) GetTemplate(appSetGenerator *argoprojiov1alpha1.Applic return &appSetGenerator.Plugin.Template } -func (g *PluginGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) { +func (g *PluginGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) { if appSetGenerator == nil { return nil, EmptyAppSetGeneratorError } @@ -113,11 +113,11 @@ func (g *PluginGenerator) getPluginFromGenerator(ctx context.Context, appSetName return pluginClient, nil } -func (g *PluginGenerator) generateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, objectsFound []map[string]interface{}, pluginParams argoprojiov1alpha1.PluginParameters, useGoTemplate bool) ([]map[string]interface{}, error) { - res := []map[string]interface{}{} +func (g *PluginGenerator) generateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, objectsFound []map[string]any, pluginParams argoprojiov1alpha1.PluginParameters, useGoTemplate bool) ([]map[string]any, error) { + res := []map[string]any{} for _, objectFound := range objectsFound { - params := map[string]interface{}{} + params := map[string]any{} if useGoTemplate { for k, v := range objectFound { @@ -133,7 +133,7 @@ func (g *PluginGenerator) generateParams(appSetGenerator *argoprojiov1alpha1.App } } - params["generator"] = map[string]interface{}{ + params["generator"] = map[string]any{ "input": map[string]argoprojiov1alpha1.PluginParameters{ "parameters": pluginParams, }, diff --git a/applicationset/generators/plugin_test.go b/applicationset/generators/plugin_test.go index 5d65554db4355d..d52e5c770b25d3 100644 --- a/applicationset/generators/plugin_test.go +++ b/applicationset/generators/plugin_test.go @@ -32,7 +32,7 @@ func TestPluginGenerateParams(t *testing.T) { inputParameters map[string]apiextensionsv1.JSON values map[string]string gotemplate bool - expected []map[string]interface{} + expected []map[string]any content []byte expectedError error }{ @@ -74,13 +74,13 @@ func TestPluginGenerateParams(t *testing.T) { "key3": 123 }] }}`), - expected: []map[string]interface{}{ + expected: []map[string]any{ { "key1": "val1", "key2.key2_1": "val2_1", "key2.key2_2.key2_2_1": "val2_2_1", "key3": "123", - "generator": map[string]interface{}{ + "generator": map[string]any{ "input": argoprojiov1alpha1.PluginInput{ Parameters: argoprojiov1alpha1.PluginParameters{ "pkey1": {Raw: []byte(`"val1"`)}, @@ -134,7 +134,7 @@ func TestPluginGenerateParams(t *testing.T) { "key3": 123 }] }}`), - expected: []map[string]interface{}{ + expected: []map[string]any{ { "key1": "val1", "key2.key2_1": "val2_1", @@ -142,7 +142,7 @@ func TestPluginGenerateParams(t *testing.T) { "key3": "123", "values.valuekey1": "valuevalue1", "values.valuekey2": "templated-val1", - "generator": map[string]interface{}{ + "generator": map[string]any{ "input": argoprojiov1alpha1.PluginInput{ Parameters: argoprojiov1alpha1.PluginParameters{ "pkey1": {Raw: []byte(`"val1"`)}, @@ -192,17 +192,17 @@ func TestPluginGenerateParams(t *testing.T) { "key3": 123 }] }}`), - expected: []map[string]interface{}{ + expected: []map[string]any{ { "key1": "val1", - "key2": map[string]interface{}{ + "key2": map[string]any{ "key2_1": "val2_1", - "key2_2": map[string]interface{}{ + "key2_2": map[string]any{ "key2_2_1": "val2_2_1", }, }, "key3": float64(123), - "generator": map[string]interface{}{ + "generator": map[string]any{ "input": argoprojiov1alpha1.PluginInput{ Parameters: argoprojiov1alpha1.PluginParameters{ "pkey1": {Raw: []byte(`"val1"`)}, @@ -251,14 +251,14 @@ func TestPluginGenerateParams(t *testing.T) { "key3": 123, "pkey2": "valplugin" }]}}`), - expected: []map[string]interface{}{ + expected: []map[string]any{ { "key1": "val1", "key2.key2_1": "val2_1", "key2.key2_2.key2_2_1": "val2_2_1", "key3": "123", "pkey2": "valplugin", - "generator": map[string]interface{}{ + "generator": map[string]any{ "input": argoprojiov1alpha1.PluginInput{ Parameters: argoprojiov1alpha1.PluginParameters{ "pkey1": {Raw: []byte(`"val1"`)}, @@ -305,14 +305,14 @@ func TestPluginGenerateParams(t *testing.T) { "key3": 123 }] }}`), - expected: []map[string]interface{}{ + expected: []map[string]any{ { "key1": "val1", "key2.key2_1": "val2_1", "key2.key2_2.key2_2_1": "val2_2_1", "key3": "123", - "generator": map[string]interface{}{ - "input": map[string]map[string]interface{}{ + "generator": map[string]any{ + "input": map[string]map[string]any{ "parameters": {}, }, }, @@ -344,7 +344,7 @@ func TestPluginGenerateParams(t *testing.T) { inputParameters: map[string]apiextensionsv1.JSON{}, gotemplate: false, content: []byte(`{"input": {"parameters": []}}`), - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: nil, }, { @@ -371,7 +371,7 @@ func TestPluginGenerateParams(t *testing.T) { inputParameters: map[string]apiextensionsv1.JSON{}, gotemplate: false, content: []byte(`wrong body ...`), - expected: []map[string]interface{}{}, + expected: []map[string]any{}, expectedError: errors.New("error listing params: error get api 'set': invalid character 'w' looking for beginning of value: wrong body ..."), }, { @@ -411,14 +411,14 @@ func TestPluginGenerateParams(t *testing.T) { "key3": 123, "pkey2": "valplugin" }]}}`), - expected: []map[string]interface{}{ + expected: []map[string]any{ { "key1": "val1", "key2.key2_1": "val2_1", "key2.key2_2.key2_2_1": "val2_2_1", "key3": "123", "pkey2": "valplugin", - "generator": map[string]interface{}{ + "generator": map[string]any{ "input": argoprojiov1alpha1.PluginInput{ Parameters: argoprojiov1alpha1.PluginParameters{ "pkey1": {Raw: []byte(`"val1"`)}, @@ -460,13 +460,13 @@ func TestPluginGenerateParams(t *testing.T) { "key3": 123 }] }}`), - expected: []map[string]interface{}{ + expected: []map[string]any{ { "key1": "val1", "key2.key2_1": "val2_1", "key2.key2_2.key2_2_1": "val2_2_1", "key3": "123", - "generator": map[string]interface{}{ + "generator": map[string]any{ "input": argoprojiov1alpha1.PluginInput{ Parameters: argoprojiov1alpha1.PluginParameters{ "pkey1": {Raw: []byte(`"val1"`)}, @@ -507,13 +507,13 @@ func TestPluginGenerateParams(t *testing.T) { "key3": 123 }] }}`), - expected: []map[string]interface{}{ + expected: []map[string]any{ { "key1": "val1", "key2.key2_1": "val2_1", "key2.key2_2.key2_2_1": "val2_2_1", "key3": "123", - "generator": map[string]interface{}{ + "generator": map[string]any{ "input": argoprojiov1alpha1.PluginInput{ Parameters: argoprojiov1alpha1.PluginParameters{ "pkey1": {Raw: []byte(`"val1"`)}, @@ -562,13 +562,13 @@ func TestPluginGenerateParams(t *testing.T) { "key3": 123 }] }}`), - expected: []map[string]interface{}{ + expected: []map[string]any{ { "key1": "val1", "key2.key2_1": "val2_1", "key2.key2_2.key2_2_1": "val2_2_1", "key3": "123", - "generator": map[string]interface{}{ + "generator": map[string]any{ "input": argoprojiov1alpha1.PluginInput{ Parameters: argoprojiov1alpha1.PluginParameters{ "pkey1": {Raw: []byte(`"val1"`)}, @@ -609,13 +609,13 @@ func TestPluginGenerateParams(t *testing.T) { "key3": 123 }] }}`), - expected: []map[string]interface{}{ + expected: []map[string]any{ { "key1": "val1", "key2.key2_1": "val2_1", "key2.key2_2.key2_2_1": "val2_2_1", "key3": "123", - "generator": map[string]interface{}{ + "generator": map[string]any{ "input": argoprojiov1alpha1.PluginInput{ Parameters: argoprojiov1alpha1.PluginParameters{ "pkey1": {Raw: []byte(`"val1"`)}, diff --git a/applicationset/generators/pull_request.go b/applicationset/generators/pull_request.go index c1fd1a1c5ebc42..fb9c46ee0f9ba9 100644 --- a/applicationset/generators/pull_request.go +++ b/applicationset/generators/pull_request.go @@ -51,7 +51,7 @@ func (g *PullRequestGenerator) GetTemplate(appSetGenerator *argoprojiov1alpha1.A return &appSetGenerator.PullRequest.Template } -func (g *PullRequestGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) { +func (g *PullRequestGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) { if appSetGenerator == nil { return nil, EmptyAppSetGeneratorError } @@ -70,7 +70,7 @@ func (g *PullRequestGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha if err != nil { return nil, fmt.Errorf("error listing repos: %w", err) } - params := make([]map[string]interface{}, 0, len(pulls)) + params := make([]map[string]any, 0, len(pulls)) // In order to follow the DNS label standard as defined in RFC 1123, // we need to limit the 'branch' to 50 to give room to append/suffix-ing it @@ -96,7 +96,7 @@ func (g *PullRequestGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha shortSHALength7 = len(pull.HeadSHA) } - paramMap := map[string]interface{}{ + paramMap := map[string]any{ "number": strconv.Itoa(pull.Number), "title": pull.Title, "branch": pull.Branch, diff --git a/applicationset/generators/pull_request_test.go b/applicationset/generators/pull_request_test.go index 875c6cf73787e1..557f419672b5d8 100644 --- a/applicationset/generators/pull_request_test.go +++ b/applicationset/generators/pull_request_test.go @@ -17,7 +17,7 @@ func TestPullRequestGithubGenerateParams(t *testing.T) { ctx := context.Background() cases := []struct { selectFunc func(context.Context, *argoprojiov1alpha1.PullRequestGenerator, *argoprojiov1alpha1.ApplicationSet) (pullrequest.PullRequestService, error) - expected []map[string]interface{} + expected []map[string]any expectedErr error applicationSet argoprojiov1alpha1.ApplicationSet }{ @@ -38,7 +38,7 @@ func TestPullRequestGithubGenerateParams(t *testing.T) { nil, ) }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "number": "1", "title": "title1", @@ -71,7 +71,7 @@ func TestPullRequestGithubGenerateParams(t *testing.T) { nil, ) }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "number": "2", "title": "title2", @@ -104,7 +104,7 @@ func TestPullRequestGithubGenerateParams(t *testing.T) { nil, ) }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "number": "1", "title": "title1", @@ -149,7 +149,7 @@ func TestPullRequestGithubGenerateParams(t *testing.T) { nil, ) }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "number": "1", "title": "title1", @@ -190,7 +190,7 @@ func TestPullRequestGithubGenerateParams(t *testing.T) { nil, ) }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "number": "1", "title": "title1", diff --git a/applicationset/generators/scm_provider.go b/applicationset/generators/scm_provider.go index cf476ceeba51d2..3bbc8664c70161 100644 --- a/applicationset/generators/scm_provider.go +++ b/applicationset/generators/scm_provider.go @@ -116,7 +116,7 @@ func ScmProviderAllowed(applicationSetInfo *argoprojiov1alpha1.ApplicationSet, g return NewErrDisallowedSCMProvider(url, allowedScmProviders) } -func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) { +func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) { if appSetGenerator == nil { return nil, EmptyAppSetGeneratorError } @@ -234,7 +234,7 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha if err != nil { return nil, fmt.Errorf("error listing repos: %w", err) } - paramsArray := make([]map[string]interface{}, 0, len(repos)) + paramsArray := make([]map[string]any, 0, len(repos)) var shortSHALength int var shortSHALength7 int for _, repo := range repos { @@ -248,7 +248,7 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha shortSHALength7 = len(repo.SHA) } - params := map[string]interface{}{ + params := map[string]any{ "organization": repo.Organization, "repository": repo.Repository, "url": repo.URL, diff --git a/applicationset/generators/scm_provider_test.go b/applicationset/generators/scm_provider_test.go index a52f7e8159b863..f5ee8293e011df 100644 --- a/applicationset/generators/scm_provider_test.go +++ b/applicationset/generators/scm_provider_test.go @@ -16,7 +16,7 @@ func TestSCMProviderGenerateParams(t *testing.T) { name string repos []*scm_provider.Repository values map[string]string - expected []map[string]interface{} + expected []map[string]any expectedError error }{ { @@ -38,7 +38,7 @@ func TestSCMProviderGenerateParams(t *testing.T) { SHA: "59d0", }, }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "organization": "myorg", "repository": "repo1", @@ -79,7 +79,7 @@ func TestSCMProviderGenerateParams(t *testing.T) { "foo": "bar", "should_i_force_push_to": "{{ branch }}?", }, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "organization": "myorg", "repository": "repo3", diff --git a/applicationset/generators/value_interpolation.go b/applicationset/generators/value_interpolation.go index a87e1fab9bdb1a..a7b3f25b806b61 100644 --- a/applicationset/generators/value_interpolation.go +++ b/applicationset/generators/value_interpolation.go @@ -4,11 +4,11 @@ import ( "fmt" ) -func appendTemplatedValues(values map[string]string, params map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) error { +func appendTemplatedValues(values map[string]string, params map[string]any, useGoTemplate bool, goTemplateOptions []string) error { // We create a local map to ensure that we do not fall victim to a billion-laughs attack. We iterate through the // cluster values map and only replace values in said map if it has already been allowlisted in the params map. // Once we iterate through all the cluster values we can then safely merge the `tmp` map into the main params map. - tmp := map[string]interface{}{} + tmp := map[string]any{} for key, value := range values { result, err := replaceTemplatedString(value, params, useGoTemplate, goTemplateOptions) @@ -33,7 +33,7 @@ func appendTemplatedValues(values map[string]string, params map[string]interface return nil } -func replaceTemplatedString(value string, params map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (string, error) { +func replaceTemplatedString(value string, params map[string]any, useGoTemplate bool, goTemplateOptions []string) (string, error) { replacedTmplStr, err := render.Replace(value, params, useGoTemplate, goTemplateOptions) if err != nil { return "", fmt.Errorf("failed to replace templated string with rendered values: %w", err) diff --git a/applicationset/generators/value_interpolation_test.go b/applicationset/generators/value_interpolation_test.go index 5b490233d5d7e8..5de30be130672f 100644 --- a/applicationset/generators/value_interpolation_test.go +++ b/applicationset/generators/value_interpolation_test.go @@ -11,18 +11,18 @@ func TestValueInterpolation(t *testing.T) { testCases := []struct { name string values map[string]string - params map[string]interface{} - expected map[string]interface{} + params map[string]any + expected map[string]any }{ { name: "Simple interpolation", values: map[string]string{ "hello": "{{ world }}", }, - params: map[string]interface{}{ + params: map[string]any{ "world": "world!", }, - expected: map[string]interface{}{ + expected: map[string]any{ "world": "world!", "values.hello": "world!", }, @@ -32,8 +32,8 @@ func TestValueInterpolation(t *testing.T) { values: map[string]string{ "non-existent": "{{ non-existent }}", }, - params: map[string]interface{}{}, - expected: map[string]interface{}{ + params: map[string]any{}, + expected: map[string]any{ "values.non-existent": "{{ non-existent }}", }, }, @@ -44,8 +44,8 @@ func TestValueInterpolation(t *testing.T) { "lol2": "{{values.lol1}}{{values.lol1}}", "lol3": "{{values.lol2}}{{values.lol2}}{{values.lol2}}", }, - params: map[string]interface{}{}, - expected: map[string]interface{}{ + params: map[string]any{}, + expected: map[string]any{ "values.lol1": "lol", "values.lol2": "{{values.lol1}}{{values.lol1}}", "values.lol3": "{{values.lol2}}{{values.lol2}}{{values.lol2}}", @@ -66,18 +66,18 @@ func TestValueInterpolationWithGoTemplating(t *testing.T) { testCases := []struct { name string values map[string]string - params map[string]interface{} - expected map[string]interface{} + params map[string]any + expected map[string]any }{ { name: "Simple interpolation", values: map[string]string{ "hello": "{{ .world }}", }, - params: map[string]interface{}{ + params: map[string]any{ "world": "world!", }, - expected: map[string]interface{}{ + expected: map[string]any{ "world": "world!", "values": map[string]string{ "hello": "world!", @@ -89,8 +89,8 @@ func TestValueInterpolationWithGoTemplating(t *testing.T) { values: map[string]string{ "non_existent": "{{ default \"bar\" .non_existent }}", }, - params: map[string]interface{}{}, - expected: map[string]interface{}{ + params: map[string]any{}, + expected: map[string]any{ "values": map[string]string{ "non_existent": "bar", }, @@ -103,8 +103,8 @@ func TestValueInterpolationWithGoTemplating(t *testing.T) { "lol2": "{{.values.lol1}}{{.values.lol1}}", "lol3": "{{.values.lol2}}{{.values.lol2}}{{.values.lol2}}", }, - params: map[string]interface{}{}, - expected: map[string]interface{}{ + params: map[string]any{}, + expected: map[string]any{ "values": map[string]string{ "lol1": "lol", "lol2": "", diff --git a/applicationset/services/internal/http/client.go b/applicationset/services/internal/http/client.go index 1a4a86285a183e..07e3565eeb75d8 100644 --- a/applicationset/services/internal/http/client.go +++ b/applicationset/services/internal/http/client.go @@ -65,7 +65,7 @@ func newClient(baseURL string, options ...ClientOptionFunc) (*Client, error) { return c, nil } -func (c *Client) NewRequest(method, path string, body interface{}, options []ClientOptionFunc) (*http.Request, error) { +func (c *Client) NewRequest(method, path string, body any, options []ClientOptionFunc) (*http.Request, error) { // Make sure the given URL end with a slash if !strings.HasSuffix(c.baseURL, "/") { c.baseURL += "/" @@ -102,7 +102,7 @@ func (c *Client) NewRequest(method, path string, body interface{}, options []Cli return req, nil } -func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error) { +func (c *Client) Do(ctx context.Context, req *http.Request, v any) (*http.Response, error) { resp, err := c.client.Do(req) if err != nil { return nil, err @@ -143,7 +143,7 @@ func CheckResponse(resp *http.Response) error { return fmt.Errorf("API error with status code %d: %w", resp.StatusCode, err) } - var raw map[string]interface{} + var raw map[string]any if err := json.Unmarshal(data, &raw); err != nil { return fmt.Errorf("API error with status code %d: %s", resp.StatusCode, string(data)) } diff --git a/applicationset/services/internal/http/client_test.go b/applicationset/services/internal/http/client_test.go index a38e17474e122c..2799b99668ea5a 100644 --- a/applicationset/services/internal/http/client_test.go +++ b/applicationset/services/internal/http/client_test.go @@ -38,7 +38,7 @@ func TestClientDo(t *testing.T) { content []byte fakeServer *httptest.Server clientOptionFns []ClientOptionFunc - expected []map[string]interface{} + expected []map[string]any expectedCode int expectedError error }{ @@ -65,12 +65,12 @@ func TestClientDo(t *testing.T) { } })), clientOptionFns: nil, - expected: []map[string]interface{}{ + expected: []map[string]any{ { "key1": "val1", - "key2": map[string]interface{}{ + "key2": map[string]any{ "key2_1": "val2_1", - "key2_2": map[string]interface{}{ + "key2_2": map[string]any{ "key2_2_1": "val2_2_1", }, }, @@ -108,7 +108,7 @@ func TestClientDo(t *testing.T) { } })), clientOptionFns: nil, - expected: []map[string]interface{}(nil), + expected: []map[string]any(nil), expectedCode: http.StatusUnauthorized, expectedError: errors.New("API error with status code 401: "), }, @@ -123,7 +123,7 @@ func TestClientDo(t *testing.T) { req, err := client.NewRequest("POST", "", cc.params, nil) require.NoError(t, err, "NewRequest returned unexpected error") - var data []map[string]interface{} + var data []map[string]any resp, err := client.Do(ctx, req, &data) diff --git a/applicationset/services/plugin/plugin_service.go b/applicationset/services/plugin/plugin_service.go index 175683c434d72a..4064718c946625 100644 --- a/applicationset/services/plugin/plugin_service.go +++ b/applicationset/services/plugin/plugin_service.go @@ -20,7 +20,7 @@ type ServiceRequest struct { type Output struct { // Parameters is the list of parameter sets returned by the plugin. - Parameters []map[string]interface{} `json:"parameters"` + Parameters []map[string]any `json:"parameters"` } // ServiceResponse is the response object returned by the plugin service. diff --git a/applicationset/services/pull_request/bitbucket_cloud.go b/applicationset/services/pull_request/bitbucket_cloud.go index a9b2daf7be43bf..86d3c98129046e 100644 --- a/applicationset/services/pull_request/bitbucket_cloud.go +++ b/applicationset/services/pull_request/bitbucket_cloud.go @@ -113,12 +113,12 @@ func (b *BitbucketCloudService) List(_ context.Context) ([]*PullRequest, error) return nil, fmt.Errorf("error listing pull requests for %s/%s: %w", b.owner, b.repositorySlug, err) } - resp, ok := response.(map[string]interface{}) + resp, ok := response.(map[string]any) if !ok { return nil, errors.New("unknown type returned from bitbucket pull requests") } - repoArray, ok := resp["values"].([]interface{}) + repoArray, ok := resp["values"].([]any) if !ok { return nil, errors.New("unknown type returned from response values") } diff --git a/applicationset/services/pull_request/bitbucket_server.go b/applicationset/services/pull_request/bitbucket_server.go index 1f2be70edb428b..5ee1ea303fc797 100644 --- a/applicationset/services/pull_request/bitbucket_server.go +++ b/applicationset/services/pull_request/bitbucket_server.go @@ -64,7 +64,7 @@ func newBitbucketService(ctx context.Context, bitbucketConfig *bitbucketv1.Confi } func (b *BitbucketService) List(_ context.Context) ([]*PullRequest, error) { - paged := map[string]interface{}{ + paged := map[string]any{ "limit": 100, } diff --git a/applicationset/services/scm_provider/bitbucket_cloud.go b/applicationset/services/scm_provider/bitbucket_cloud.go index d01ddbb6185ddc..7b40d99e8c1039 100644 --- a/applicationset/services/scm_provider/bitbucket_cloud.go +++ b/applicationset/services/scm_provider/bitbucket_cloud.go @@ -154,12 +154,12 @@ func (g *BitBucketCloudProvider) listBranches(repo *Repository) ([]bitbucket.Rep } func findCloneURL(cloneProtocol string, repo *bitbucket.Repository) (*string, error) { - cloneLinks, ok := repo.Links["clone"].([]interface{}) + cloneLinks, ok := repo.Links["clone"].([]any) if !ok { return nil, errors.New("unknown type returned from repo links") } for _, link := range cloneLinks { - linkEntry, ok := link.(map[string]interface{}) + linkEntry, ok := link.(map[string]any) if !ok { return nil, errors.New("unknown type returned from clone link") } diff --git a/applicationset/services/scm_provider/bitbucket_server.go b/applicationset/services/scm_provider/bitbucket_server.go index 79baa727a14b01..f82ac37ab711d1 100644 --- a/applicationset/services/scm_provider/bitbucket_server.go +++ b/applicationset/services/scm_provider/bitbucket_server.go @@ -64,7 +64,7 @@ func newBitbucketServerProvider(ctx context.Context, bitbucketConfig *bitbucketv } func (b *BitbucketServerProvider) ListRepos(_ context.Context, cloneProtocol string) ([]*Repository, error) { - paged := map[string]interface{}{ + paged := map[string]any{ "limit": 100, } repos := []*Repository{} @@ -122,7 +122,7 @@ func (b *BitbucketServerProvider) ListRepos(_ context.Context, cloneProtocol str } func (b *BitbucketServerProvider) RepoHasPath(_ context.Context, repo *Repository, path string) (bool, error) { - opts := map[string]interface{}{ + opts := map[string]any{ "limit": 100, "at": repo.Branch, "type_": true, @@ -174,7 +174,7 @@ func (b *BitbucketServerProvider) listBranches(repo *Repository) ([]bitbucketv1. } // Otherwise, scrape the GetBranches API. branches := []bitbucketv1.Branch{} - paged := map[string]interface{}{ + paged := map[string]any{ "limit": 100, } for { diff --git a/applicationset/services/scm_provider/types.go b/applicationset/services/scm_provider/types.go index dde6db03c7c27e..b8390883925fba 100644 --- a/applicationset/services/scm_provider/types.go +++ b/applicationset/services/scm_provider/types.go @@ -13,7 +13,7 @@ type Repository struct { Branch string SHA string Labels []string - RepositoryId interface{} + RepositoryId any } type SCMProviderService interface { diff --git a/applicationset/utils/createOrUpdate.go b/applicationset/utils/createOrUpdate.go index 8cde366e2dfd83..c3ed07fc0bec78 100644 --- a/applicationset/utils/createOrUpdate.go +++ b/applicationset/utils/createOrUpdate.go @@ -115,7 +115,7 @@ func LogPatch(logCtx *log.Entry, patch client.Patch, obj *argov1alpha1.Applicati logCtx.Errorf("failed to generate patch: %v", err) } // Get the patch as a plain object so it is easier to work with in json logs. - var patchObj map[string]interface{} + var patchObj map[string]any err = json.Unmarshal(patchBytes, &patchObj) if err != nil { logCtx.Errorf("failed to unmarshal patch: %v", err) diff --git a/applicationset/utils/map.go b/applicationset/utils/map.go index 0d71f20b50a831..42cd39b715f4f4 100644 --- a/applicationset/utils/map.go +++ b/applicationset/utils/map.go @@ -4,7 +4,7 @@ import ( "fmt" ) -func ConvertToMapStringString(mapStringInterface map[string]interface{}) map[string]string { +func ConvertToMapStringString(mapStringInterface map[string]any) map[string]string { mapStringString := make(map[string]string, len(mapStringInterface)) for key, value := range mapStringInterface { @@ -13,8 +13,8 @@ func ConvertToMapStringString(mapStringInterface map[string]interface{}) map[str return mapStringString } -func ConvertToMapStringInterface(mapStringString map[string]string) map[string]interface{} { - mapStringInterface := make(map[string]interface{}, len(mapStringString)) +func ConvertToMapStringInterface(mapStringString map[string]string) map[string]any { + mapStringInterface := make(map[string]any, len(mapStringString)) for key, value := range mapStringString { mapStringInterface[key] = value @@ -22,7 +22,7 @@ func ConvertToMapStringInterface(mapStringString map[string]string) map[string]i return mapStringInterface } -func CombineStringMaps(aSI map[string]interface{}, bSI map[string]interface{}) (map[string]string, error) { +func CombineStringMaps(aSI map[string]any, bSI map[string]any) (map[string]string, error) { a := ConvertToMapStringString(aSI) b := ConvertToMapStringString(bSI) @@ -44,7 +44,7 @@ func CombineStringMaps(aSI map[string]interface{}, bSI map[string]interface{}) ( } // CombineStringMapsAllowDuplicates merges two maps. Where there are duplicates, take the latter map's value. -func CombineStringMapsAllowDuplicates(aSI map[string]interface{}, bSI map[string]interface{}) (map[string]string, error) { +func CombineStringMapsAllowDuplicates(aSI map[string]any, bSI map[string]any) (map[string]string, error) { a := ConvertToMapStringString(aSI) b := ConvertToMapStringString(bSI) diff --git a/applicationset/utils/map_test.go b/applicationset/utils/map_test.go index be033175d61f9a..679ea356cca2cd 100644 --- a/applicationset/utils/map_test.go +++ b/applicationset/utils/map_test.go @@ -11,29 +11,29 @@ import ( func TestCombineStringMaps(t *testing.T) { testCases := []struct { name string - left map[string]interface{} - right map[string]interface{} + left map[string]any + right map[string]any expected map[string]string expectedErr error }{ { name: "combines the maps", - left: map[string]interface{}{"foo": "bar"}, - right: map[string]interface{}{"a": "b"}, + left: map[string]any{"foo": "bar"}, + right: map[string]any{"a": "b"}, expected: map[string]string{"a": "b", "foo": "bar"}, expectedErr: nil, }, { name: "fails if keys are the same but value isn't", - left: map[string]interface{}{"foo": "bar", "a": "fail"}, - right: map[string]interface{}{"a": "b", "c": "d"}, + left: map[string]any{"foo": "bar", "a": "fail"}, + right: map[string]any{"a": "b", "c": "d"}, expected: map[string]string{"a": "b", "foo": "bar"}, expectedErr: errors.New("found duplicate key a with different value, a: fail ,b: b"), }, { name: "pass if keys & values are the same", - left: map[string]interface{}{"foo": "bar", "a": "b"}, - right: map[string]interface{}{"a": "b", "c": "d"}, + left: map[string]any{"foo": "bar", "a": "b"}, + right: map[string]any{"a": "b", "c": "d"}, expected: map[string]string{"a": "b", "c": "d", "foo": "bar"}, expectedErr: nil, }, diff --git a/applicationset/utils/template_functions.go b/applicationset/utils/template_functions.go index 84ab870404f1a7..f0985cf9de2bce 100644 --- a/applicationset/utils/template_functions.go +++ b/applicationset/utils/template_functions.go @@ -29,7 +29,7 @@ func SanitizeName(name string) string { // always return a string, even on marshal error (empty string). // // This is designed to be called from a template. -func toYAML(v interface{}) (string, error) { +func toYAML(v any) (string, error) { data, err := yaml.Marshal(v) if err != nil { // Swallow errors inside of a template. @@ -39,14 +39,14 @@ func toYAML(v interface{}) (string, error) { } // This has been copied from helm and may be removed as soon as it is retrofited in sprig -// fromYAML converts a YAML document into a map[string]interface{}. +// fromYAML converts a YAML document into a map[string]any. // // This is not a general-purpose YAML parser, and will not parse all valid // YAML documents. Additionally, because its intended use is within templates // it tolerates errors. It will insert the returned error message string into // m["Error"] in the returned map. -func fromYAML(str string) (map[string]interface{}, error) { - m := map[string]interface{}{} +func fromYAML(str string) (map[string]any, error) { + m := map[string]any{} if err := yaml.Unmarshal([]byte(str), &m); err != nil { return nil, err @@ -55,14 +55,14 @@ func fromYAML(str string) (map[string]interface{}, error) { } // This has been copied from helm and may be removed as soon as it is retrofited in sprig -// fromYAMLArray converts a YAML array into a []interface{}. +// fromYAMLArray converts a YAML array into a []any. // // This is not a general-purpose YAML parser, and will not parse all valid // YAML documents. Additionally, because its intended use is within templates // it tolerates errors. It will insert the returned error message string as // the first and only item in the returned array. -func fromYAMLArray(str string) ([]interface{}, error) { - a := []interface{}{} +func fromYAMLArray(str string) ([]any, error) { + a := []any{} if err := yaml.Unmarshal([]byte(str), &a); err != nil { return nil, err diff --git a/applicationset/utils/utils.go b/applicationset/utils/utils.go index 4bfca4971bada5..51b7ae51c22e31 100644 --- a/applicationset/utils/utils.go +++ b/applicationset/utils/utils.go @@ -42,8 +42,8 @@ func init() { } type Renderer interface { - RenderTemplateParams(tmpl *argoappsv1.Application, syncPolicy *argoappsv1.ApplicationSetSyncPolicy, params map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (*argoappsv1.Application, error) - Replace(tmpl string, replaceMap map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (string, error) + RenderTemplateParams(tmpl *argoappsv1.Application, syncPolicy *argoappsv1.ApplicationSetSyncPolicy, params map[string]any, useGoTemplate bool, goTemplateOptions []string) (*argoappsv1.Application, error) + Replace(tmpl string, replaceMap map[string]any, useGoTemplate bool, goTemplateOptions []string) (string, error) } type Render struct{} @@ -81,7 +81,7 @@ func ConvertYAMLToJSON(str string) (string, error) { // This function is in charge of searching all String fields of the object recursively and apply templating // thanks to https://gist.github.com/randallmlough/1fd78ec8a1034916ca52281e3b886dc7 -func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) error { +func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[string]any, useGoTemplate bool, goTemplateOptions []string) error { switch original.Kind() { // The first cases handle nested structures and translate them recursively // If it is a pointer we need to unwrap and call once again @@ -137,7 +137,7 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri if currentType == "time.Time" { copy.Field(i).Set(original.Field(i)) } else if currentType == "Raw.k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" || currentType == "Raw.k8s.io/apimachinery/pkg/runtime" { - var unmarshaled interface{} + var unmarshaled any originalBytes := original.Field(i).Bytes() convertedToJson, err := ConvertYAMLToJSON(string(originalBytes)) if err != nil { @@ -153,7 +153,7 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri if err != nil { return fmt.Errorf("failed to deeply replace JSON field contents: %w", err) } - jsonCopyInterface := jsonCopy.Interface().(*interface{}) + jsonCopyInterface := jsonCopy.Interface().(*any) data, err := json.Marshal(jsonCopyInterface) if err != nil { return fmt.Errorf("failed to marshal templated JSON field: %w", err) @@ -250,7 +250,7 @@ func isNillable(v reflect.Value) bool { return false } -func (r *Render) RenderTemplateParams(tmpl *argoappsv1.Application, syncPolicy *argoappsv1.ApplicationSetSyncPolicy, params map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (*argoappsv1.Application, error) { +func (r *Render) RenderTemplateParams(tmpl *argoappsv1.Application, syncPolicy *argoappsv1.ApplicationSetSyncPolicy, params map[string]any, useGoTemplate bool, goTemplateOptions []string) (*argoappsv1.Application, error) { if tmpl == nil { return nil, errors.New("application template is empty") } @@ -281,7 +281,7 @@ func (r *Render) RenderTemplateParams(tmpl *argoappsv1.Application, syncPolicy * return replacedTmpl, nil } -func (r *Render) RenderGeneratorParams(gen *argoappsv1.ApplicationSetGenerator, params map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (*argoappsv1.ApplicationSetGenerator, error) { +func (r *Render) RenderGeneratorParams(gen *argoappsv1.ApplicationSetGenerator, params map[string]any, useGoTemplate bool, goTemplateOptions []string) (*argoappsv1.ApplicationSetGenerator, error) { if gen == nil { return nil, errors.New("generator is empty") } @@ -306,7 +306,7 @@ var isTemplatedRegex = regexp.MustCompile(".*{{.*}}.*") // Replace executes basic string substitution of a template with replacement values. // remaining in the substituted template. -func (r *Render) Replace(tmpl string, replaceMap map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (string, error) { +func (r *Render) Replace(tmpl string, replaceMap map[string]any, useGoTemplate bool, goTemplateOptions []string) (string, error) { if useGoTemplate { template, err := template.New("").Funcs(sprigFuncMap).Parse(tmpl) if err != nil { @@ -395,20 +395,20 @@ func invalidGenerators(applicationSetInfo *argoappsv1.ApplicationSet) (bool, map func addInvalidGeneratorNames(names map[string]bool, applicationSetInfo *argoappsv1.ApplicationSet, index int) { // The generator names are stored in the "kubectl.kubernetes.io/last-applied-configuration" annotation config := applicationSetInfo.ObjectMeta.Annotations["kubectl.kubernetes.io/last-applied-configuration"] - var values map[string]interface{} + var values map[string]any err := json.Unmarshal([]byte(config), &values) if err != nil { log.Warnf("couldn't unmarshal kubectl.kubernetes.io/last-applied-configuration: %+v", config) return } - spec, ok := values["spec"].(map[string]interface{}) + spec, ok := values["spec"].(map[string]any) if !ok { log.Warn("coundn't get spec from kubectl.kubernetes.io/last-applied-configuration annotation") return } - generators, ok := spec["generators"].([]interface{}) + generators, ok := spec["generators"].([]any) if !ok { log.Warn("coundn't get generators from kubectl.kubernetes.io/last-applied-configuration annotation") return @@ -419,7 +419,7 @@ func addInvalidGeneratorNames(names map[string]bool, applicationSetInfo *argoapp return } - generator, ok := generators[index].(map[string]interface{}) + generator, ok := generators[index].(map[string]any) if !ok { log.Warn("coundn't get generator from kubectl.kubernetes.io/last-applied-configuration annotation") return @@ -457,7 +457,7 @@ func NormalizeBitbucketBasePath(basePath string) string { // // Returns: // - string: The generated URL-friendly slug based on the input name and options. -func SlugifyName(args ...interface{}) string { +func SlugifyName(args ...any) string { // Default values for arguments maxSize := 50 EnableSmartTruncate := true diff --git a/applicationset/utils/utils_test.go b/applicationset/utils/utils_test.go index 8d19a2cffa2608..6c66186649ef3d 100644 --- a/applicationset/utils/utils_test.go +++ b/applicationset/utils/utils_test.go @@ -62,14 +62,14 @@ func TestRenderTemplateParams(t *testing.T) { tests := []struct { name string fieldVal string - params map[string]interface{} + params map[string]any expectedVal string }{ { name: "simple substitution", fieldVal: "{{one}}", expectedVal: "two", - params: map[string]interface{}{ + params: map[string]any{ "one": "two", }, }, @@ -77,7 +77,7 @@ func TestRenderTemplateParams(t *testing.T) { name: "simple substitution with whitespace", fieldVal: "{{ one }}", expectedVal: "two", - params: map[string]interface{}{ + params: map[string]any{ "one": "two", }, }, @@ -86,7 +86,7 @@ func TestRenderTemplateParams(t *testing.T) { name: "template characters but not in a template", fieldVal: "}} {{", expectedVal: "}} {{", - params: map[string]interface{}{ + params: map[string]any{ "one": "two", }, }, @@ -95,7 +95,7 @@ func TestRenderTemplateParams(t *testing.T) { name: "nested template", fieldVal: "{{ }}", expectedVal: "{{ }}", - params: map[string]interface{}{ + params: map[string]any{ "one": "{{ }}", }, }, @@ -103,7 +103,7 @@ func TestRenderTemplateParams(t *testing.T) { name: "field with whitespace", fieldVal: "{{ }}", expectedVal: "{{ }}", - params: map[string]interface{}{ + params: map[string]any{ " ": "two", "": "three", }, @@ -113,7 +113,7 @@ func TestRenderTemplateParams(t *testing.T) { name: "template contains itself, containing itself", fieldVal: "{{one}}", expectedVal: "{{one}}", - params: map[string]interface{}{ + params: map[string]any{ "{{one}}": "{{one}}", }, }, @@ -122,7 +122,7 @@ func TestRenderTemplateParams(t *testing.T) { name: "template contains itself, containing something else", fieldVal: "{{one}}", expectedVal: "{{one}}", - params: map[string]interface{}{ + params: map[string]any{ "{{one}}": "{{two}}", }, }, @@ -131,7 +131,7 @@ func TestRenderTemplateParams(t *testing.T) { name: "templates are case sensitive", fieldVal: "{{ONE}}", expectedVal: "{{ONE}}", - params: map[string]interface{}{ + params: map[string]any{ "{{one}}": "two", }, }, @@ -139,7 +139,7 @@ func TestRenderTemplateParams(t *testing.T) { name: "multiple on a line", fieldVal: "{{one}}{{one}}", expectedVal: "twotwo", - params: map[string]interface{}{ + params: map[string]any{ "one": "two", }, }, @@ -147,7 +147,7 @@ func TestRenderTemplateParams(t *testing.T) { name: "multiple different on a line", fieldVal: "{{one}}{{three}}", expectedVal: "twofour", - params: map[string]interface{}{ + params: map[string]any{ "one": "two", "three": "four", }, @@ -156,7 +156,7 @@ func TestRenderTemplateParams(t *testing.T) { name: "multiple different on a line with quote", fieldVal: "{{one}} {{three}}", expectedVal: "\"hello\" world four", - params: map[string]interface{}{ + params: map[string]any{ "one": "\"hello\" world", "three": "four", }, @@ -195,7 +195,7 @@ func TestRenderTemplateParams(t *testing.T) { } func TestRenderHelmValuesObjectJson(t *testing.T) { - params := map[string]interface{}{ + params := map[string]any{ "test": "Hello world", } @@ -240,15 +240,15 @@ func TestRenderHelmValuesObjectJson(t *testing.T) { require.NoError(t, err) assert.NotNil(t, newApplication) - var unmarshaled interface{} + var unmarshaled any err = json.Unmarshal(newApplication.Spec.Source.Helm.ValuesObject.Raw, &unmarshaled) require.NoError(t, err) - assert.Equal(t, "Hello world", unmarshaled.(map[string]interface{})["some"].(map[string]interface{})["string"]) + assert.Equal(t, "Hello world", unmarshaled.(map[string]any)["some"].(map[string]any)["string"]) } func TestRenderHelmValuesObjectYaml(t *testing.T) { - params := map[string]interface{}{ + params := map[string]any{ "test": "Hello world", } @@ -290,11 +290,11 @@ func TestRenderHelmValuesObjectYaml(t *testing.T) { require.NoError(t, err) assert.NotNil(t, newApplication) - var unmarshaled interface{} + var unmarshaled any err = json.Unmarshal(newApplication.Spec.Source.Helm.ValuesObject.Raw, &unmarshaled) require.NoError(t, err) - assert.Equal(t, "Hello world", unmarshaled.(map[string]interface{})["some"].(map[string]interface{})["string"]) + assert.Equal(t, "Hello world", unmarshaled.(map[string]any)["some"].(map[string]any)["string"]) } func TestRenderTemplateParamsGoTemplate(t *testing.T) { @@ -339,7 +339,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { tests := []struct { name string fieldVal string - params map[string]interface{} + params map[string]any expectedVal string errorMessage string templateOptions []string @@ -348,7 +348,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "simple substitution", fieldVal: "{{ .one }}", expectedVal: "two", - params: map[string]interface{}{ + params: map[string]any{ "one": "two", }, }, @@ -356,7 +356,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "simple substitution with whitespace", fieldVal: "{{ .one }}", expectedVal: "two", - params: map[string]interface{}{ + params: map[string]any{ "one": "two", }, }, @@ -364,7 +364,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "template contains itself, containing itself", fieldVal: "{{ .one }}", expectedVal: "{{one}}", - params: map[string]interface{}{ + params: map[string]any{ "one": "{{one}}", }, }, @@ -373,7 +373,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "template contains itself, containing something else", fieldVal: "{{ .one }}", expectedVal: "{{two}}", - params: map[string]interface{}{ + params: map[string]any{ "one": "{{two}}", }, }, @@ -381,7 +381,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "multiple on a line", fieldVal: "{{.one}}{{.one}}", expectedVal: "twotwo", - params: map[string]interface{}{ + params: map[string]any{ "one": "two", }, }, @@ -389,7 +389,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "multiple different on a line", fieldVal: "{{.one}}{{.three}}", expectedVal: "twofour", - params: map[string]interface{}{ + params: map[string]any{ "one": "two", "three": "four", }, @@ -398,7 +398,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "multiple different on a line with quote", fieldVal: "{{.one}} {{.three}}", expectedVal: "\"hello\" world four", - params: map[string]interface{}{ + params: map[string]any{ "one": "\"hello\" world", "three": "four", }, @@ -407,9 +407,9 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "depth", fieldVal: "{{ .image.version }}", expectedVal: "latest", - params: map[string]interface{}{ + params: map[string]any{ "replicas": 3, - "image": map[string]interface{}{ + "image": map[string]any{ "name": "busybox", "version": "latest", }, @@ -419,9 +419,9 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "multiple depth", fieldVal: "{{ .image.name }}:{{ .image.version }}", expectedVal: "busybox:latest", - params: map[string]interface{}{ + params: map[string]any{ "replicas": 3, - "image": map[string]interface{}{ + "image": map[string]any{ "name": "busybox", "version": "latest", }, @@ -431,9 +431,9 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "if ok", fieldVal: "{{ if .hpa.enabled }}{{ .hpa.maxReplicas }}{{ else }}{{ .replicas }}{{ end }}", expectedVal: "5", - params: map[string]interface{}{ + params: map[string]any{ "replicas": 3, - "hpa": map[string]interface{}{ + "hpa": map[string]any{ "enabled": true, "minReplicas": 1, "maxReplicas": 5, @@ -444,9 +444,9 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "if not ok", fieldVal: "{{ if .hpa.enabled }}{{ .hpa.maxReplicas }}{{ else }}{{ .replicas }}{{ end }}", expectedVal: "3", - params: map[string]interface{}{ + params: map[string]any{ "replicas": 3, - "hpa": map[string]interface{}{ + "hpa": map[string]any{ "enabled": false, "minReplicas": 1, "maxReplicas": 5, @@ -457,16 +457,16 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "loop", fieldVal: "{{ range .volumes }}[{{ .name }}]{{ end }}", expectedVal: "[volume-one][volume-two]", - params: map[string]interface{}{ + params: map[string]any{ "replicas": 3, - "volumes": []map[string]interface{}{ + "volumes": []map[string]any{ { "name": "volume-one", - "emptyDir": map[string]interface{}{}, + "emptyDir": map[string]any{}, }, { "name": "volume-two", - "emptyDir": map[string]interface{}{}, + "emptyDir": map[string]any{}, }, }, }, @@ -475,8 +475,8 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "Index", fieldVal: `{{ index .admin "admin-ca" }}, {{ index .admin "admin-jks" }}`, expectedVal: "value admin ca, value admin jks", - params: map[string]interface{}{ - "admin": map[string]interface{}{ + params: map[string]any{ + "admin": map[string]any{ "admin-ca": "value admin ca", "admin-jks": "value admin jks", }, @@ -486,8 +486,8 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "Index", fieldVal: `{{ index .admin "admin-ca" }}, \\ "Hello world", {{ index .admin "admin-jks" }}`, expectedVal: `value "admin" ca with \, \\ "Hello world", value admin jks`, - params: map[string]interface{}{ - "admin": map[string]interface{}{ + params: map[string]any{ + "admin": map[string]any{ "admin-ca": `value "admin" ca with \`, "admin-jks": "value admin jks", }, @@ -497,7 +497,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "quote", fieldVal: `{{.quote}}`, expectedVal: `"`, - params: map[string]interface{}{ + params: map[string]any{ "quote": `"`, }, }, @@ -505,13 +505,13 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "Test No Data", fieldVal: `{{.data}}`, expectedVal: "{{.data}}", - params: map[string]interface{}{}, + params: map[string]any{}, }, { name: "Test Parse Error", fieldVal: `{{functiondoesnotexist}}`, expectedVal: "", - params: map[string]interface{}{ + params: map[string]any{ "data": `a data string`, }, errorMessage: `failed to parse template {{functiondoesnotexist}}: template: :1: function "functiondoesnotexist" not defined`, @@ -520,7 +520,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "Test template error", fieldVal: `{{.data.test}}`, expectedVal: "", - params: map[string]interface{}{ + params: map[string]any{ "data": `a data string`, }, errorMessage: `failed to execute go template {{.data.test}}: template: :1:7: executing "" at <.data.test>: can't evaluate field test in type interface {}`, @@ -529,7 +529,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "lookup missing value with missingkey=default", fieldVal: `--> {{.doesnotexist}} <--`, expectedVal: `--> <--`, - params: map[string]interface{}{ + params: map[string]any{ // if no params are passed then for some reason templating is skipped "unused": "this is not used", }, @@ -538,7 +538,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "lookup missing value with missingkey=error", fieldVal: `--> {{.doesnotexist}} <--`, expectedVal: "", - params: map[string]interface{}{ + params: map[string]any{ // if no params are passed then for some reason templating is skipped "unused": "this is not used", }, @@ -549,9 +549,9 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "toYaml", fieldVal: `{{ toYaml . | indent 2 }}`, expectedVal: " foo:\n bar:\n bool: true\n number: 2\n str: Hello world", - params: map[string]interface{}{ - "foo": map[string]interface{}{ - "bar": map[string]interface{}{ + params: map[string]any{ + "foo": map[string]any{ + "bar": map[string]any{ "bool": true, "number": 2, "str": "Hello world", @@ -564,7 +564,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { fieldVal: `{{ toYaml . | indent 2 }}`, expectedVal: " foo:\n bar:\n bool: true\n number: 2\n str: Hello world", errorMessage: "failed to execute go template {{ toYaml . | indent 2 }}: template: :1:3: executing \"\" at : error calling toYaml: error marshaling into JSON: json: unsupported type: func(*string)", - params: map[string]interface{}{ + params: map[string]any{ "foo": func(test *string) { }, }, @@ -573,7 +573,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "fromYaml", fieldVal: `{{ get (fromYaml .value) "hello" }}`, expectedVal: "world", - params: map[string]interface{}{ + params: map[string]any{ "value": "hello: world", }, }, @@ -582,7 +582,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { fieldVal: `{{ get (fromYaml .value) "hello" }}`, expectedVal: "world", errorMessage: "failed to execute go template {{ get (fromYaml .value) \"hello\" }}: template: :1:8: executing \"\" at : error calling fromYaml: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go value of type map[string]interface {}", - params: map[string]interface{}{ + params: map[string]any{ "value": "non\n compliant\n yaml", }, }, @@ -590,7 +590,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { name: "fromYamlArray", fieldVal: `{{ fromYamlArray .value | last }}`, expectedVal: "bonjour tout le monde", - params: map[string]interface{}{ + params: map[string]any{ "value": "- hello world\n- bonjour tout le monde", }, }, @@ -599,7 +599,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { fieldVal: `{{ fromYamlArray .value | last }}`, expectedVal: "bonjour tout le monde", errorMessage: "failed to execute go template {{ fromYamlArray .value | last }}: template: :1:3: executing \"\" at : error calling fromYamlArray: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go value of type []interface {}", - params: map[string]interface{}{ + params: map[string]any{ "value": "non\n compliant\n yaml", }, }, @@ -645,7 +645,7 @@ func TestRenderGeneratorParams_does_not_panic(t *testing.T) { // This test verifies that the RenderGeneratorParams function does not panic when the value in a map is a non- // nillable type. This is a regression test. render := Render{} - params := map[string]interface{}{ + params := map[string]any{ "branch": "master", } generator := &argoappsv1.ApplicationSetGenerator{ @@ -679,7 +679,7 @@ func TestRenderTemplateKeys(t *testing.T) { }, } - params := map[string]interface{}{ + params := map[string]any{ "key": "some-key", "value": "some-value", } @@ -699,7 +699,7 @@ func TestRenderTemplateKeys(t *testing.T) { }, } - params := map[string]interface{}{ + params := map[string]any{ "key": "some-key", "value": "some-value", } @@ -804,7 +804,7 @@ func TestRenderTemplateParamsFinalizers(t *testing.T) { application := emptyApplication.DeepCopy() application.Finalizers = c.existingFinalizers - params := map[string]interface{}{ + params := map[string]any{ "one": "two", } diff --git a/applicationset/webhook/webhook.go b/applicationset/webhook/webhook.go index a886cba7c47ef3..5da70572172c25 100644 --- a/applicationset/webhook/webhook.go +++ b/applicationset/webhook/webhook.go @@ -37,7 +37,7 @@ type WebhookHandler struct { azuredevops *azuredevops.Webhook client client.Client generators map[string]generators.Generator - queue chan interface{} + queue chan any } type gitGeneratorInfo struct { @@ -94,7 +94,7 @@ func NewWebhookHandler(namespace string, webhookParallelism int, argocdSettingsM azuredevops: azuredevopsHandler, client: client, generators: generators, - queue: make(chan interface{}, payloadQueueSize), + queue: make(chan any, payloadQueueSize), } webhookHandler.startWorkerPool(webhookParallelism) @@ -118,7 +118,7 @@ func (h *WebhookHandler) startWorkerPool(webhookParallelism int) { } } -func (h *WebhookHandler) HandleEvent(payload interface{}) { +func (h *WebhookHandler) HandleEvent(payload any) { gitGenInfo := getGitGeneratorInfo(payload) prGenInfo := getPRGeneratorInfo(payload) if gitGenInfo == nil && prGenInfo == nil { @@ -157,7 +157,7 @@ func (h *WebhookHandler) HandleEvent(payload interface{}) { } func (h *WebhookHandler) Handler(w http.ResponseWriter, r *http.Request) { - var payload interface{} + var payload any var err error switch { @@ -191,7 +191,7 @@ func (h *WebhookHandler) Handler(w http.ResponseWriter, r *http.Request) { } } -func getGitGeneratorInfo(payload interface{}) *gitGeneratorInfo { +func getGitGeneratorInfo(payload any) *gitGeneratorInfo { var ( webURL string revision string @@ -236,7 +236,7 @@ func getGitGeneratorInfo(payload interface{}) *gitGeneratorInfo { } } -func getPRGeneratorInfo(payload interface{}) *prGeneratorInfo { +func getPRGeneratorInfo(payload any) *prGeneratorInfo { var info prGeneratorInfo switch payload := payload.(type) { case github.PullRequestPayload: @@ -517,7 +517,7 @@ func (h *WebhookHandler) shouldRefreshMatrixGenerator(gen *v1alpha1.MatrixGenera // Generate params for first child generator relGenerators := generators.GetRelevantGenerators(requestedGenerator0, h.generators) - params := []map[string]interface{}{} + params := []map[string]any{} for _, g := range relGenerators { p, err := g.GenerateParams(requestedGenerator0, appSet, h.client) if err != nil { diff --git a/applicationset/webhook/webhook_test.go b/applicationset/webhook/webhook_test.go index c8715e57776e0c..1d5ba90d0dddf3 100644 --- a/applicationset/webhook/webhook_test.go +++ b/applicationset/webhook/webhook_test.go @@ -39,8 +39,8 @@ func (g *generatorMock) GetTemplate(appSetGenerator *v1alpha1.ApplicationSetGene return &v1alpha1.ApplicationSetTemplate{} } -func (g *generatorMock) GenerateParams(appSetGenerator *v1alpha1.ApplicationSetGenerator, _ *v1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, error) { - return []map[string]interface{}{}, nil +func (g *generatorMock) GenerateParams(appSetGenerator *v1alpha1.ApplicationSetGenerator, _ *v1alpha1.ApplicationSet, client client.Client) ([]map[string]any, error) { + return []map[string]any{}, nil } func (g *generatorMock) GetRequeueAfter(appSetGenerator *v1alpha1.ApplicationSetGenerator) time.Duration { diff --git a/cmd/argocd-dex/commands/argocd_dex.go b/cmd/argocd-dex/commands/argocd_dex.go index f674266738944c..5bdde7e572bdb6 100644 --- a/cmd/argocd-dex/commands/argocd_dex.go +++ b/cmd/argocd-dex/commands/argocd_dex.go @@ -181,14 +181,14 @@ func NewGenDexConfigCommand() *cobra.Command { return nil } if out == "" { - dexCfg := make(map[string]interface{}) + dexCfg := make(map[string]any) err := yaml.Unmarshal(dexCfgBytes, &dexCfg) errors.CheckError(err) if staticClientsInterface, ok := dexCfg["staticClients"]; ok { - if staticClients, ok := staticClientsInterface.([]interface{}); ok { + if staticClients, ok := staticClientsInterface.([]any); ok { for i := range staticClients { staticClient := staticClients[i] - if mappings, ok := staticClient.(map[string]interface{}); ok { + if mappings, ok := staticClient.(map[string]any); ok { for key := range mappings { if key == "secret" { mappings[key] = "******" @@ -220,8 +220,8 @@ func NewGenDexConfigCommand() *cobra.Command { return &command } -func iterateStringFields(obj interface{}, callback func(name string, val string) string) { - if mapField, ok := obj.(map[string]interface{}); ok { +func iterateStringFields(obj any, callback func(name string, val string) string) { + if mapField, ok := obj.(map[string]any); ok { for field, val := range mapField { if strVal, ok := val.(string); ok { mapField[field] = callback(field, strVal) @@ -229,7 +229,7 @@ func iterateStringFields(obj interface{}, callback func(name string, val string) iterateStringFields(val, callback) } } - } else if arrayField, ok := obj.([]interface{}); ok { + } else if arrayField, ok := obj.([]any); ok { for i := range arrayField { iterateStringFields(arrayField[i], callback) } @@ -237,7 +237,7 @@ func iterateStringFields(obj interface{}, callback func(name string, val string) } func redactor(dirtyString string) string { - config := make(map[string]interface{}) + config := make(map[string]any) err := yaml.Unmarshal([]byte(dirtyString), &config) errors.CheckError(err) iterateStringFields(config, func(name string, val string) string { diff --git a/cmd/argocd/commands/admin/admin_test.go b/cmd/argocd/commands/admin/admin_test.go index 85f59b5dee6992..e46dd15f565d63 100644 --- a/cmd/argocd/commands/admin/admin_test.go +++ b/cmd/argocd/commands/admin/admin_test.go @@ -12,12 +12,12 @@ import ( ) func TestGetAdditionalNamespaces(t *testing.T) { - createArgoCDCmdCMWithKeys := func(data map[string]interface{}) *unstructured.Unstructured { + createArgoCDCmdCMWithKeys := func(data map[string]any) *unstructured.Unstructured { return &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "v1", "kind": "ConfigMap", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "argocd-cmd-params-cm", "namespace": "argocd", }, @@ -27,33 +27,33 @@ func TestGetAdditionalNamespaces(t *testing.T) { } testCases := []struct { - CmdParamsKeys map[string]interface{} + CmdParamsKeys map[string]any expected argocdAdditonalNamespaces description string }{ { description: "empty configmap should return no additional namespaces", - CmdParamsKeys: map[string]interface{}{}, + CmdParamsKeys: map[string]any{}, expected: argocdAdditonalNamespaces{applicationNamespaces: []string{}, applicationsetNamespaces: []string{}}, }, { description: "empty strings in respective keys in cm shoud return empty namespace list", - CmdParamsKeys: map[string]interface{}{applicationsetNamespacesCmdParamsKey: "", applicationNamespacesCmdParamsKey: ""}, + CmdParamsKeys: map[string]any{applicationsetNamespacesCmdParamsKey: "", applicationNamespacesCmdParamsKey: ""}, expected: argocdAdditonalNamespaces{applicationNamespaces: []string{}, applicationsetNamespaces: []string{}}, }, { description: "when only one of the keys in the cm is set only correct respective list of namespaces should be returned", - CmdParamsKeys: map[string]interface{}{applicationNamespacesCmdParamsKey: "foo, bar*"}, + CmdParamsKeys: map[string]any{applicationNamespacesCmdParamsKey: "foo, bar*"}, expected: argocdAdditonalNamespaces{applicationsetNamespaces: []string{}, applicationNamespaces: []string{"foo", "bar*"}}, }, { description: "when only one of the keys in the cm is set only correct respective list of namespaces should be returned", - CmdParamsKeys: map[string]interface{}{applicationsetNamespacesCmdParamsKey: "foo, bar*"}, + CmdParamsKeys: map[string]any{applicationsetNamespacesCmdParamsKey: "foo, bar*"}, expected: argocdAdditonalNamespaces{applicationNamespaces: []string{}, applicationsetNamespaces: []string{"foo", "bar*"}}, }, { description: "whitespaces are removed for both multiple and single namespace", - CmdParamsKeys: map[string]interface{}{applicationNamespacesCmdParamsKey: " bar ", applicationsetNamespacesCmdParamsKey: " foo , bar* "}, + CmdParamsKeys: map[string]any{applicationNamespacesCmdParamsKey: " bar ", applicationsetNamespacesCmdParamsKey: " foo , bar* "}, expected: argocdAdditonalNamespaces{applicationNamespaces: []string{"bar"}, applicationsetNamespaces: []string{"foo", "bar*"}}, }, } diff --git a/cmd/argocd/commands/admin/app.go b/cmd/argocd/commands/admin/app.go index 68500577efa784..91cb432578058c 100644 --- a/cmd/argocd/commands/admin/app.go +++ b/cmd/argocd/commands/admin/app.go @@ -159,7 +159,7 @@ func (r *reconcileResults) getAppsMap() map[string]appReconcileResult { return res } -func printLine(format string, a ...interface{}) { +func printLine(format string, a ...any) { _, _ = fmt.Printf(format+"\n", a...) } @@ -186,12 +186,12 @@ func NewDiffReconcileResults() *cobra.Command { return command } -func toUnstructured(val interface{}) (*unstructured.Unstructured, error) { +func toUnstructured(val any) (*unstructured.Unstructured, error) { data, err := json.Marshal(val) if err != nil { return nil, fmt.Errorf("error while marhsalling value: %w", err) } - res := make(map[string]interface{}) + res := make(map[string]any) err = json.Unmarshal(data, &res) if err != nil { return nil, fmt.Errorf("error while unmarhsalling data: %w", err) @@ -384,7 +384,7 @@ func reconcileApplications( appLister := appInformerFactory.Argoproj().V1alpha1().Applications().Lister() projLister := appInformerFactory.Argoproj().V1alpha1().AppProjects().Lister() - server, err := metrics.NewMetricsServer("", appLister, func(obj interface{}) bool { + server, err := metrics.NewMetricsServer("", appLister, func(obj any) bool { return true }, func(r *http.Request) error { return nil diff --git a/cmd/argocd/commands/admin/generatespec_utils.go b/cmd/argocd/commands/admin/generatespec_utils.go index 71d59c56da94de..97344ced7b95e4 100644 --- a/cmd/argocd/commands/admin/generatespec_utils.go +++ b/cmd/argocd/commands/admin/generatespec_utils.go @@ -36,7 +36,7 @@ func getOutWriter(inline bool, filePath string) (io.Writer, io.Closer, error) { } // PrintResources prints a single resource in YAML or JSON format to stdout according to the output format -func PrintResources(output string, out io.Writer, resources ...interface{}) error { +func PrintResources(output string, out io.Writer, resources ...any) error { for i, resource := range resources { if secret, ok := resource.(*v1.Secret); ok { convertSecretData(secret) @@ -47,7 +47,7 @@ func PrintResources(output string, out io.Writer, resources ...interface{}) erro } resources[i] = filteredResource } - var obj interface{} = resources + var obj any = resources if len(resources) == 1 { obj = resources[0] } @@ -74,13 +74,13 @@ func PrintResources(output string, out io.Writer, resources ...interface{}) erro } // omit fields such as status, creationTimestamp and metadata.namespace in k8s objects -func omitFields(resource interface{}) (interface{}, error) { +func omitFields(resource any) (any, error) { jsonBytes, err := json.Marshal(resource) if err != nil { return nil, err } - toMap := make(map[string]interface{}) + toMap := make(map[string]any) err = json.Unmarshal(jsonBytes, &toMap) if err != nil { return nil, err @@ -88,7 +88,7 @@ func omitFields(resource interface{}) (interface{}, error) { delete(toMap, "status") if v, ok := toMap["metadata"]; ok { - if metadata, ok := v.(map[string]interface{}); ok { + if metadata, ok := v.(map[string]any); ok { delete(metadata, "creationTimestamp") delete(metadata, "namespace") } diff --git a/cmd/argocd/commands/app.go b/cmd/argocd/commands/app.go index 0b7245def64cd4..9a4ca5c977dbd2 100644 --- a/cmd/argocd/commands/app.go +++ b/cmd/argocd/commands/app.go @@ -1615,7 +1615,7 @@ func printApplicationNames(apps []argoappv1.Application) { func printApplicationTable(apps []argoappv1.Application, output *string) { w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) var fmtStr string - headers := []interface{}{"NAME", "CLUSTER", "NAMESPACE", "PROJECT", "STATUS", "HEALTH", "SYNCPOLICY", "CONDITIONS"} + headers := []any{"NAME", "CLUSTER", "NAMESPACE", "PROJECT", "STATUS", "HEALTH", "SYNCPOLICY", "CONDITIONS"} if *output == "wide" { fmtStr = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" headers = append(headers, "REPO", "PATH", "TARGET") @@ -1624,7 +1624,7 @@ func printApplicationTable(apps []argoappv1.Application, output *string) { } _, _ = fmt.Fprintf(w, fmtStr, headers...) for _, app := range apps { - vals := []interface{}{ + vals := []any{ app.QualifiedName(), getServer(&app), app.Spec.Destination.Namespace, @@ -2338,9 +2338,9 @@ func (rs *resourceState) Key() string { return fmt.Sprintf("%s/%s/%s/%s", rs.Group, rs.Kind, rs.Namespace, rs.Name) } -func (rs *resourceState) FormatItems() []interface{} { +func (rs *resourceState) FormatItems() []any { timeStr := time.Now().Format("2006-01-02T15:04:05-07:00") - return []interface{}{timeStr, rs.Group, rs.Kind, rs.Namespace, rs.Name, rs.Status, rs.Health, rs.Hook, rs.Message} + return []any{timeStr, rs.Group, rs.Kind, rs.Namespace, rs.Name, rs.Status, rs.Health, rs.Hook, rs.Message} } // Merge merges the new state with any different contents from another resourceState. diff --git a/cmd/argocd/commands/app_resources.go b/cmd/argocd/commands/app_resources.go index e7cc47fa8b76af..325af2b8d9df7f 100644 --- a/cmd/argocd/commands/app_resources.go +++ b/cmd/argocd/commands/app_resources.go @@ -236,7 +236,7 @@ func printResources(listAll bool, orphaned bool, appResourceTree *v1alpha1.Appli printTreeViewAppResourcesOrphaned(mapUidToNode, mapParentToChild, parentNode, w) } } else { - headers := []interface{}{"GROUP", "KIND", "NAMESPACE", "NAME", "ORPHANED"} + headers := []any{"GROUP", "KIND", "NAMESPACE", "NAME", "ORPHANED"} fmtStr := "%s\t%s\t%s\t%s\t%s\n" _, _ = fmt.Fprintf(w, fmtStr, headers...) if !orphaned || listAll { diff --git a/cmd/argocd/commands/app_test.go b/cmd/argocd/commands/app_test.go index 57aede02a5b49b..c177b98a786111 100644 --- a/cmd/argocd/commands/app_test.go +++ b/cmd/argocd/commands/app_test.go @@ -367,20 +367,20 @@ func TestFindRevisionHistoryWithPassedIdThatNotExist(t *testing.T) { func Test_groupObjsByKey(t *testing.T) { localObjs := []*unstructured.Unstructured{ { - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "v1", "kind": "Pod", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "pod-name", "namespace": "default", }, }, }, { - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "apiextensions.k8s.io/v1", "kind": "CustomResourceDefinition", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "certificates.cert-manager.io", }, }, @@ -388,20 +388,20 @@ func Test_groupObjsByKey(t *testing.T) { } liveObjs := []*unstructured.Unstructured{ { - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "v1", "kind": "Pod", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "pod-name", "namespace": "default", }, }, }, { - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "apiextensions.k8s.io/v1", "kind": "CustomResourceDefinition", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "certificates.cert-manager.io", }, }, diff --git a/cmd/argocd/commands/applicationset.go b/cmd/argocd/commands/applicationset.go index 3dcc905182258c..64ed8d3b450e05 100644 --- a/cmd/argocd/commands/applicationset.go +++ b/cmd/argocd/commands/applicationset.go @@ -257,7 +257,7 @@ func NewApplicationSetGenerateCommand(clientOpts *argocdclient.ClientOptions) *c switch output { case "yaml", "json": - var resources []interface{} + var resources []any for i := range appsList { app := appsList[i] // backfill api version and kind because k8s client always return empty values for these fields @@ -396,7 +396,7 @@ func printApplicationSetNames(apps []arogappsetv1.ApplicationSet) { func printApplicationSetTable(apps []arogappsetv1.ApplicationSet, output *string) { w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) var fmtStr string - headers := []interface{}{"NAME", "PROJECT", "SYNCPOLICY", "CONDITIONS"} + headers := []any{"NAME", "PROJECT", "SYNCPOLICY", "CONDITIONS"} if *output == "wide" { fmtStr = "%s\t%s\t%s\t%s\t%s\t%s\t%s\n" headers = append(headers, "REPO", "PATH", "TARGET") @@ -411,7 +411,7 @@ func printApplicationSetTable(apps []arogappsetv1.ApplicationSet, output *string conditions = append(conditions, condition) } } - vals := []interface{}{ + vals := []any{ app.QualifiedName(), app.Spec.Template.Spec.Project, app.Spec.SyncPolicy, diff --git a/cmd/argocd/commands/common.go b/cmd/argocd/commands/common.go index 849b9a48f02b62..9b924e063b7868 100644 --- a/cmd/argocd/commands/common.go +++ b/cmd/argocd/commands/common.go @@ -17,7 +17,7 @@ const ( ) // PrintResource prints a single resource in YAML or JSON format to stdout according to the output format -func PrintResource(resource interface{}, output string) error { +func PrintResource(resource any, output string) error { switch output { case "json": jsonBytes, err := json.MarshalIndent(resource, "", " ") @@ -38,7 +38,7 @@ func PrintResource(resource interface{}, output string) error { } // PrintResourceList marshals & prints a list of resources to stdout according to the output format -func PrintResourceList(resources interface{}, output string, single bool) error { +func PrintResourceList(resources any, output string, single bool) error { kt := reflect.ValueOf(resources) // Sometimes, we want to marshal the first resource of a slice or array as single item if kt.Kind() == reflect.Slice || kt.Kind() == reflect.Array { diff --git a/cmd/argocd/commands/headless/headless.go b/cmd/argocd/commands/headless/headless.go index c8d69b441d9f5b..4845062eef7208 100644 --- a/cmd/argocd/commands/headless/headless.go +++ b/cmd/argocd/commands/headless/headless.go @@ -88,7 +88,7 @@ func (c *forwardCacheClient) Rename(oldKey string, newKey string, expiration tim }) } -func (c *forwardCacheClient) Get(key string, obj interface{}) error { +func (c *forwardCacheClient) Get(key string, obj any) error { return c.doLazy(func(client cache.CacheClient) error { return client.Get(key, obj) }) diff --git a/cmd/argocd/commands/projectwindows.go b/cmd/argocd/commands/projectwindows.go index 589064b240351c..beb08617477f44 100644 --- a/cmd/argocd/commands/projectwindows.go +++ b/cmd/argocd/commands/projectwindows.go @@ -354,13 +354,13 @@ argocd proj windows list test-project`, func printSyncWindows(proj *v1alpha1.AppProject) { w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) var fmtStr string - headers := []interface{}{"ID", "STATUS", "KIND", "SCHEDULE", "DURATION", "APPLICATIONS", "NAMESPACES", "CLUSTERS", "MANUALSYNC", "TIMEZONE"} + headers := []any{"ID", "STATUS", "KIND", "SCHEDULE", "DURATION", "APPLICATIONS", "NAMESPACES", "CLUSTERS", "MANUALSYNC", "TIMEZONE"} fmtStr = strings.Repeat("%s\t", len(headers)) + "\n" fmt.Fprintf(w, fmtStr, headers...) if proj.Spec.SyncWindows.HasWindows() { for i, window := range proj.Spec.SyncWindows { isActive, _ := window.Active() - vals := []interface{}{ + vals := []any{ strconv.Itoa(i), formatBoolOutput(isActive), window.Kind, diff --git a/cmd/argocd/commands/version.go b/cmd/argocd/commands/version.go index 8c69c4195c3ad1..ee7385d06d8f9f 100644 --- a/cmd/argocd/commands/version.go +++ b/cmd/argocd/commands/version.go @@ -45,7 +45,7 @@ func NewVersionCmd(clientOpts *argocdclient.ClientOptions, serverVersion *versio cv := common.GetVersion() switch output { case "yaml", "json": - v := make(map[string]interface{}) + v := make(map[string]any) if short { v["client"] = map[string]string{cliName: cv.Version} diff --git a/cmpserver/plugin/plugin.go b/cmpserver/plugin/plugin.go index 7eb61acf4cfbc4..ba149c39d16df8 100644 --- a/cmpserver/plugin/plugin.go +++ b/cmpserver/plugin/plugin.go @@ -172,7 +172,7 @@ func getTempDirMustCleanup(baseDir string) (workDir string, cleanup func(), err } cleanup = func() { if err := os.RemoveAll(workDir); err != nil { - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ common.SecurityField: common.SecurityHigh, common.SecurityCWEField: common.SecurityCWEIncompleteCleanup, }).Errorf("Failed to clean up temp directory: %s", err) @@ -315,7 +315,7 @@ func (s *Service) matchRepository(ctx context.Context, workdir string, envEntrie appPath, err := securejoin.SecureJoin(workdir, appRelPath) if err != nil { - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ common.SecurityField: common.SecurityHigh, common.SecurityCWEField: common.SecurityCWEIncompleteCleanup, }).Errorf("error joining workdir %q and appRelPath %q: %v", workdir, appRelPath, err) diff --git a/cmpserver/plugin/plugin_test.go b/cmpserver/plugin/plugin_test.go index 30bd0a97bedc5e..7120eb9f37e05c 100644 --- a/cmpserver/plugin/plugin_test.go +++ b/cmpserver/plugin/plugin_test.go @@ -806,11 +806,11 @@ func (m *MockParametersAnnouncementStream) Context() context.Context { return context.Background() } -func (m *MockParametersAnnouncementStream) SendMsg(interface{}) error { +func (m *MockParametersAnnouncementStream) SendMsg(any) error { return nil } -func (m *MockParametersAnnouncementStream) RecvMsg(interface{}) error { +func (m *MockParametersAnnouncementStream) RecvMsg(any) error { return nil } diff --git a/cmpserver/server.go b/cmpserver/server.go index 5d7eacd2fd35f3..0fd2f56845862b 100644 --- a/cmpserver/server.go +++ b/cmpserver/server.go @@ -35,7 +35,7 @@ type ArgoCDCMPServer struct { opts []grpc.ServerOption initConstants plugin.CMPServerInitConstants stopCh chan os.Signal - doneCh chan interface{} + doneCh chan any sig os.Signal } @@ -75,7 +75,7 @@ func NewServer(initConstants plugin.CMPServerInitConstants) (*ArgoCDCMPServer, e log: serverLog, opts: serverOpts, stopCh: make(chan os.Signal), - doneCh: make(chan interface{}), + doneCh: make(chan any), initConstants: initConstants, }, nil } diff --git a/controller/appcontroller.go b/controller/appcontroller.go index 22d737f985e608..8c10e040ef1b7f 100644 --- a/controller/appcontroller.go +++ b/controller/appcontroller.go @@ -233,7 +233,7 @@ func NewApplicationController( projInformer := v1alpha1.NewAppProjectInformer(applicationClientset, namespace, appResyncPeriod, indexers) var err error _, err = projInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { if key, err := cache.MetaNamespaceKeyFunc(obj); err == nil { ctrl.projectRefreshQueue.AddRateLimited(key) if projMeta, ok := obj.(metav1.Object); ok { @@ -241,7 +241,7 @@ func NewApplicationController( } } }, - UpdateFunc: func(old, new interface{}) { + UpdateFunc: func(old, new any) { if key, err := cache.MetaNamespaceKeyFunc(new); err == nil { ctrl.projectRefreshQueue.AddRateLimited(key) if projMeta, ok := new.(metav1.Object); ok { @@ -249,7 +249,7 @@ func NewApplicationController( } } }, - DeleteFunc: func(obj interface{}) { + DeleteFunc: func(obj any) { if key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj); err == nil { // immediately push to queue for deletes ctrl.projectRefreshQueue.Add(key) @@ -326,7 +326,7 @@ func (ctrl *ApplicationController) InvalidateProjectsCache(names ...string) { ctrl.projByNameCache.Delete(name) } } else if ctrl != nil { - ctrl.projByNameCache.Range(func(key, _ interface{}) bool { + ctrl.projByNameCache.Range(func(key, _ any) bool { ctrl.projByNameCache.Delete(key) return true }) @@ -1123,8 +1123,8 @@ func (ctrl *ApplicationController) finalizeProjectDeletion(proj *appv1.AppProjec func (ctrl *ApplicationController) removeProjectFinalizer(proj *appv1.AppProject) error { proj.RemoveFinalizer() var patch []byte - patch, _ = json.Marshal(map[string]interface{}{ - "metadata": map[string]interface{}{ + patch, _ = json.Marshal(map[string]any{ + "metadata": map[string]any{ "finalizers": proj.Finalizers, }, }) @@ -1323,8 +1323,8 @@ func (ctrl *ApplicationController) updateFinalizers(app *appv1.Application) erro } var patch []byte - patch, _ = json.Marshal(map[string]interface{}{ - "metadata": map[string]interface{}{ + patch, _ = json.Marshal(map[string]any{ + "metadata": map[string]any{ "finalizers": app.Finalizers, }, }) @@ -1345,8 +1345,8 @@ func (ctrl *ApplicationController) setAppCondition(app *appv1.Application, condi app.Status.SetConditions([]appv1.ApplicationCondition{condition}, map[appv1.ApplicationConditionType]bool{condition.Type: true}) var patch []byte - patch, err := json.Marshal(map[string]interface{}{ - "status": map[string]interface{}{ + patch, err := json.Marshal(map[string]any{ + "status": map[string]any{ "conditions": app.Status.Conditions, }, }) @@ -1504,8 +1504,8 @@ func (ctrl *ApplicationController) setOperationState(app *appv1.Application, sta now := metav1.Now() state.FinishedAt = &now } - patch := map[string]interface{}{ - "status": map[string]interface{}{ + patch := map[string]any{ + "status": map[string]any{ "operationState": state, }, } @@ -1975,7 +1975,7 @@ func (ctrl *ApplicationController) normalizeApplication(orig, app *appv1.Applica } } -func createMergePatch(orig, new interface{}) ([]byte, bool, error) { +func createMergePatch(orig, new any) ([]byte, bool, error) { origBytes, err := json.Marshal(orig) if err != nil { return nil, false, err @@ -2255,7 +2255,7 @@ func (ctrl *ApplicationController) isAppNamespaceAllowed(app *appv1.Application) return app.Namespace == ctrl.namespace || glob.MatchStringInList(ctrl.applicationNamespaces, app.Namespace, glob.REGEXP) } -func (ctrl *ApplicationController) canProcessApp(obj interface{}) bool { +func (ctrl *ApplicationController) canProcessApp(obj any) bool { app, ok := obj.(*appv1.Application) if !ok { return false @@ -2324,7 +2324,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar &appv1.Application{}, refreshTimeout, cache.Indexers{ - cache.NamespaceIndex: func(obj interface{}) ([]string, error) { + cache.NamespaceIndex: func(obj any) ([]string, error) { app, ok := obj.(*appv1.Application) if ok { // We only generally work with applications that are in one @@ -2350,7 +2350,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar return cache.MetaNamespaceIndexFunc(obj) }, - orphanedIndex: func(obj interface{}) (i []string, e error) { + orphanedIndex: func(obj any) (i []string, e error) { app, ok := obj.(*appv1.Application) if !ok { return nil, nil @@ -2374,7 +2374,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar lister := applisters.NewApplicationLister(informer.GetIndexer()) _, err := informer.AddEventHandler( cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { if !ctrl.canProcessApp(obj) { return } @@ -2387,7 +2387,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar ctrl.clusterSharding.AddApp(newApp) } }, - UpdateFunc: func(old, new interface{}) { + UpdateFunc: func(old, new any) { if !ctrl.canProcessApp(new) { return } @@ -2423,7 +2423,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar } ctrl.clusterSharding.UpdateApp(newApp) }, - DeleteFunc: func(obj interface{}) { + DeleteFunc: func(obj any) { if !ctrl.canProcessApp(obj) { return } diff --git a/controller/appcontroller_test.go b/controller/appcontroller_test.go index 8c4c3b4d88341a..1cfc6239597110 100644 --- a/controller/appcontroller_test.go +++ b/controller/appcontroller_test.go @@ -539,8 +539,8 @@ func createFakeApp(testApp string) *v1alpha1.Application { return &app } -func newFakeCM() map[string]interface{} { - var cm map[string]interface{} +func newFakeCM() map[string]any { + var cm map[string]any err := yaml.Unmarshal([]byte(fakeStrayResource), &cm) if err != nil { panic(err) @@ -548,8 +548,8 @@ func newFakeCM() map[string]interface{} { return cm } -func newFakePostDeleteHook() map[string]interface{} { - var hook map[string]interface{} +func newFakePostDeleteHook() map[string]any { + var hook map[string]any err := yaml.Unmarshal([]byte(fakePostDeleteHook), &hook) if err != nil { panic(err) @@ -557,8 +557,8 @@ func newFakePostDeleteHook() map[string]interface{} { return hook } -func newFakeRoleBinding() map[string]interface{} { - var roleBinding map[string]interface{} +func newFakeRoleBinding() map[string]any { + var roleBinding map[string]any err := yaml.Unmarshal([]byte(fakeRoleBinding), &roleBinding) if err != nil { panic(err) @@ -566,8 +566,8 @@ func newFakeRoleBinding() map[string]interface{} { return roleBinding } -func newFakeRole() map[string]interface{} { - var role map[string]interface{} +func newFakeRole() map[string]any { + var role map[string]any err := yaml.Unmarshal([]byte(fakeRole), &role) if err != nil { panic(err) @@ -575,8 +575,8 @@ func newFakeRole() map[string]interface{} { return role } -func newFakeServiceAccount() map[string]interface{} { - var serviceAccount map[string]interface{} +func newFakeServiceAccount() map[string]any { + var serviceAccount map[string]any err := yaml.Unmarshal([]byte(fakeServiceAccount), &serviceAccount) if err != nil { panic(err) @@ -1053,8 +1053,8 @@ func TestFinalizeAppDeletion(t *testing.T) { app.SetPostDeleteFinalizer() app.Spec.Destination.Namespace = test.FakeArgoCDNamespace liveHook := &unstructured.Unstructured{Object: newFakePostDeleteHook()} - conditions := []interface{}{ - map[string]interface{}{ + conditions := []any{ + map[string]any{ "type": "Complete", "status": "True", }, @@ -1097,8 +1097,8 @@ func TestFinalizeAppDeletion(t *testing.T) { liveRole := &unstructured.Unstructured{Object: newFakeRole()} liveServiceAccount := &unstructured.Unstructured{Object: newFakeServiceAccount()} liveHook := &unstructured.Unstructured{Object: newFakePostDeleteHook()} - conditions := []interface{}{ - map[string]interface{}{ + conditions := []any{ + map[string]any{ "type": "Complete", "status": "True", }, @@ -1654,7 +1654,7 @@ func TestUpdateReconciledAt(t *testing.T) { key, _ := cache.MetaNamespaceKeyFunc(app) fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) fakeAppCs.ReactionChain = nil - receivedPatch := map[string]interface{}{} + receivedPatch := map[string]any{} fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { if patchAction, ok := action.(kubetesting.PatchAction); ok { require.NoError(t, json.Unmarshal(patchAction.GetPatch(), &receivedPatch)) @@ -1663,7 +1663,7 @@ func TestUpdateReconciledAt(t *testing.T) { }) t.Run("UpdatedOnFullReconciliation", func(t *testing.T) { - receivedPatch = map[string]interface{}{} + receivedPatch = map[string]any{} ctrl.requestAppRefresh(app.Name, CompareWithLatest.Pointer(), nil) ctrl.appRefreshQueue.AddRateLimited(key) @@ -1679,7 +1679,7 @@ func TestUpdateReconciledAt(t *testing.T) { }) t.Run("NotUpdatedOnPartialReconciliation", func(t *testing.T) { - receivedPatch = map[string]interface{}{} + receivedPatch = map[string]any{} ctrl.appRefreshQueue.AddRateLimited(key) ctrl.requestAppRefresh(app.Name, CompareWithRecent.Pointer(), nil) @@ -1950,7 +1950,7 @@ func TestFinalizeProjectDeletion_DoesNotHaveApplications(t *testing.T) { ctrl := newFakeController(&fakeData{apps: []runtime.Object{&defaultProj}}, nil) fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) - receivedPatch := map[string]interface{}{} + receivedPatch := map[string]any{} fakeAppCs.PrependReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { if patchAction, ok := action.(kubetesting.PatchAction); ok { require.NoError(t, json.Unmarshal(patchAction.GetPatch(), &receivedPatch)) @@ -1960,8 +1960,8 @@ func TestFinalizeProjectDeletion_DoesNotHaveApplications(t *testing.T) { err := ctrl.finalizeProjectDeletion(proj) require.NoError(t, err) - assert.Equal(t, map[string]interface{}{ - "metadata": map[string]interface{}{ + assert.Equal(t, map[string]any{ + "metadata": map[string]any{ "finalizers": nil, }, }, receivedPatch) @@ -1975,7 +1975,7 @@ func TestProcessRequestedAppOperation_FailedNoRetries(t *testing.T) { } ctrl := newFakeController(&fakeData{apps: []runtime.Object{app}}, nil) fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) - receivedPatch := map[string]interface{}{} + receivedPatch := map[string]any{} fakeAppCs.PrependReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { if patchAction, ok := action.(kubetesting.PatchAction); ok { require.NoError(t, json.Unmarshal(patchAction.GetPatch(), &receivedPatch)) @@ -2000,7 +2000,7 @@ func TestProcessRequestedAppOperation_InvalidDestination(t *testing.T) { proj.Spec.SourceNamespaces = []string{test.FakeArgoCDNamespace} ctrl := newFakeController(&fakeData{apps: []runtime.Object{app, &proj}}, nil) fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) - receivedPatch := map[string]interface{}{} + receivedPatch := map[string]any{} func() { fakeAppCs.Lock() defer fakeAppCs.Unlock() @@ -2029,7 +2029,7 @@ func TestProcessRequestedAppOperation_FailedHasRetries(t *testing.T) { } ctrl := newFakeController(&fakeData{apps: []runtime.Object{app}}, nil) fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) - receivedPatch := map[string]interface{}{} + receivedPatch := map[string]any{} fakeAppCs.PrependReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { if patchAction, ok := action.(kubetesting.PatchAction); ok { require.NoError(t, json.Unmarshal(patchAction.GetPatch(), &receivedPatch)) @@ -2072,7 +2072,7 @@ func TestProcessRequestedAppOperation_RunningPreviouslyFailed(t *testing.T) { } ctrl := newFakeController(data, nil) fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) - receivedPatch := map[string]interface{}{} + receivedPatch := map[string]any{} fakeAppCs.PrependReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { if patchAction, ok := action.(kubetesting.PatchAction); ok { require.NoError(t, json.Unmarshal(patchAction.GetPatch(), &receivedPatch)) @@ -2105,7 +2105,7 @@ func TestProcessRequestedAppOperation_HasRetriesTerminated(t *testing.T) { } ctrl := newFakeController(data, nil) fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) - receivedPatch := map[string]interface{}{} + receivedPatch := map[string]any{} fakeAppCs.PrependReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { if patchAction, ok := action.(kubetesting.PatchAction); ok { require.NoError(t, json.Unmarshal(patchAction.GetPatch(), &receivedPatch)) @@ -2132,7 +2132,7 @@ func TestProcessRequestedAppOperation_Successful(t *testing.T) { }}, }, nil) fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) - receivedPatch := map[string]interface{}{} + receivedPatch := map[string]any{} fakeAppCs.PrependReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { if patchAction, ok := action.(kubetesting.PatchAction); ok { require.NoError(t, json.Unmarshal(patchAction.GetPatch(), &receivedPatch)) @@ -2275,7 +2275,7 @@ func Test_canProcessAppSkipReconcileAnnotation(t *testing.T) { ctrl := newFakeController(&fakeData{}, nil) tests := []struct { name string - input interface{} + input any expected bool }{ {"No skip reconcile annotation", newFakeApp(), true}, @@ -2355,7 +2355,7 @@ func TestHelmValuesObjectHasReplaceStrategy(t *testing.T) { Source: v1alpha1.ApplicationSource{ Helm: &v1alpha1.ApplicationSourceHelm{ ValuesObject: &runtime.RawExtension{ - Object: &unstructured.Unstructured{Object: map[string]interface{}{"key": []string{"value"}}}, + Object: &unstructured.Unstructured{Object: map[string]any{"key": []string{"value"}}}, }, }, }, @@ -2367,7 +2367,7 @@ func TestHelmValuesObjectHasReplaceStrategy(t *testing.T) { Source: v1alpha1.ApplicationSource{ Helm: &v1alpha1.ApplicationSourceHelm{ ValuesObject: &runtime.RawExtension{ - Object: &unstructured.Unstructured{Object: map[string]interface{}{"key": []string{"value-modified1"}}}, + Object: &unstructured.Unstructured{Object: map[string]any{"key": []string{"value-modified1"}}}, }, }, }, @@ -2402,7 +2402,7 @@ func TestAppStatusIsReplaced(t *testing.T) { require.NoError(t, err) require.True(t, ok) - patchObj := map[string]interface{}{} + patchObj := map[string]any{} require.NoError(t, json.Unmarshal(patchData, &patchObj)) val, has, err := unstructured.NestedFieldNoCopy(patchObj, "sync", "comparedTo", "destination", "server") diff --git a/controller/cache/cache.go b/controller/cache/cache.go index 266c6ab0fd6cc4..0a95917df87856 100644 --- a/controller/cache/cache.go +++ b/controller/cache/cache.go @@ -536,7 +536,7 @@ func (c *liveStateCache) getCluster(server string) (clustercache.ClusterCache, e clustercache.SetSettings(cacheSettings.clusterSettings), clustercache.SetNamespaces(cluster.Namespaces), clustercache.SetClusterResources(cluster.ClusterResources), - clustercache.SetPopulateResourceInfoHandler(func(un *unstructured.Unstructured, isRoot bool) (interface{}, bool) { + clustercache.SetPopulateResourceInfoHandler(func(un *unstructured.Unstructured, isRoot bool) (any, bool) { res := &ResourceInfo{} populateNodeInfo(un, res, resourceCustomLabels) c.lock.RLock() @@ -733,7 +733,7 @@ func (c *liveStateCache) GetVersionsInfo(serverURL string) (string, []kube.APIRe return clusterInfo.GetServerVersion(), clusterInfo.GetAPIResources(), nil } -func (c *liveStateCache) isClusterHasApps(apps []interface{}, cluster *appv1.Cluster) bool { +func (c *liveStateCache) isClusterHasApps(apps []any, cluster *appv1.Cluster) bool { for _, obj := range apps { app, ok := obj.(*appv1.Application) if !ok { diff --git a/controller/cache/info.go b/controller/cache/info.go index 635000e688ce38..619a07fc9d85a8 100644 --- a/controller/cache/info.go +++ b/controller/cache/info.go @@ -79,7 +79,7 @@ func getIngress(un *unstructured.Unstructured) []v1.LoadBalancerIngress { } res := make([]v1.LoadBalancerIngress, 0) for _, item := range ingress { - if lbIngress, ok := item.(map[string]interface{}); ok { + if lbIngress, ok := item.(map[string]any); ok { if hostname := lbIngress["hostname"]; hostname != nil { res = append(res, v1.LoadBalancerIngress{Hostname: fmt.Sprintf("%s", hostname)}) } else if ip := lbIngress["ip"]; ip != nil { @@ -105,7 +105,7 @@ func populateServiceInfo(un *unstructured.Unstructured, res *ResourceInfo) { res.NetworkingInfo = &v1alpha1.ResourceNetworkingInfo{TargetLabels: targetLabels, Ingress: ingress, ExternalURLs: urls} } -func getServiceName(backend map[string]interface{}, gvk schema.GroupVersionKind) (string, error) { +func getServiceName(backend map[string]any, gvk schema.GroupVersionKind) (string, error) { switch gvk.Group { case "extensions": return fmt.Sprintf("%s", backend["serviceName"]), nil @@ -139,7 +139,7 @@ func populateIngressInfo(un *unstructured.Unstructured, res *ResourceInfo) { urlsSet := make(map[string]bool) if rules, ok, err := unstructured.NestedSlice(un.Object, "spec", "rules"); ok && err == nil { for i := range rules { - rule, ok := rules[i].(map[string]interface{}) + rule, ok := rules[i].(map[string]any) if !ok { continue } @@ -157,7 +157,7 @@ func populateIngressInfo(un *unstructured.Unstructured, res *ResourceInfo) { continue } for i := range paths { - path, ok := paths[i].(map[string]interface{}) + path, ok := paths[i].(map[string]any) if !ok { continue } @@ -179,7 +179,7 @@ func populateIngressInfo(un *unstructured.Unstructured, res *ResourceInfo) { stringPort := "http" if tls, ok, err := unstructured.NestedSlice(un.Object, "spec", "tls"); ok && err == nil { for i := range tls { - tlsline, ok := tls[i].(map[string]interface{}) + tlsline, ok := tls[i].(map[string]any) secretName := tlsline["secretName"] if ok && secretName != nil { stringPort = "https" @@ -190,7 +190,7 @@ func populateIngressInfo(un *unstructured.Unstructured, res *ResourceInfo) { continue } if hosts := tlsline["hosts"]; hosts != nil { - tlshosts, ok := tlsline["hosts"].(map[string]interface{}) + tlshosts, ok := tlsline["hosts"].(map[string]any) if ok { for j := range tlshosts { if tlshosts[j] == host { @@ -233,7 +233,7 @@ func populateIstioVirtualServiceInfo(un *unstructured.Unstructured, res *Resourc if rules, ok, err := unstructured.NestedSlice(un.Object, "spec", "http"); ok && err == nil { for i := range rules { - rule, ok := rules[i].(map[string]interface{}) + rule, ok := rules[i].(map[string]any) if !ok { continue } @@ -242,7 +242,7 @@ func populateIstioVirtualServiceInfo(un *unstructured.Unstructured, res *Resourc continue } for i := range routes { - route, ok := routes[i].(map[string]interface{}) + route, ok := routes[i].(map[string]any) if !ok { continue } diff --git a/controller/cache/info_test.go b/controller/cache/info_test.go index db58d209f19b8e..70a3ebeae7f451 100644 --- a/controller/cache/info_test.go +++ b/controller/cache/info_test.go @@ -20,7 +20,7 @@ import ( ) func strToUnstructured(jsonStr string) *unstructured.Unstructured { - obj := make(map[string]interface{}) + obj := make(map[string]any) err := yaml.Unmarshal([]byte(jsonStr), &obj) errors.CheckError(err) return &unstructured.Unstructured{Object: obj} diff --git a/controller/metrics/metrics.go b/controller/metrics/metrics.go index 70339499e0a13d..7ddcf9eaea4094 100644 --- a/controller/metrics/metrics.go +++ b/controller/metrics/metrics.go @@ -172,7 +172,7 @@ var ( ) // NewMetricsServer returns a new prometheus server which collects application metrics -func NewMetricsServer(addr string, appLister applister.ApplicationLister, appFilter func(obj interface{}) bool, healthCheck func(r *http.Request) error, appLabels []string, appConditions []string) (*MetricsServer, error) { +func NewMetricsServer(addr string, appLister applister.ApplicationLister, appFilter func(obj any) bool, healthCheck func(r *http.Request) error, appLabels []string, appConditions []string) (*MetricsServer, error) { hostname, err := os.Hostname() if err != nil { return nil, err @@ -350,13 +350,13 @@ func (m *MetricsServer) SetExpiration(cacheExpiration time.Duration) error { type appCollector struct { store applister.ApplicationLister - appFilter func(obj interface{}) bool + appFilter func(obj any) bool appLabels []string appConditions []string } // NewAppCollector returns a prometheus collector for application metrics -func NewAppCollector(appLister applister.ApplicationLister, appFilter func(obj interface{}) bool, appLabels []string, appConditions []string) prometheus.Collector { +func NewAppCollector(appLister applister.ApplicationLister, appFilter func(obj any) bool, appLabels []string, appConditions []string) prometheus.Collector { return &appCollector{ store: appLister, appFilter: appFilter, @@ -366,7 +366,7 @@ func NewAppCollector(appLister applister.ApplicationLister, appFilter func(obj i } // NewAppRegistry creates a new prometheus registry that collects applications -func NewAppRegistry(appLister applister.ApplicationLister, appFilter func(obj interface{}) bool, appLabels []string, appConditions []string) *prometheus.Registry { +func NewAppRegistry(appLister applister.ApplicationLister, appFilter func(obj any) bool, appLabels []string, appConditions []string) *prometheus.Registry { registry := prometheus.NewRegistry() registry.MustRegister(NewAppCollector(appLister, appFilter, appLabels, appConditions)) return registry diff --git a/controller/metrics/metrics_test.go b/controller/metrics/metrics_test.go index 383cb0c0c3d5ac..5410e274e386c7 100644 --- a/controller/metrics/metrics_test.go +++ b/controller/metrics/metrics_test.go @@ -175,7 +175,7 @@ var noOpHealthCheck = func(r *http.Request) error { return nil } -var appFilter = func(obj interface{}) bool { +var appFilter = func(obj any) bool { return true } diff --git a/controller/sync.go b/controller/sync.go index 13d31311a8a28a..81dc317feb353a 100644 --- a/controller/sync.go +++ b/controller/sync.go @@ -529,7 +529,7 @@ func getMergePatch(original, modified *unstructured.Unstructured, lookupPatchMet // applyMergePatch will apply the given patch in the obj and return the patched // unstructure. -func applyMergePatch(obj *unstructured.Unstructured, patch []byte, versionedObject interface{}) (*unstructured.Unstructured, error) { +func applyMergePatch(obj *unstructured.Unstructured, patch []byte, versionedObject any) (*unstructured.Unstructured, error) { originalJSON, err := obj.MarshalJSON() if err != nil { return nil, err diff --git a/controller/sync_test.go b/controller/sync_test.go index 5560ffc2ec9713..bd790bc1c8cd6b 100644 --- a/controller/sync_test.go +++ b/controller/sync_test.go @@ -508,19 +508,19 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) { require.Len(t, patchedTargets, 1) // live should have 1 entry - require.Len(t, dig[[]any](f.comparisonResult.reconciliationResult.Live[0].Object, []interface{}{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors"}), 1) + require.Len(t, dig[[]any](f.comparisonResult.reconciliationResult.Live[0].Object, []any{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors"}), 1) // assert some arbitrary field to show `entries[0]` is not an empty object - require.Equal(t, "sample-header", dig[string](f.comparisonResult.reconciliationResult.Live[0].Object, []interface{}{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors", 0, "entries", 0, "requestHeader", "headerName"})) + require.Equal(t, "sample-header", dig[string](f.comparisonResult.reconciliationResult.Live[0].Object, []any{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors", 0, "entries", 0, "requestHeader", "headerName"})) // target has 2 entries - require.Len(t, dig[[]any](f.comparisonResult.reconciliationResult.Target[0].Object, []interface{}{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors", 0, "entries"}), 2) + require.Len(t, dig[[]any](f.comparisonResult.reconciliationResult.Target[0].Object, []any{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors", 0, "entries"}), 2) // assert some arbitrary field to show `entries[0]` is not an empty object - require.Equal(t, "sample-header", dig[string](f.comparisonResult.reconciliationResult.Target[0].Object, []interface{}{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors", 0, "entries", 0, "requestHeaderValueMatch", "headers", 0, "name"})) + require.Equal(t, "sample-header", dig[string](f.comparisonResult.reconciliationResult.Target[0].Object, []any{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors", 0, "entries", 0, "requestHeaderValueMatch", "headers", 0, "name"})) // It should be *1* entries in the array - require.Len(t, dig[[]any](patchedTargets[0].Object, []interface{}{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors"}), 1) + require.Len(t, dig[[]any](patchedTargets[0].Object, []any{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors"}), 1) // and it should NOT equal an empty object - require.Len(t, dig[any](patchedTargets[0].Object, []interface{}{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors", 0, "entries", 0}), 1) + require.Len(t, dig[any](patchedTargets[0].Object, []any{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors", 0, "entries", 0}), 1) }) t.Run("will correctly set array entries if new entries have been added", func(t *testing.T) { // given @@ -548,10 +548,10 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) { require.True(t, ok) assert.Len(t, containers, 1) - ports := containers[0].(map[string]interface{})["ports"].([]interface{}) + ports := containers[0].(map[string]any)["ports"].([]any) assert.Len(t, ports, 1) - env := containers[0].(map[string]interface{})["env"].([]interface{}) + env := containers[0].(map[string]any)["env"].([]any) assert.Len(t, env, 3) first := env[0] @@ -559,14 +559,14 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) { third := env[2] // Currently the defined order at this time is the insertion order of the target manifest. - assert.Equal(t, "SOME_ENV_VAR", first.(map[string]interface{})["name"]) - assert.Equal(t, "some_value", first.(map[string]interface{})["value"]) + assert.Equal(t, "SOME_ENV_VAR", first.(map[string]any)["name"]) + assert.Equal(t, "some_value", first.(map[string]any)["value"]) - assert.Equal(t, "SOME_OTHER_ENV_VAR", second.(map[string]interface{})["name"]) - assert.Equal(t, "some_other_value", second.(map[string]interface{})["value"]) + assert.Equal(t, "SOME_OTHER_ENV_VAR", second.(map[string]any)["name"]) + assert.Equal(t, "some_other_value", second.(map[string]any)["value"]) - assert.Equal(t, "YET_ANOTHER_ENV_VAR", third.(map[string]interface{})["name"]) - assert.Equal(t, "yet_another_value", third.(map[string]interface{})["value"]) + assert.Equal(t, "YET_ANOTHER_ENV_VAR", third.(map[string]any)["name"]) + assert.Equal(t, "yet_another_value", third.(map[string]any)["value"]) }) t.Run("ignore-deployment-image-replicas-changes-additive", func(t *testing.T) { @@ -598,7 +598,7 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) { metadata, ok, err := unstructured.NestedMap(targets[0].Object, "metadata") require.NoError(t, err) require.True(t, ok) - labels, ok := metadata["labels"].(map[string]interface{}) + labels, ok := metadata["labels"].(map[string]any) require.True(t, ok) assert.Len(t, labels, 2) assert.Equal(t, "web", labels["appProcess"]) @@ -609,29 +609,29 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) { assert.Equal(t, int64(1), spec["replicas"]) - template, ok := spec["template"].(map[string]interface{}) + template, ok := spec["template"].(map[string]any) require.True(t, ok) - tMetadata, ok := template["metadata"].(map[string]interface{}) + tMetadata, ok := template["metadata"].(map[string]any) require.True(t, ok) - tLabels, ok := tMetadata["labels"].(map[string]interface{}) + tLabels, ok := tMetadata["labels"].(map[string]any) require.True(t, ok) assert.Len(t, tLabels, 2) assert.Equal(t, "web", tLabels["appProcess"]) - tSpec, ok := template["spec"].(map[string]interface{}) + tSpec, ok := template["spec"].(map[string]any) require.True(t, ok) containers, ok, err := unstructured.NestedSlice(tSpec, "containers") require.NoError(t, err) require.True(t, ok) assert.Len(t, containers, 1) - first := containers[0].(map[string]interface{}) + first := containers[0].(map[string]any) assert.Equal(t, "alpine:3", first["image"]) - resources, ok := first["resources"].(map[string]interface{}) + resources, ok := first["resources"].(map[string]any) require.True(t, ok) - requests, ok := resources["requests"].(map[string]interface{}) + requests, ok := resources["requests"].(map[string]any) require.True(t, ok) assert.Equal(t, "400m", requests["cpu"]) @@ -640,7 +640,7 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) { require.True(t, ok) assert.Len(t, env, 1) - env0 := env[0].(map[string]interface{}) + env0 := env[0].(map[string]any) assert.Equal(t, "EV", env0["name"]) assert.Equal(t, "here", env0["value"]) }) @@ -1411,15 +1411,15 @@ func TestSyncWithImpersonate(t *testing.T) { }) } -func dig[T any](obj interface{}, path []interface{}) T { +func dig[T any](obj any, path []any) T { i := obj for _, segment := range path { switch segment.(type) { case int: - i = i.([]interface{})[segment.(int)] + i = i.([]any)[segment.(int)] case string: - i = i.(map[string]interface{})[segment.(string)] + i = i.(map[string]any)[segment.(string)] default: panic("invalid path for object") } diff --git a/hack/dev-mounter/main.go b/hack/dev-mounter/main.go index b74d46c170326d..c53ec4d8b84651 100644 --- a/hack/dev-mounter/main.go +++ b/hack/dev-mounter/main.go @@ -49,7 +49,7 @@ func newCommand() *cobra.Command { cmNameToPath[parts[0]] = parts[1] } - handledConfigMap := func(obj interface{}) { + handledConfigMap := func(obj any) { cm, ok := obj.(*v1.ConfigMap) if !ok { return @@ -99,7 +99,7 @@ func newCommand() *cobra.Command { informer := factory.Core().V1().ConfigMaps().Informer() _, err = informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: handledConfigMap, - UpdateFunc: func(oldObj, newObj interface{}) { + UpdateFunc: func(oldObj, newObj any) { handledConfigMap(newObj) }, }) diff --git a/hack/gen-crd-spec/main.go b/hack/gen-crd-spec/main.go index 16c0022dd1cb15..4cce0b257965f8 100644 --- a/hack/gen-crd-spec/main.go +++ b/hack/gen-crd-spec/main.go @@ -94,13 +94,13 @@ func toCRD(un *unstructured.Unstructured, removeDesc bool) *extensionsobj.Custom return &crd } -func removeDescription(v interface{}) { +func removeDescription(v any) { switch v := v.(type) { - case []interface{}: + case []any: for _, v := range v { removeDescription(v) } - case map[string]interface{}: + case map[string]any: if _, ok := v["description"]; ok { _, ok := v["description"].(string) if ok { diff --git a/hack/gen-docs/main.go b/hack/gen-docs/main.go index c39f4628a432c8..a51c59eac9c873 100644 --- a/hack/gen-docs/main.go +++ b/hack/gen-docs/main.go @@ -43,22 +43,22 @@ func updateMkDocsNav(parent string, child string, subchild string, files []strin if e := yaml.Unmarshal(data, &un.Object); e != nil { return e } - nav := un.Object["nav"].([]interface{}) + nav := un.Object["nav"].([]any) rootitem, _ := findNavItem(nav, parent) if rootitem == nil { return fmt.Errorf("can't find '%s' root item in mkdoc.yml", parent) } - rootnavitemmap := rootitem.(map[interface{}]interface{}) - childnav, _ := findNavItem(rootnavitemmap[parent].([]interface{}), child) + rootnavitemmap := rootitem.(map[any]any) + childnav, _ := findNavItem(rootnavitemmap[parent].([]any), child) if childnav == nil { return fmt.Errorf("can't find '%s' chile item under '%s' parent item in mkdoc.yml", child, parent) } - childnavmap := childnav.(map[interface{}]interface{}) - childnavitems := childnavmap[child].([]interface{}) + childnavmap := childnav.(map[any]any) + childnavitems := childnavmap[child].([]any) childnavitems = removeNavItem(childnavitems, subchild) - commands := make(map[string]interface{}) + commands := make(map[string]any) commands[subchild] = files childnavmap[child] = append(childnavitems, commands) newmkdocs, err := yaml.Marshal(un.Object) @@ -79,9 +79,9 @@ func trimPrefixes(files []string, prefix string) { } } -func findNavItem(nav []interface{}, key string) (interface{}, int) { +func findNavItem(nav []any, key string) (any, int) { for i, item := range nav { - o, ismap := item.(map[interface{}]interface{}) + o, ismap := item.(map[any]any) if ismap { if _, ok := o[key]; ok { return o, i @@ -91,7 +91,7 @@ func findNavItem(nav []interface{}, key string) (interface{}, int) { return nil, -1 } -func removeNavItem(nav []interface{}, key string) []interface{} { +func removeNavItem(nav []any, key string) []any { _, i := findNavItem(nav, key) if i != -1 { nav = append(nav[:i], nav[i+1:]...) diff --git a/hack/known_types/main.go b/hack/known_types/main.go index 247fadffd908ca..88fdbadb459dec 100644 --- a/hack/known_types/main.go +++ b/hack/known_types/main.go @@ -65,7 +65,7 @@ func newCommand() *cobra.Command { docs = append(docs, fmt.Sprintf("%s/%s", shortPackagePath, typeName.Name())) mapItems = append(mapItems, fmt.Sprintf(` - knownTypes["%s/%s"] = func() interface{} { + knownTypes["%s/%s"] = func() any { return &%s.%s{} }`, shortPackagePath, typeName.Name(), alias, typeName.Name())) } diff --git a/notification_controller/controller/controller_test.go b/notification_controller/controller/controller_test.go index ca901cf2c1890c..a1c7082a559d71 100644 --- a/notification_controller/controller/controller_test.go +++ b/notification_controller/controller/controller_test.go @@ -29,8 +29,8 @@ func TestIsAppSyncStatusRefreshed(t *testing.T) { { name: "No OperationState", app: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{}, + Object: map[string]any{ + "status": map[string]any{}, }, }, expectedValue: true, @@ -38,9 +38,9 @@ func TestIsAppSyncStatusRefreshed(t *testing.T) { { name: "No FinishedAt, Completed Phase", app: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ - "operationState": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ + "operationState": map[string]any{ "phase": "Succeeded", }, }, @@ -51,9 +51,9 @@ func TestIsAppSyncStatusRefreshed(t *testing.T) { { name: "FinishedAt After ReconciledAt & ObservedAt", app: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ - "operationState": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ + "operationState": map[string]any{ "finishedAt": "2021-01-01T01:05:00Z", "phase": "Succeeded", }, @@ -67,9 +67,9 @@ func TestIsAppSyncStatusRefreshed(t *testing.T) { { name: "FinishedAt Before ReconciledAt & ObservedAt", app: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ - "operationState": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ + "operationState": map[string]any{ "finishedAt": "2021-01-01T01:02:00Z", "phase": "Succeeded", }, @@ -92,8 +92,8 @@ func TestIsAppSyncStatusRefreshed(t *testing.T) { func TestGetAppProj_invalidProjectNestedString(t *testing.T) { app := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{}, + Object: map[string]any{ + "spec": map[string]any{}, }, } informer := cache.NewSharedIndexInformer(nil, nil, 0, nil) @@ -176,8 +176,8 @@ func TestInitTimeout(t *testing.T) { func TestCheckAppNotInAdditionalNamespaces(t *testing.T) { app := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{}, + Object: map[string]any{ + "spec": map[string]any{}, }, } namespace := "argocd" diff --git a/pkg/apiclient/application/forwarder_overwrite.go b/pkg/apiclient/application/forwarder_overwrite.go index 4769775f9671f2..ed48b0d559824e 100644 --- a/pkg/apiclient/application/forwarder_overwrite.go +++ b/pkg/apiclient/application/forwarder_overwrite.go @@ -21,48 +21,48 @@ import ( // appFields is a map of fields that can be selected from an application. // The manually maintained list is required because application list response might include thousands of applications // and JSON based field handling is too slow. -var appFields = map[string]func(app *v1alpha1.Application) interface{}{ - "metadata.name": func(app *v1alpha1.Application) interface{} { return app.Name }, - "metadata.namespace": func(app *v1alpha1.Application) interface{} { return app.Namespace }, - "metadata.annotations": func(app *v1alpha1.Application) interface{} { return app.Annotations }, - "metadata.labels": func(app *v1alpha1.Application) interface{} { return app.Labels }, - "metadata.creationTimestamp": func(app *v1alpha1.Application) interface{} { return app.CreationTimestamp }, - "metadata.deletionTimestamp": func(app *v1alpha1.Application) interface{} { return app.DeletionTimestamp }, - "spec": func(app *v1alpha1.Application) interface{} { return app.Spec }, - "status.sync.status": func(app *v1alpha1.Application) interface{} { return app.Status.Sync.Status }, - "status.health": func(app *v1alpha1.Application) interface{} { return app.Status.Health }, - "status.summary": func(app *v1alpha1.Application) interface{} { return app.Status.Summary }, - "status.operationState.startedAt": func(app *v1alpha1.Application) interface{} { +var appFields = map[string]func(app *v1alpha1.Application) any{ + "metadata.name": func(app *v1alpha1.Application) any { return app.Name }, + "metadata.namespace": func(app *v1alpha1.Application) any { return app.Namespace }, + "metadata.annotations": func(app *v1alpha1.Application) any { return app.Annotations }, + "metadata.labels": func(app *v1alpha1.Application) any { return app.Labels }, + "metadata.creationTimestamp": func(app *v1alpha1.Application) any { return app.CreationTimestamp }, + "metadata.deletionTimestamp": func(app *v1alpha1.Application) any { return app.DeletionTimestamp }, + "spec": func(app *v1alpha1.Application) any { return app.Spec }, + "status.sync.status": func(app *v1alpha1.Application) any { return app.Status.Sync.Status }, + "status.health": func(app *v1alpha1.Application) any { return app.Status.Health }, + "status.summary": func(app *v1alpha1.Application) any { return app.Status.Summary }, + "status.operationState.startedAt": func(app *v1alpha1.Application) any { if app.Status.OperationState != nil { return app.Status.OperationState.StartedAt } return nil }, - "status.operationState.finishedAt": func(app *v1alpha1.Application) interface{} { + "status.operationState.finishedAt": func(app *v1alpha1.Application) any { if app.Status.OperationState != nil { return app.Status.OperationState.FinishedAt } return nil }, - "status.resources": func(app *v1alpha1.Application) interface{} { + "status.resources": func(app *v1alpha1.Application) any { if len(app.Status.Resources) > 0 { return app.Status.Resources } return nil }, - "operation.sync": func(app *v1alpha1.Application) interface{} { + "operation.sync": func(app *v1alpha1.Application) any { if app.Operation != nil { return app.Operation.Sync } return nil }, - "status.operationState.phase": func(app *v1alpha1.Application) interface{} { + "status.operationState.phase": func(app *v1alpha1.Application) any { if app.Status.OperationState != nil { return app.Status.OperationState.Phase } return nil }, - "status.operationState.operation.sync": func(app *v1alpha1.Application) interface{} { + "status.operationState.operation.sync": func(app *v1alpha1.Application) any { if app.Status.OperationState != nil { return app.Status.OperationState.SyncResult } @@ -70,11 +70,11 @@ var appFields = map[string]func(app *v1alpha1.Application) interface{}{ }, } -func processApplicationListField(v interface{}, fields map[string]interface{}, exclude bool) (interface{}, error) { +func processApplicationListField(v any, fields map[string]any, exclude bool) (any, error) { if appList, ok := v.(*v1alpha1.ApplicationList); ok { - var items []map[string]interface{} + var items []map[string]any for _, app := range appList.Items { - converted := make(map[string]interface{}) + converted := make(map[string]any) items = append(items, converted) for field, fn := range appFields { if _, ok := fields["items."+field]; ok == exclude { @@ -92,9 +92,9 @@ func processApplicationListField(v interface{}, fields map[string]interface{}, e item[subField] = value } else { if _, ok := item[subField]; !ok { - item[subField] = make(map[string]interface{}) + item[subField] = make(map[string]any) } - nestedMap, ok := item[subField].(map[string]interface{}) + nestedMap, ok := item[subField].(map[string]any) if !ok { return nil, fmt.Errorf("field %s is not a map", field) } @@ -103,7 +103,7 @@ func processApplicationListField(v interface{}, fields map[string]interface{}, e } } } - return map[string]interface{}{ + return map[string]any{ "items": items, "metadata": appList.ListMeta, }, nil diff --git a/pkg/apiclient/application/forwarder_overwrite_test.go b/pkg/apiclient/application/forwarder_overwrite_test.go index 370a84173997b3..27aa579fe6f88d 100644 --- a/pkg/apiclient/application/forwarder_overwrite_test.go +++ b/pkg/apiclient/application/forwarder_overwrite_test.go @@ -17,12 +17,12 @@ func TestProcessApplicationListField_SyncOperation(t *testing.T) { }}}}, } - res, err := processApplicationListField(&list, map[string]interface{}{"items.operation.sync": true}, false) + res, err := processApplicationListField(&list, map[string]any{"items.operation.sync": true}, false) require.NoError(t, err) - resMap, ok := res.(map[string]interface{}) + resMap, ok := res.(map[string]any) require.True(t, ok) - items, ok := resMap["items"].([]map[string]interface{}) + items, ok := resMap["items"].([]map[string]any) require.True(t, ok) item := test.ToMap(items[0]) @@ -38,12 +38,12 @@ func TestProcessApplicationListField_SyncOperationMissing(t *testing.T) { Items: []v1alpha1.Application{{Operation: nil}}, } - res, err := processApplicationListField(&list, map[string]interface{}{"items.operation.sync": true}, false) + res, err := processApplicationListField(&list, map[string]any{"items.operation.sync": true}, false) require.NoError(t, err) - resMap, ok := res.(map[string]interface{}) + resMap, ok := res.(map[string]any) require.True(t, ok) - items, ok := resMap["items"].([]map[string]interface{}) + items, ok := resMap["items"].([]map[string]any) require.True(t, ok) item := test.ToMap(items[0]) diff --git a/pkg/apiclient/grpcproxy.go b/pkg/apiclient/grpcproxy.go index 9d3c849c992b3a..70fcafb805f7dc 100644 --- a/pkg/apiclient/grpcproxy.go +++ b/pkg/apiclient/grpcproxy.go @@ -31,11 +31,11 @@ const ( type noopCodec struct{} -func (noopCodec) Marshal(v interface{}) ([]byte, error) { +func (noopCodec) Marshal(v any) ([]byte, error) { return v.([]byte), nil } -func (noopCodec) Unmarshal(data []byte, v interface{}) error { +func (noopCodec) Unmarshal(data []byte, v any) error { pointer := v.(*[]byte) *pointer = data return nil @@ -118,7 +118,7 @@ func (c *client) startGRPCProxy() (*grpc.Server, net.Listener, error) { MinTime: common.GetGRPCKeepAliveEnforcementMinimum(), }, ), - grpc.UnknownServiceHandler(func(srv interface{}, stream grpc.ServerStream) error { + grpc.UnknownServiceHandler(func(srv any, stream grpc.ServerStream) error { fullMethodName, ok := grpc.MethodFromServerStream(stream) if !ok { return errors.New("Unable to get method name from stream context.") diff --git a/pkg/apis/application/v1alpha1/openapi_generated.go b/pkg/apis/application/v1alpha1/openapi_generated.go index 28492686a8003d..e11b186964db75 100644 --- a/pkg/apis/application/v1alpha1/openapi_generated.go +++ b/pkg/apis/application/v1alpha1/openapi_generated.go @@ -239,19 +239,19 @@ func schema_pkg_apis_application_v1alpha1_AppProject(ref common.ReferenceCallbac }, "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), }, }, "spec": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.AppProjectSpec"), }, }, "status": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.AppProjectStatus"), }, }, @@ -287,7 +287,7 @@ func schema_pkg_apis_application_v1alpha1_AppProjectList(ref common.ReferenceCal }, "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), }, }, @@ -297,7 +297,7 @@ func schema_pkg_apis_application_v1alpha1_AppProjectList(ref common.ReferenceCal Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.AppProject"), }, }, @@ -342,7 +342,7 @@ func schema_pkg_apis_application_v1alpha1_AppProjectSpec(ref common.ReferenceCal Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationDestination"), }, }, @@ -363,7 +363,7 @@ func schema_pkg_apis_application_v1alpha1_AppProjectSpec(ref common.ReferenceCal Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ProjectRole"), }, }, @@ -377,7 +377,7 @@ func schema_pkg_apis_application_v1alpha1_AppProjectSpec(ref common.ReferenceCal Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind"), }, }, @@ -391,7 +391,7 @@ func schema_pkg_apis_application_v1alpha1_AppProjectSpec(ref common.ReferenceCal Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind"), }, }, @@ -424,7 +424,7 @@ func schema_pkg_apis_application_v1alpha1_AppProjectSpec(ref common.ReferenceCal Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind"), }, }, @@ -438,7 +438,7 @@ func schema_pkg_apis_application_v1alpha1_AppProjectSpec(ref common.ReferenceCal Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.SignatureKey"), }, }, @@ -452,7 +452,7 @@ func schema_pkg_apis_application_v1alpha1_AppProjectSpec(ref common.ReferenceCal Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind"), }, }, @@ -488,7 +488,7 @@ func schema_pkg_apis_application_v1alpha1_AppProjectSpec(ref common.ReferenceCal Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationDestinationServiceAccount"), }, }, @@ -518,7 +518,7 @@ func schema_pkg_apis_application_v1alpha1_AppProjectStatus(ref common.ReferenceC Allows: true, Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.JWTTokens"), }, }, @@ -556,19 +556,19 @@ func schema_pkg_apis_application_v1alpha1_Application(ref common.ReferenceCallba }, "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), }, }, "spec": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSpec"), }, }, "status": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationStatus"), }, }, @@ -715,7 +715,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationList(ref common.ReferenceCa }, "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), }, }, @@ -725,7 +725,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationList(ref common.ReferenceCa Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.Application"), }, }, @@ -842,19 +842,19 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSet(ref common.ReferenceCal }, "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), }, }, "spec": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetSpec"), }, }, "status": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetStatus"), }, }, @@ -1079,7 +1079,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetList(ref common.Referenc }, "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), }, }, @@ -1089,7 +1089,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetList(ref common.Referenc Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSet"), }, }, @@ -1235,7 +1235,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetRolloutStep(ref common.R Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationMatchExpression"), }, }, @@ -1267,7 +1267,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetRolloutStrategy(ref comm Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetRolloutStep"), }, }, @@ -1301,7 +1301,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetSpec(ref common.Referenc Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetGenerator"), }, }, @@ -1310,7 +1310,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetSpec(ref common.Referenc }, "template": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTemplate"), }, }, @@ -1356,7 +1356,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetSpec(ref common.Referenc Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetResourceIgnoreDifferences"), }, }, @@ -1392,7 +1392,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetStatus(ref common.Refere Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetCondition"), }, }, @@ -1405,7 +1405,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetStatus(ref common.Refere Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetApplicationStatus"), }, }, @@ -1419,7 +1419,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetStatus(ref common.Refere Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ResourceStatus"), }, }, @@ -1496,13 +1496,13 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetTemplate(ref common.Refe Properties: map[string]spec.Schema{ "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTemplateMeta"), }, }, "spec": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSpec"), }, }, @@ -1654,7 +1654,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSetTree(ref common.Referenc Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ResourceNode"), }, }, @@ -1762,7 +1762,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSourceDirectory(ref common. "jsonnet": { SchemaProps: spec.SchemaProps{ Description: "Jsonnet holds options specific to Jsonnet", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSourceJsonnet"), }, }, @@ -1817,7 +1817,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSourceHelm(ref common.Refer Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.HelmParameter"), }, }, @@ -1850,7 +1850,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSourceHelm(ref common.Refer Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.HelmFileParameter"), }, }, @@ -1942,7 +1942,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSourceJsonnet(ref common.Re Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.JsonnetVar"), }, }, @@ -1956,7 +1956,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSourceJsonnet(ref common.Re Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.JsonnetVar"), }, }, @@ -2096,7 +2096,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSourceKustomize(ref common. Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.KustomizeReplica"), }, }, @@ -2110,7 +2110,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSourceKustomize(ref common. Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.KustomizePatch"), }, }, @@ -2200,7 +2200,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSourcePlugin(ref common.Ref Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSourcePluginParameter"), }, }, @@ -2257,7 +2257,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSpec(ref common.ReferenceCa "destination": { SchemaProps: spec.SchemaProps{ Description: "Destination is a reference to the target Kubernetes server and namespace", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationDestination"), }, }, @@ -2282,7 +2282,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSpec(ref common.ReferenceCa Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ResourceIgnoreDifferences"), }, }, @@ -2296,7 +2296,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSpec(ref common.ReferenceCa Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.Info"), }, }, @@ -2317,7 +2317,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationSpec(ref common.ReferenceCa Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSource"), }, }, @@ -2353,7 +2353,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationStatus(ref common.Reference Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ResourceStatus"), }, }, @@ -2363,14 +2363,14 @@ func schema_pkg_apis_application_v1alpha1_ApplicationStatus(ref common.Reference "sync": { SchemaProps: spec.SchemaProps{ Description: "Sync contains information about the application's current sync status", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.SyncStatus"), }, }, "health": { SchemaProps: spec.SchemaProps{ Description: "Health contains information about the application's current health status", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.HealthStatus"), }, }, @@ -2381,7 +2381,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationStatus(ref common.Reference Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.RevisionHistory"), }, }, @@ -2395,7 +2395,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationStatus(ref common.Reference Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationCondition"), }, }, @@ -2430,7 +2430,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationStatus(ref common.Reference "summary": { SchemaProps: spec.SchemaProps{ Description: "Summary contains a list of URLs and container images used by this application", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSummary"), }, }, @@ -2466,7 +2466,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationStatus(ref common.Reference "sourceHydrator": { SchemaProps: spec.SchemaProps{ Description: "SourceHydrator stores information about the current state of source hydration", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.SourceHydratorStatus"), }, }, @@ -2535,7 +2535,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationTree(ref common.ReferenceCa Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ResourceNode"), }, }, @@ -2549,7 +2549,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationTree(ref common.ReferenceCa Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ResourceNode"), }, }, @@ -2563,7 +2563,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationTree(ref common.ReferenceCa Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.HostInfo"), }, }, @@ -2595,7 +2595,7 @@ func schema_pkg_apis_application_v1alpha1_ApplicationWatchEvent(ref common.Refer "application": { SchemaProps: spec.SchemaProps{ Description: "Application is:\n * If Type is Added or Modified: the new state of the object.\n * If Type is Deleted: the state of the object immediately before deletion.\n * If Type is Error: *api.Status is recommended; other types may make sense\n depending on context.", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.Application"), }, }, @@ -2783,14 +2783,14 @@ func schema_pkg_apis_application_v1alpha1_Cluster(ref common.ReferenceCallback) "config": { SchemaProps: spec.SchemaProps{ Description: "Config holds cluster information for connecting to a cluster", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ClusterConfig"), }, }, "connectionState": { SchemaProps: spec.SchemaProps{ Description: "Deprecated: use Info.ConnectionState field instead. ConnectionState contains information about cluster connection state", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ConnectionState"), }, }, @@ -2825,7 +2825,7 @@ func schema_pkg_apis_application_v1alpha1_Cluster(ref common.ReferenceCallback) "info": { SchemaProps: spec.SchemaProps{ Description: "Info holds information about cluster cache and state", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ClusterInfo"), }, }, @@ -2956,7 +2956,7 @@ func schema_pkg_apis_application_v1alpha1_ClusterConfig(ref common.ReferenceCall "tlsClientConfig": { SchemaProps: spec.SchemaProps{ Description: "TLSClientConfig contains settings to enable transport layer security", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.TLSClientConfig"), }, }, @@ -2991,13 +2991,13 @@ func schema_pkg_apis_application_v1alpha1_ClusterGenerator(ref common.ReferenceC "selector": { SchemaProps: spec.SchemaProps{ Description: "Selector defines a label selector to match against all clusters registered with ArgoCD. Clusters today are stored as Kubernetes Secrets, thus the Secret labels will be used for matching the selector.", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), }, }, "template": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTemplate"), }, }, @@ -3042,7 +3042,7 @@ func schema_pkg_apis_application_v1alpha1_ClusterInfo(ref common.ReferenceCallba "connectionState": { SchemaProps: spec.SchemaProps{ Description: "ConnectionState contains information about the connection to the cluster", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ConnectionState"), }, }, @@ -3056,7 +3056,7 @@ func schema_pkg_apis_application_v1alpha1_ClusterInfo(ref common.ReferenceCallba "cacheInfo": { SchemaProps: spec.SchemaProps{ Description: "CacheInfo contains information about the cluster cache", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ClusterCacheInfo"), }, }, @@ -3101,7 +3101,7 @@ func schema_pkg_apis_application_v1alpha1_ClusterList(ref common.ReferenceCallba Properties: map[string]spec.Schema{ "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), }, }, @@ -3111,7 +3111,7 @@ func schema_pkg_apis_application_v1alpha1_ClusterList(ref common.ReferenceCallba Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.Cluster"), }, }, @@ -3178,14 +3178,14 @@ func schema_pkg_apis_application_v1alpha1_ComparedTo(ref common.ReferenceCallbac "source": { SchemaProps: spec.SchemaProps{ Description: "Source is a reference to the application's source used for comparison", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSource"), }, }, "destination": { SchemaProps: spec.SchemaProps{ Description: "Destination is a reference to the application's destination used for comparison", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationDestination"), }, }, @@ -3196,7 +3196,7 @@ func schema_pkg_apis_application_v1alpha1_ComparedTo(ref common.ReferenceCallbac Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSource"), }, }, @@ -3210,7 +3210,7 @@ func schema_pkg_apis_application_v1alpha1_ComparedTo(ref common.ReferenceCallbac Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ResourceIgnoreDifferences"), }, }, @@ -3281,7 +3281,7 @@ func schema_pkg_apis_application_v1alpha1_ConfigManagementPlugin(ref common.Refe }, "generate": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.Command"), }, }, @@ -3433,13 +3433,13 @@ func schema_pkg_apis_application_v1alpha1_DuckTypeGenerator(ref common.Reference }, "labelSelector": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), }, }, "template": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTemplate"), }, }, @@ -3662,7 +3662,7 @@ func schema_pkg_apis_application_v1alpha1_GitGenerator(ref common.ReferenceCallb Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.GitDirectoryGeneratorItem"), }, }, @@ -3675,7 +3675,7 @@ func schema_pkg_apis_application_v1alpha1_GitGenerator(ref common.ReferenceCallb Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.GitFileGeneratorItem"), }, }, @@ -3697,7 +3697,7 @@ func schema_pkg_apis_application_v1alpha1_GitGenerator(ref common.ReferenceCallb }, "template": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTemplate"), }, }, @@ -3798,7 +3798,7 @@ func schema_pkg_apis_application_v1alpha1_GnuPGPublicKeyList(ref common.Referenc Properties: map[string]spec.Schema{ "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), }, }, @@ -3808,7 +3808,7 @@ func schema_pkg_apis_application_v1alpha1_GnuPGPublicKeyList(ref common.Referenc Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.GnuPGPublicKey"), }, }, @@ -3967,7 +3967,7 @@ func schema_pkg_apis_application_v1alpha1_HostInfo(ref common.ReferenceCallback) Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.HostResourceInfo"), }, }, @@ -3976,7 +3976,7 @@ func schema_pkg_apis_application_v1alpha1_HostInfo(ref common.ReferenceCallback) }, "systemInfo": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/api/core/v1.NodeSystemInfo"), }, }, @@ -4076,7 +4076,7 @@ func schema_pkg_apis_application_v1alpha1_HydrateOperation(ref common.ReferenceC "sourceHydrator": { SchemaProps: spec.SchemaProps{ Description: "SourceHydrator holds the hydrator config used for the hydrate operation", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.SourceHydrator"), }, }, @@ -4211,7 +4211,7 @@ func schema_pkg_apis_application_v1alpha1_JWTTokens(ref common.ReferenceCallback Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.JWTToken"), }, }, @@ -4537,7 +4537,7 @@ func schema_pkg_apis_application_v1alpha1_ListGenerator(ref common.ReferenceCall }, "template": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTemplate"), }, }, @@ -4611,7 +4611,7 @@ func schema_pkg_apis_application_v1alpha1_MatrixGenerator(ref common.ReferenceCa Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetNestedGenerator"), }, }, @@ -4620,7 +4620,7 @@ func schema_pkg_apis_application_v1alpha1_MatrixGenerator(ref common.ReferenceCa }, "template": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTemplate"), }, }, @@ -4646,7 +4646,7 @@ func schema_pkg_apis_application_v1alpha1_MergeGenerator(ref common.ReferenceCal Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetNestedGenerator"), }, }, @@ -4669,7 +4669,7 @@ func schema_pkg_apis_application_v1alpha1_MergeGenerator(ref common.ReferenceCal }, "template": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTemplate"), }, }, @@ -4695,7 +4695,7 @@ func schema_pkg_apis_application_v1alpha1_NestedMatrixGenerator(ref common.Refer Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTerminalGenerator"), }, }, @@ -4724,7 +4724,7 @@ func schema_pkg_apis_application_v1alpha1_NestedMergeGenerator(ref common.Refere Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTerminalGenerator"), }, }, @@ -4770,7 +4770,7 @@ func schema_pkg_apis_application_v1alpha1_Operation(ref common.ReferenceCallback "initiatedBy": { SchemaProps: spec.SchemaProps{ Description: "InitiatedBy contains information about who initiated the operations", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.OperationInitiator"), }, }, @@ -4790,7 +4790,7 @@ func schema_pkg_apis_application_v1alpha1_Operation(ref common.ReferenceCallback "retry": { SchemaProps: spec.SchemaProps{ Description: "Retry controls the strategy to apply if a sync fails", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.RetryStrategy"), }, }, @@ -4839,7 +4839,7 @@ func schema_pkg_apis_application_v1alpha1_OperationState(ref common.ReferenceCal "operation": { SchemaProps: spec.SchemaProps{ Description: "Operation is the original requested operation", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.Operation"), }, }, @@ -4999,7 +4999,7 @@ func schema_pkg_apis_application_v1alpha1_OrphanedResourcesMonitorSettings(ref c Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.OrphanedResourceKey"), }, }, @@ -5103,13 +5103,13 @@ func schema_pkg_apis_application_v1alpha1_PluginGenerator(ref common.ReferenceCa Properties: map[string]spec.Schema{ "configMapRef": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.PluginConfigMapRef"), }, }, "input": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.PluginInput"), }, }, @@ -5122,7 +5122,7 @@ func schema_pkg_apis_application_v1alpha1_PluginGenerator(ref common.ReferenceCa }, "template": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTemplate"), }, }, @@ -5223,7 +5223,7 @@ func schema_pkg_apis_application_v1alpha1_ProjectRole(ref common.ReferenceCallba Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.JWTToken"), }, }, @@ -5289,7 +5289,7 @@ func schema_pkg_apis_application_v1alpha1_PullRequestGenerator(ref common.Refere Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.PullRequestGeneratorFilter"), }, }, @@ -5305,7 +5305,7 @@ func schema_pkg_apis_application_v1alpha1_PullRequestGenerator(ref common.Refere }, "template": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTemplate"), }, }, @@ -5737,7 +5737,7 @@ func schema_pkg_apis_application_v1alpha1_RefTarget(ref common.ReferenceCallback Properties: map[string]spec.Schema{ "Repo": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.Repository"), }, }, @@ -5900,7 +5900,7 @@ func schema_pkg_apis_application_v1alpha1_RepoCredsList(ref common.ReferenceCall Properties: map[string]spec.Schema{ "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), }, }, @@ -5910,7 +5910,7 @@ func schema_pkg_apis_application_v1alpha1_RepoCredsList(ref common.ReferenceCall Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.RepoCreds"), }, }, @@ -5965,7 +5965,7 @@ func schema_pkg_apis_application_v1alpha1_Repository(ref common.ReferenceCallbac "connectionState": { SchemaProps: spec.SchemaProps{ Description: "ConnectionState contains information about the current state of connection to the repository server", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ConnectionState"), }, }, @@ -6166,7 +6166,7 @@ func schema_pkg_apis_application_v1alpha1_RepositoryCertificateList(ref common.R Properties: map[string]spec.Schema{ "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), }, }, @@ -6177,7 +6177,7 @@ func schema_pkg_apis_application_v1alpha1_RepositoryCertificateList(ref common.R Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.RepositoryCertificate"), }, }, @@ -6202,7 +6202,7 @@ func schema_pkg_apis_application_v1alpha1_RepositoryList(ref common.ReferenceCal Properties: map[string]spec.Schema{ "metadata": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), }, }, @@ -6245,7 +6245,7 @@ func schema_pkg_apis_application_v1alpha1_ResourceAction(ref common.ReferenceCal Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ResourceActionParam"), }, }, @@ -6359,7 +6359,7 @@ func schema_pkg_apis_application_v1alpha1_ResourceActions(ref common.ReferenceCa Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ResourceActionDefinition"), }, }, @@ -6574,7 +6574,7 @@ func schema_pkg_apis_application_v1alpha1_ResourceNetworkingInfo(ref common.Refe Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ResourceRef"), }, }, @@ -6602,7 +6602,7 @@ func schema_pkg_apis_application_v1alpha1_ResourceNetworkingInfo(ref common.Refe Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("k8s.io/api/core/v1.LoadBalancerIngress"), }, }, @@ -6681,7 +6681,7 @@ func schema_pkg_apis_application_v1alpha1_ResourceNode(ref common.ReferenceCallb Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ResourceRef"), }, }, @@ -6694,7 +6694,7 @@ func schema_pkg_apis_application_v1alpha1_ResourceNode(ref common.ReferenceCallb Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.InfoItem"), }, }, @@ -6774,13 +6774,13 @@ func schema_pkg_apis_application_v1alpha1_ResourceOverride(ref common.ReferenceC }, "IgnoreDifferences": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.OverrideIgnoreDiff"), }, }, "IgnoreResourceUpdates": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.OverrideIgnoreDiff"), }, }, @@ -6790,7 +6790,7 @@ func schema_pkg_apis_application_v1alpha1_ResourceOverride(ref common.ReferenceC Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.KnownTypeField"), }, }, @@ -7077,7 +7077,7 @@ func schema_pkg_apis_application_v1alpha1_RevisionHistory(ref common.ReferenceCa "source": { SchemaProps: spec.SchemaProps{ Description: "Source is a reference to the application source used for the sync operation", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSource"), }, }, @@ -7094,7 +7094,7 @@ func schema_pkg_apis_application_v1alpha1_RevisionHistory(ref common.ReferenceCa Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSource"), }, }, @@ -7119,7 +7119,7 @@ func schema_pkg_apis_application_v1alpha1_RevisionHistory(ref common.ReferenceCa "initiatedBy": { SchemaProps: spec.SchemaProps{ Description: "InitiatedBy contains information about who initiated the operations", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.OperationInitiator"), }, }, @@ -7235,7 +7235,7 @@ func schema_pkg_apis_application_v1alpha1_SCMProviderGenerator(ref common.Refere Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.SCMProviderGeneratorFilter"), }, }, @@ -7258,7 +7258,7 @@ func schema_pkg_apis_application_v1alpha1_SCMProviderGenerator(ref common.Refere }, "template": { SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSetTemplate"), }, }, @@ -7806,14 +7806,14 @@ func schema_pkg_apis_application_v1alpha1_SourceHydrator(ref common.ReferenceCal "drySource": { SchemaProps: spec.SchemaProps{ Description: "DrySource specifies where the dry \"don't repeat yourself\" manifest source lives.", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.DrySource"), }, }, "syncSource": { SchemaProps: spec.SchemaProps{ Description: "SyncSource specifies where to sync hydrated manifests from.", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.SyncSource"), }, }, @@ -7883,7 +7883,7 @@ func schema_pkg_apis_application_v1alpha1_SuccessfulHydrateOperation(ref common. "sourceHydrator": { SchemaProps: spec.SchemaProps{ Description: "SourceHydrator holds the hydrator config used for the hydrate operation", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.SourceHydrator"), }, }, @@ -7936,7 +7936,7 @@ func schema_pkg_apis_application_v1alpha1_SyncOperation(ref common.ReferenceCall Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.SyncOperationResource"), }, }, @@ -7986,7 +7986,7 @@ func schema_pkg_apis_application_v1alpha1_SyncOperation(ref common.ReferenceCall Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSource"), }, }, @@ -8087,7 +8087,7 @@ func schema_pkg_apis_application_v1alpha1_SyncOperationResult(ref common.Referen "source": { SchemaProps: spec.SchemaProps{ Description: "Source records the application source information of the sync, used for comparing auto-sync", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSource"), }, }, @@ -8098,7 +8098,7 @@ func schema_pkg_apis_application_v1alpha1_SyncOperationResult(ref common.Referen Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ApplicationSource"), }, }, @@ -8265,7 +8265,7 @@ func schema_pkg_apis_application_v1alpha1_SyncStatus(ref common.ReferenceCallbac "comparedTo": { SchemaProps: spec.SchemaProps{ Description: "ComparedTo contains information about what has been compared", - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.ComparedTo"), }, }, @@ -8598,7 +8598,7 @@ func schema_pkg_apis_application_v1alpha1_rawResourceOverride(ref common.Referen Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, + Default: map[string]any{}, Ref: ref("github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1.KnownTypeField"), }, }, diff --git a/pkg/apis/application/v1alpha1/types.go b/pkg/apis/application/v1alpha1/types.go index 8282ce5337d391..8aa6f92605d0f0 100644 --- a/pkg/apis/application/v1alpha1/types.go +++ b/pkg/apis/application/v1alpha1/types.go @@ -953,7 +953,7 @@ func (p ApplicationSourcePluginParameter) Equals(other ApplicationSourcePluginPa // // There are efforts to change things upstream, but nothing has been merged yet. See https://github.com/golang/go/issues/37711 func (p ApplicationSourcePluginParameter) MarshalJSON() ([]byte, error) { - out := map[string]interface{}{} + out := map[string]any{} out["name"] = p.Name if p.String_ != nil { out["string"] = p.String_ diff --git a/pkg/apis/application/v1alpha1/values.go b/pkg/apis/application/v1alpha1/values.go index 1c0d6b76de703e..e642e667933b69 100644 --- a/pkg/apis/application/v1alpha1/values.go +++ b/pkg/apis/application/v1alpha1/values.go @@ -21,13 +21,13 @@ func (h *ApplicationSourceHelm) SetValuesString(value string) error { if err != nil { return fmt.Errorf("failed converting yaml to json: %w", err) } - var v interface{} + var v any if err := json.Unmarshal(data, &v); err != nil { return fmt.Errorf("failed to unmarshal json: %w", err) } switch v.(type) { case string: - case map[string]interface{}: + case map[string]any: default: return fmt.Errorf("invalid type %q", reflect.TypeOf(v)) } diff --git a/pkg/ratelimiter/ratelimiter.go b/pkg/ratelimiter/ratelimiter.go index b9f0f4a19fe6f7..7da3573bbfbeb3 100644 --- a/pkg/ratelimiter/ratelimiter.go +++ b/pkg/ratelimiter/ratelimiter.go @@ -51,7 +51,7 @@ type failureData struct { // dealing with max failures and expiration/resets are up dependent on the cooldown period type ItemExponentialRateLimiterWithAutoReset[T comparable] struct { failuresLock sync.Mutex - failures map[interface{}]failureData + failures map[any]failureData baseDelay time.Duration maxDelay time.Duration @@ -63,7 +63,7 @@ var _ workqueue.TypedRateLimiter[string] = &ItemExponentialRateLimiterWithAutoRe func NewItemExponentialRateLimiterWithAutoReset[T comparable](baseDelay, maxDelay, failureCoolDown time.Duration, backoffFactor float64) workqueue.TypedRateLimiter[T] { return &ItemExponentialRateLimiterWithAutoReset[T]{ - failures: map[interface{}]failureData{}, + failures: map[any]failureData{}, baseDelay: baseDelay, maxDelay: maxDelay, coolDown: failureCoolDown, diff --git a/reposerver/cache/cache_test.go b/reposerver/cache/cache_test.go index f8279693c2afbd..46039fa8407461 100644 --- a/reposerver/cache/cache_test.go +++ b/reposerver/cache/cache_test.go @@ -253,7 +253,7 @@ func TestCachedManifestResponse_HashBehavior(t *testing.T) { func getInMemoryCacheContents(t *testing.T, inMemCache *cacheutil.InMemoryCache) map[string]*CachedManifestResponse { t.Helper() - items, err := inMemCache.Items(func() interface{} { return &CachedManifestResponse{} }) + items, err := inMemCache.Items(func() any { return &CachedManifestResponse{} }) require.NoError(t, err) result := map[string]*CachedManifestResponse{} @@ -306,7 +306,7 @@ func TestCachedManifestResponse_ShallowCopyExpectedFields(t *testing.T) { return } - jsonMap := map[string]interface{}{} + jsonMap := map[string]any{} err = json.Unmarshal(str, &jsonMap) if err != nil { assert.FailNow(t, "Unable to unmarshal", err) diff --git a/reposerver/repository/repository.go b/reposerver/repository/repository.go index 1bbba4f27f1f11..18c5cf3fa49bab 100644 --- a/reposerver/repository/repository.go +++ b/reposerver/repository/repository.go @@ -541,7 +541,7 @@ func (s *Service) GenerateManifest(ctx context.Context, q *apiclient.ManifestReq operation := func(repoRoot, commitSHA, cacheKey string, ctxSrc operationContextSrc) error { // do not generate manifests if Path and Chart fields are not set for a source in Multiple Sources if q.HasMultipleSources && q.ApplicationSource.Path == "" && q.ApplicationSource.Chart == "" { - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ "source": q.ApplicationSource, }).Debugf("not generating manifests as path and chart fields are empty") res = &apiclient.ManifestResponse{ @@ -2519,7 +2519,7 @@ func checkoutRevision(gitClient git.Client, revision string, submoduleEnabled bo revisionPresent := gitClient.IsRevisionPresent(revision) - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ "skipFetch": revisionPresent, }).Debugf("Checking out revision %v", revision) diff --git a/reposerver/repository/repository_test.go b/reposerver/repository/repository_test.go index 10492971a1e73e..9e611e65471b6c 100644 --- a/reposerver/repository/repository_test.go +++ b/reposerver/repository/repository_test.go @@ -1984,7 +1984,7 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { require.True(t, ok) containers, ok, _ := unstructured.NestedSlice(deployment.Object, "spec", "template", "spec", "containers") require.True(t, ok) - image, ok, _ := unstructured.NestedString(containers[0].(map[string]interface{}), "image") + image, ok, _ := unstructured.NestedString(containers[0].(map[string]any), "image") require.True(t, ok) assert.Equal(t, "gcr.io/heptio-images/ks-guestbook-demo:0.2", image) }) @@ -2014,7 +2014,7 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { require.True(t, ok) containers, ok, _ := unstructured.NestedSlice(deployment.Object, "spec", "template", "spec", "containers") require.True(t, ok) - image, ok, _ := unstructured.NestedString(containers[0].(map[string]interface{}), "image") + image, ok, _ := unstructured.NestedString(containers[0].(map[string]any), "image") require.True(t, ok) assert.Equal(t, "gcr.io/heptio-images/ks-guestbook-demo:0.2", image) }) @@ -2045,7 +2045,7 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { require.True(t, ok) containers, ok, _ := unstructured.NestedSlice(deployment.Object, "spec", "template", "spec", "containers") require.True(t, ok) - image, ok, _ := unstructured.NestedString(containers[0].(map[string]interface{}), "image") + image, ok, _ := unstructured.NestedString(containers[0].(map[string]any), "image") require.True(t, ok) assert.Equal(t, "gcr.io/heptio-images/ks-guestbook-demo:0.3", image) }) @@ -2098,7 +2098,7 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { require.True(t, ok) containers, ok, _ := unstructured.NestedSlice(deployment.Object, "spec", "template", "spec", "containers") require.True(t, ok) - image, ok, _ := unstructured.NestedString(containers[0].(map[string]interface{}), "image") + image, ok, _ := unstructured.NestedString(containers[0].(map[string]any), "image") require.True(t, ok) assert.Equal(t, "gcr.io/heptio-images/ks-guestbook-demo:0.1", image) }) diff --git a/server/account/account_test.go b/server/account/account_test.go index 81e0abc0785f44..669238344a443f 100644 --- a/server/account/account_test.go +++ b/server/account/account_test.go @@ -32,7 +32,7 @@ const ( // return an AccountServer which returns fake data func newTestAccountServer(ctx context.Context, opts ...func(cm *v1.ConfigMap, secret *v1.Secret)) (*Server, *session.Server) { - return newTestAccountServerExt(ctx, func(claims jwt.Claims, rvals ...interface{}) bool { + return newTestAccountServerExt(ctx, func(claims jwt.Claims, rvals ...any) bool { return true }, opts...) } @@ -153,7 +153,7 @@ func TestUpdatePassword_AdminUpdatesAnotherUser(t *testing.T) { } func TestUpdatePassword_DoesNotHavePermissions(t *testing.T) { - enforcer := func(claims jwt.Claims, rvals ...interface{}) bool { + enforcer := func(claims jwt.Claims, rvals ...any) bool { return false } @@ -319,7 +319,7 @@ func TestCanI_GetLogsAllowNoSwitch(t *testing.T) { } func TestCanI_GetLogsDenySwitchOn(t *testing.T) { - enforcer := func(claims jwt.Claims, rvals ...interface{}) bool { + enforcer := func(claims jwt.Claims, rvals ...any) bool { return false } diff --git a/server/application/application.go b/server/application/application.go index 645071839a9283..fa98f8c2ce71f5 100644 --- a/server/application/application.go +++ b/server/application/application.go @@ -157,7 +157,7 @@ func (s *Server) getAppEnforceRBAC(ctx context.Context, action, project, namespa if user == "" { user = "Unknown user" } - logCtx := log.WithFields(map[string]interface{}{ + logCtx := log.WithFields(map[string]any{ "user": user, "application": name, "namespace": namespace, @@ -166,7 +166,7 @@ func (s *Server) getAppEnforceRBAC(ctx context.Context, action, project, namespa // The user has provided everything we need to perform an initial RBAC check. givenRBACName := security.RBACName(s.ns, project, namespace, name) if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceApplications, action, givenRBACName); err != nil { - logCtx.WithFields(map[string]interface{}{ + logCtx.WithFields(map[string]any{ "project": project, argocommon.SecurityField: argocommon.SecurityMedium, }).Warnf("user tried to %s application which they do not have access to: %s", action, err) @@ -196,7 +196,7 @@ func (s *Server) getAppEnforceRBAC(ctx context.Context, action, project, namespa // perform a second RBAC check to ensure that the user has access to the actual Application's project (not just the // project they specified in the request). if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceApplications, action, a.RBACName(s.ns)); err != nil { - logCtx.WithFields(map[string]interface{}{ + logCtx.WithFields(map[string]any{ "project": a.Spec.Project, argocommon.SecurityField: argocommon.SecurityMedium, }).Warnf("user tried to %s application which they do not have access to: %s", action, err) @@ -215,7 +215,7 @@ func (s *Server) getAppEnforceRBAC(ctx context.Context, action, project, namespa effectiveProject = a.Spec.Project } if project != "" && effectiveProject != project { - logCtx.WithFields(map[string]interface{}{ + logCtx.WithFields(map[string]any{ "project": a.Spec.Project, argocommon.SecurityField: argocommon.SecurityMedium, }).Warnf("user tried to %s application in project %s, but the application is in project %s", action, project, effectiveProject) @@ -1064,7 +1064,7 @@ func (s *Server) getAppProject(ctx context.Context, a *appv1.Application, logCtx var applicationNotAllowedToUseProjectErr *appv1.ErrApplicationNotAllowedToUseProject if errors.As(err, &applicationNotAllowedToUseProjectErr) { - logCtx.WithFields(map[string]interface{}{ + logCtx.WithFields(map[string]any{ "project": a.Spec.Project, argocommon.SecurityField: argocommon.SecurityMedium, }).Warnf("error getting app project: %s", err) @@ -1114,8 +1114,8 @@ func (s *Server) Delete(ctx context.Context, q *application.ApplicationDeleteReq // Although the cascaded deletion/propagation policy finalizer is not set when apps are created via // API, they will often be set by the user as part of declarative config. As part of a delete // request, we always calculate the patch to see if we need to set/unset the finalizer. - patch, err := json.Marshal(map[string]interface{}{ - "metadata": map[string]interface{}{ + patch, err := json.Marshal(map[string]any{ + "metadata": map[string]any{ "finalizers": a.Finalizers, }, }) @@ -2163,7 +2163,7 @@ func (s *Server) getObjectsForDeepLinks(ctx context.Context, app *appv1.Applicat } if err := argo.ValidateDestination(ctx, &app.Spec.Destination, s.db); err != nil { - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ "application": app.GetName(), "ns": app.GetNamespace(), "destination": app.Spec.Destination, @@ -2180,7 +2180,7 @@ func (s *Server) getObjectsForDeepLinks(ctx context.Context, app *appv1.Applicat } clst, err := s.db.GetCluster(ctx, app.Spec.Destination.Server) if err != nil { - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ "application": app.GetName(), "ns": app.GetNamespace(), "destination": app.Spec.Destination, @@ -2600,7 +2600,7 @@ func (s *Server) createResource(ctx context.Context, config *rest.Config, newObj // splitStatusPatch splits a patch into two: one for a non-status patch, and the status-only patch. // Returns nil for either if the patch doesn't have modifications to non-status, or status, respectively. func splitStatusPatch(patch []byte) ([]byte, []byte, error) { - var obj map[string]interface{} + var obj map[string]any err := json.Unmarshal(patch, &obj) if err != nil { return nil, nil, err @@ -2608,7 +2608,7 @@ func splitStatusPatch(patch []byte) ([]byte, []byte, error) { var nonStatusPatch, statusPatch []byte if statusVal, ok := obj["status"]; ok { // calculate the status-only patch - statusObj := map[string]interface{}{ + statusObj := map[string]any{ "status": statusVal, } statusPatch, err = json.Marshal(statusObj) diff --git a/server/application/application_test.go b/server/application/application_test.go index f796937649013a..5db9b2be8d3400 100644 --- a/server/application/application_test.go +++ b/server/application/application_test.go @@ -95,9 +95,9 @@ func (b broadcasterMock) Subscribe(ch chan *appv1.ApplicationWatchEvent, filters return func() {} } -func (broadcasterMock) OnAdd(interface{}, bool) {} -func (broadcasterMock) OnUpdate(interface{}, interface{}) {} -func (broadcasterMock) OnDelete(interface{}) {} +func (broadcasterMock) OnAdd(any, bool) {} +func (broadcasterMock) OnUpdate(any, any) {} +func (broadcasterMock) OnDelete(any) {} func fakeRepo() *appsv1.Repository { return &appsv1.Repository{ @@ -585,11 +585,11 @@ func (t *TestServerStream) Context() context.Context { return t.ctx } -func (t *TestServerStream) SendMsg(m interface{}) error { +func (t *TestServerStream) SendMsg(m any) error { return nil } -func (t *TestServerStream) RecvMsg(m interface{}) error { +func (t *TestServerStream) RecvMsg(m any) error { return nil } @@ -637,11 +637,11 @@ func (t *TestResourceTreeServer) Context() context.Context { return t.ctx } -func (t *TestResourceTreeServer) SendMsg(m interface{}) error { +func (t *TestResourceTreeServer) SendMsg(m any) error { return nil } -func (t *TestResourceTreeServer) RecvMsg(m interface{}) error { +func (t *TestResourceTreeServer) RecvMsg(m any) error { return nil } @@ -667,11 +667,11 @@ func (t *TestPodLogsServer) Context() context.Context { return t.ctx } -func (t *TestPodLogsServer) SendMsg(m interface{}) error { +func (t *TestPodLogsServer) SendMsg(m any) error { return nil } -func (t *TestPodLogsServer) RecvMsg(m interface{}) error { +func (t *TestPodLogsServer) RecvMsg(m any) error { return nil } diff --git a/server/application/broadcaster.go b/server/application/broadcaster.go index c8a562123ad191..75cf809b43743d 100644 --- a/server/application/broadcaster.go +++ b/server/application/broadcaster.go @@ -26,9 +26,9 @@ func (s *subscriber) matches(event *appv1.ApplicationWatchEvent) bool { // Broadcaster is an interface for broadcasting application informer watch events to multiple subscribers. type Broadcaster interface { Subscribe(ch chan *appv1.ApplicationWatchEvent, filters ...func(event *appv1.ApplicationWatchEvent) bool) func() - OnAdd(interface{}, bool) - OnUpdate(interface{}, interface{}) - OnDelete(interface{}) + OnAdd(any, bool) + OnUpdate(any, any) + OnDelete(any) } type broadcasterHandler struct { @@ -76,19 +76,19 @@ func (b *broadcasterHandler) Subscribe(ch chan *appv1.ApplicationWatchEvent, fil } } -func (b *broadcasterHandler) OnAdd(obj interface{}, _ bool) { +func (b *broadcasterHandler) OnAdd(obj any, _ bool) { if app, ok := obj.(*appv1.Application); ok { b.notify(&appv1.ApplicationWatchEvent{Application: *app, Type: watch.Added}) } } -func (b *broadcasterHandler) OnUpdate(_, newObj interface{}) { +func (b *broadcasterHandler) OnUpdate(_, newObj any) { if app, ok := newObj.(*appv1.Application); ok { b.notify(&appv1.ApplicationWatchEvent{Application: *app, Type: watch.Modified}) } } -func (b *broadcasterHandler) OnDelete(obj interface{}) { +func (b *broadcasterHandler) OnDelete(obj any) { if app, ok := obj.(*appv1.Application); ok { b.notify(&appv1.ApplicationWatchEvent{Application: *app, Type: watch.Deleted}) } diff --git a/server/application/websocket_test.go b/server/application/websocket_test.go index d2222e1bdeb25a..c51253c64240a5 100644 --- a/server/application/websocket_test.go +++ b/server/application/websocket_test.go @@ -130,7 +130,7 @@ func TestValidateWithAdminPermissions(t *testing.T) { enf := newEnforcer() _ = enf.SetBuiltinPolicy(assets.BuiltinPolicyCSV) enf.SetDefaultRole("role:admin") - enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...interface{}) bool { + enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { return true }) ts := newTestTerminalSession(w, r) @@ -150,7 +150,7 @@ func TestValidateWithoutPermissions(t *testing.T) { enf := newEnforcer() _ = enf.SetBuiltinPolicy(assets.BuiltinPolicyCSV) enf.SetDefaultRole("role:test") - enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...interface{}) bool { + enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { return false }) ts := newTestTerminalSession(w, r) diff --git a/server/cluster/cluster_test.go b/server/cluster/cluster_test.go index f5540dd30753db..e65337446f150b 100644 --- a/server/cluster/cluster_test.go +++ b/server/cluster/cluster_test.go @@ -129,7 +129,7 @@ func newEnforcer() *rbac.Enforcer { enforcer := rbac.NewEnforcer(fake.NewClientset(test.NewFakeConfigMap()), test.FakeArgoCDNamespace, common.ArgoCDRBACConfigMapName, nil) _ = enforcer.SetBuiltinPolicy(assets.BuiltinPolicyCSV) enforcer.SetDefaultRole("role:test") - enforcer.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...interface{}) bool { + enforcer.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { return true }) return enforcer diff --git a/server/deeplinks/deeplinks.go b/server/deeplinks/deeplinks.go index 933dcde42decb4..aad7c601dd243e 100644 --- a/server/deeplinks/deeplinks.go +++ b/server/deeplinks/deeplinks.go @@ -62,8 +62,8 @@ func SanitizeCluster(cluster *v1alpha1.Cluster) (*unstructured.Unstructured, err }) } -func CreateDeepLinksObject(resourceObj *unstructured.Unstructured, app *unstructured.Unstructured, cluster *unstructured.Unstructured, project *unstructured.Unstructured) map[string]interface{} { - deeplinkObj := map[string]interface{}{} +func CreateDeepLinksObject(resourceObj *unstructured.Unstructured, app *unstructured.Unstructured, cluster *unstructured.Unstructured, project *unstructured.Unstructured) map[string]any { + deeplinkObj := map[string]any{} if resourceObj != nil { deeplinkObj[ResourceDeepLinkKey] = resourceObj.Object } @@ -80,7 +80,7 @@ func CreateDeepLinksObject(resourceObj *unstructured.Unstructured, app *unstruct return deeplinkObj } -func EvaluateDeepLinksResponse(obj map[string]interface{}, name string, links []settings.DeepLink) (*application.LinksResponse, []string) { +func EvaluateDeepLinksResponse(obj map[string]any, name string, links []settings.DeepLink) (*application.LinksResponse, []string) { finalLinks := []*application.LinkInfo{} errors := []string{} for _, link := range links { diff --git a/server/extension/extension.go b/server/extension/extension.go index cba62c3bb591c8..cc40764642b827 100644 --- a/server/extension/extension.go +++ b/server/extension/extension.go @@ -332,7 +332,7 @@ func (a *DefaultApplicationGetter) Get(ns, name string) (*v1alpha1.Application, // RbacEnforcer defines the contract to enforce rbac rules type RbacEnforcer interface { - EnforceErr(rvals ...interface{}) error + EnforceErr(rvals ...any) error } // Manager is the object that will be responsible for registering @@ -416,7 +416,7 @@ func parseAndValidateConfig(s *settings.ArgoCDSettings) (*ExtensionConfigs, erro configs := ExtensionConfigs{} for extName, extConfig := range s.ExtensionConfig { - extConfigMap := map[string]interface{}{} + extConfigMap := map[string]any{} err := yaml.Unmarshal([]byte(extConfig), &extConfigMap) if err != nil { return nil, fmt.Errorf("invalid extension config: %w", err) diff --git a/server/project/project.go b/server/project/project.go index cac913715b6231..6e01e95edfa2a1 100644 --- a/server/project/project.go +++ b/server/project/project.go @@ -165,7 +165,7 @@ func (s *Server) ListLinks(ctx context.Context, q *project.ListProjectLinksReque projName := q.GetName() if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionGet, projName); err != nil { - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ "project": projName, }).Warnf("unauthorized access to project, error=%v", err.Error()) return nil, fmt.Errorf("unauthorized access to project %v", projName) diff --git a/server/project/project_test.go b/server/project/project_test.go index d4d9c3e40e4eb4..9d99904b861712 100644 --- a/server/project/project_test.go +++ b/server/project/project_test.go @@ -714,7 +714,7 @@ func newEnforcer(kubeclientset *fake.Clientset) *rbac.Enforcer { enforcer := rbac.NewEnforcer(kubeclientset, testNamespace, common.ArgoCDRBACConfigMapName, nil) _ = enforcer.SetBuiltinPolicy(assets.BuiltinPolicyCSV) enforcer.SetDefaultRole("role:admin") - enforcer.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...interface{}) bool { + enforcer.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { return true }) return enforcer diff --git a/server/rbacpolicy/rbacpolicy.go b/server/rbacpolicy/rbacpolicy.go index ea2b0ee0c166df..1b81c36b7e640a 100644 --- a/server/rbacpolicy/rbacpolicy.go +++ b/server/rbacpolicy/rbacpolicy.go @@ -110,7 +110,7 @@ func GetProjectRoleFromSubject(subject string) (string, string, bool) { } // EnforceClaims is an RBAC claims enforcer specific to the Argo CD API server -func (p *RBACPolicyEnforcer) EnforceClaims(claims jwt.Claims, rvals ...interface{}) bool { +func (p *RBACPolicyEnforcer) EnforceClaims(claims jwt.Claims, rvals ...any) bool { mapClaims, err := jwtutil.MapClaims(claims) if err != nil { return false @@ -135,7 +135,7 @@ func (p *RBACPolicyEnforcer) EnforceClaims(claims jwt.Claims, rvals ...interface // Check the subject. This is typically the 'admin' case. // NOTE: the call to EnforceWithCustomEnforcer will also consider the default role - vals := append([]interface{}{subject}, rvals[1:]...) + vals := append([]any{subject}, rvals[1:]...) if p.enf.EnforceWithCustomEnforcer(enforcer, vals...) { return true } @@ -157,7 +157,7 @@ func (p *RBACPolicyEnforcer) EnforceClaims(claims jwt.Claims, rvals ...interface for gpidx := range groupingPolicies { // Prefilter user groups by groups defined in the model if groupingPolicies[gpidx][0] == groups[gidx] { - vals := append([]interface{}{groups[gidx]}, rvals[1:]...) + vals := append([]any{groups[gidx]}, rvals[1:]...) if p.enf.EnforceWithCustomEnforcer(enforcer, vals...) { return true } @@ -172,7 +172,7 @@ func (p *RBACPolicyEnforcer) EnforceClaims(claims jwt.Claims, rvals ...interface // getProjectFromRequest parses the project name from the RBAC request and returns the associated // project (if it exists) -func (p *RBACPolicyEnforcer) getProjectFromRequest(rvals ...interface{}) *v1alpha1.AppProject { +func (p *RBACPolicyEnforcer) getProjectFromRequest(rvals ...any) *v1alpha1.AppProject { if len(rvals) != 4 { return nil } @@ -200,7 +200,7 @@ func (p *RBACPolicyEnforcer) getProjectFromRequest(rvals ...interface{}) *v1alph } // enforceProjectToken will check to see the valid token has not yet been revoked in the project -func (p *RBACPolicyEnforcer) enforceProjectToken(subject string, proj *v1alpha1.AppProject, rvals ...interface{}) bool { +func (p *RBACPolicyEnforcer) enforceProjectToken(subject string, proj *v1alpha1.AppProject, rvals ...any) bool { subjectSplit := strings.Split(subject, ":") if len(subjectSplit) != 3 { return false @@ -211,6 +211,6 @@ func (p *RBACPolicyEnforcer) enforceProjectToken(subject string, proj *v1alpha1. return false } - vals := append([]interface{}{subject}, rvals[1:]...) + vals := append([]any{subject}, rvals[1:]...) return p.enf.EnforceRuntimePolicy(proj.Name, proj.ProjectPoliciesString(), vals...) } diff --git a/server/repository/repository_test.go b/server/repository/repository_test.go index 7b4b77bca2ab11..c7127fd3966bc0 100644 --- a/server/repository/repository_test.go +++ b/server/repository/repository_test.go @@ -965,7 +965,7 @@ func newEnforcer(kubeclientset *fake.Clientset) *rbac.Enforcer { enforcer := rbac.NewEnforcer(kubeclientset, testNamespace, common.ArgoCDRBACConfigMapName, nil) _ = enforcer.SetBuiltinPolicy(assets.BuiltinPolicyCSV) enforcer.SetDefaultRole("role:admin") - enforcer.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...interface{}) bool { + enforcer.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { return true }) return enforcer diff --git a/server/server.go b/server/server.go index 29c7da2ab1552f..dbeea6923760d9 100644 --- a/server/server.go +++ b/server/server.go @@ -933,7 +933,7 @@ func (a *ArgoCDServer) newGRPCServer() (*grpc.Server, application.AppResourceTre grpc_prometheus.StreamServerInterceptor, grpc_auth.StreamServerInterceptor(a.Authenticate), grpc_util.UserAgentStreamServerInterceptor(common.ArgoCDUserAgentName, clientConstraint), - grpc_util.PayloadStreamServerInterceptor(a.log, true, func(ctx context.Context, fullMethodName string, servingObject interface{}) bool { + grpc_util.PayloadStreamServerInterceptor(a.log, true, func(ctx context.Context, fullMethodName string, servingObject any) bool { return !sensitiveMethods[fullMethodName] }), grpc_util.ErrorCodeK8sStreamServerInterceptor(), @@ -947,7 +947,7 @@ func (a *ArgoCDServer) newGRPCServer() (*grpc.Server, application.AppResourceTre grpc_prometheus.UnaryServerInterceptor, grpc_auth.UnaryServerInterceptor(a.Authenticate), grpc_util.UserAgentUnaryServerInterceptor(common.ArgoCDUserAgentName, clientConstraint), - grpc_util.PayloadUnaryServerInterceptor(a.log, true, func(ctx context.Context, fullMethodName string, servingObject interface{}) bool { + grpc_util.PayloadUnaryServerInterceptor(a.log, true, func(ctx context.Context, fullMethodName string, servingObject any) bool { return !sensitiveMethods[fullMethodName] }), grpc_util.ErrorCodeK8sUnaryServerInterceptor(), @@ -1626,7 +1626,7 @@ func (bf *bug21955Workaround) ServeHTTP(w http.ResponseWriter, r *http.Request) bf.handler.ServeHTTP(w, r) } -func bug21955WorkaroundInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { +func bug21955WorkaroundInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { if rq, ok := req.(*repositorypkg.RepoQuery); ok { repo, err := url.QueryUnescape(rq.Repo) if err != nil { diff --git a/server/server_test.go b/server/server_test.go index 02bab631ef6640..2122cba5b96cee 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -778,7 +778,7 @@ func TestAuthenticate_3rd_party_JWTs(t *testing.T) { anonymousEnabled bool claims jwt.RegisteredClaims expectedErrorContains string - expectedClaims interface{} + expectedClaims any useDex bool } tests := []testData{ @@ -933,7 +933,7 @@ func TestAuthenticate_no_request_metadata(t *testing.T) { test string anonymousEnabled bool expectedErrorContains string - expectedClaims interface{} + expectedClaims any } tests := []testData{ { @@ -976,7 +976,7 @@ func TestAuthenticate_no_SSO(t *testing.T) { test string anonymousEnabled bool expectedErrorMessage string - expectedClaims interface{} + expectedClaims any } tests := []testData{ { @@ -1026,7 +1026,7 @@ func TestAuthenticate_bad_request_metadata(t *testing.T) { anonymousEnabled bool metadata metadata.MD expectedErrorMessage string - expectedClaims interface{} + expectedClaims any } tests := []testData{ { diff --git a/test/e2e/cli_test.go b/test/e2e/cli_test.go index 1472116be7e939..3a923e57311a78 100644 --- a/test/e2e/cli_test.go +++ b/test/e2e/cli_test.go @@ -21,7 +21,7 @@ func TestCliAppCommand(t *testing.T) { And(func() { output, err := RunCli("app", "sync", Name(), "--timeout", "90") require.NoError(t, err) - vars := map[string]interface{}{"Name": Name(), "Namespace": DeploymentNamespace()} + vars := map[string]any{"Name": Name(), "Namespace": DeploymentNamespace()} assert.Contains(t, NormalizeOutput(output), Tmpl(`Pod {{.Namespace}} pod Synced Progressing pod/pod created`, vars)) assert.Contains(t, NormalizeOutput(output), Tmpl(`Pod {{.Namespace}} hook Succeeded Sync pod/hook created`, vars)) }). @@ -33,7 +33,7 @@ func TestCliAppCommand(t *testing.T) { require.NoError(t, err) expected := Tmpl( `{{.Name}} https://kubernetes.default.svc {{.Namespace}} default Synced Healthy Manual `, - map[string]interface{}{"Name": Name(), "Namespace": DeploymentNamespace()}) + map[string]any{"Name": Name(), "Namespace": DeploymentNamespace()}) assert.Contains(t, NormalizeOutput(output), expected) }) } diff --git a/test/e2e/clusterdecisiongenerator_e2e_test.go b/test/e2e/clusterdecisiongenerator_e2e_test.go index 3ee4a30509cbbe..ee30ff6118153f 100644 --- a/test/e2e/clusterdecisiongenerator_e2e_test.go +++ b/test/e2e/clusterdecisiongenerator_e2e_test.go @@ -47,8 +47,8 @@ func TestSimpleClusterDecisionResourceGeneratorExternalNamespace(t *testing.T) { var expectedAppNewNamespace *argov1alpha1.Application var expectedAppNewMetadata *argov1alpha1.Application - clusterList := []interface{}{ - map[string]interface{}{ + clusterList := []any{ + map[string]any{ "clusterName": "cluster1", "reason": "argotest", }, @@ -155,8 +155,8 @@ func TestSimpleClusterDecisionResourceGenerator(t *testing.T) { var expectedAppNewNamespace *argov1alpha1.Application var expectedAppNewMetadata *argov1alpha1.Application - clusterList := []interface{}{ - map[string]interface{}{ + clusterList := []any{ + map[string]any{ "clusterName": "cluster1", "reason": "argotest", }, @@ -262,12 +262,12 @@ func TestSimpleClusterDecisionResourceGeneratorAddingCluster(t *testing.T) { expectedAppCluster2.Spec.Destination.Name = "cluster2" expectedAppCluster2.ObjectMeta.Name = "cluster2-guestbook" - clusterList := []interface{}{ - map[string]interface{}{ + clusterList := []any{ + map[string]any{ "clusterName": "cluster1", "reason": "argotest", }, - map[string]interface{}{ + map[string]any{ "clusterName": "cluster2", "reason": "argotest", }, @@ -357,12 +357,12 @@ func TestSimpleClusterDecisionResourceGeneratorDeletingClusterSecret(t *testing. expectedAppCluster2.Spec.Destination.Name = "cluster2" expectedAppCluster2.ObjectMeta.Name = "cluster2-guestbook" - clusterList := []interface{}{ - map[string]interface{}{ + clusterList := []any{ + map[string]any{ "clusterName": "cluster1", "reason": "argotest", }, - map[string]interface{}{ + map[string]any{ "clusterName": "cluster2", "reason": "argotest", }, @@ -454,19 +454,19 @@ func TestSimpleClusterDecisionResourceGeneratorDeletingClusterFromResource(t *te expectedAppCluster2.Spec.Destination.Name = "cluster2" expectedAppCluster2.ObjectMeta.Name = "cluster2-guestbook" - clusterList := []interface{}{ - map[string]interface{}{ + clusterList := []any{ + map[string]any{ "clusterName": "cluster1", "reason": "argotest", }, - map[string]interface{}{ + map[string]any{ "clusterName": "cluster2", "reason": "argotest", }, } - clusterListSmall := []interface{}{ - map[string]interface{}{ + clusterListSmall := []any{ + map[string]any{ "clusterName": "cluster1", "reason": "argotest", }, diff --git a/test/e2e/fixture/admin/utils/backup.go b/test/e2e/fixture/admin/utils/backup.go index 79bd8905186035..ca55d319943e57 100644 --- a/test/e2e/fixture/admin/utils/backup.go +++ b/test/e2e/fixture/admin/utils/backup.go @@ -21,7 +21,7 @@ func GetExportedResourcesFromOutput(output string) (ExportedResources, error) { continue } - var resourceData map[string]interface{} + var resourceData map[string]any if err := yaml.Unmarshal([]byte(doc), &resourceData); err != nil { return nil, fmt.Errorf("error unmarshaling YAML: %w", err) diff --git a/test/e2e/fixture/app/actions.go b/test/e2e/fixture/app/actions.go index 9a61f81b5f6139..f17418e87adf2b 100644 --- a/test/e2e/fixture/app/actions.go +++ b/test/e2e/fixture/app/actions.go @@ -312,7 +312,7 @@ func (a *Actions) Declarative(filename string) *Actions { func (a *Actions) DeclarativeWithCustomRepo(filename string, repoURL string) *Actions { a.context.t.Helper() - values := map[string]interface{}{ + values := map[string]any{ "ArgoCDNamespace": fixture.TestNamespace(), "DeploymentNamespace": fixture.DeploymentNamespace(), "Name": a.context.AppName(), diff --git a/test/e2e/fixture/applicationsets/actions.go b/test/e2e/fixture/applicationsets/actions.go index 27adae8497d758..08c03bb4f872c2 100644 --- a/test/e2e/fixture/applicationsets/actions.go +++ b/test/e2e/fixture/applicationsets/actions.go @@ -333,14 +333,14 @@ func (a *Actions) CreatePlacementDecision(placementDecisionName string) *Actions } placementDecision := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ + Object: map[string]any{ + "metadata": map[string]any{ "name": placementDecisionName, "namespace": fixture.TestNamespace(), }, "kind": "PlacementDecision", "apiVersion": "cluster.open-cluster-management.io/v1alpha1", - "status": map[string]interface{}{}, + "status": map[string]any{}, }, } @@ -356,7 +356,7 @@ func (a *Actions) CreatePlacementDecision(placementDecisionName string) *Actions return a } -func (a *Actions) StatusUpdatePlacementDecision(placementDecisionName string, clusterList []interface{}) *Actions { +func (a *Actions) StatusUpdatePlacementDecision(placementDecisionName string, clusterList []any) *Actions { a.context.t.Helper() fixtureClient := utils.GetE2EFixtureK8sClient().DynamicClientset @@ -365,7 +365,7 @@ func (a *Actions) StatusUpdatePlacementDecision(placementDecisionName string, cl placementDecisionName, metav1.GetOptions{}) - placementDecision.Object["status"] = map[string]interface{}{ + placementDecision.Object["status"] = map[string]any{ "decisions": clusterList, } diff --git a/test/e2e/fixture/applicationsets/utils/errrors.go b/test/e2e/fixture/applicationsets/utils/errrors.go index e88fb05d8a006e..5137da6d8eada4 100644 --- a/test/e2e/fixture/applicationsets/utils/errrors.go +++ b/test/e2e/fixture/applicationsets/utils/errrors.go @@ -37,13 +37,13 @@ func CheckErrorWithCode(err error, exitcode int) { // FailOnErr panics if there is an error. It returns the first value so you can use it if you cast it: // text := FailOrErr(Foo)).(string) -func FailOnErr(v interface{}, err error) interface{} { +func FailOnErr(v any, err error) any { CheckError(err) return v } // Fatal is a wrapper for logrus.Fatal() to exit with custom code -func Fatal(exitcode int, args ...interface{}) { +func Fatal(exitcode int, args ...any) { exitfunc := func() { os.Exit(exitcode) } @@ -52,7 +52,7 @@ func Fatal(exitcode int, args ...interface{}) { } // Fatalf is a wrapper for logrus.Fatalf() to exit with custom code -func Fatalf(exitcode int, format string, args ...interface{}) { +func Fatalf(exitcode int, format string, args ...any) { exitfunc := func() { os.Exit(exitcode) } diff --git a/test/e2e/fixture/applicationsets/utils/fixture.go b/test/e2e/fixture/applicationsets/utils/fixture.go index 571e8148a29796..249ebd3f525ba6 100644 --- a/test/e2e/fixture/applicationsets/utils/fixture.go +++ b/test/e2e/fixture/applicationsets/utils/fixture.go @@ -349,7 +349,7 @@ func init() { } // PrettyPrintJson is a utility function for debugging purposes -func PrettyPrintJson(obj interface{}) string { +func PrettyPrintJson(obj any) string { bytes, err := json.MarshalIndent(obj, "", " ") if err != nil { return err.Error() @@ -372,7 +372,7 @@ func DnsFriendly(str string, postfix string) string { return str + postfix } -func MustToUnstructured(obj interface{}) *unstructured.Unstructured { +func MustToUnstructured(obj any) *unstructured.Unstructured { uObj, err := ToUnstructured(obj) if err != nil { panic(err) @@ -381,7 +381,7 @@ func MustToUnstructured(obj interface{}) *unstructured.Unstructured { } // ToUnstructured converts a concrete K8s API type to an unstructured object -func ToUnstructured(obj interface{}) (*unstructured.Unstructured, error) { +func ToUnstructured(obj any) (*unstructured.Unstructured, error) { uObj, err := runtime.NewTestUnstructuredConverter(equality.Semantic).ToUnstructured(obj) if err != nil { return nil, err diff --git a/test/e2e/fixture/fixture.go b/test/e2e/fixture/fixture.go index cbcd0e55746886..c62a836f1e3985 100644 --- a/test/e2e/fixture/fixture.go +++ b/test/e2e/fixture/fixture.go @@ -1115,7 +1115,7 @@ func AddTag(name string) { } // create the resource by creating using "kubectl apply", with bonus templating -func Declarative(filename string, values interface{}) (string, error) { +func Declarative(filename string, values any) (string, error) { bytes, err := os.ReadFile(path.Join("testdata", filename)) CheckError(err) diff --git a/test/e2e/fixture/http.go b/test/e2e/fixture/http.go index 68e674f9f8b36c..54de570ffd63c8 100644 --- a/test/e2e/fixture/http.go +++ b/test/e2e/fixture/http.go @@ -44,7 +44,7 @@ func DoHttpRequest(method string, path string, host string, data ...byte) (*http } // DoHttpJsonRequest executes a http request against the Argo CD API server and unmarshals the response body as JSON -func DoHttpJsonRequest(method string, path string, result interface{}, data ...byte) error { +func DoHttpJsonRequest(method string, path string, result any, data ...byte) error { resp, err := DoHttpRequest(method, path, "", data...) if err != nil { return err diff --git a/test/e2e/fixture/tmpl.go b/test/e2e/fixture/tmpl.go index 559c910144dd1d..3e50a6c07009b0 100644 --- a/test/e2e/fixture/tmpl.go +++ b/test/e2e/fixture/tmpl.go @@ -10,7 +10,7 @@ import ( ) // utility method to template a string using a map -func Tmpl(text string, values interface{}) string { +func Tmpl(text string, values any) string { parse, err := template.New(text).Parse(text) CheckError(err) buf := new(bytes.Buffer) diff --git a/test/e2e/merge_e2e_test.go b/test/e2e/merge_e2e_test.go index 95437b9f2892dc..0cf71f2a191af0 100644 --- a/test/e2e/merge_e2e_test.go +++ b/test/e2e/merge_e2e_test.go @@ -434,7 +434,7 @@ func TestMergeTerminalMergeGeneratorSelector(t *testing.T) { Delete().Then().Expect(ApplicationsDoNotExist(expectedApps1)).Expect(ApplicationsDoNotExist(expectedApps2)) } -func toAPIExtensionsJSON(t *testing.T, g interface{}) *apiextensionsv1.JSON { +func toAPIExtensionsJSON(t *testing.T, g any) *apiextensionsv1.JSON { t.Helper() resVal, err := json.Marshal(g) if err != nil { diff --git a/test/testutil.go b/test/testutil.go index 3ad755bfdca696..e02fc5bc839087 100644 --- a/test/testutil.go +++ b/test/testutil.go @@ -78,7 +78,7 @@ func MustLoadFileToString(path string) string { } func YamlToUnstructured(yamlStr string) *unstructured.Unstructured { - obj := make(map[string]interface{}) + obj := make(map[string]any) err := yaml.Unmarshal([]byte(yamlStr), &obj) if err != nil { panic(err) @@ -95,13 +95,13 @@ func YamlToApplication(yamlStr string) *v1alpha1.Application { return &app } -// ToMap converts any object to a map[string]interface{} -func ToMap(obj interface{}) map[string]interface{} { +// ToMap converts any object to a map[string]any +func ToMap(obj any) map[string]any { data, err := json.Marshal(obj) if err != nil { panic(err) } - var res map[string]interface{} + var res map[string]any err = json.Unmarshal(data, &res) if err != nil { panic(err) diff --git a/util/argo/argo.go b/util/argo/argo.go index 30eb59b8ef49b2..c599c18bb15284 100644 --- a/util/argo/argo.go +++ b/util/argo/argo.go @@ -228,8 +228,8 @@ func FilterByNameP(apps []*argoappv1.Application, name string) []*argoappv1.Appl // RefreshApp updates the refresh annotation of an application to coerce the controller to process it func RefreshApp(appIf v1alpha1.ApplicationInterface, name string, refreshType argoappv1.RefreshType) (*argoappv1.Application, error) { - metadata := map[string]interface{}{ - "metadata": map[string]interface{}{ + metadata := map[string]any{ + "metadata": map[string]any{ "annotations": map[string]string{ argoappv1.AnnotationKeyRefresh: string(refreshType), argoappv1.AnnotationKeyHydrate: "normal", @@ -1104,7 +1104,7 @@ func mergeVirtualProject(proj *argoappv1.AppProject, globalProj *argoappv1.AppPr return proj } -func GenerateSpecIsDifferentErrorMessage(entity string, a, b interface{}) string { +func GenerateSpecIsDifferentErrorMessage(entity string, a, b any) string { basicMsg := fmt.Sprintf("existing %s spec is different; use upsert flag to force update", entity) difference, _ := GetDifferentPathsBetweenStructs(a, b) if len(difference) == 0 { @@ -1113,7 +1113,7 @@ func GenerateSpecIsDifferentErrorMessage(entity string, a, b interface{}) string return fmt.Sprintf("%s; difference in keys %q", basicMsg, strings.Join(difference, ",")) } -func GetDifferentPathsBetweenStructs(a, b interface{}) ([]string, error) { +func GetDifferentPathsBetweenStructs(a, b any) ([]string, error) { var difference []string changelog, err := diff.Diff(a, b) if err != nil { diff --git a/util/argo/managedfields/managed_fields.go b/util/argo/managedfields/managed_fields.go index 1ead8f452195a8..d5c8cda5e88e91 100644 --- a/util/argo/managedfields/managed_fields.go +++ b/util/argo/managedfields/managed_fields.go @@ -52,14 +52,14 @@ func Normalize(live, config *unstructured.Unstructured, trustedManagers []string return liveCopy, configCopy, nil } lvu := results.live.AsValue().Unstructured() - l, ok := lvu.(map[string]interface{}) + l, ok := lvu.(map[string]any) if !ok { return nil, nil, fmt.Errorf("error converting live typedValue: expected map got %T", lvu) } normLive := &unstructured.Unstructured{Object: l} cvu := results.config.AsValue().Unstructured() - c, ok := cvu.(map[string]interface{}) + c, ok := cvu.(map[string]any) if !ok { return nil, nil, fmt.Errorf("error converting config typedValue: expected map got %T", cvu) } diff --git a/util/argo/managedfields/managed_fields_test.go b/util/argo/managedfields/managed_fields_test.go index 3034a878584182..1ad6a65fb819a3 100644 --- a/util/argo/managedfields/managed_fields_test.go +++ b/util/argo/managedfields/managed_fields_test.go @@ -170,7 +170,7 @@ func getNestedFloat64(t *testing.T, obj *unstructured.Unstructured, fields ...st } func StrToUnstructured(jsonStr string) *unstructured.Unstructured { - obj := make(map[string]interface{}) + obj := make(map[string]any) err := yaml.Unmarshal([]byte(jsonStr), &obj) if err != nil { panic(err) diff --git a/util/argo/normalizers/corev1_known_types.go b/util/argo/normalizers/corev1_known_types.go index 3f4ef5d1842eef..51f655b28b7c90 100644 --- a/util/argo/normalizers/corev1_known_types.go +++ b/util/argo/normalizers/corev1_known_types.go @@ -4,697 +4,697 @@ package normalizers import corev1 "k8s.io/api/core/v1" func init() { - knownTypes["core/v1/AWSElasticBlockStoreVolumeSource"] = func() interface{} { + knownTypes["core/v1/AWSElasticBlockStoreVolumeSource"] = func() any { return &corev1.AWSElasticBlockStoreVolumeSource{} } - knownTypes["core/v1/Affinity"] = func() interface{} { + knownTypes["core/v1/Affinity"] = func() any { return &corev1.Affinity{} } - knownTypes["core/v1/AppArmorProfile"] = func() interface{} { + knownTypes["core/v1/AppArmorProfile"] = func() any { return &corev1.AppArmorProfile{} } - knownTypes["core/v1/AttachedVolume"] = func() interface{} { + knownTypes["core/v1/AttachedVolume"] = func() any { return &corev1.AttachedVolume{} } - knownTypes["core/v1/AvoidPods"] = func() interface{} { + knownTypes["core/v1/AvoidPods"] = func() any { return &corev1.AvoidPods{} } - knownTypes["core/v1/AzureDiskVolumeSource"] = func() interface{} { + knownTypes["core/v1/AzureDiskVolumeSource"] = func() any { return &corev1.AzureDiskVolumeSource{} } - knownTypes["core/v1/AzureFilePersistentVolumeSource"] = func() interface{} { + knownTypes["core/v1/AzureFilePersistentVolumeSource"] = func() any { return &corev1.AzureFilePersistentVolumeSource{} } - knownTypes["core/v1/AzureFileVolumeSource"] = func() interface{} { + knownTypes["core/v1/AzureFileVolumeSource"] = func() any { return &corev1.AzureFileVolumeSource{} } - knownTypes["core/v1/Binding"] = func() interface{} { + knownTypes["core/v1/Binding"] = func() any { return &corev1.Binding{} } - knownTypes["core/v1/CSIPersistentVolumeSource"] = func() interface{} { + knownTypes["core/v1/CSIPersistentVolumeSource"] = func() any { return &corev1.CSIPersistentVolumeSource{} } - knownTypes["core/v1/CSIVolumeSource"] = func() interface{} { + knownTypes["core/v1/CSIVolumeSource"] = func() any { return &corev1.CSIVolumeSource{} } - knownTypes["core/v1/Capabilities"] = func() interface{} { + knownTypes["core/v1/Capabilities"] = func() any { return &corev1.Capabilities{} } - knownTypes["core/v1/CephFSPersistentVolumeSource"] = func() interface{} { + knownTypes["core/v1/CephFSPersistentVolumeSource"] = func() any { return &corev1.CephFSPersistentVolumeSource{} } - knownTypes["core/v1/CephFSVolumeSource"] = func() interface{} { + knownTypes["core/v1/CephFSVolumeSource"] = func() any { return &corev1.CephFSVolumeSource{} } - knownTypes["core/v1/CinderPersistentVolumeSource"] = func() interface{} { + knownTypes["core/v1/CinderPersistentVolumeSource"] = func() any { return &corev1.CinderPersistentVolumeSource{} } - knownTypes["core/v1/CinderVolumeSource"] = func() interface{} { + knownTypes["core/v1/CinderVolumeSource"] = func() any { return &corev1.CinderVolumeSource{} } - knownTypes["core/v1/ClientIPConfig"] = func() interface{} { + knownTypes["core/v1/ClientIPConfig"] = func() any { return &corev1.ClientIPConfig{} } - knownTypes["core/v1/ClusterTrustBundleProjection"] = func() interface{} { + knownTypes["core/v1/ClusterTrustBundleProjection"] = func() any { return &corev1.ClusterTrustBundleProjection{} } - knownTypes["core/v1/ComponentCondition"] = func() interface{} { + knownTypes["core/v1/ComponentCondition"] = func() any { return &corev1.ComponentCondition{} } - knownTypes["core/v1/ComponentStatus"] = func() interface{} { + knownTypes["core/v1/ComponentStatus"] = func() any { return &corev1.ComponentStatus{} } - knownTypes["core/v1/ComponentStatusList"] = func() interface{} { + knownTypes["core/v1/ComponentStatusList"] = func() any { return &corev1.ComponentStatusList{} } - knownTypes["core/v1/ConfigMap"] = func() interface{} { + knownTypes["core/v1/ConfigMap"] = func() any { return &corev1.ConfigMap{} } - knownTypes["core/v1/ConfigMapEnvSource"] = func() interface{} { + knownTypes["core/v1/ConfigMapEnvSource"] = func() any { return &corev1.ConfigMapEnvSource{} } - knownTypes["core/v1/ConfigMapKeySelector"] = func() interface{} { + knownTypes["core/v1/ConfigMapKeySelector"] = func() any { return &corev1.ConfigMapKeySelector{} } - knownTypes["core/v1/ConfigMapList"] = func() interface{} { + knownTypes["core/v1/ConfigMapList"] = func() any { return &corev1.ConfigMapList{} } - knownTypes["core/v1/ConfigMapNodeConfigSource"] = func() interface{} { + knownTypes["core/v1/ConfigMapNodeConfigSource"] = func() any { return &corev1.ConfigMapNodeConfigSource{} } - knownTypes["core/v1/ConfigMapProjection"] = func() interface{} { + knownTypes["core/v1/ConfigMapProjection"] = func() any { return &corev1.ConfigMapProjection{} } - knownTypes["core/v1/ConfigMapVolumeSource"] = func() interface{} { + knownTypes["core/v1/ConfigMapVolumeSource"] = func() any { return &corev1.ConfigMapVolumeSource{} } - knownTypes["core/v1/Container"] = func() interface{} { + knownTypes["core/v1/Container"] = func() any { return &corev1.Container{} } - knownTypes["core/v1/ContainerImage"] = func() interface{} { + knownTypes["core/v1/ContainerImage"] = func() any { return &corev1.ContainerImage{} } - knownTypes["core/v1/ContainerPort"] = func() interface{} { + knownTypes["core/v1/ContainerPort"] = func() any { return &corev1.ContainerPort{} } - knownTypes["core/v1/ContainerResizePolicy"] = func() interface{} { + knownTypes["core/v1/ContainerResizePolicy"] = func() any { return &corev1.ContainerResizePolicy{} } - knownTypes["core/v1/ContainerState"] = func() interface{} { + knownTypes["core/v1/ContainerState"] = func() any { return &corev1.ContainerState{} } - knownTypes["core/v1/ContainerStateRunning"] = func() interface{} { + knownTypes["core/v1/ContainerStateRunning"] = func() any { return &corev1.ContainerStateRunning{} } - knownTypes["core/v1/ContainerStateTerminated"] = func() interface{} { + knownTypes["core/v1/ContainerStateTerminated"] = func() any { return &corev1.ContainerStateTerminated{} } - knownTypes["core/v1/ContainerStateWaiting"] = func() interface{} { + knownTypes["core/v1/ContainerStateWaiting"] = func() any { return &corev1.ContainerStateWaiting{} } - knownTypes["core/v1/ContainerStatus"] = func() interface{} { + knownTypes["core/v1/ContainerStatus"] = func() any { return &corev1.ContainerStatus{} } - knownTypes["core/v1/ContainerUser"] = func() interface{} { + knownTypes["core/v1/ContainerUser"] = func() any { return &corev1.ContainerUser{} } - knownTypes["core/v1/DaemonEndpoint"] = func() interface{} { + knownTypes["core/v1/DaemonEndpoint"] = func() any { return &corev1.DaemonEndpoint{} } - knownTypes["core/v1/DownwardAPIProjection"] = func() interface{} { + knownTypes["core/v1/DownwardAPIProjection"] = func() any { return &corev1.DownwardAPIProjection{} } - knownTypes["core/v1/DownwardAPIVolumeFile"] = func() interface{} { + knownTypes["core/v1/DownwardAPIVolumeFile"] = func() any { return &corev1.DownwardAPIVolumeFile{} } - knownTypes["core/v1/DownwardAPIVolumeSource"] = func() interface{} { + knownTypes["core/v1/DownwardAPIVolumeSource"] = func() any { return &corev1.DownwardAPIVolumeSource{} } - knownTypes["core/v1/EmptyDirVolumeSource"] = func() interface{} { + knownTypes["core/v1/EmptyDirVolumeSource"] = func() any { return &corev1.EmptyDirVolumeSource{} } - knownTypes["core/v1/EndpointAddress"] = func() interface{} { + knownTypes["core/v1/EndpointAddress"] = func() any { return &corev1.EndpointAddress{} } - knownTypes["core/v1/EndpointPort"] = func() interface{} { + knownTypes["core/v1/EndpointPort"] = func() any { return &corev1.EndpointPort{} } - knownTypes["core/v1/EndpointSubset"] = func() interface{} { + knownTypes["core/v1/EndpointSubset"] = func() any { return &corev1.EndpointSubset{} } - knownTypes["core/v1/Endpoints"] = func() interface{} { + knownTypes["core/v1/Endpoints"] = func() any { return &corev1.Endpoints{} } - knownTypes["core/v1/EndpointsList"] = func() interface{} { + knownTypes["core/v1/EndpointsList"] = func() any { return &corev1.EndpointsList{} } - knownTypes["core/v1/EnvFromSource"] = func() interface{} { + knownTypes["core/v1/EnvFromSource"] = func() any { return &corev1.EnvFromSource{} } - knownTypes["core/v1/EnvVar"] = func() interface{} { + knownTypes["core/v1/EnvVar"] = func() any { return &corev1.EnvVar{} } - knownTypes["core/v1/EnvVarSource"] = func() interface{} { + knownTypes["core/v1/EnvVarSource"] = func() any { return &corev1.EnvVarSource{} } - knownTypes["core/v1/EphemeralContainer"] = func() interface{} { + knownTypes["core/v1/EphemeralContainer"] = func() any { return &corev1.EphemeralContainer{} } - knownTypes["core/v1/EphemeralContainerCommon"] = func() interface{} { + knownTypes["core/v1/EphemeralContainerCommon"] = func() any { return &corev1.EphemeralContainerCommon{} } - knownTypes["core/v1/EphemeralVolumeSource"] = func() interface{} { + knownTypes["core/v1/EphemeralVolumeSource"] = func() any { return &corev1.EphemeralVolumeSource{} } - knownTypes["core/v1/Event"] = func() interface{} { + knownTypes["core/v1/Event"] = func() any { return &corev1.Event{} } - knownTypes["core/v1/EventList"] = func() interface{} { + knownTypes["core/v1/EventList"] = func() any { return &corev1.EventList{} } - knownTypes["core/v1/EventSeries"] = func() interface{} { + knownTypes["core/v1/EventSeries"] = func() any { return &corev1.EventSeries{} } - knownTypes["core/v1/EventSource"] = func() interface{} { + knownTypes["core/v1/EventSource"] = func() any { return &corev1.EventSource{} } - knownTypes["core/v1/ExecAction"] = func() interface{} { + knownTypes["core/v1/ExecAction"] = func() any { return &corev1.ExecAction{} } - knownTypes["core/v1/FCVolumeSource"] = func() interface{} { + knownTypes["core/v1/FCVolumeSource"] = func() any { return &corev1.FCVolumeSource{} } - knownTypes["core/v1/FlexPersistentVolumeSource"] = func() interface{} { + knownTypes["core/v1/FlexPersistentVolumeSource"] = func() any { return &corev1.FlexPersistentVolumeSource{} } - knownTypes["core/v1/FlexVolumeSource"] = func() interface{} { + knownTypes["core/v1/FlexVolumeSource"] = func() any { return &corev1.FlexVolumeSource{} } - knownTypes["core/v1/FlockerVolumeSource"] = func() interface{} { + knownTypes["core/v1/FlockerVolumeSource"] = func() any { return &corev1.FlockerVolumeSource{} } - knownTypes["core/v1/GCEPersistentDiskVolumeSource"] = func() interface{} { + knownTypes["core/v1/GCEPersistentDiskVolumeSource"] = func() any { return &corev1.GCEPersistentDiskVolumeSource{} } - knownTypes["core/v1/GRPCAction"] = func() interface{} { + knownTypes["core/v1/GRPCAction"] = func() any { return &corev1.GRPCAction{} } - knownTypes["core/v1/GitRepoVolumeSource"] = func() interface{} { + knownTypes["core/v1/GitRepoVolumeSource"] = func() any { return &corev1.GitRepoVolumeSource{} } - knownTypes["core/v1/GlusterfsPersistentVolumeSource"] = func() interface{} { + knownTypes["core/v1/GlusterfsPersistentVolumeSource"] = func() any { return &corev1.GlusterfsPersistentVolumeSource{} } - knownTypes["core/v1/GlusterfsVolumeSource"] = func() interface{} { + knownTypes["core/v1/GlusterfsVolumeSource"] = func() any { return &corev1.GlusterfsVolumeSource{} } - knownTypes["core/v1/HTTPGetAction"] = func() interface{} { + knownTypes["core/v1/HTTPGetAction"] = func() any { return &corev1.HTTPGetAction{} } - knownTypes["core/v1/HTTPHeader"] = func() interface{} { + knownTypes["core/v1/HTTPHeader"] = func() any { return &corev1.HTTPHeader{} } - knownTypes["core/v1/HostAlias"] = func() interface{} { + knownTypes["core/v1/HostAlias"] = func() any { return &corev1.HostAlias{} } - knownTypes["core/v1/HostIP"] = func() interface{} { + knownTypes["core/v1/HostIP"] = func() any { return &corev1.HostIP{} } - knownTypes["core/v1/HostPathVolumeSource"] = func() interface{} { + knownTypes["core/v1/HostPathVolumeSource"] = func() any { return &corev1.HostPathVolumeSource{} } - knownTypes["core/v1/ISCSIPersistentVolumeSource"] = func() interface{} { + knownTypes["core/v1/ISCSIPersistentVolumeSource"] = func() any { return &corev1.ISCSIPersistentVolumeSource{} } - knownTypes["core/v1/ISCSIVolumeSource"] = func() interface{} { + knownTypes["core/v1/ISCSIVolumeSource"] = func() any { return &corev1.ISCSIVolumeSource{} } - knownTypes["core/v1/ImageVolumeSource"] = func() interface{} { + knownTypes["core/v1/ImageVolumeSource"] = func() any { return &corev1.ImageVolumeSource{} } - knownTypes["core/v1/KeyToPath"] = func() interface{} { + knownTypes["core/v1/KeyToPath"] = func() any { return &corev1.KeyToPath{} } - knownTypes["core/v1/Lifecycle"] = func() interface{} { + knownTypes["core/v1/Lifecycle"] = func() any { return &corev1.Lifecycle{} } - knownTypes["core/v1/LifecycleHandler"] = func() interface{} { + knownTypes["core/v1/LifecycleHandler"] = func() any { return &corev1.LifecycleHandler{} } - knownTypes["core/v1/LimitRange"] = func() interface{} { + knownTypes["core/v1/LimitRange"] = func() any { return &corev1.LimitRange{} } - knownTypes["core/v1/LimitRangeItem"] = func() interface{} { + knownTypes["core/v1/LimitRangeItem"] = func() any { return &corev1.LimitRangeItem{} } - knownTypes["core/v1/LimitRangeList"] = func() interface{} { + knownTypes["core/v1/LimitRangeList"] = func() any { return &corev1.LimitRangeList{} } - knownTypes["core/v1/LimitRangeSpec"] = func() interface{} { + knownTypes["core/v1/LimitRangeSpec"] = func() any { return &corev1.LimitRangeSpec{} } - knownTypes["core/v1/LinuxContainerUser"] = func() interface{} { + knownTypes["core/v1/LinuxContainerUser"] = func() any { return &corev1.LinuxContainerUser{} } - knownTypes["core/v1/List"] = func() interface{} { + knownTypes["core/v1/List"] = func() any { return &corev1.List{} } - knownTypes["core/v1/LoadBalancerIngress"] = func() interface{} { + knownTypes["core/v1/LoadBalancerIngress"] = func() any { return &corev1.LoadBalancerIngress{} } - knownTypes["core/v1/LoadBalancerStatus"] = func() interface{} { + knownTypes["core/v1/LoadBalancerStatus"] = func() any { return &corev1.LoadBalancerStatus{} } - knownTypes["core/v1/LocalObjectReference"] = func() interface{} { + knownTypes["core/v1/LocalObjectReference"] = func() any { return &corev1.LocalObjectReference{} } - knownTypes["core/v1/LocalVolumeSource"] = func() interface{} { + knownTypes["core/v1/LocalVolumeSource"] = func() any { return &corev1.LocalVolumeSource{} } - knownTypes["core/v1/ModifyVolumeStatus"] = func() interface{} { + knownTypes["core/v1/ModifyVolumeStatus"] = func() any { return &corev1.ModifyVolumeStatus{} } - knownTypes["core/v1/NFSVolumeSource"] = func() interface{} { + knownTypes["core/v1/NFSVolumeSource"] = func() any { return &corev1.NFSVolumeSource{} } - knownTypes["core/v1/Namespace"] = func() interface{} { + knownTypes["core/v1/Namespace"] = func() any { return &corev1.Namespace{} } - knownTypes["core/v1/NamespaceCondition"] = func() interface{} { + knownTypes["core/v1/NamespaceCondition"] = func() any { return &corev1.NamespaceCondition{} } - knownTypes["core/v1/NamespaceList"] = func() interface{} { + knownTypes["core/v1/NamespaceList"] = func() any { return &corev1.NamespaceList{} } - knownTypes["core/v1/NamespaceSpec"] = func() interface{} { + knownTypes["core/v1/NamespaceSpec"] = func() any { return &corev1.NamespaceSpec{} } - knownTypes["core/v1/NamespaceStatus"] = func() interface{} { + knownTypes["core/v1/NamespaceStatus"] = func() any { return &corev1.NamespaceStatus{} } - knownTypes["core/v1/Node"] = func() interface{} { + knownTypes["core/v1/Node"] = func() any { return &corev1.Node{} } - knownTypes["core/v1/NodeAddress"] = func() interface{} { + knownTypes["core/v1/NodeAddress"] = func() any { return &corev1.NodeAddress{} } - knownTypes["core/v1/NodeAffinity"] = func() interface{} { + knownTypes["core/v1/NodeAffinity"] = func() any { return &corev1.NodeAffinity{} } - knownTypes["core/v1/NodeCondition"] = func() interface{} { + knownTypes["core/v1/NodeCondition"] = func() any { return &corev1.NodeCondition{} } - knownTypes["core/v1/NodeConfigSource"] = func() interface{} { + knownTypes["core/v1/NodeConfigSource"] = func() any { return &corev1.NodeConfigSource{} } - knownTypes["core/v1/NodeConfigStatus"] = func() interface{} { + knownTypes["core/v1/NodeConfigStatus"] = func() any { return &corev1.NodeConfigStatus{} } - knownTypes["core/v1/NodeDaemonEndpoints"] = func() interface{} { + knownTypes["core/v1/NodeDaemonEndpoints"] = func() any { return &corev1.NodeDaemonEndpoints{} } - knownTypes["core/v1/NodeFeatures"] = func() interface{} { + knownTypes["core/v1/NodeFeatures"] = func() any { return &corev1.NodeFeatures{} } - knownTypes["core/v1/NodeList"] = func() interface{} { + knownTypes["core/v1/NodeList"] = func() any { return &corev1.NodeList{} } - knownTypes["core/v1/NodeProxyOptions"] = func() interface{} { + knownTypes["core/v1/NodeProxyOptions"] = func() any { return &corev1.NodeProxyOptions{} } - knownTypes["core/v1/NodeRuntimeHandler"] = func() interface{} { + knownTypes["core/v1/NodeRuntimeHandler"] = func() any { return &corev1.NodeRuntimeHandler{} } - knownTypes["core/v1/NodeRuntimeHandlerFeatures"] = func() interface{} { + knownTypes["core/v1/NodeRuntimeHandlerFeatures"] = func() any { return &corev1.NodeRuntimeHandlerFeatures{} } - knownTypes["core/v1/NodeSelector"] = func() interface{} { + knownTypes["core/v1/NodeSelector"] = func() any { return &corev1.NodeSelector{} } - knownTypes["core/v1/NodeSelectorRequirement"] = func() interface{} { + knownTypes["core/v1/NodeSelectorRequirement"] = func() any { return &corev1.NodeSelectorRequirement{} } - knownTypes["core/v1/NodeSelectorTerm"] = func() interface{} { + knownTypes["core/v1/NodeSelectorTerm"] = func() any { return &corev1.NodeSelectorTerm{} } - knownTypes["core/v1/NodeSpec"] = func() interface{} { + knownTypes["core/v1/NodeSpec"] = func() any { return &corev1.NodeSpec{} } - knownTypes["core/v1/NodeStatus"] = func() interface{} { + knownTypes["core/v1/NodeStatus"] = func() any { return &corev1.NodeStatus{} } - knownTypes["core/v1/NodeSystemInfo"] = func() interface{} { + knownTypes["core/v1/NodeSystemInfo"] = func() any { return &corev1.NodeSystemInfo{} } - knownTypes["core/v1/ObjectFieldSelector"] = func() interface{} { + knownTypes["core/v1/ObjectFieldSelector"] = func() any { return &corev1.ObjectFieldSelector{} } - knownTypes["core/v1/ObjectReference"] = func() interface{} { + knownTypes["core/v1/ObjectReference"] = func() any { return &corev1.ObjectReference{} } - knownTypes["core/v1/PersistentVolume"] = func() interface{} { + knownTypes["core/v1/PersistentVolume"] = func() any { return &corev1.PersistentVolume{} } - knownTypes["core/v1/PersistentVolumeClaim"] = func() interface{} { + knownTypes["core/v1/PersistentVolumeClaim"] = func() any { return &corev1.PersistentVolumeClaim{} } - knownTypes["core/v1/PersistentVolumeClaimCondition"] = func() interface{} { + knownTypes["core/v1/PersistentVolumeClaimCondition"] = func() any { return &corev1.PersistentVolumeClaimCondition{} } - knownTypes["core/v1/PersistentVolumeClaimList"] = func() interface{} { + knownTypes["core/v1/PersistentVolumeClaimList"] = func() any { return &corev1.PersistentVolumeClaimList{} } - knownTypes["core/v1/PersistentVolumeClaimSpec"] = func() interface{} { + knownTypes["core/v1/PersistentVolumeClaimSpec"] = func() any { return &corev1.PersistentVolumeClaimSpec{} } - knownTypes["core/v1/PersistentVolumeClaimStatus"] = func() interface{} { + knownTypes["core/v1/PersistentVolumeClaimStatus"] = func() any { return &corev1.PersistentVolumeClaimStatus{} } - knownTypes["core/v1/PersistentVolumeClaimTemplate"] = func() interface{} { + knownTypes["core/v1/PersistentVolumeClaimTemplate"] = func() any { return &corev1.PersistentVolumeClaimTemplate{} } - knownTypes["core/v1/PersistentVolumeClaimVolumeSource"] = func() interface{} { + knownTypes["core/v1/PersistentVolumeClaimVolumeSource"] = func() any { return &corev1.PersistentVolumeClaimVolumeSource{} } - knownTypes["core/v1/PersistentVolumeList"] = func() interface{} { + knownTypes["core/v1/PersistentVolumeList"] = func() any { return &corev1.PersistentVolumeList{} } - knownTypes["core/v1/PersistentVolumeSource"] = func() interface{} { + knownTypes["core/v1/PersistentVolumeSource"] = func() any { return &corev1.PersistentVolumeSource{} } - knownTypes["core/v1/PersistentVolumeSpec"] = func() interface{} { + knownTypes["core/v1/PersistentVolumeSpec"] = func() any { return &corev1.PersistentVolumeSpec{} } - knownTypes["core/v1/PersistentVolumeStatus"] = func() interface{} { + knownTypes["core/v1/PersistentVolumeStatus"] = func() any { return &corev1.PersistentVolumeStatus{} } - knownTypes["core/v1/PhotonPersistentDiskVolumeSource"] = func() interface{} { + knownTypes["core/v1/PhotonPersistentDiskVolumeSource"] = func() any { return &corev1.PhotonPersistentDiskVolumeSource{} } - knownTypes["core/v1/Pod"] = func() interface{} { + knownTypes["core/v1/Pod"] = func() any { return &corev1.Pod{} } - knownTypes["core/v1/PodAffinity"] = func() interface{} { + knownTypes["core/v1/PodAffinity"] = func() any { return &corev1.PodAffinity{} } - knownTypes["core/v1/PodAffinityTerm"] = func() interface{} { + knownTypes["core/v1/PodAffinityTerm"] = func() any { return &corev1.PodAffinityTerm{} } - knownTypes["core/v1/PodAntiAffinity"] = func() interface{} { + knownTypes["core/v1/PodAntiAffinity"] = func() any { return &corev1.PodAntiAffinity{} } - knownTypes["core/v1/PodAttachOptions"] = func() interface{} { + knownTypes["core/v1/PodAttachOptions"] = func() any { return &corev1.PodAttachOptions{} } - knownTypes["core/v1/PodCondition"] = func() interface{} { + knownTypes["core/v1/PodCondition"] = func() any { return &corev1.PodCondition{} } - knownTypes["core/v1/PodDNSConfig"] = func() interface{} { + knownTypes["core/v1/PodDNSConfig"] = func() any { return &corev1.PodDNSConfig{} } - knownTypes["core/v1/PodDNSConfigOption"] = func() interface{} { + knownTypes["core/v1/PodDNSConfigOption"] = func() any { return &corev1.PodDNSConfigOption{} } - knownTypes["core/v1/PodExecOptions"] = func() interface{} { + knownTypes["core/v1/PodExecOptions"] = func() any { return &corev1.PodExecOptions{} } - knownTypes["core/v1/PodIP"] = func() interface{} { + knownTypes["core/v1/PodIP"] = func() any { return &corev1.PodIP{} } - knownTypes["core/v1/PodList"] = func() interface{} { + knownTypes["core/v1/PodList"] = func() any { return &corev1.PodList{} } - knownTypes["core/v1/PodLogOptions"] = func() interface{} { + knownTypes["core/v1/PodLogOptions"] = func() any { return &corev1.PodLogOptions{} } - knownTypes["core/v1/PodOS"] = func() interface{} { + knownTypes["core/v1/PodOS"] = func() any { return &corev1.PodOS{} } - knownTypes["core/v1/PodPortForwardOptions"] = func() interface{} { + knownTypes["core/v1/PodPortForwardOptions"] = func() any { return &corev1.PodPortForwardOptions{} } - knownTypes["core/v1/PodProxyOptions"] = func() interface{} { + knownTypes["core/v1/PodProxyOptions"] = func() any { return &corev1.PodProxyOptions{} } - knownTypes["core/v1/PodReadinessGate"] = func() interface{} { + knownTypes["core/v1/PodReadinessGate"] = func() any { return &corev1.PodReadinessGate{} } - knownTypes["core/v1/PodResourceClaim"] = func() interface{} { + knownTypes["core/v1/PodResourceClaim"] = func() any { return &corev1.PodResourceClaim{} } - knownTypes["core/v1/PodResourceClaimStatus"] = func() interface{} { + knownTypes["core/v1/PodResourceClaimStatus"] = func() any { return &corev1.PodResourceClaimStatus{} } - knownTypes["core/v1/PodSchedulingGate"] = func() interface{} { + knownTypes["core/v1/PodSchedulingGate"] = func() any { return &corev1.PodSchedulingGate{} } - knownTypes["core/v1/PodSecurityContext"] = func() interface{} { + knownTypes["core/v1/PodSecurityContext"] = func() any { return &corev1.PodSecurityContext{} } - knownTypes["core/v1/PodSignature"] = func() interface{} { + knownTypes["core/v1/PodSignature"] = func() any { return &corev1.PodSignature{} } - knownTypes["core/v1/PodSpec"] = func() interface{} { + knownTypes["core/v1/PodSpec"] = func() any { return &corev1.PodSpec{} } - knownTypes["core/v1/PodStatus"] = func() interface{} { + knownTypes["core/v1/PodStatus"] = func() any { return &corev1.PodStatus{} } - knownTypes["core/v1/PodStatusResult"] = func() interface{} { + knownTypes["core/v1/PodStatusResult"] = func() any { return &corev1.PodStatusResult{} } - knownTypes["core/v1/PodTemplate"] = func() interface{} { + knownTypes["core/v1/PodTemplate"] = func() any { return &corev1.PodTemplate{} } - knownTypes["core/v1/PodTemplateList"] = func() interface{} { + knownTypes["core/v1/PodTemplateList"] = func() any { return &corev1.PodTemplateList{} } - knownTypes["core/v1/PodTemplateSpec"] = func() interface{} { + knownTypes["core/v1/PodTemplateSpec"] = func() any { return &corev1.PodTemplateSpec{} } - knownTypes["core/v1/PortStatus"] = func() interface{} { + knownTypes["core/v1/PortStatus"] = func() any { return &corev1.PortStatus{} } - knownTypes["core/v1/PortworxVolumeSource"] = func() interface{} { + knownTypes["core/v1/PortworxVolumeSource"] = func() any { return &corev1.PortworxVolumeSource{} } - knownTypes["core/v1/Preconditions"] = func() interface{} { + knownTypes["core/v1/Preconditions"] = func() any { return &corev1.Preconditions{} } - knownTypes["core/v1/PreferAvoidPodsEntry"] = func() interface{} { + knownTypes["core/v1/PreferAvoidPodsEntry"] = func() any { return &corev1.PreferAvoidPodsEntry{} } - knownTypes["core/v1/PreferredSchedulingTerm"] = func() interface{} { + knownTypes["core/v1/PreferredSchedulingTerm"] = func() any { return &corev1.PreferredSchedulingTerm{} } - knownTypes["core/v1/Probe"] = func() interface{} { + knownTypes["core/v1/Probe"] = func() any { return &corev1.Probe{} } - knownTypes["core/v1/ProbeHandler"] = func() interface{} { + knownTypes["core/v1/ProbeHandler"] = func() any { return &corev1.ProbeHandler{} } - knownTypes["core/v1/ProjectedVolumeSource"] = func() interface{} { + knownTypes["core/v1/ProjectedVolumeSource"] = func() any { return &corev1.ProjectedVolumeSource{} } - knownTypes["core/v1/QuobyteVolumeSource"] = func() interface{} { + knownTypes["core/v1/QuobyteVolumeSource"] = func() any { return &corev1.QuobyteVolumeSource{} } - knownTypes["core/v1/RBDPersistentVolumeSource"] = func() interface{} { + knownTypes["core/v1/RBDPersistentVolumeSource"] = func() any { return &corev1.RBDPersistentVolumeSource{} } - knownTypes["core/v1/RBDVolumeSource"] = func() interface{} { + knownTypes["core/v1/RBDVolumeSource"] = func() any { return &corev1.RBDVolumeSource{} } - knownTypes["core/v1/RangeAllocation"] = func() interface{} { + knownTypes["core/v1/RangeAllocation"] = func() any { return &corev1.RangeAllocation{} } - knownTypes["core/v1/ReplicationController"] = func() interface{} { + knownTypes["core/v1/ReplicationController"] = func() any { return &corev1.ReplicationController{} } - knownTypes["core/v1/ReplicationControllerCondition"] = func() interface{} { + knownTypes["core/v1/ReplicationControllerCondition"] = func() any { return &corev1.ReplicationControllerCondition{} } - knownTypes["core/v1/ReplicationControllerList"] = func() interface{} { + knownTypes["core/v1/ReplicationControllerList"] = func() any { return &corev1.ReplicationControllerList{} } - knownTypes["core/v1/ReplicationControllerSpec"] = func() interface{} { + knownTypes["core/v1/ReplicationControllerSpec"] = func() any { return &corev1.ReplicationControllerSpec{} } - knownTypes["core/v1/ReplicationControllerStatus"] = func() interface{} { + knownTypes["core/v1/ReplicationControllerStatus"] = func() any { return &corev1.ReplicationControllerStatus{} } - knownTypes["core/v1/ResourceClaim"] = func() interface{} { + knownTypes["core/v1/ResourceClaim"] = func() any { return &corev1.ResourceClaim{} } - knownTypes["core/v1/ResourceFieldSelector"] = func() interface{} { + knownTypes["core/v1/ResourceFieldSelector"] = func() any { return &corev1.ResourceFieldSelector{} } - knownTypes["core/v1/ResourceHealth"] = func() interface{} { + knownTypes["core/v1/ResourceHealth"] = func() any { return &corev1.ResourceHealth{} } - knownTypes["core/v1/ResourceList"] = func() interface{} { + knownTypes["core/v1/ResourceList"] = func() any { return &corev1.ResourceList{} } - knownTypes["core/v1/ResourceQuota"] = func() interface{} { + knownTypes["core/v1/ResourceQuota"] = func() any { return &corev1.ResourceQuota{} } - knownTypes["core/v1/ResourceQuotaList"] = func() interface{} { + knownTypes["core/v1/ResourceQuotaList"] = func() any { return &corev1.ResourceQuotaList{} } - knownTypes["core/v1/ResourceQuotaSpec"] = func() interface{} { + knownTypes["core/v1/ResourceQuotaSpec"] = func() any { return &corev1.ResourceQuotaSpec{} } - knownTypes["core/v1/ResourceQuotaStatus"] = func() interface{} { + knownTypes["core/v1/ResourceQuotaStatus"] = func() any { return &corev1.ResourceQuotaStatus{} } - knownTypes["core/v1/ResourceRequirements"] = func() interface{} { + knownTypes["core/v1/ResourceRequirements"] = func() any { return &corev1.ResourceRequirements{} } - knownTypes["core/v1/ResourceStatus"] = func() interface{} { + knownTypes["core/v1/ResourceStatus"] = func() any { return &corev1.ResourceStatus{} } - knownTypes["core/v1/SELinuxOptions"] = func() interface{} { + knownTypes["core/v1/SELinuxOptions"] = func() any { return &corev1.SELinuxOptions{} } - knownTypes["core/v1/ScaleIOPersistentVolumeSource"] = func() interface{} { + knownTypes["core/v1/ScaleIOPersistentVolumeSource"] = func() any { return &corev1.ScaleIOPersistentVolumeSource{} } - knownTypes["core/v1/ScaleIOVolumeSource"] = func() interface{} { + knownTypes["core/v1/ScaleIOVolumeSource"] = func() any { return &corev1.ScaleIOVolumeSource{} } - knownTypes["core/v1/ScopeSelector"] = func() interface{} { + knownTypes["core/v1/ScopeSelector"] = func() any { return &corev1.ScopeSelector{} } - knownTypes["core/v1/ScopedResourceSelectorRequirement"] = func() interface{} { + knownTypes["core/v1/ScopedResourceSelectorRequirement"] = func() any { return &corev1.ScopedResourceSelectorRequirement{} } - knownTypes["core/v1/SeccompProfile"] = func() interface{} { + knownTypes["core/v1/SeccompProfile"] = func() any { return &corev1.SeccompProfile{} } - knownTypes["core/v1/Secret"] = func() interface{} { + knownTypes["core/v1/Secret"] = func() any { return &corev1.Secret{} } - knownTypes["core/v1/SecretEnvSource"] = func() interface{} { + knownTypes["core/v1/SecretEnvSource"] = func() any { return &corev1.SecretEnvSource{} } - knownTypes["core/v1/SecretKeySelector"] = func() interface{} { + knownTypes["core/v1/SecretKeySelector"] = func() any { return &corev1.SecretKeySelector{} } - knownTypes["core/v1/SecretList"] = func() interface{} { + knownTypes["core/v1/SecretList"] = func() any { return &corev1.SecretList{} } - knownTypes["core/v1/SecretProjection"] = func() interface{} { + knownTypes["core/v1/SecretProjection"] = func() any { return &corev1.SecretProjection{} } - knownTypes["core/v1/SecretReference"] = func() interface{} { + knownTypes["core/v1/SecretReference"] = func() any { return &corev1.SecretReference{} } - knownTypes["core/v1/SecretVolumeSource"] = func() interface{} { + knownTypes["core/v1/SecretVolumeSource"] = func() any { return &corev1.SecretVolumeSource{} } - knownTypes["core/v1/SecurityContext"] = func() interface{} { + knownTypes["core/v1/SecurityContext"] = func() any { return &corev1.SecurityContext{} } - knownTypes["core/v1/SerializedReference"] = func() interface{} { + knownTypes["core/v1/SerializedReference"] = func() any { return &corev1.SerializedReference{} } - knownTypes["core/v1/Service"] = func() interface{} { + knownTypes["core/v1/Service"] = func() any { return &corev1.Service{} } - knownTypes["core/v1/ServiceAccount"] = func() interface{} { + knownTypes["core/v1/ServiceAccount"] = func() any { return &corev1.ServiceAccount{} } - knownTypes["core/v1/ServiceAccountList"] = func() interface{} { + knownTypes["core/v1/ServiceAccountList"] = func() any { return &corev1.ServiceAccountList{} } - knownTypes["core/v1/ServiceAccountTokenProjection"] = func() interface{} { + knownTypes["core/v1/ServiceAccountTokenProjection"] = func() any { return &corev1.ServiceAccountTokenProjection{} } - knownTypes["core/v1/ServiceList"] = func() interface{} { + knownTypes["core/v1/ServiceList"] = func() any { return &corev1.ServiceList{} } - knownTypes["core/v1/ServicePort"] = func() interface{} { + knownTypes["core/v1/ServicePort"] = func() any { return &corev1.ServicePort{} } - knownTypes["core/v1/ServiceProxyOptions"] = func() interface{} { + knownTypes["core/v1/ServiceProxyOptions"] = func() any { return &corev1.ServiceProxyOptions{} } - knownTypes["core/v1/ServiceSpec"] = func() interface{} { + knownTypes["core/v1/ServiceSpec"] = func() any { return &corev1.ServiceSpec{} } - knownTypes["core/v1/ServiceStatus"] = func() interface{} { + knownTypes["core/v1/ServiceStatus"] = func() any { return &corev1.ServiceStatus{} } - knownTypes["core/v1/SessionAffinityConfig"] = func() interface{} { + knownTypes["core/v1/SessionAffinityConfig"] = func() any { return &corev1.SessionAffinityConfig{} } - knownTypes["core/v1/SleepAction"] = func() interface{} { + knownTypes["core/v1/SleepAction"] = func() any { return &corev1.SleepAction{} } - knownTypes["core/v1/StorageOSPersistentVolumeSource"] = func() interface{} { + knownTypes["core/v1/StorageOSPersistentVolumeSource"] = func() any { return &corev1.StorageOSPersistentVolumeSource{} } - knownTypes["core/v1/StorageOSVolumeSource"] = func() interface{} { + knownTypes["core/v1/StorageOSVolumeSource"] = func() any { return &corev1.StorageOSVolumeSource{} } - knownTypes["core/v1/Sysctl"] = func() interface{} { + knownTypes["core/v1/Sysctl"] = func() any { return &corev1.Sysctl{} } - knownTypes["core/v1/TCPSocketAction"] = func() interface{} { + knownTypes["core/v1/TCPSocketAction"] = func() any { return &corev1.TCPSocketAction{} } - knownTypes["core/v1/Taint"] = func() interface{} { + knownTypes["core/v1/Taint"] = func() any { return &corev1.Taint{} } - knownTypes["core/v1/Toleration"] = func() interface{} { + knownTypes["core/v1/Toleration"] = func() any { return &corev1.Toleration{} } - knownTypes["core/v1/TopologySelectorLabelRequirement"] = func() interface{} { + knownTypes["core/v1/TopologySelectorLabelRequirement"] = func() any { return &corev1.TopologySelectorLabelRequirement{} } - knownTypes["core/v1/TopologySelectorTerm"] = func() interface{} { + knownTypes["core/v1/TopologySelectorTerm"] = func() any { return &corev1.TopologySelectorTerm{} } - knownTypes["core/v1/TopologySpreadConstraint"] = func() interface{} { + knownTypes["core/v1/TopologySpreadConstraint"] = func() any { return &corev1.TopologySpreadConstraint{} } - knownTypes["core/v1/TypedLocalObjectReference"] = func() interface{} { + knownTypes["core/v1/TypedLocalObjectReference"] = func() any { return &corev1.TypedLocalObjectReference{} } - knownTypes["core/v1/TypedObjectReference"] = func() interface{} { + knownTypes["core/v1/TypedObjectReference"] = func() any { return &corev1.TypedObjectReference{} } - knownTypes["core/v1/Volume"] = func() interface{} { + knownTypes["core/v1/Volume"] = func() any { return &corev1.Volume{} } - knownTypes["core/v1/VolumeDevice"] = func() interface{} { + knownTypes["core/v1/VolumeDevice"] = func() any { return &corev1.VolumeDevice{} } - knownTypes["core/v1/VolumeMount"] = func() interface{} { + knownTypes["core/v1/VolumeMount"] = func() any { return &corev1.VolumeMount{} } - knownTypes["core/v1/VolumeMountStatus"] = func() interface{} { + knownTypes["core/v1/VolumeMountStatus"] = func() any { return &corev1.VolumeMountStatus{} } - knownTypes["core/v1/VolumeNodeAffinity"] = func() interface{} { + knownTypes["core/v1/VolumeNodeAffinity"] = func() any { return &corev1.VolumeNodeAffinity{} } - knownTypes["core/v1/VolumeProjection"] = func() interface{} { + knownTypes["core/v1/VolumeProjection"] = func() any { return &corev1.VolumeProjection{} } - knownTypes["core/v1/VolumeResourceRequirements"] = func() interface{} { + knownTypes["core/v1/VolumeResourceRequirements"] = func() any { return &corev1.VolumeResourceRequirements{} } - knownTypes["core/v1/VolumeSource"] = func() interface{} { + knownTypes["core/v1/VolumeSource"] = func() any { return &corev1.VolumeSource{} } - knownTypes["core/v1/VsphereVirtualDiskVolumeSource"] = func() interface{} { + knownTypes["core/v1/VsphereVirtualDiskVolumeSource"] = func() any { return &corev1.VsphereVirtualDiskVolumeSource{} } - knownTypes["core/v1/WeightedPodAffinityTerm"] = func() interface{} { + knownTypes["core/v1/WeightedPodAffinityTerm"] = func() any { return &corev1.WeightedPodAffinityTerm{} } - knownTypes["core/v1/WindowsSecurityContextOptions"] = func() interface{} { + knownTypes["core/v1/WindowsSecurityContextOptions"] = func() any { return &corev1.WindowsSecurityContextOptions{} } } diff --git a/util/argo/normalizers/diff_normalizer.go b/util/argo/normalizers/diff_normalizer.go index f728128053f6b1..145042963695dd 100644 --- a/util/argo/normalizers/diff_normalizer.go +++ b/util/argo/normalizers/diff_normalizer.go @@ -70,7 +70,7 @@ type jqNormalizerPatch struct { } func (np *jqNormalizerPatch) Apply(data []byte) ([]byte, error) { - dataJson := make(map[string]interface{}) + dataJson := make(map[string]any) err := json.Unmarshal(data, &dataJson) if err != nil { return nil, err diff --git a/util/argo/normalizers/diff_normalizer_test.go b/util/argo/normalizers/diff_normalizer_test.go index 32d133d6e8385e..e236a71bff9919 100644 --- a/util/argo/normalizers/diff_normalizer_test.go +++ b/util/argo/normalizers/diff_normalizer_test.go @@ -167,9 +167,9 @@ func TestNormalizeJQPathExpression(t *testing.T) { deployment := test.NewDeployment() - var initContainers []interface{} - initContainers = append(initContainers, map[string]interface{}{"name": "init-container-0"}) - initContainers = append(initContainers, map[string]interface{}{"name": "init-container-1"}) + var initContainers []any + initContainers = append(initContainers, map[string]any{"name": "init-container-0"}) + initContainers = append(initContainers, map[string]any{"name": "init-container-1"}) err = unstructured.SetNestedSlice(deployment.Object, initContainers, "spec", "template", "spec", "initContainers") require.NoError(t, err) @@ -185,7 +185,7 @@ func TestNormalizeJQPathExpression(t *testing.T) { assert.True(t, has) assert.Len(t, actualInitContainers, 1) - actualInitContainerName, has, err := unstructured.NestedString(actualInitContainers[0].(map[string]interface{}), "name") + actualInitContainerName, has, err := unstructured.NestedString(actualInitContainers[0].(map[string]any), "name") require.NoError(t, err) assert.True(t, has) assert.Equal(t, "init-container-1", actualInitContainerName) diff --git a/util/argo/normalizers/knowntypes_normalizer.go b/util/argo/normalizers/knowntypes_normalizer.go index f96a366a75d6a1..6fc45c6806afda 100644 --- a/util/argo/normalizers/knowntypes_normalizer.go +++ b/util/argo/normalizers/knowntypes_normalizer.go @@ -17,11 +17,11 @@ import ( ) //go:generate go run github.com/argoproj/argo-cd/v2/hack/known_types corev1 k8s.io/api/core/v1 corev1_known_types.go --docs diffing_known_types.txt -var knownTypes = map[string]func() interface{}{} +var knownTypes = map[string]func() any{} type knownTypeField struct { fieldPath []string - newFieldFn func() interface{} + newFieldFn func() any } type knownTypesNormalizer struct { @@ -30,10 +30,10 @@ type knownTypesNormalizer struct { // Register some non-code-generated types here. The bulk of them are in corev1_known_types.go func init() { - knownTypes["core/Quantity"] = func() interface{} { + knownTypes["core/Quantity"] = func() any { return &resource.Quantity{} } - knownTypes["meta/v1/Duration"] = func() interface{} { + knownTypes["meta/v1/Duration"] = func() any { return &metav1.Duration{} } } @@ -62,7 +62,7 @@ func (n *knownTypesNormalizer) ensureDefaultCRDsConfigured() { if _, ok := n.typeFields[rolloutGK]; !ok { n.typeFields[rolloutGK] = []knownTypeField{{ fieldPath: []string{"spec", "template", "spec"}, - newFieldFn: func() interface{} { + newFieldFn: func() any { return &v1.PodSpec{} }, }} @@ -81,15 +81,15 @@ func (n *knownTypesNormalizer) addKnownField(gk schema.GroupKind, fieldPath stri return nil } -func normalize(obj map[string]interface{}, field knownTypeField, fieldPath []string) error { +func normalize(obj map[string]any, field knownTypeField, fieldPath []string) error { for i := range fieldPath { if nestedField, ok, err := unstructured.NestedFieldNoCopy(obj, fieldPath[:i+1]...); err == nil && ok { - items, ok := nestedField.([]interface{}) + items, ok := nestedField.([]any) if !ok { continue } for j := range items { - item, ok := items[j].(map[string]interface{}) + item, ok := items[j].(map[string]any) if !ok { continue } @@ -125,7 +125,7 @@ func normalize(obj map[string]interface{}, field knownTypeField, fieldPath []str return nil } -func remarshal(fieldVal interface{}, field knownTypeField) (interface{}, error) { +func remarshal(fieldVal any, field knownTypeField) (any, error) { data, err := json.Marshal(fieldVal) if err != nil { return nil, err @@ -139,7 +139,7 @@ func remarshal(fieldVal interface{}, field knownTypeField) (interface{}, error) if err != nil { return nil, err } - var newFieldVal interface{} + var newFieldVal any err = json.Unmarshal(data, &newFieldVal) if err != nil { return nil, err diff --git a/util/argo/normalizers/knowntypes_normalizer_test.go b/util/argo/normalizers/knowntypes_normalizer_test.go index ea2a66ab9d6f89..432eaf5a9b8835 100644 --- a/util/argo/normalizers/knowntypes_normalizer_test.go +++ b/util/argo/normalizers/knowntypes_normalizer_test.go @@ -50,7 +50,7 @@ func mustUnmarshalYAML(yamlStr string) *unstructured.Unstructured { } // nolint:unparam -func nestedSliceMap(obj map[string]interface{}, i int, path ...string) (map[string]interface{}, error) { +func nestedSliceMap(obj map[string]any, i int, path ...string) (map[string]any, error) { items, ok, err := unstructured.NestedSlice(obj, path...) if err != nil { return nil, err @@ -61,7 +61,7 @@ func nestedSliceMap(obj map[string]interface{}, i int, path ...string) (map[stri if len(items) < i { return nil, fmt.Errorf("field %s has less than %d items", strings.Join(path, "."), i) } - if item, ok := items[i].(map[string]interface{}); !ok { + if item, ok := items[i].(map[string]any); !ok { return nil, fmt.Errorf("field %s[%d] is not map", strings.Join(path, "."), i) } else { return item, nil diff --git a/util/cache/appstate/cache.go b/util/cache/appstate/cache.go index f0c335abb9287a..49a4bb3f290ae0 100644 --- a/util/cache/appstate/cache.go +++ b/util/cache/appstate/cache.go @@ -47,11 +47,11 @@ func AddCacheFlagsToCmd(cmd *cobra.Command, opts ...cacheutil.Options) func() (* } } -func (c *Cache) GetItem(key string, item interface{}) error { +func (c *Cache) GetItem(key string, item any) error { return c.Cache.GetItem(key, item) } -func (c *Cache) SetItem(key string, item interface{}, expiration time.Duration, delete bool) error { +func (c *Cache) SetItem(key string, item any, expiration time.Duration, delete bool) error { return c.Cache.SetItem(key, item, &cacheutil.CacheActionOpts{Expiration: expiration, Delete: delete}) } diff --git a/util/cache/cache.go b/util/cache/cache.go index 2e8d0ad0e4bbee..240a940f14be36 100644 --- a/util/cache/cache.go +++ b/util/cache/cache.go @@ -269,7 +269,7 @@ func (c *Cache) generateFullKey(key string) string { } // Sets or deletes an item in cache -func (c *Cache) SetItem(key string, item interface{}, opts *CacheActionOpts) error { +func (c *Cache) SetItem(key string, item any, opts *CacheActionOpts) error { if item == nil { return errors.New("cannot set nil item in cache") } @@ -285,7 +285,7 @@ func (c *Cache) SetItem(key string, item interface{}, opts *CacheActionOpts) err } } -func (c *Cache) GetItem(key string, item interface{}) error { +func (c *Cache) GetItem(key string, item any) error { key = c.generateFullKey(key) if item == nil { return fmt.Errorf("cannot get item into a nil for key %s", key) diff --git a/util/cache/client.go b/util/cache/client.go index f5bb7b9427507f..3ef73dd9ffc4c0 100644 --- a/util/cache/client.go +++ b/util/cache/client.go @@ -14,7 +14,7 @@ var ( type Item struct { Key string - Object interface{} + Object any CacheActionOpts CacheActionOpts } @@ -30,7 +30,7 @@ type CacheActionOpts struct { type CacheClient interface { Set(item *Item) error Rename(oldKey string, newKey string, expiration time.Duration) error - Get(key string, obj interface{}) error + Get(key string, obj any) error Delete(key string) error OnUpdated(ctx context.Context, key string, callback func() error) error NotifyUpdated(key string) error diff --git a/util/cache/inmemory.go b/util/cache/inmemory.go index c46b02b942584a..5f1544c20f4eb4 100644 --- a/util/cache/inmemory.go +++ b/util/cache/inmemory.go @@ -17,7 +17,7 @@ func NewInMemoryCache(expiration time.Duration) *InMemoryCache { } func init() { - gob.Register([]interface{}{}) + gob.Register([]any{}) } // compile-time validation of adherence of the CacheClient contract @@ -53,7 +53,7 @@ func (i *InMemoryCache) Rename(oldKey string, newKey string, expiration time.Dur } // HasSame returns true if key with the same value already present in cache -func (i *InMemoryCache) HasSame(key string, obj interface{}) (bool, error) { +func (i *InMemoryCache) HasSame(key string, obj any) (bool, error) { var buf bytes.Buffer err := gob.NewEncoder(&buf).Encode(obj) if err != nil { @@ -71,7 +71,7 @@ func (i *InMemoryCache) HasSame(key string, obj interface{}) (bool, error) { return bytes.Equal(buf.Bytes(), existingBuf.Bytes()), nil } -func (i *InMemoryCache) Get(key string, obj interface{}) error { +func (i *InMemoryCache) Get(key string, obj any) error { bufIf, found := i.memCache.Get(key) if !found { return ErrCacheMiss @@ -99,8 +99,8 @@ func (i *InMemoryCache) NotifyUpdated(key string) error { // Items return a list of items in the cache; requires passing a constructor function // so that the items can be decoded from gob format. -func (i *InMemoryCache) Items(createNewObject func() interface{}) (map[string]interface{}, error) { - result := map[string]interface{}{} +func (i *InMemoryCache) Items(createNewObject func() any) (map[string]any, error) { + result := map[string]any{} for key, value := range i.memCache.Items() { buf := value.Object.(bytes.Buffer) diff --git a/util/cache/mocks/cacheclient.go b/util/cache/mocks/cacheclient.go index 2fdd9fc37f8be9..fb468eb581d8b0 100644 --- a/util/cache/mocks/cacheclient.go +++ b/util/cache/mocks/cacheclient.go @@ -35,7 +35,7 @@ func (c *MockCacheClient) Set(item *cache.Item) error { return c.BaseCache.Set(item) } -func (c *MockCacheClient) Get(key string, obj interface{}) error { +func (c *MockCacheClient) Get(key string, obj any) error { args := c.Called(key, obj) if len(args) > 0 && args.Get(0) != nil { return args.Get(0).(error) diff --git a/util/cache/redis.go b/util/cache/redis.go index 2c938b6998bb77..5f0de926f7dd2c 100644 --- a/util/cache/redis.go +++ b/util/cache/redis.go @@ -63,7 +63,7 @@ func (r *redisCache) getKey(key string) string { } } -func (r *redisCache) marshal(obj interface{}) ([]byte, error) { +func (r *redisCache) marshal(obj any) ([]byte, error) { buf := bytes.NewBuffer([]byte{}) var w io.Writer = buf if r.redisCompressionType == RedisCompressionGZip { @@ -87,7 +87,7 @@ func (r *redisCache) marshal(obj interface{}) ([]byte, error) { return buf.Bytes(), nil } -func (r *redisCache) unmarshal(data []byte, obj interface{}) error { +func (r *redisCache) unmarshal(data []byte, obj any) error { buf := bytes.NewReader(data) var reader io.Reader = buf if r.redisCompressionType == RedisCompressionGZip { @@ -131,7 +131,7 @@ func (r *redisCache) Set(item *Item) error { }) } -func (r *redisCache) Get(key string, obj interface{}) error { +func (r *redisCache) Get(key string, obj any) error { var data []byte err := r.cache.Get(context.TODO(), r.getKey(key), &data) if errors.Is(err, rediscache.ErrCacheMiss) { diff --git a/util/cache/twolevelclient.go b/util/cache/twolevelclient.go index f2210998448763..87d7100381c364 100644 --- a/util/cache/twolevelclient.go +++ b/util/cache/twolevelclient.go @@ -45,7 +45,7 @@ func (c *twoLevelClient) Set(item *Item) error { // Get returns cache value from in-memory cache if it present. Otherwise loads it from external cache and persists // in memory to avoid future requests to external cache. -func (c *twoLevelClient) Get(key string, obj interface{}) error { +func (c *twoLevelClient) Get(key string, obj any) error { err := c.inMemoryCache.Get(key, obj) if err == nil { return nil diff --git a/util/clusterauth/clusterauth.go b/util/clusterauth/clusterauth.go index d57e27792ecb6d..c5ef8395f3348b 100644 --- a/util/clusterauth/clusterauth.go +++ b/util/clusterauth/clusterauth.go @@ -77,7 +77,7 @@ func CreateServiceAccount( return nil } -func upsert(kind string, name string, create func() (interface{}, error), update func() (interface{}, error)) error { +func upsert(kind string, name string, create func() (any, error), update func() (any, error)) error { _, err := create() if err != nil { if !apierr.IsAlreadyExists(err) { @@ -105,9 +105,9 @@ func upsertClusterRole(clientset kubernetes.Interface, name string, rules []rbac }, Rules: rules, } - return upsert("ClusterRole", name, func() (interface{}, error) { + return upsert("ClusterRole", name, func() (any, error) { return clientset.RbacV1().ClusterRoles().Create(context.Background(), &clusterRole, metav1.CreateOptions{}) - }, func() (interface{}, error) { + }, func() (any, error) { return clientset.RbacV1().ClusterRoles().Update(context.Background(), &clusterRole, metav1.UpdateOptions{}) }) } @@ -123,9 +123,9 @@ func upsertRole(clientset kubernetes.Interface, name string, namespace string, r }, Rules: rules, } - return upsert("Role", fmt.Sprintf("%s/%s", namespace, name), func() (interface{}, error) { + return upsert("Role", fmt.Sprintf("%s/%s", namespace, name), func() (any, error) { return clientset.RbacV1().Roles(namespace).Create(context.Background(), &role, metav1.CreateOptions{}) - }, func() (interface{}, error) { + }, func() (any, error) { return clientset.RbacV1().Roles(namespace).Update(context.Background(), &role, metav1.UpdateOptions{}) }) } @@ -146,9 +146,9 @@ func upsertClusterRoleBinding(clientset kubernetes.Interface, name string, clust }, Subjects: []rbacv1.Subject{subject}, } - return upsert("ClusterRoleBinding", name, func() (interface{}, error) { + return upsert("ClusterRoleBinding", name, func() (any, error) { return clientset.RbacV1().ClusterRoleBindings().Create(context.Background(), &roleBinding, metav1.CreateOptions{}) - }, func() (interface{}, error) { + }, func() (any, error) { return clientset.RbacV1().ClusterRoleBindings().Update(context.Background(), &roleBinding, metav1.UpdateOptions{}) }) } @@ -169,9 +169,9 @@ func upsertRoleBinding(clientset kubernetes.Interface, name string, roleName str }, Subjects: []rbacv1.Subject{subject}, } - return upsert("RoleBinding", fmt.Sprintf("%s/%s", namespace, name), func() (interface{}, error) { + return upsert("RoleBinding", fmt.Sprintf("%s/%s", namespace, name), func() (any, error) { return clientset.RbacV1().RoleBindings(namespace).Create(context.Background(), &roleBinding, metav1.CreateOptions{}) - }, func() (interface{}, error) { + }, func() (any, error) { return clientset.RbacV1().RoleBindings(namespace).Update(context.Background(), &roleBinding, metav1.UpdateOptions{}) }) } diff --git a/util/config/reader.go b/util/config/reader.go index 9674a2ef5bc008..35b33b9d8a0ff7 100644 --- a/util/config/reader.go +++ b/util/config/reader.go @@ -10,7 +10,7 @@ import ( ) // UnmarshalReader is used to read manifests from stdin -func UnmarshalReader(reader io.Reader, obj interface{}) error { +func UnmarshalReader(reader io.Reader, obj any) error { data, err := io.ReadAll(reader) if err != nil { return err @@ -19,7 +19,7 @@ func UnmarshalReader(reader io.Reader, obj interface{}) error { } // unmarshalObject tries to convert a YAML or JSON byte array into the provided type. -func unmarshalObject(data []byte, obj interface{}) error { +func unmarshalObject(data []byte, obj any) error { // first, try unmarshaling as JSON // Based on technique from Kubectl, which supports both YAML and JSON: // https://mlafeldt.github.io/blog/teaching-go-programs-to-love-json-and-yaml/ @@ -35,7 +35,7 @@ func unmarshalObject(data []byte, obj interface{}) error { // MarshalLocalYAMLFile writes JSON or YAML to a file on disk. // The caller is responsible for checking error return values. -func MarshalLocalYAMLFile(path string, obj interface{}) error { +func MarshalLocalYAMLFile(path string, obj any) error { yamlData, err := yaml.Marshal(obj) if err == nil { err = os.WriteFile(path, yamlData, 0o600) @@ -45,7 +45,7 @@ func MarshalLocalYAMLFile(path string, obj interface{}) error { // UnmarshalLocalFile retrieves JSON or YAML from a file on disk. // The caller is responsible for checking error return values. -func UnmarshalLocalFile(path string, obj interface{}) error { +func UnmarshalLocalFile(path string, obj any) error { data, err := os.ReadFile(path) if err == nil { err = unmarshalObject(data, obj) @@ -53,13 +53,13 @@ func UnmarshalLocalFile(path string, obj interface{}) error { return err } -func Unmarshal(data []byte, obj interface{}) error { +func Unmarshal(data []byte, obj any) error { return unmarshalObject(data, obj) } // UnmarshalRemoteFile retrieves JSON or YAML through a GET request. // The caller is responsible for checking error return values. -func UnmarshalRemoteFile(url string, obj interface{}) error { +func UnmarshalRemoteFile(url string, obj any) error { data, err := ReadRemoteFile(url) if err == nil { err = unmarshalObject(data, obj) diff --git a/util/db/secrets.go b/util/db/secrets.go index 38136d8c43dba3..a1fd515dcf12e3 100644 --- a/util/db/secrets.go +++ b/util/db/secrets.go @@ -123,17 +123,17 @@ func (db *db) watchSecrets(ctx context.Context, options.LabelSelector = labelSelector.String() } secretEventHandler := cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { if secretObj, ok := obj.(*apiv1.Secret); ok { handleAddEvent(secretObj) } }, - DeleteFunc: func(obj interface{}) { + DeleteFunc: func(obj any) { if secretObj, ok := obj.(*apiv1.Secret); ok { handleDeleteEvent(secretObj) } }, - UpdateFunc: func(oldObj, newObj interface{}) { + UpdateFunc: func(oldObj, newObj any) { if oldSecretObj, ok := oldObj.(*apiv1.Secret); ok { if newSecretObj, ok := newObj.(*apiv1.Secret); ok { handleModEvent(oldSecretObj, newSecretObj) diff --git a/util/dex/config.go b/util/dex/config.go index 480ca077dcb615..549d10c6c551a2 100644 --- a/util/dex/config.go +++ b/util/dex/config.go @@ -21,28 +21,28 @@ func GenerateDexConfigYAML(argocdSettings *settings.ArgoCDSettings, disableTls b if err != nil { return nil, fmt.Errorf("failed to infer redirect url from config: %w", err) } - var dexCfg map[string]interface{} + var dexCfg map[string]any err = yaml.Unmarshal([]byte(argocdSettings.DexConfig), &dexCfg) if err != nil { return nil, fmt.Errorf("failed to unmarshal dex.config from configmap: %w", err) } dexCfg["issuer"] = argocdSettings.IssuerURL() - dexCfg["storage"] = map[string]interface{}{ + dexCfg["storage"] = map[string]any{ "type": "memory", } if disableTls { - dexCfg["web"] = map[string]interface{}{ + dexCfg["web"] = map[string]any{ "http": "0.0.0.0:5556", } } else { - dexCfg["web"] = map[string]interface{}{ + dexCfg["web"] = map[string]any{ "https": "0.0.0.0:5556", "tlsCert": "/tmp/tls.crt", "tlsKey": "/tmp/tls.key", } } - if loggerCfg, found := dexCfg["logger"].(map[string]interface{}); found { + if loggerCfg, found := dexCfg["logger"].(map[string]any); found { if _, found := loggerCfg["level"]; !found { loggerCfg["level"] = slogLevelFromLogrus(os.Getenv(common.EnvLogLevel)) } @@ -50,25 +50,25 @@ func GenerateDexConfigYAML(argocdSettings *settings.ArgoCDSettings, disableTls b loggerCfg["format"] = os.Getenv(common.EnvLogFormat) } } else { - dexCfg["logger"] = map[string]interface{}{ + dexCfg["logger"] = map[string]any{ "level": slogLevelFromLogrus(os.Getenv(common.EnvLogLevel)), "format": os.Getenv(common.EnvLogFormat), } } - dexCfg["grpc"] = map[string]interface{}{ + dexCfg["grpc"] = map[string]any{ "addr": "0.0.0.0:5557", } - dexCfg["telemetry"] = map[string]interface{}{ + dexCfg["telemetry"] = map[string]any{ "http": "0.0.0.0:5558", } - if oauth2Cfg, found := dexCfg["oauth2"].(map[string]interface{}); found { + if oauth2Cfg, found := dexCfg["oauth2"].(map[string]any); found { if _, found := oauth2Cfg["skipApprovalScreen"].(bool); !found { oauth2Cfg["skipApprovalScreen"] = true } } else { - dexCfg["oauth2"] = map[string]interface{}{ + dexCfg["oauth2"] = map[string]any{ "skipApprovalScreen": true, } } @@ -77,13 +77,13 @@ func GenerateDexConfigYAML(argocdSettings *settings.ArgoCDSettings, disableTls b if err != nil { return nil, fmt.Errorf("failed to infer additional redirect urls from config: %w", err) } - argoCDStaticClient := map[string]interface{}{ + argoCDStaticClient := map[string]any{ "id": common.ArgoCDClientAppID, "name": common.ArgoCDClientAppName, "secret": argocdSettings.DexOAuth2ClientSecret(), "redirectURIs": append([]string{redirectURL}, additionalRedirectURLs...), } - argoCDPKCEStaticClient := map[string]interface{}{ + argoCDPKCEStaticClient := map[string]any{ "id": "argo-cd-pkce", "name": "Argo CD PKCE", "redirectURIs": []string{ @@ -91,7 +91,7 @@ func GenerateDexConfigYAML(argocdSettings *settings.ArgoCDSettings, disableTls b }, "public": true, } - argoCDCLIStaticClient := map[string]interface{}{ + argoCDCLIStaticClient := map[string]any{ "id": common.ArgoCDCLIClientAppID, "name": common.ArgoCDCLIClientAppName, "public": true, @@ -101,23 +101,23 @@ func GenerateDexConfigYAML(argocdSettings *settings.ArgoCDSettings, disableTls b }, } - staticClients, ok := dexCfg["staticClients"].([]interface{}) + staticClients, ok := dexCfg["staticClients"].([]any) if ok { - dexCfg["staticClients"] = append([]interface{}{argoCDStaticClient, argoCDCLIStaticClient, argoCDPKCEStaticClient}, staticClients...) + dexCfg["staticClients"] = append([]any{argoCDStaticClient, argoCDCLIStaticClient, argoCDPKCEStaticClient}, staticClients...) } else { - dexCfg["staticClients"] = []interface{}{argoCDStaticClient, argoCDCLIStaticClient, argoCDPKCEStaticClient} + dexCfg["staticClients"] = []any{argoCDStaticClient, argoCDCLIStaticClient, argoCDPKCEStaticClient} } dexRedirectURL, err := argocdSettings.DexRedirectURL() if err != nil { return nil, err } - connectors, ok := dexCfg["connectors"].([]interface{}) + connectors, ok := dexCfg["connectors"].([]any) if !ok { return nil, errors.New("malformed Dex configuration found") } for i, connectorIf := range connectors { - connector, ok := connectorIf.(map[string]interface{}) + connector, ok := connectorIf.(map[string]any) if !ok { return nil, errors.New("malformed Dex configuration found") } @@ -125,7 +125,7 @@ func GenerateDexConfigYAML(argocdSettings *settings.ArgoCDSettings, disableTls b if !needsRedirectURI(connectorType) { continue } - connectorCfg, ok := connector["config"].(map[string]interface{}) + connectorCfg, ok := connector["config"].(map[string]any) if !ok { return nil, errors.New("malformed Dex configuration found") } diff --git a/util/dex/dex_test.go b/util/dex/dex_test.go index c4413b626eea60..3bca3134bd917c 100644 --- a/util/dex/dex_test.go +++ b/util/dex/dex_test.go @@ -258,15 +258,15 @@ func Test_GenerateDexConfig(t *testing.T) { config, err := GenerateDexConfigYAML(&s, false) require.NoError(t, err) assert.NotNil(t, config) - var dexCfg map[string]interface{} + var dexCfg map[string]any err = yaml.Unmarshal(config, &dexCfg) if err != nil { panic(err.Error()) } - connectors, ok := dexCfg["connectors"].([]interface{}) + connectors, ok := dexCfg["connectors"].([]any) assert.True(t, ok) for i, connectorsIf := range connectors { - config := connectorsIf.(map[string]interface{})["config"].(map[string]interface{}) + config := connectorsIf.(map[string]any)["config"].(map[string]any) if i == 0 { assert.Equal(t, "foobar", config["clientSecret"]) } else if i == 1 { @@ -284,15 +284,15 @@ func Test_GenerateDexConfig(t *testing.T) { config, err := GenerateDexConfigYAML(&s, false) require.NoError(t, err) assert.NotNil(t, config) - var dexCfg map[string]interface{} + var dexCfg map[string]any err = yaml.Unmarshal(config, &dexCfg) if err != nil { panic(err.Error()) } - connectors, ok := dexCfg["connectors"].([]interface{}) + connectors, ok := dexCfg["connectors"].([]any) assert.True(t, ok) for i, connectorsIf := range connectors { - config := connectorsIf.(map[string]interface{})["config"].(map[string]interface{}) + config := connectorsIf.(map[string]any)["config"].(map[string]any) if i == 0 { assert.Equal(t, "foobar", config["clientSecret"]) } else if i == 1 { @@ -312,12 +312,12 @@ func Test_GenerateDexConfig(t *testing.T) { config, err := GenerateDexConfigYAML(&s, false) require.NoError(t, err) assert.NotNil(t, config) - var dexCfg map[string]interface{} + var dexCfg map[string]any err = yaml.Unmarshal(config, &dexCfg) if err != nil { panic(err.Error()) } - loggerCfg, ok := dexCfg["logger"].(map[string]interface{}) + loggerCfg, ok := dexCfg["logger"].(map[string]any) assert.True(t, ok) level, ok := loggerCfg["level"].(string) @@ -340,12 +340,12 @@ func Test_GenerateDexConfig(t *testing.T) { config, err := GenerateDexConfigYAML(&s, false) require.NoError(t, err) assert.NotNil(t, config) - var dexCfg map[string]interface{} + var dexCfg map[string]any err = yaml.Unmarshal(config, &dexCfg) if err != nil { panic(err.Error()) } - loggerCfg, ok := dexCfg["logger"].(map[string]interface{}) + loggerCfg, ok := dexCfg["logger"].(map[string]any) assert.True(t, ok) level, ok := loggerCfg["level"].(string) @@ -377,18 +377,18 @@ func Test_GenerateDexConfig(t *testing.T) { config, err := GenerateDexConfigYAML(&s, false) require.NoError(t, err) assert.NotNil(t, config) - var dexCfg map[string]interface{} + var dexCfg map[string]any err = yaml.Unmarshal(config, &dexCfg) if err != nil { panic(err.Error()) } - clients, ok := dexCfg["staticClients"].([]interface{}) + clients, ok := dexCfg["staticClients"].([]any) assert.True(t, ok) assert.Len(t, clients, 4) - customClient := clients[3].(map[string]interface{}) + customClient := clients[3].(map[string]any) assert.Equal(t, "argo-workflow", customClient["id"].(string)) - assert.Len(t, customClient["redirectURIs"].([]interface{}), 1) + assert.Len(t, customClient["redirectURIs"].([]any), 1) }) t.Run("Custom static clients secret dereference with trailing CRLF", func(t *testing.T) { s := settings.ArgoCDSettings{ @@ -399,16 +399,16 @@ func Test_GenerateDexConfig(t *testing.T) { config, err := GenerateDexConfigYAML(&s, false) require.NoError(t, err) assert.NotNil(t, config) - var dexCfg map[string]interface{} + var dexCfg map[string]any err = yaml.Unmarshal(config, &dexCfg) if err != nil { panic(err.Error()) } - clients, ok := dexCfg["staticClients"].([]interface{}) + clients, ok := dexCfg["staticClients"].([]any) assert.True(t, ok) assert.Len(t, clients, 4) - customClient := clients[3].(map[string]interface{}) + customClient := clients[3].(map[string]any) assert.Equal(t, "barfoo", customClient["secret"]) }) t.Run("Override dex oauth2 configuration", func(t *testing.T) { @@ -419,12 +419,12 @@ func Test_GenerateDexConfig(t *testing.T) { config, err := GenerateDexConfigYAML(&s, false) require.NoError(t, err) assert.NotNil(t, config) - var dexCfg map[string]interface{} + var dexCfg map[string]any err = yaml.Unmarshal(config, &dexCfg) if err != nil { panic(err.Error()) } - oauth2Config, ok := dexCfg["oauth2"].(map[string]interface{}) + oauth2Config, ok := dexCfg["oauth2"].(map[string]any) assert.True(t, ok) pwConn, ok := oauth2Config["passwordConnector"].(string) assert.True(t, ok) @@ -442,12 +442,12 @@ func Test_GenerateDexConfig(t *testing.T) { config, err := GenerateDexConfigYAML(&s, false) require.NoError(t, err) assert.NotNil(t, config) - var dexCfg map[string]interface{} + var dexCfg map[string]any err = yaml.Unmarshal(config, &dexCfg) if err != nil { panic(err.Error()) } - oauth2Config, ok := dexCfg["oauth2"].(map[string]interface{}) + oauth2Config, ok := dexCfg["oauth2"].(map[string]any) assert.True(t, ok) pwConn, ok := oauth2Config["passwordConnector"].(string) assert.True(t, ok) diff --git a/util/errors/errors.go b/util/errors/errors.go index 2c98083273d5e1..0ccd0c5a2a63ce 100644 --- a/util/errors/errors.go +++ b/util/errors/errors.go @@ -28,13 +28,13 @@ func CheckError(err error) { // FailOnErr panics if there is an error. It returns the first value so you can use it if you cast it: // text := FailOrErr(Foo)).(string) -func FailOnErr(v interface{}, err error) interface{} { +func FailOnErr(v any, err error) any { CheckError(err) return v } // Fatal is a wrapper for logrus.Fatal() to exit with custom code -func Fatal(exitcode int, args ...interface{}) { +func Fatal(exitcode int, args ...any) { exitfunc := func() { os.Exit(exitcode) } @@ -43,7 +43,7 @@ func Fatal(exitcode int, args ...interface{}) { } // Fatalf is a wrapper for logrus.Fatalf() to exit with custom code -func Fatalf(exitcode int, format string, args ...interface{}) { +func Fatalf(exitcode int, format string, args ...any) { exitfunc := func() { os.Exit(exitcode) } diff --git a/util/gpg/gpg.go b/util/gpg/gpg.go index 5bfaf99e929216..a7e305dbddbc97 100644 --- a/util/gpg/gpg.go +++ b/util/gpg/gpg.go @@ -691,7 +691,7 @@ func ParseGitCommitVerification(signature string) PGPVerifyResult { // in the keyring will be installed to the keyring, files that exist in the keyring but do not exist in // the directory will be deleted. func SyncKeyRingFromDirectory(basePath string) ([]string, []string, error) { - configured := make(map[string]interface{}) + configured := make(map[string]any) newKeys := make([]string, 0) fingerprints := make([]string, 0) removedKeys := make([]string, 0) diff --git a/util/grpc/errors.go b/util/grpc/errors.go index 1bd3686fa2b103..0d323e4d1108eb 100644 --- a/util/grpc/errors.go +++ b/util/grpc/errors.go @@ -104,7 +104,7 @@ func kubeErrToGRPC(err error) error { // ErrorCodeGitUnaryServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any. func ErrorCodeGitUnaryServerInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { resp, err = handler(ctx, req) return resp, gitErrToGRPC(err) } @@ -112,7 +112,7 @@ func ErrorCodeGitUnaryServerInterceptor() grpc.UnaryServerInterceptor { // ErrorCodeGitStreamServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any. func ErrorCodeGitStreamServerInterceptor() grpc.StreamServerInterceptor { - return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { err := handler(srv, ss) return gitErrToGRPC(err) } @@ -120,7 +120,7 @@ func ErrorCodeGitStreamServerInterceptor() grpc.StreamServerInterceptor { // ErrorCodeK8sUnaryServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any. func ErrorCodeK8sUnaryServerInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { resp, err = handler(ctx, req) return resp, kubeErrToGRPC(err) } @@ -128,7 +128,7 @@ func ErrorCodeK8sUnaryServerInterceptor() grpc.UnaryServerInterceptor { // ErrorCodeK8sStreamServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any. func ErrorCodeK8sStreamServerInterceptor() grpc.StreamServerInterceptor { - return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { err := handler(srv, ss) return kubeErrToGRPC(err) } diff --git a/util/grpc/grpc.go b/util/grpc/grpc.go index cc4c6b46e03f64..bc6526a6f4739d 100644 --- a/util/grpc/grpc.go +++ b/util/grpc/grpc.go @@ -23,7 +23,7 @@ import ( // PanicLoggerUnaryServerInterceptor returns a new unary server interceptor for recovering from panics and returning error func PanicLoggerUnaryServerInterceptor(log *logrus.Entry) grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ any, err error) { defer func() { if r := recover(); r != nil { log.Errorf("Recovered from panic: %+v\n%s", r, debug.Stack()) @@ -36,7 +36,7 @@ func PanicLoggerUnaryServerInterceptor(log *logrus.Entry) grpc.UnaryServerInterc // PanicLoggerStreamServerInterceptor returns a new streaming server interceptor for recovering from panics and returning error func PanicLoggerStreamServerInterceptor(log *logrus.Entry) grpc.StreamServerInterceptor { - return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { + return func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { defer func() { if r := recover(); r != nil { log.Errorf("Recovered from panic: %+v\n%s", r, debug.Stack()) @@ -55,8 +55,8 @@ func BlockingDial(ctx context.Context, network, address string, creds credential // grpc.Dial doesn't provide any information on permanent connection errors (like // TLS handshake failures). So in order to provide good error messages, we need a // custom dialer that can provide that info. That means we manage the TLS handshake. - result := make(chan interface{}, 1) - writeResult := func(res interface{}) { + result := make(chan any, 1) + writeResult := func(res any) { // non-blocking write: we only need the first result select { case result <- res: @@ -96,7 +96,7 @@ func BlockingDial(ctx context.Context, network, address string, creds credential ) // nolint:staticcheck conn, err := grpc.DialContext(ctx, address, opts...) - var res interface{} + var res any if err != nil { res = err } else { @@ -169,7 +169,7 @@ func TestTLS(address string, dialTime time.Duration) (*TLSTestResult, error) { } func WithTimeout(duration time.Duration) grpc.UnaryClientInterceptor { - return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { clientDeadline := time.Now().Add(duration) ctx, cancel := context.WithDeadline(ctx, clientDeadline) defer cancel() diff --git a/util/grpc/json.go b/util/grpc/json.go index 93e8f9688b2bdc..9852e526270cda 100644 --- a/util/grpc/json.go +++ b/util/grpc/json.go @@ -16,7 +16,7 @@ func (j *JSONMarshaler) ContentType() string { } // Marshal implements gwruntime.Marshaler. -func (j *JSONMarshaler) Marshal(v interface{}) ([]byte, error) { +func (j *JSONMarshaler) Marshal(v any) ([]byte, error) { return json.Marshal(v) } @@ -31,12 +31,12 @@ func (j *JSONMarshaler) NewEncoder(w io.Writer) gwruntime.Encoder { } // Unmarshal implements gwruntime.Marshaler. -func (j *JSONMarshaler) Unmarshal(data []byte, v interface{}) error { +func (j *JSONMarshaler) Unmarshal(data []byte, v any) error { return json.Unmarshal(data, v) } // MustMarshal is a convenience function to marshal an object successfully or panic -func MustMarshal(v interface{}) []byte { +func MustMarshal(v any) []byte { bytes, err := json.Marshal(v) if err != nil { panic(err) diff --git a/util/grpc/logging.go b/util/grpc/logging.go index 271111977473b6..5bbc39c1591e92 100644 --- a/util/grpc/logging.go +++ b/util/grpc/logging.go @@ -15,12 +15,12 @@ import ( "google.golang.org/grpc" ) -func logRequest(entry *logrus.Entry, info string, pbMsg interface{}, ctx context.Context, logClaims bool) { +func logRequest(entry *logrus.Entry, info string, pbMsg any, ctx context.Context, logClaims bool) { if logClaims { claims := ctx.Value("claims") mapClaims, ok := claims.(jwt.MapClaims) if ok { - copy := make(map[string]interface{}) + copy := make(map[string]any) for k, v := range mapClaims { if k != "groups" || entry.Logger.IsLevelEnabled(logrus.DebugLevel) { copy[k] = v @@ -58,11 +58,11 @@ type loggingServerStream struct { info string } -func (l *loggingServerStream) SendMsg(m interface{}) error { +func (l *loggingServerStream) SendMsg(m any) error { return l.ServerStream.SendMsg(m) } -func (l *loggingServerStream) RecvMsg(m interface{}) error { +func (l *loggingServerStream) RecvMsg(m any) error { err := l.ServerStream.RecvMsg(m) if err == nil { logRequest(l.entry, l.info, m, l.ServerStream.Context(), l.logClaims) @@ -71,7 +71,7 @@ func (l *loggingServerStream) RecvMsg(m interface{}) error { } func PayloadStreamServerInterceptor(entry *logrus.Entry, logClaims bool, decider grpc_logging.ServerPayloadLoggingDecider) grpc.StreamServerInterceptor { - return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if !decider(stream.Context(), info.FullMethod, srv) { return handler(srv, stream) } @@ -82,7 +82,7 @@ func PayloadStreamServerInterceptor(entry *logrus.Entry, logClaims bool, decider } func PayloadUnaryServerInterceptor(entry *logrus.Entry, logClaims bool, decider grpc_logging.ServerPayloadLoggingDecider) grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if !decider(ctx, info.FullMethod, info.Server) { return handler(ctx, req) } diff --git a/util/grpc/logging_test.go b/util/grpc/logging_test.go index 98be425928b691..9970259bddb8c2 100644 --- a/util/grpc/logging_test.go +++ b/util/grpc/logging_test.go @@ -26,10 +26,10 @@ func Test_JSONLogging(t *testing.T) { req := new(account.CreateTokenRequest) req.Name = "create-token-name" info := &grpc.UnaryServerInfo{} - handler := func(ctx context.Context, req interface{}) (interface{}, error) { + handler := func(ctx context.Context, req any) (any, error) { return nil, nil } - decider := func(ctx context.Context, fullMethodName string, servingObject interface{}) bool { + decider := func(ctx context.Context, fullMethodName string, servingObject any) bool { return true } interceptor := PayloadUnaryServerInterceptor(entry, false, decider) @@ -47,10 +47,10 @@ func Test_logRequest(t *testing.T) { req := new(account.CreateTokenRequest) req.Name = "create-token-name" info := &grpc.UnaryServerInfo{} - handler := func(ctx context.Context, req interface{}) (interface{}, error) { + handler := func(ctx context.Context, req any) (any, error) { return nil, nil } - decider := func(ctx context.Context, fullMethodName string, servingObject interface{}) bool { + decider := func(ctx context.Context, fullMethodName string, servingObject any) bool { return true } diff --git a/util/grpc/sanitizer.go b/util/grpc/sanitizer.go index 36739e7def1cb1..45bd8f82ac7f2c 100644 --- a/util/grpc/sanitizer.go +++ b/util/grpc/sanitizer.go @@ -19,7 +19,7 @@ const ( // ErrorSanitizerUnaryServerInterceptor returns a new unary server interceptor that sanitizes error messages // and provides Sanitizer to define replacements. func ErrorSanitizerUnaryServerInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { sanitizer := NewSanitizer() resp, err = handler(ContextWithSanitizer(ctx, sanitizer), req) if err == nil { diff --git a/util/grpc/sanitizer_test.go b/util/grpc/sanitizer_test.go index bd7108b6d00858..ba016a1cd38d18 100644 --- a/util/grpc/sanitizer_test.go +++ b/util/grpc/sanitizer_test.go @@ -40,7 +40,7 @@ func TestSanitizer_RegexReplacement(t *testing.T) { func TestErrorSanitizerUnaryServerInterceptor(t *testing.T) { interceptor := ErrorSanitizerUnaryServerInterceptor() - _, err := interceptor(context.Background(), nil, nil, func(ctx context.Context, req interface{}) (interface{}, error) { + _, err := interceptor(context.Background(), nil, nil, func(ctx context.Context, req any) (any, error) { sanitizer, ok := SanitizerFromContext(ctx) require.True(t, ok) sanitizer.AddReplacement("/my-random/path", ".") diff --git a/util/grpc/useragent.go b/util/grpc/useragent.go index c71f5e1a8a6f28..a05d51c669499a 100644 --- a/util/grpc/useragent.go +++ b/util/grpc/useragent.go @@ -18,7 +18,7 @@ func UserAgentUnaryServerInterceptor(clientName, constraintStr string) grpc.Unar if err != nil { panic(err) } - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if err := userAgentEnforcer(ctx, clientName, constraintStr, semVerConstraint); err != nil { return nil, err } @@ -33,7 +33,7 @@ func UserAgentStreamServerInterceptor(clientName, constraintStr string) grpc.Str if err != nil { panic(err) } - return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if err := userAgentEnforcer(stream.Context(), clientName, constraintStr, semVerConstraint); err != nil { return err } diff --git a/util/helm/helm.go b/util/helm/helm.go index fb557010c85a0f..ec6f0e9bf604e4 100644 --- a/util/helm/helm.go +++ b/util/helm/helm.go @@ -169,7 +169,7 @@ func (h *helm) GetParameters(valuesFiles []pathutil.ResolvedFilePath, appPath, r output := map[string]string{} for _, file := range values { - values := map[string]interface{}{} + values := map[string]any{} if err := yaml.Unmarshal([]byte(file), &values); err != nil { return nil, fmt.Errorf("failed to parse values: %w", err) } @@ -179,13 +179,13 @@ func (h *helm) GetParameters(valuesFiles []pathutil.ResolvedFilePath, appPath, r return output, nil } -func flatVals(input interface{}, output map[string]string, prefixes ...string) { +func flatVals(input any, output map[string]string, prefixes ...string) { switch i := input.(type) { - case map[string]interface{}: + case map[string]any: for k, v := range i { flatVals(v, output, append(prefixes, k)...) } - case []interface{}: + case []any: p := append([]string(nil), prefixes...) for j, v := range i { flatVals(v, output, append(p[0:len(p)-1], fmt.Sprintf("%s[%v]", prefixes[len(p)-1], j))...) diff --git a/util/helm/helm_test.go b/util/helm/helm_test.go index 2d72a87745f253..a8957c177686a7 100644 --- a/util/helm/helm_test.go +++ b/util/helm/helm_test.go @@ -184,21 +184,21 @@ func Test_flatVals(t *testing.T) { t.Run("Map", func(t *testing.T) { output := map[string]string{} - flatVals(map[string]interface{}{"foo": map[string]interface{}{"bar": "baz"}}, output) + flatVals(map[string]any{"foo": map[string]any{"bar": "baz"}}, output) assert.Equal(t, map[string]string{"foo.bar": "baz"}, output) }) t.Run("Array", func(t *testing.T) { output := map[string]string{} - flatVals(map[string]interface{}{"foo": []interface{}{"bar", "baz"}}, output) + flatVals(map[string]any{"foo": []any{"bar", "baz"}}, output) assert.Equal(t, map[string]string{"foo[0]": "bar", "foo[1]": "baz"}, output) }) t.Run("Val", func(t *testing.T) { output := map[string]string{} - flatVals(map[string]interface{}{"foo": 1}, output) + flatVals(map[string]any{"foo": 1}, output) assert.Equal(t, map[string]string{"foo": "1"}, output) }) diff --git a/util/jwt/jwt.go b/util/jwt/jwt.go index 585025990bf8d1..7bd0cc4b8b252a 100644 --- a/util/jwt/jwt.go +++ b/util/jwt/jwt.go @@ -56,7 +56,7 @@ func GetScopeValues(claims jwtgo.MapClaims, scopes []string) []string { } switch val := scopeIf.(type) { - case []interface{}: + case []any: for _, groupIf := range val { group, ok := groupIf.(string) if ok { @@ -107,7 +107,7 @@ func ExpirationTime(m jwtgo.MapClaims) (time.Time, error) { return time.Unix(exp, 0), err } -func Claims(in interface{}) jwtgo.Claims { +func Claims(in any) jwtgo.Claims { claims, ok := in.(jwtgo.Claims) if ok { return claims diff --git a/util/kube/kube.go b/util/kube/kube.go index aa96dfc4d3fff6..6cd1378a2c71fe 100644 --- a/util/kube/kube.go +++ b/util/kube/kube.go @@ -47,7 +47,7 @@ func SetAppInstanceLabel(target *unstructured.Unstructured, key, val string) err return err } if !ok || templateLabels == nil { - templateLabels = make(map[string]interface{}) + templateLabels = make(map[string]any) } templateLabels[key] = val err = unstructured.SetNestedMap(target.UnstructuredContent(), templateLabels, "spec", "template", "metadata", "labels") @@ -85,7 +85,7 @@ func SetAppInstanceLabel(target *unstructured.Unstructured, key, val string) err return err } if !ok || templateLabels == nil { - templateLabels = make(map[string]interface{}) + templateLabels = make(map[string]any) } templateLabels[key] = val err = unstructured.SetNestedMap(target.UnstructuredContent(), templateLabels, "spec", "template", "metadata", "labels") @@ -186,8 +186,8 @@ func RemoveAnnotation(un *unstructured.Unstructured, key string) error { } // nestedNullableStringMap returns a copy of map[string]string value of a nested field. -// Returns false if value is not found and an error if not one of map[string]interface{} or nil, or contains non-string values in the map. -func nestedNullableStringMap(obj map[string]interface{}, fields ...string) (map[string]string, error) { +// Returns false if value is not found and an error if not one of map[string]any or nil, or contains non-string values in the map. +func nestedNullableStringMap(obj map[string]any, fields ...string) (map[string]string, error) { var m map[string]string val, found, err := unstructured.NestedFieldNoCopy(obj, fields...) if err != nil { diff --git a/util/kustomize/kustomize.go b/util/kustomize/kustomize.go index 1836aa1613ff87..9aa5b5b1f2b51b 100644 --- a/util/kustomize/kustomize.go +++ b/util/kustomize/kustomize.go @@ -258,25 +258,25 @@ func (k *kustomize) Build(opts *v1alpha1.ApplicationSourceKustomize, kustomizeOp if err != nil { return nil, nil, nil, fmt.Errorf("failed to load kustomization.yaml: %w", err) } - var kustomization interface{} + var kustomization any err = yaml.Unmarshal(b, &kustomization) if err != nil { return nil, nil, nil, fmt.Errorf("failed to unmarshal kustomization.yaml: %w", err) } - kMap, ok := kustomization.(map[string]interface{}) + kMap, ok := kustomization.(map[string]any) if !ok { - return nil, nil, nil, fmt.Errorf("expected kustomization.yaml to be type map[string]interface{}, but got %T", kMap) + return nil, nil, nil, fmt.Errorf("expected kustomization.yaml to be type map[string]any, but got %T", kMap) } patches, ok := kMap["patches"] if ok { // The kustomization.yaml already had a patches field, so we need to append to it. - patchesList, ok := patches.([]interface{}) + patchesList, ok := patches.([]any) if !ok { - return nil, nil, nil, fmt.Errorf("expected 'patches' field in kustomization.yaml to be []interface{}, but got %T", patches) + return nil, nil, nil, fmt.Errorf("expected 'patches' field in kustomization.yaml to be []any, but got %T", patches) } // Since the patches from the Application manifest are typed, we need to convert them to a type which // can be appended to the existing list. - untypedPatches := make([]interface{}, len(opts.Patches)) + untypedPatches := make([]any, len(opts.Patches)) for i := range opts.Patches { untypedPatches[i] = opts.Patches[i] } @@ -469,13 +469,13 @@ func getImageParameters(objs []*unstructured.Unstructured) []Image { return images } -func getImages(object map[string]interface{}) []Image { +func getImages(object map[string]any) []Image { var images []Image for k, v := range object { - if array, ok := v.([]interface{}); ok { + if array, ok := v.([]any); ok { if k == "containers" || k == "initContainers" { for _, obj := range array { - if mapObj, isMapObj := obj.(map[string]interface{}); isMapObj { + if mapObj, isMapObj := obj.(map[string]any); isMapObj { if image, hasImage := mapObj["image"]; hasImage { images = append(images, fmt.Sprintf("%s", image)) } @@ -483,12 +483,12 @@ func getImages(object map[string]interface{}) []Image { } } else { for i := range array { - if mapObj, isMapObj := array[i].(map[string]interface{}); isMapObj { + if mapObj, isMapObj := array[i].(map[string]any); isMapObj { images = append(images, getImages(mapObj)...) } } } - } else if objMap, ok := v.(map[string]interface{}); ok { + } else if objMap, ok := v.(map[string]any); ok { images = append(images, getImages(objMap)...) } } diff --git a/util/kustomize/kustomize_test.go b/util/kustomize/kustomize_test.go index 27299495fd9be5..eb0395fd0c7a92 100644 --- a/util/kustomize/kustomize_test.go +++ b/util/kustomize/kustomize_test.go @@ -489,14 +489,14 @@ func TestKustomizeBuildPatches(t *testing.T) { assert.True(t, found) ports, found, err := unstructured.NestedSlice( - containers[0].(map[string]interface{}), + containers[0].(map[string]any), "ports", ) assert.True(t, found) require.NoError(t, err) port, found, err := unstructured.NestedInt64( - ports[0].(map[string]interface{}), + ports[0].(map[string]any), "containerPort", ) @@ -505,7 +505,7 @@ func TestKustomizeBuildPatches(t *testing.T) { assert.Equal(t, int64(443), port) name, found, err := unstructured.NestedString( - containers[0].(map[string]interface{}), + containers[0].(map[string]any), "name", ) assert.True(t, found) diff --git a/util/log/logrus.go b/util/log/logrus.go index dd583fb5a37ce8..ad5fce46e38cfd 100644 --- a/util/log/logrus.go +++ b/util/log/logrus.go @@ -18,7 +18,7 @@ const ( ) func NewLogrusLogger(fieldLogger logrus.FieldLogger) logr.Logger { - return adapter.New(fieldLogger, adapter.WithFormatter(func(val interface{}) string { + return adapter.New(fieldLogger, adapter.WithFormatter(func(val any) string { return fmt.Sprintf("%v", val) })) } diff --git a/util/lua/custom_actions_test.go b/util/lua/custom_actions_test.go index 4b7a06bf7dc7e8..1447f146815d1f 100644 --- a/util/lua/custom_actions_test.go +++ b/util/lua/custom_actions_test.go @@ -28,7 +28,7 @@ func (t testNormalizer) Normalize(un *unstructured.Unstructured) error { } switch un.GetKind() { case "Job": - err := unstructured.SetNestedField(un.Object, map[string]interface{}{"name": "not sure why this works"}, "metadata") + err := unstructured.SetNestedField(un.Object, map[string]any{"name": "not sure why this works"}, "metadata") if err != nil { return fmt.Errorf("failed to normalize Job: %w", err) } @@ -215,13 +215,13 @@ func getExpectedObjectList(t *testing.T, path string) *unstructured.Unstructured yamlString := bytes.NewBuffer(yamlBytes).String() if yamlString[0] == '-' { // The string represents a new-style action array output, where each member is a wrapper around a k8s unstructured resource - objList := make([]map[string]interface{}, 5) + objList := make([]map[string]any, 5) err = yaml.Unmarshal(yamlBytes, &objList) errors.CheckError(err) unstructuredList.Items = make([]unstructured.Unstructured, len(objList)) // Append each map in objList to the Items field of the new object for i, obj := range objList { - unstructuredObj, ok := obj["unstructuredObj"].(map[string]interface{}) + unstructuredObj, ok := obj["unstructuredObj"].(map[string]any) if !ok { t.Error("Wrong type of unstructuredObj") } @@ -229,7 +229,7 @@ func getExpectedObjectList(t *testing.T, path string) *unstructured.Unstructured } } else { // The string represents an old-style action object output, which is a k8s unstructured resource - obj := make(map[string]interface{}) + obj := make(map[string]any) err = yaml.Unmarshal(yamlBytes, &obj) errors.CheckError(err) unstructuredList.Items = make([]unstructured.Unstructured, 1) diff --git a/util/lua/health_test.go b/util/lua/health_test.go index a1fdadafc0a0c4..c2e4e6766343d4 100644 --- a/util/lua/health_test.go +++ b/util/lua/health_test.go @@ -26,7 +26,7 @@ type IndividualTest struct { func getObj(path string) *unstructured.Unstructured { yamlBytes, err := os.ReadFile(path) errors.CheckError(err) - obj := make(map[string]interface{}) + obj := make(map[string]any) err = yaml.Unmarshal(yamlBytes, &obj) errors.CheckError(err) diff --git a/util/lua/lua.go b/util/lua/lua.go index ed8067cc926a98..6f3501e31d7e08 100644 --- a/util/lua/lua.go +++ b/util/lua/lua.go @@ -239,7 +239,7 @@ func UnmarshalToImpactedResources(resources string) ([]ImpactedResource, error) // cleanReturnedObj Lua cannot distinguish an empty table as an array or map, and the library we are using choose to // decoded an empty table into an empty array. This function prevents the lua scripts from unintentionally changing an // empty struct into empty arrays -func cleanReturnedObj(newObj, obj map[string]interface{}) map[string]interface{} { +func cleanReturnedObj(newObj, obj map[string]any) map[string]any { mapToReturn := newObj for key := range obj { if newValueInterface, ok := newObj[key]; ok { @@ -248,19 +248,19 @@ func cleanReturnedObj(newObj, obj map[string]interface{}) map[string]interface{} continue } switch newValue := newValueInterface.(type) { - case map[string]interface{}: - if oldValue, ok := oldValueInterface.(map[string]interface{}); ok { + case map[string]any: + if oldValue, ok := oldValueInterface.(map[string]any); ok { convertedMap := cleanReturnedObj(newValue, oldValue) mapToReturn[key] = convertedMap } - case []interface{}: + case []any: switch oldValue := oldValueInterface.(type) { - case map[string]interface{}: + case map[string]any: if len(newValue) == 0 { mapToReturn[key] = oldValue } - case []interface{}: + case []any: newArray := cleanReturnedArray(newValue, oldValue) mapToReturn[key] = newArray } @@ -272,17 +272,17 @@ func cleanReturnedObj(newObj, obj map[string]interface{}) map[string]interface{} // cleanReturnedArray allows Argo CD to recurse into nested arrays when checking for unintentional empty struct to // empty array conversions. -func cleanReturnedArray(newObj, obj []interface{}) []interface{} { +func cleanReturnedArray(newObj, obj []any) []any { arrayToReturn := newObj for i := range newObj { switch newValue := newObj[i].(type) { - case map[string]interface{}: - if oldValue, ok := obj[i].(map[string]interface{}); ok { + case map[string]any: + if oldValue, ok := obj[i].(map[string]any); ok { convertedMap := cleanReturnedObj(newValue, oldValue) arrayToReturn[i] = convertedMap } - case []interface{}: - if oldValue, ok := obj[i].([]interface{}); ok { + case []any: + if oldValue, ok := obj[i].([]any); ok { convertedMap := cleanReturnedArray(newValue, oldValue) arrayToReturn[i] = convertedMap } @@ -311,7 +311,7 @@ func (vm VM) ExecuteResourceActionDiscovery(obj *unstructured.Unstructured, scri if noAvailableActions(jsonBytes) { continue } - actionsMap := make(map[string]interface{}) + actionsMap := make(map[string]any) err = json.Unmarshal(jsonBytes, &actionsMap) if err != nil { return nil, fmt.Errorf("error unmarshaling action table: %w", err) @@ -350,8 +350,8 @@ func (vm VM) ExecuteResourceActionDiscovery(obj *unstructured.Unstructured, scri } // Actions are enabled by default -func isActionDisabled(actionsMap interface{}) bool { - actions, ok := actionsMap.(map[string]interface{}) +func isActionDisabled(actionsMap any) bool { + actions, ok := actionsMap.(map[string]any) if !ok { return false } @@ -366,8 +366,8 @@ func isActionDisabled(actionsMap interface{}) bool { return false } -func emptyResourceActionFromLua(i interface{}) bool { - _, ok := i.([]interface{}) +func emptyResourceActionFromLua(i any) bool { + _, ok := i.([]any) return ok } @@ -481,7 +481,7 @@ func isValidHealthStatusCode(statusCode health.HealthStatusCode) bool { // Took logic from the link below and added the int, int32, and int64 types since the value would have type int64 // while actually running in the controller and it was not reproducible through testing. // https://github.com/layeh/gopher-json/blob/97fed8db84274c421dbfffbb28ec859901556b97/json.go#L154 -func decodeValue(l *lua.LState, value interface{}) lua.LValue { +func decodeValue(l *lua.LState, value any) lua.LValue { switch converted := value.(type) { case bool: return lua.LBool(converted) @@ -497,13 +497,13 @@ func decodeValue(l *lua.LState, value interface{}) lua.LValue { return lua.LNumber(converted) case int64: return lua.LNumber(converted) - case []interface{}: + case []any: arr := l.CreateTable(len(converted), 0) for _, item := range converted { arr.Append(decodeValue(l, item)) } return arr - case map[string]interface{}: + case map[string]any: tbl := l.CreateTable(0, len(converted)) for key, item := range converted { tbl.RawSetH(lua.LString(key), decodeValue(l, item)) diff --git a/util/lua/lua_test.go b/util/lua/lua_test.go index ae26448bedb150..ec058d1635e234 100644 --- a/util/lua/lua_test.go +++ b/util/lua/lua_test.go @@ -69,7 +69,7 @@ end return a` func StrToUnstructured(jsonStr string) *unstructured.Unstructured { - obj := make(map[string]interface{}) + obj := make(map[string]any) err := yaml.Unmarshal([]byte(jsonStr), &obj) if err != nil { panic(err) diff --git a/util/notification/expression/expr.go b/util/notification/expression/expr.go index f00f245dc9cb0f..92f931b6b62782 100644 --- a/util/notification/expression/expr.go +++ b/util/notification/expression/expr.go @@ -10,20 +10,20 @@ import ( "github.com/argoproj/argo-cd/v2/util/notification/expression/time" ) -var helpers = map[string]interface{}{} +var helpers = map[string]any{} func init() { - helpers = make(map[string]interface{}) + helpers = make(map[string]any) register("time", time.NewExprs()) register("strings", strings.NewExprs()) } -func register(namespace string, entry map[string]interface{}) { +func register(namespace string, entry map[string]any) { helpers[namespace] = entry } -func Spawn(app *unstructured.Unstructured, argocdService service.Service, vars map[string]interface{}) map[string]interface{} { - clone := make(map[string]interface{}) +func Spawn(app *unstructured.Unstructured, argocdService service.Service, vars map[string]any) map[string]any { + clone := make(map[string]any) for k := range vars { clone[k] = vars[k] } diff --git a/util/notification/expression/repo/repo.go b/util/notification/expression/repo/repo.go index df9943d41bf115..a141d50dd1b870 100644 --- a/util/notification/expression/repo/repo.go +++ b/util/notification/expression/repo/repo.go @@ -93,12 +93,12 @@ func repoURLToHTTPS(rawURL string) string { return parsed.String() } -func NewExprs(argocdService service.Service, app *unstructured.Unstructured) map[string]interface{} { - return map[string]interface{}{ +func NewExprs(argocdService service.Service, app *unstructured.Unstructured) map[string]any { + return map[string]any{ "RepoURLToHTTPS": repoURLToHTTPS, "FullNameByRepoURL": FullNameByRepoURL, "QueryEscape": url.QueryEscape, - "GetCommitMetadata": func(commitSHA string) interface{} { + "GetCommitMetadata": func(commitSHA string) any { meta, err := getCommitMetadata(commitSHA, app, argocdService) if err != nil { panic(err) @@ -106,7 +106,7 @@ func NewExprs(argocdService service.Service, app *unstructured.Unstructured) map return *meta }, - "GetAppDetails": func() interface{} { + "GetAppDetails": func() any { appDetails, err := getAppDetails(app, argocdService) if err != nil { panic(err) diff --git a/util/notification/expression/strings/strings.go b/util/notification/expression/strings/strings.go index 8b29430ddedefc..de0617fca15fcf 100644 --- a/util/notification/expression/strings/strings.go +++ b/util/notification/expression/strings/strings.go @@ -4,8 +4,8 @@ import ( "strings" ) -func NewExprs() map[string]interface{} { - return map[string]interface{}{ +func NewExprs() map[string]any { + return map[string]any{ "ReplaceAll": replaceAll, "ToUpper": toUpper, "ToLower": toLower, diff --git a/util/notification/expression/time/time.go b/util/notification/expression/time/time.go index 63aa31c3d3d130..24b79f57e3ec47 100644 --- a/util/notification/expression/time/time.go +++ b/util/notification/expression/time/time.go @@ -6,8 +6,8 @@ import ( var now = time.Now -func NewExprs() map[string]interface{} { - return map[string]interface{}{ +func NewExprs() map[string]any { + return map[string]any{ // Functions "Parse": parse, "Now": now, diff --git a/util/notification/expression/time/time_test.go b/util/notification/expression/time/time_test.go index a450260bea399c..7a178027b84615 100644 --- a/util/notification/expression/time/time_test.go +++ b/util/notification/expression/time/time_test.go @@ -54,7 +54,7 @@ func Test_NewExprs_Now(t *testing.T) { vm, err := expr.Compile("time.Now().Truncate(time.Hour).Format(time.RFC3339)") require.NoError(t, err) - val, err := expr.Run(vm, map[string]interface{}{"time": NewExprs()}) + val, err := expr.Run(vm, map[string]any{"time": NewExprs()}) require.NoError(t, err) assert.Equal(t, "2022-09-26T11:00:00Z", val) diff --git a/util/notification/settings/legacy.go b/util/notification/settings/legacy.go index 04ade75159a88c..7b1457923e8f9c 100644 --- a/util/notification/settings/legacy.go +++ b/util/notification/settings/legacy.go @@ -51,7 +51,7 @@ type legacyServicesConfig struct { Webhook []legacyWebhookOptions `json:"webhook"` } -func mergePatch(orig interface{}, other interface{}) error { +func mergePatch(orig any, other any) error { origData, err := json.Marshal(orig) if err != nil { return fmt.Errorf("error marshaling json for original: %w", err) diff --git a/util/notification/settings/settings.go b/util/notification/settings/settings.go index b274300873d767..14c693014789ce 100644 --- a/util/notification/settings/settings.go +++ b/util/notification/settings/settings.go @@ -64,8 +64,8 @@ func initGetVarsWithoutSecret(argocdService service.Service, cfg *api.Config, co return nil, err } - return func(obj map[string]interface{}, dest services.Destination) map[string]interface{} { - return expression.Spawn(&unstructured.Unstructured{Object: obj}, argocdService, map[string]interface{}{ + return func(obj map[string]any, dest services.Destination) map[string]any { + return expression.Spawn(&unstructured.Unstructured{Object: obj}, argocdService, map[string]any{ "app": obj, "context": injectLegacyVar(context, dest.Service), }) @@ -78,8 +78,8 @@ func initGetVars(argocdService service.Service, cfg *api.Config, configMap *v1.C return nil, err } - return func(obj map[string]interface{}, dest services.Destination) map[string]interface{} { - return expression.Spawn(&unstructured.Unstructured{Object: obj}, argocdService, map[string]interface{}{ + return func(obj map[string]any, dest services.Destination) map[string]any { + return expression.Spawn(&unstructured.Unstructured{Object: obj}, argocdService, map[string]any{ "app": obj, "context": injectLegacyVar(context, dest.Service), "secrets": secret.Data, diff --git a/util/notification/settings/settings_test.go b/util/notification/settings/settings_test.go index 8c3a8c5bf9ddbb..004b91c3538e49 100644 --- a/util/notification/settings/settings_test.go +++ b/util/notification/settings/settings_test.go @@ -66,12 +66,12 @@ func TestInitGetVars(t *testing.T) { testDestination := services.Destination{ Service: "webhook", } - emptyAppData := map[string]interface{}{} + emptyAppData := map[string]any{} varsProvider, _ := initGetVars(argocdService, &config, ¬ificationsCm, ¬ificationsSecret) t.Run("Vars provider serves Application data on app key", func(t *testing.T) { - appData := map[string]interface{}{ + appData := map[string]any{ "name": "app-name", } result := varsProvider(appData, testDestination) diff --git a/util/oidc/oidc_test.go b/util/oidc/oidc_test.go index 40c606dcd96715..c9dd36cc42f51e 100644 --- a/util/oidc/oidc_test.go +++ b/util/oidc/oidc_test.go @@ -608,7 +608,7 @@ func TestGetUserInfo(t *testing.T) { tests := []struct { name string userInfoPath string - expectedOutput interface{} + expectedOutput any expectError bool expectUnauthenticated bool expectedCacheItems []struct { // items to check in cache after function call @@ -772,7 +772,7 @@ func TestGetUserInfo(t *testing.T) { { name: "call UserInfo with valid accessToken in cache", userInfoPath: "/user-info", - expectedOutput: jwt.MapClaims{"groups": []interface{}{"githubOrg:engineers"}}, + expectedOutput: jwt.MapClaims{"groups": []any{"githubOrg:engineers"}}, expectError: false, expectUnauthenticated: false, expectedCacheItems: []struct { diff --git a/util/oidc/templates.go b/util/oidc/templates.go index 4b013edea0ba78..1a57d375d695c2 100644 --- a/util/oidc/templates.go +++ b/util/oidc/templates.go @@ -51,7 +51,7 @@ func renderToken(w http.ResponseWriter, redirectURL, idToken, refreshToken strin }) } -func renderTemplate(w http.ResponseWriter, tmpl *template.Template, data interface{}) { +func renderTemplate(w http.ResponseWriter, tmpl *template.Template, data any) { err := tmpl.Execute(w, data) if err == nil { return diff --git a/util/rbac/rbac.go b/util/rbac/rbac.go index 1446620d58bd0e..fcb5874d015ef5 100644 --- a/util/rbac/rbac.go +++ b/util/rbac/rbac.go @@ -46,7 +46,7 @@ const ( // CasbinEnforcer represents methods that must be implemented by a Casbin enforces type CasbinEnforcer interface { EnableLog(bool) - Enforce(rvals ...interface{}) (bool, error) + Enforce(rvals ...any) (bool, error) LoadPolicy() error EnableEnforce(bool) AddFunction(name string, function govaluate.ExpressionFunction) @@ -140,9 +140,9 @@ func (e *Enforcer) tryGetCabinEnforcer(project string, policy string) (CasbinEnf } // ClaimsEnforcerFunc is func template to enforce a JWT claims. The subject is replaced -type ClaimsEnforcerFunc func(claims jwt.Claims, rvals ...interface{}) bool +type ClaimsEnforcerFunc func(claims jwt.Claims, rvals ...any) bool -func newEnforcerSafe(matchFunction govaluate.ExpressionFunction, params ...interface{}) (e CasbinEnforcer, err error) { +func newEnforcerSafe(matchFunction govaluate.ExpressionFunction, params ...any) (e CasbinEnforcer, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("%v", r) @@ -193,7 +193,7 @@ func (e *Enforcer) LoadPolicy() error { } // Glob match func -func globMatchFunc(args ...interface{}) (interface{}, error) { +func globMatchFunc(args ...any) (any, error) { if len(args) < 2 { return false, nil } @@ -236,12 +236,12 @@ func (e *Enforcer) SetClaimsEnforcerFunc(claimsEnforcer ClaimsEnforcerFunc) { // Enforce is a wrapper around casbin.Enforce to additionally enforce a default role and a custom // claims function -func (e *Enforcer) Enforce(rvals ...interface{}) bool { +func (e *Enforcer) Enforce(rvals ...any) bool { return enforce(e.getCabinEnforcer("", ""), e.defaultRole, e.claimsEnforcerFunc, rvals...) } // EnforceErr is a convenience helper to wrap a failed enforcement with a detailed error about the request -func (e *Enforcer) EnforceErr(rvals ...interface{}) error { +func (e *Enforcer) EnforceErr(rvals ...any) error { if !e.Enforce(rvals...) { errMsg := "permission denied" if len(rvals) > 0 { @@ -272,7 +272,7 @@ func (e *Enforcer) EnforceErr(rvals ...interface{}) error { // EnforceRuntimePolicy enforces a policy defined at run-time which augments the built-in and // user-defined policy. This allows any explicit denies of the built-in, and user-defined policies // to override the run-time policy. Runs normal enforcement if run-time policy is empty. -func (e *Enforcer) EnforceRuntimePolicy(project string, policy string, rvals ...interface{}) bool { +func (e *Enforcer) EnforceRuntimePolicy(project string, policy string, rvals ...any) bool { enf := e.CreateEnforcerWithRuntimePolicy(project, policy) return e.EnforceWithCustomEnforcer(enf, rvals...) } @@ -285,15 +285,15 @@ func (e *Enforcer) CreateEnforcerWithRuntimePolicy(project string, policy string } // EnforceWithCustomEnforcer wraps enforce with an custom enforcer -func (e *Enforcer) EnforceWithCustomEnforcer(enf CasbinEnforcer, rvals ...interface{}) bool { +func (e *Enforcer) EnforceWithCustomEnforcer(enf CasbinEnforcer, rvals ...any) bool { return enforce(enf, e.defaultRole, e.claimsEnforcerFunc, rvals...) } // enforce is a helper to additionally check a default role and invoke a custom claims enforcement function -func enforce(enf CasbinEnforcer, defaultRole string, claimsEnforcerFunc ClaimsEnforcerFunc, rvals ...interface{}) bool { +func enforce(enf CasbinEnforcer, defaultRole string, claimsEnforcerFunc ClaimsEnforcerFunc, rvals ...any) bool { // check the default role if defaultRole != "" && len(rvals) >= 2 { - if ok, err := enf.Enforce(append([]interface{}{defaultRole}, rvals[1:]...)...); ok && err == nil { + if ok, err := enf.Enforce(append([]any{defaultRole}, rvals[1:]...)...); ok && err == nil { return true } } @@ -310,9 +310,9 @@ func enforce(enf CasbinEnforcer, defaultRole string, claimsEnforcerFunc ClaimsEn if claimsEnforcerFunc != nil && claimsEnforcerFunc(s, rvals...) { return true } - rvals = append([]interface{}{""}, rvals[1:]...) + rvals = append([]any{""}, rvals[1:]...) default: - rvals = append([]interface{}{""}, rvals[1:]...) + rvals = append([]any{""}, rvals[1:]...) } ok, err := enf.Enforce(rvals...) return ok && err == nil @@ -365,7 +365,7 @@ func (e *Enforcer) runInformer(ctx context.Context, onUpdated func(cm *apiv1.Con cmInformer := e.newInformer() _, err := cmInformer.AddEventHandler( cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { if cm, ok := obj.(*apiv1.ConfigMap); ok { err := e.syncUpdate(cm, onUpdated) if err != nil { @@ -375,7 +375,7 @@ func (e *Enforcer) runInformer(ctx context.Context, onUpdated func(cm *apiv1.Con } } }, - UpdateFunc: func(old, new interface{}) { + UpdateFunc: func(old, new any) { oldCM := old.(*apiv1.ConfigMap) newCM := new.(*apiv1.ConfigMap) if oldCM.ResourceVersion == newCM.ResourceVersion { diff --git a/util/rbac/rbac_test.go b/util/rbac/rbac_test.go index 686d283a3ee50b..c5ce20bc53add7 100644 --- a/util/rbac/rbac_test.go +++ b/util/rbac/rbac_test.go @@ -115,7 +115,7 @@ func TestBuiltinPolicyEnforcer(t *testing.T) { // now set builtin policy _ = enf.SetBuiltinPolicy(assets.BuiltinPolicyCSV) - allowed := [][]interface{}{ + allowed := [][]any{ {"admin", "applications", "get", "foo/bar"}, {"admin", "applications", "delete", "foo/bar"}, {"role:readonly", "applications", "get", "foo/bar"}, @@ -128,7 +128,7 @@ func TestBuiltinPolicyEnforcer(t *testing.T) { } } - disallowed := [][]interface{}{ + disallowed := [][]any{ {"role:readonly", "applications", "create", "foo/bar"}, {"role:readonly", "applications", "delete", "foo/bar"}, } @@ -215,7 +215,7 @@ p, alice, *, get, foo/obj, allow p, mike, *, get, foo/obj, deny ` _ = enf.SetUserPolicy(policy) - enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...interface{}) bool { + enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { return false }) @@ -279,7 +279,7 @@ func TestClaimsEnforcerFunc(t *testing.T) { Subject: "foo", } assert.False(t, enf.Enforce(&claims, "applications", "get", "foo/bar")) - enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...interface{}) bool { + enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { return true }) assert.True(t, enf.Enforce(&claims, "applications", "get", "foo/bar")) @@ -308,7 +308,7 @@ func TestClaimsEnforcerFuncWithRuntimePolicy(t *testing.T) { Subject: "foo", } assert.False(t, enf.EnforceRuntimePolicy("", runtimePolicy, claims, "applications", "get", "foo/bar")) - enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...interface{}) bool { + enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { return true }) assert.True(t, enf.EnforceRuntimePolicy("", runtimePolicy, claims, "applications", "get", "foo/bar")) diff --git a/util/session/sessionmanager.go b/util/session/sessionmanager.go index c04523d243e367..cb02c11872b701 100644 --- a/util/session/sessionmanager.go +++ b/util/session/sessionmanager.go @@ -210,7 +210,7 @@ func (mgr *SessionManager) Parse(tokenString string) (jwt.Claims, string, error) if err != nil { return nil, "", err } - token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) { + token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (any, error) { // Don't forget to validate the alg is what you expect: if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) diff --git a/util/settings/settings.go b/util/settings/settings.go index 5ea3dcc0a6cc83..c48b76baf2a1fd 100644 --- a/util/settings/settings.go +++ b/util/settings/settings.go @@ -228,7 +228,7 @@ type KustomizeSettings struct { var ( ByClusterURLIndexer = "byClusterURL" - byClusterURLIndexerFunc = func(obj interface{}) ([]string, error) { + byClusterURLIndexerFunc = func(obj any) ([]string, error) { s, ok := obj.(*apiv1.Secret) if !ok { return nil, nil @@ -245,7 +245,7 @@ var ( return nil, nil } ByClusterNameIndexer = "byClusterName" - byClusterNameIndexerFunc = func(obj interface{}) ([]string, error) { + byClusterNameIndexerFunc = func(obj any) ([]string, error) { s, ok := obj.(*apiv1.Secret) if !ok { return nil, nil @@ -264,8 +264,8 @@ var ( ByProjectClusterIndexer = "byProjectCluster" ByProjectRepoIndexer = "byProjectRepo" ByProjectRepoWriteIndexer = "byProjectRepoWrite" - byProjectIndexerFunc = func(secretType string) func(obj interface{}) ([]string, error) { - return func(obj interface{}) ([]string, error) { + byProjectIndexerFunc = func(secretType string) func(obj any) ([]string, error) { + return func(obj any) ([]string, error) { s, ok := obj.(*apiv1.Secret) if !ok { return nil, nil @@ -1389,14 +1389,14 @@ func (mgr *SettingsManager) initialize(ctx context.Context) error { } eventHandler := cache.ResourceEventHandlerFuncs{ - UpdateFunc: func(oldObj, newObj interface{}) { + UpdateFunc: func(oldObj, newObj any) { mgr.invalidateCache() mgr.onRepoOrClusterChanged() }, - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { mgr.onRepoOrClusterChanged() }, - DeleteFunc: func(obj interface{}) { + DeleteFunc: func(obj any) { mgr.onRepoOrClusterChanged() }, } @@ -1445,14 +1445,14 @@ func (mgr *SettingsManager) initialize(ctx context.Context) error { } now := time.Now() handler := cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { if metaObj, ok := obj.(metav1.Object); ok { if metaObj.GetCreationTimestamp().After(now) { tryNotify() } } }, - UpdateFunc: func(oldObj, newObj interface{}) { + UpdateFunc: func(oldObj, newObj any) { oldMeta, oldOk := oldObj.(metav1.Common) newMeta, newOk := newObj.(metav1.Common) if oldOk && newOk && oldMeta.GetResourceVersion() != newMeta.GetResourceVersion() { @@ -1849,8 +1849,8 @@ func (a *ArgoCDSettings) GetServerEncryptionKey() ([]byte, error) { return crypto.KeyFromPassphrase(string(a.ServerSignature)) } -func UnmarshalDexConfig(config string) (map[string]interface{}, error) { - var dexCfg map[string]interface{} +func UnmarshalDexConfig(config string) (map[string]any, error) { + var dexCfg map[string]any err := yaml.Unmarshal([]byte(config), &dexCfg) return dexCfg, err } @@ -1859,7 +1859,7 @@ func (a *ArgoCDSettings) oidcConfig() *oidcConfig { if a.OIDCConfigRAW == "" { return nil } - configMap := map[string]interface{}{} + configMap := map[string]any{} err := yaml.Unmarshal([]byte(a.OIDCConfigRAW), &configMap) if err != nil { log.Warnf("invalid oidc config: %v", err) @@ -2232,13 +2232,13 @@ func (mgr *SettingsManager) InitializeSettings(insecureModeEnabled bool) (*ArgoC // ReplaceMapSecrets takes a json object and recursively looks for any secret key references in the // object and replaces the value with the secret value -func ReplaceMapSecrets(obj map[string]interface{}, secretValues map[string]string) map[string]interface{} { - newObj := make(map[string]interface{}) +func ReplaceMapSecrets(obj map[string]any, secretValues map[string]string) map[string]any { + newObj := make(map[string]any) for k, v := range obj { switch val := v.(type) { - case map[string]interface{}: + case map[string]any: newObj[k] = ReplaceMapSecrets(val, secretValues) - case []interface{}: + case []any: newObj[k] = replaceListSecrets(val, secretValues) case string: newObj[k] = ReplaceStringSecret(val, secretValues) @@ -2249,13 +2249,13 @@ func ReplaceMapSecrets(obj map[string]interface{}, secretValues map[string]strin return newObj } -func replaceListSecrets(obj []interface{}, secretValues map[string]string) []interface{} { - newObj := make([]interface{}, len(obj)) +func replaceListSecrets(obj []any, secretValues map[string]string) []any { + newObj := make([]any, len(obj)) for i, v := range obj { switch val := v.(type) { - case map[string]interface{}: + case map[string]any: newObj[i] = ReplaceMapSecrets(val, secretValues) - case []interface{}: + case []any: newObj[i] = replaceListSecrets(val, secretValues) case string: newObj[i] = ReplaceStringSecret(val, secretValues) diff --git a/util/tls/tls.go b/util/tls/tls.go index e15ae4963fd8f0..09a15ff08c3a53 100644 --- a/util/tls/tls.go +++ b/util/tls/tls.go @@ -179,7 +179,7 @@ func AddTLSFlagsToCmd(cmd *cobra.Command) func() (ConfigCustomizer, error) { } } -func publicKey(priv interface{}) interface{} { +func publicKey(priv any) any { switch k := priv.(type) { case *rsa.PrivateKey: return &k.PublicKey @@ -190,7 +190,7 @@ func publicKey(priv interface{}) interface{} { } } -func pemBlockForKey(priv interface{}) *pem.Block { +func pemBlockForKey(priv any) *pem.Block { switch k := priv.(type) { case *rsa.PrivateKey: return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)} diff --git a/util/webhook/webhook.go b/util/webhook/webhook.go index f56a25a4c42178..208050602cdf8c 100644 --- a/util/webhook/webhook.go +++ b/util/webhook/webhook.go @@ -62,7 +62,7 @@ type ArgoCDWebhookHandler struct { azuredevops *azuredevops.Webhook gogs *gogs.Webhook settingsSrc settingsSource - queue chan interface{} + queue chan any maxWebhookPayloadSizeB int64 } @@ -106,7 +106,7 @@ func NewHandler(namespace string, applicationNamespaces []string, webhookParalle repoCache: repoCache, serverCache: serverCache, db: argoDB, - queue: make(chan interface{}, payloadQueueSize), + queue: make(chan any, payloadQueueSize), maxWebhookPayloadSizeB: maxWebhookPayloadSizeB, } @@ -138,7 +138,7 @@ func ParseRevision(ref string) string { // affectedRevisionInfo examines a payload from a webhook event, and extracts the repo web URL, // the revision, and whether or not this affected origin/HEAD (the default branch of the repository) -func affectedRevisionInfo(payloadIf interface{}) (webURLs []string, revision string, change changeInfo, touchedHead bool, changedFiles []string) { +func affectedRevisionInfo(payloadIf any) (webURLs []string, revision string, change changeInfo, touchedHead bool, changedFiles []string) { switch payload := payloadIf.(type) { case azuredevops.GitPushEvent: // See: https://learn.microsoft.com/en-us/azure/devops/service-hooks/events?view=azure-devops#git.push @@ -205,8 +205,8 @@ func affectedRevisionInfo(payloadIf interface{}) (webURLs []string, revision str // Webhook module does not parse the inner links if payload.Repository.Links != nil { - for _, l := range payload.Repository.Links["clone"].([]interface{}) { - link := l.(map[string]interface{}) + for _, l := range payload.Repository.Links["clone"].([]any) { + link := l.(map[string]any) if link["name"] == "http" { webURLs = append(webURLs, link["href"].(string)) } @@ -250,7 +250,7 @@ type changeInfo struct { } // HandleEvent handles webhook events for repo push events -func (a *ArgoCDWebhookHandler) HandleEvent(payload interface{}) { +func (a *ArgoCDWebhookHandler) HandleEvent(payload any) { webURLs, revision, change, touchedHead, changedFiles := affectedRevisionInfo(payload) // NOTE: the webURL does not include the .git extension if len(webURLs) == 0 { @@ -408,7 +408,7 @@ func sourceUsesURL(source v1alpha1.ApplicationSource, webURL string, repoRegexp } func (a *ArgoCDWebhookHandler) Handler(w http.ResponseWriter, r *http.Request) { - var payload interface{} + var payload any var err error r.Body = http.MaxBytesReader(w, r.Body, a.maxWebhookPayloadSizeB) diff --git a/util/webhook/webhook_test.go b/util/webhook/webhook_test.go index 9dd4695918e302..89dfb302ebf66c 100644 --- a/util/webhook/webhook_test.go +++ b/util/webhook/webhook_test.go @@ -518,7 +518,7 @@ func Test_affectedRevisionInfo_appRevisionHasChanged(t *testing.T) { Changes: []bitbucketserver.RepositoryChange{ {Reference: bitbucketserver.RepositoryReference{ID: "refs/heads/" + branchName}}, }, - Repository: bitbucketserver.Repository{Links: map[string]interface{}{"clone": []interface{}{}}}, + Repository: bitbucketserver.Repository{Links: map[string]any{"clone": []any{}}}, } } @@ -531,7 +531,7 @@ func Test_affectedRevisionInfo_appRevisionHasChanged(t *testing.T) { tests := []struct { hasChanged bool targetRevision string - hookPayload interface{} + hookPayload any name string }{ // Edge cases for bitbucket.