From 065fc31a92eecd35c9b1ee8a1bb9751d6374f58e Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 2 Jan 2025 16:32:46 -0500 Subject: [PATCH 01/41] chore(deps): update module github.com/golangci/golangci-lint to v1.63.2 (#21343) Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci-build.yaml | 2 +- hack/installers/install-lint-tools.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci-build.yaml b/.github/workflows/ci-build.yaml index d28dd666c7969..3945b37b24bdc 100644 --- a/.github/workflows/ci-build.yaml +++ b/.github/workflows/ci-build.yaml @@ -112,7 +112,7 @@ jobs: uses: golangci/golangci-lint-action@971e284b6050e8a5849b72094c50ab08da042db8 # v6.1.1 with: # renovate: datasource=go packageName=github.com/golangci/golangci-lint versioning=regex:^v(?\d+)\.(?\d+)\.(?\d+)?$ - version: v1.62.2 + version: v1.63.2 args: --verbose test-go: diff --git a/hack/installers/install-lint-tools.sh b/hack/installers/install-lint-tools.sh index 3dbc9e24be8c9..87468f3ce0b42 100755 --- a/hack/installers/install-lint-tools.sh +++ b/hack/installers/install-lint-tools.sh @@ -2,6 +2,6 @@ set -eux -o pipefail # renovate: datasource=go packageName=github.com/golangci/golangci-lint -GOLANGCI_LINT_VERSION=1.62.2 +GOLANGCI_LINT_VERSION=1.63.2 GO111MODULE=on go install "github.com/golangci/golangci-lint/cmd/golangci-lint@v${GOLANGCI_LINT_VERSION}" From b6770bdb7985b30a8badec5fda3ff4fde542d0cc Mon Sep 17 00:00:00 2001 From: Amin Arefzadeh <36985186+aminarefzadeh@users.noreply.github.com> Date: Fri, 3 Jan 2025 01:03:26 +0330 Subject: [PATCH 02/41] chore: Add divar.ir to USERS.md (#21344) Signed-off-by: Amin Arefzadeh --- USERS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/USERS.md b/USERS.md index 9135d45f8d0e3..ecc6ee6736826 100644 --- a/USERS.md +++ b/USERS.md @@ -95,6 +95,7 @@ Currently, the following organizations are **officially** using Argo CD: 1. [Devopsi - Poland Software/DevOps Consulting](https://devopsi.pl/) 1. [Devtron Labs](https://github.com/devtron-labs/devtron) 1. [DigitalOcean](https://www.digitalocean.com) +1. [Divar](https://divar.ir) 1. [Divistant](https://divistant.com) 1. [Dott](https://ridedott.com) 1. [Doximity](https://www.doximity.com/) From 33f2a6fea169bc0fabbf6d2474377928bb763c37 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 2 Jan 2025 22:09:59 +0000 Subject: [PATCH 03/41] chore(deps): update module github.com/golangci/golangci-lint to v1.63.3 (#21348) Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci-build.yaml | 2 +- hack/installers/install-lint-tools.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci-build.yaml b/.github/workflows/ci-build.yaml index 3945b37b24bdc..578fb1d511d46 100644 --- a/.github/workflows/ci-build.yaml +++ b/.github/workflows/ci-build.yaml @@ -112,7 +112,7 @@ jobs: uses: golangci/golangci-lint-action@971e284b6050e8a5849b72094c50ab08da042db8 # v6.1.1 with: # renovate: datasource=go packageName=github.com/golangci/golangci-lint versioning=regex:^v(?\d+)\.(?\d+)\.(?\d+)?$ - version: v1.63.2 + version: v1.63.3 args: --verbose test-go: diff --git a/hack/installers/install-lint-tools.sh b/hack/installers/install-lint-tools.sh index 87468f3ce0b42..4f371866128e3 100755 --- a/hack/installers/install-lint-tools.sh +++ b/hack/installers/install-lint-tools.sh @@ -2,6 +2,6 @@ set -eux -o pipefail # renovate: datasource=go packageName=github.com/golangci/golangci-lint -GOLANGCI_LINT_VERSION=1.63.2 +GOLANGCI_LINT_VERSION=1.63.3 GO111MODULE=on go install "github.com/golangci/golangci-lint/cmd/golangci-lint@v${GOLANGCI_LINT_VERSION}" From 6087b4f903f0d862618bb43e8496c86c6ea1494d Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Fri, 3 Jan 2025 00:23:28 +0100 Subject: [PATCH 04/41] chore: use github.com/golang-jwt/jwt/v5 (#21276) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 5 +++++ cmd/argocd/commands/login.go | 2 +- cmd/argocd/commands/login_test.go | 2 +- cmd/argocd/commands/project_role.go | 2 +- go.mod | 4 ++-- pkg/apiclient/apiclient.go | 5 +++-- server/account/account_test.go | 2 +- server/application/application_test.go | 2 +- server/application/websocket_test.go | 2 +- server/cluster/cluster_test.go | 2 +- server/logout/logout.go | 2 +- server/logout/logout_test.go | 2 +- server/project/project.go | 2 +- server/project/project_test.go | 2 +- server/rbacpolicy/rbacpolicy.go | 2 +- server/rbacpolicy/rbacpolicy_test.go | 2 +- server/repository/repository_test.go | 2 +- server/server.go | 2 +- server/server_test.go | 2 +- util/clusterauth/clusterauth.go | 10 ++-------- util/clusterauth/clusterauth_test.go | 15 +++++++++------ util/grpc/logging.go | 2 +- util/grpc/logging_test.go | 2 +- util/jwt/jwt.go | 2 +- util/jwt/jwt_test.go | 2 +- util/localconfig/localconfig.go | 2 +- util/oidc/oidc.go | 2 +- util/oidc/oidc_test.go | 2 +- util/rbac/rbac.go | 2 +- util/rbac/rbac_test.go | 2 +- util/security/jwt_test.go | 2 +- util/session/sessionmanager.go | 2 +- util/session/sessionmanager_test.go | 20 ++++++-------------- util/test/testutil.go | 2 +- 34 files changed, 55 insertions(+), 60 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index b2c2c0ac51043..ddd4555e2f5c8 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -45,11 +45,16 @@ linters-settings: gomodguard: blocked: modules: + - github.com/golang-jwt/jwt/v4: + recommendations: + - github.com/golang-jwt/jwt/v5 - github.com/pkg/errors: recommendations: - errors importas: alias: + - alias: jwtgo + pkg: github.com/golang-jwt/jwt/v5 - alias: metav1 pkg: k8s.io/apimachinery/pkg/apis/meta/v1 - alias: stderrors diff --git a/cmd/argocd/commands/login.go b/cmd/argocd/commands/login.go index 72b89dae1771c..2843972e7e476 100644 --- a/cmd/argocd/commands/login.go +++ b/cmd/argocd/commands/login.go @@ -13,7 +13,7 @@ import ( "time" "github.com/coreos/go-oidc/v3/oidc" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" log "github.com/sirupsen/logrus" "github.com/skratchdot/open-golang/open" "github.com/spf13/cobra" diff --git a/cmd/argocd/commands/login_test.go b/cmd/argocd/commands/login_test.go index 420b484674901..91cf3e11388b3 100644 --- a/cmd/argocd/commands/login_test.go +++ b/cmd/argocd/commands/login_test.go @@ -7,7 +7,7 @@ import ( utils "github.com/argoproj/argo-cd/v2/util/io" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" ) diff --git a/cmd/argocd/commands/project_role.go b/cmd/argocd/commands/project_role.go index a0da6793fa7e6..759608575908b 100644 --- a/cmd/argocd/commands/project_role.go +++ b/cmd/argocd/commands/project_role.go @@ -8,7 +8,7 @@ import ( "time" timeutil "github.com/argoproj/pkg/time" - jwtgo "github.com/golang-jwt/jwt/v4" + jwtgo "github.com/golang-jwt/jwt/v5" "github.com/spf13/cobra" "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless" diff --git a/go.mod b/go.mod index 2a8a1b1d6bee8..b2125cb037cb8 100644 --- a/go.mod +++ b/go.mod @@ -39,7 +39,7 @@ require ( github.com/gobwas/glob v0.2.3 github.com/gogits/go-gogs-client v0.0.0-20200905025246-8bb8a50cb355 github.com/gogo/protobuf v1.3.2 - github.com/golang-jwt/jwt/v4 v4.5.1 + github.com/golang-jwt/jwt/v5 v5.2.1 github.com/golang/protobuf v1.5.4 github.com/google/btree v1.1.3 github.com/google/go-cmp v0.6.0 @@ -137,7 +137,7 @@ require ( github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/go-fed/httpsig v1.1.0 // indirect github.com/go-jose/go-jose/v4 v4.0.2 // indirect - github.com/golang-jwt/jwt/v5 v5.2.1 // indirect + github.com/golang-jwt/jwt/v4 v4.5.1 // indirect github.com/google/gnostic-models v0.6.8 // indirect github.com/google/s2a-go v0.1.7 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect diff --git a/pkg/apiclient/apiclient.go b/pkg/apiclient/apiclient.go index 4aba674e2b329..efea9c550fdec 100644 --- a/pkg/apiclient/apiclient.go +++ b/pkg/apiclient/apiclient.go @@ -16,7 +16,7 @@ import ( "time" "github.com/coreos/go-oidc/v3/oidc" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/golang/protobuf/ptypes/empty" grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry" @@ -402,7 +402,8 @@ func (c *client) refreshAuthToken(localCfg *localconfig.LocalConfig, ctxName, co if err != nil { return err } - if claims.Valid() == nil { + validator := jwt.NewValidator() + if validator.Validate(claims) == nil { // token is still valid return nil } diff --git a/server/account/account_test.go b/server/account/account_test.go index 81e0abc0785f4..eb20c3195d21b 100644 --- a/server/account/account_test.go +++ b/server/account/account_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" diff --git a/server/application/application_test.go b/server/application/application_test.go index 8161f39a1a7f9..4ec2fa8cfacff 100644 --- a/server/application/application_test.go +++ b/server/application/application_test.go @@ -17,7 +17,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/utils/kube" "github.com/argoproj/gitops-engine/pkg/utils/kube/kubetest" "github.com/argoproj/pkg/sync" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/server/application/websocket_test.go b/server/application/websocket_test.go index 2575db2cedf28..ac2166d2ef481 100644 --- a/server/application/websocket_test.go +++ b/server/application/websocket_test.go @@ -16,7 +16,7 @@ import ( "github.com/argoproj/argo-cd/v2/util/assets" "github.com/argoproj/argo-cd/v2/util/rbac" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/server/cluster/cluster_test.go b/server/cluster/cluster_test.go index 8ac0a0a05e5bc..7496b83eec6a4 100644 --- a/server/cluster/cluster_test.go +++ b/server/cluster/cluster_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/argoproj/argo-cd/v2/server/rbacpolicy" "github.com/argoproj/argo-cd/v2/util/assets" diff --git a/server/logout/logout.go b/server/logout/logout.go index e94424bc7035a..cbbdfd5c3c293 100644 --- a/server/logout/logout.go +++ b/server/logout/logout.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" log "github.com/sirupsen/logrus" "github.com/argoproj/argo-cd/v2/common" diff --git a/server/logout/logout_test.go b/server/logout/logout_test.go index 83bf8ee5d92f3..9571de128e693 100644 --- a/server/logout/logout_test.go +++ b/server/logout/logout_test.go @@ -15,7 +15,7 @@ import ( "github.com/argoproj/argo-cd/v2/util/session" "github.com/argoproj/argo-cd/v2/util/settings" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" diff --git a/server/project/project.go b/server/project/project.go index cac913715b623..c361d9d990882 100644 --- a/server/project/project.go +++ b/server/project/project.go @@ -8,7 +8,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/utils/kube" "github.com/argoproj/pkg/sync" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/google/uuid" log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" diff --git a/server/project/project_test.go b/server/project/project_test.go index a5fe5d292b3c1..2c3ad6755ab94 100644 --- a/server/project/project_test.go +++ b/server/project/project_test.go @@ -10,7 +10,7 @@ import ( "github.com/argoproj/argo-cd/v2/util/db" "github.com/argoproj/pkg/sync" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/server/rbacpolicy/rbacpolicy.go b/server/rbacpolicy/rbacpolicy.go index ea2b0ee0c166d..08bff84c30b7c 100644 --- a/server/rbacpolicy/rbacpolicy.go +++ b/server/rbacpolicy/rbacpolicy.go @@ -3,7 +3,7 @@ package rbacpolicy import ( "strings" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" log "github.com/sirupsen/logrus" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" diff --git a/server/rbacpolicy/rbacpolicy_test.go b/server/rbacpolicy/rbacpolicy_test.go index ae8a9442e80df..b0674ecce577c 100644 --- a/server/rbacpolicy/rbacpolicy_test.go +++ b/server/rbacpolicy/rbacpolicy_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" diff --git a/server/repository/repository_test.go b/server/repository/repository_test.go index 01e158570c8b7..f1d3fe5ffd08b 100644 --- a/server/repository/repository_test.go +++ b/server/repository/repository_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/server/server.go b/server/server.go index 29c7da2ab1552..55f35fe818240 100644 --- a/server/server.go +++ b/server/server.go @@ -33,7 +33,7 @@ import ( "github.com/argoproj/notifications-engine/pkg/api" "github.com/argoproj/pkg/sync" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/gorilla/handlers" grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth" diff --git a/server/server_test.go b/server/server_test.go index 02bab631ef664..c466e0fe9c629 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -15,7 +15,7 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/util/clusterauth/clusterauth.go b/util/clusterauth/clusterauth.go index d57e27792ecb6..0ec1de7a60609 100644 --- a/util/clusterauth/clusterauth.go +++ b/util/clusterauth/clusterauth.go @@ -7,7 +7,7 @@ import ( "strings" "time" - jwt "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" @@ -368,17 +368,11 @@ func UninstallRBAC(clientset kubernetes.Interface, namespace, bindingName, roleN } type ServiceAccountClaims struct { - Sub string `json:"sub"` - Iss string `json:"iss"` Namespace string `json:"kubernetes.io/serviceaccount/namespace"` SecretName string `json:"kubernetes.io/serviceaccount/secret.name"` ServiceAccountName string `json:"kubernetes.io/serviceaccount/service-account.name"` ServiceAccountUID string `json:"kubernetes.io/serviceaccount/service-account.uid"` -} - -// Valid satisfies the jwt.Claims interface to enable JWT parsing -func (sac *ServiceAccountClaims) Valid() error { - return nil + jwt.RegisteredClaims } // ParseServiceAccountToken parses a Kubernetes service account token diff --git a/util/clusterauth/clusterauth_test.go b/util/clusterauth/clusterauth_test.go index 73a99d58d78aa..8f21f39bd22b4 100644 --- a/util/clusterauth/clusterauth_test.go +++ b/util/clusterauth/clusterauth_test.go @@ -6,6 +6,7 @@ import ( "testing" "time" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" @@ -27,12 +28,14 @@ const ( ) var testClaims = ServiceAccountClaims{ - Sub: "system:serviceaccount:kube-system:argocd-manager", - Iss: "kubernetes/serviceaccount", - Namespace: "kube-system", - SecretName: "argocd-manager-token-tj79r", - ServiceAccountName: "argocd-manager", - ServiceAccountUID: "91dd37cf-8d92-11e9-a091-d65f2ae7fa8d", + "kube-system", + "argocd-manager-token-tj79r", + "argocd-manager", + "91dd37cf-8d92-11e9-a091-d65f2ae7fa8d", + jwt.RegisteredClaims{ + Subject: "system:serviceaccount:kube-system:argocd-manager", + Issuer: "kubernetes/serviceaccount", + }, } func newServiceAccount() *corev1.ServiceAccount { diff --git a/util/grpc/logging.go b/util/grpc/logging.go index 271111977473b..6b244e4b95695 100644 --- a/util/grpc/logging.go +++ b/util/grpc/logging.go @@ -8,7 +8,7 @@ import ( "github.com/gogo/protobuf/jsonpb" "github.com/gogo/protobuf/proto" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" grpc_logging "github.com/grpc-ecosystem/go-grpc-middleware/logging" ctx_logrus "github.com/grpc-ecosystem/go-grpc-middleware/tags/logrus" "github.com/sirupsen/logrus" diff --git a/util/grpc/logging_test.go b/util/grpc/logging_test.go index 98be425928b69..4dfbaf1c2816e 100644 --- a/util/grpc/logging_test.go +++ b/util/grpc/logging_test.go @@ -6,7 +6,7 @@ import ( "fmt" "testing" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/util/jwt/jwt.go b/util/jwt/jwt.go index 585025990bf8d..e2ca9e92141e9 100644 --- a/util/jwt/jwt.go +++ b/util/jwt/jwt.go @@ -6,7 +6,7 @@ import ( "strings" "time" - jwtgo "github.com/golang-jwt/jwt/v4" + jwtgo "github.com/golang-jwt/jwt/v5" ) // MapClaims converts a jwt.Claims to a MapClaims diff --git a/util/jwt/jwt_test.go b/util/jwt/jwt_test.go index 1b0ac87fe9752..5ef645abb81f9 100644 --- a/util/jwt/jwt_test.go +++ b/util/jwt/jwt_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - jwt "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/util/localconfig/localconfig.go b/util/localconfig/localconfig.go index 1a0685f753c49..dc18ebedca796 100644 --- a/util/localconfig/localconfig.go +++ b/util/localconfig/localconfig.go @@ -7,7 +7,7 @@ import ( "path" "strings" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/argoproj/argo-cd/v2/util/config" configUtil "github.com/argoproj/argo-cd/v2/util/config" diff --git a/util/oidc/oidc.go b/util/oidc/oidc.go index 94f13b7d3e919..45c47ad8689d6 100644 --- a/util/oidc/oidc.go +++ b/util/oidc/oidc.go @@ -17,7 +17,7 @@ import ( "time" gooidc "github.com/coreos/go-oidc/v3/oidc" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" log "github.com/sirupsen/logrus" "golang.org/x/oauth2" diff --git a/util/oidc/oidc_test.go b/util/oidc/oidc_test.go index 40c606dcd9671..82f06367be9c1 100644 --- a/util/oidc/oidc_test.go +++ b/util/oidc/oidc_test.go @@ -14,7 +14,7 @@ import ( "time" gooidc "github.com/coreos/go-oidc/v3/oidc" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/oauth2" diff --git a/util/rbac/rbac.go b/util/rbac/rbac.go index 1446620d58bd0..1d0d6e8a87c4b 100644 --- a/util/rbac/rbac.go +++ b/util/rbac/rbac.go @@ -18,7 +18,7 @@ import ( "github.com/casbin/casbin/v2/model" "github.com/casbin/casbin/v2/util" "github.com/casbin/govaluate" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" gocache "github.com/patrickmn/go-cache" log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" diff --git a/util/rbac/rbac_test.go b/util/rbac/rbac_test.go index 686d283a3ee50..f24b0be317f43 100644 --- a/util/rbac/rbac_test.go +++ b/util/rbac/rbac_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/util/security/jwt_test.go b/util/security/jwt_test.go index f8131259c1138..87b6cfb7dd636 100644 --- a/util/security/jwt_test.go +++ b/util/security/jwt_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/util/session/sessionmanager.go b/util/session/sessionmanager.go index c04523d243e36..c27c92e0a3045 100644 --- a/util/session/sessionmanager.go +++ b/util/session/sessionmanager.go @@ -14,7 +14,7 @@ import ( "time" "github.com/coreos/go-oidc/v3/oidc" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/google/uuid" log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" diff --git a/util/session/sessionmanager_test.go b/util/session/sessionmanager_test.go index efee1951e7899..82d3472f3f3e0 100644 --- a/util/session/sessionmanager_test.go +++ b/util/session/sessionmanager_test.go @@ -14,7 +14,7 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" @@ -220,16 +220,8 @@ func TestSessionManager_ProjectToken(t *testing.T) { }) } -type claimsMock struct { - err error -} - -func (cm *claimsMock) Valid() error { - return cm.err -} - type tokenVerifierMock struct { - claims *claimsMock + claims *jwt.RegisteredClaims err error } @@ -258,7 +250,7 @@ func TestSessionManager_WithAuthMiddleware(t *testing.T) { name string authDisabled bool cookieHeader bool - verifiedClaims *claimsMock + verifiedClaims *jwt.RegisteredClaims verifyTokenErr error expectedStatusCode int expectedResponseBody *string @@ -269,7 +261,7 @@ func TestSessionManager_WithAuthMiddleware(t *testing.T) { name: "will authenticate successfully", authDisabled: false, cookieHeader: true, - verifiedClaims: &claimsMock{}, + verifiedClaims: &jwt.RegisteredClaims{}, verifyTokenErr: nil, expectedStatusCode: http.StatusOK, expectedResponseBody: strPointer("Ok"), @@ -287,7 +279,7 @@ func TestSessionManager_WithAuthMiddleware(t *testing.T) { name: "will return 400 if no cookie header", authDisabled: false, cookieHeader: false, - verifiedClaims: &claimsMock{}, + verifiedClaims: &jwt.RegisteredClaims{}, verifyTokenErr: nil, expectedStatusCode: http.StatusBadRequest, expectedResponseBody: nil, @@ -296,7 +288,7 @@ func TestSessionManager_WithAuthMiddleware(t *testing.T) { name: "will return 401 verify token fails", authDisabled: false, cookieHeader: true, - verifiedClaims: &claimsMock{}, + verifiedClaims: &jwt.RegisteredClaims{}, verifyTokenErr: stderrors.New("token error"), expectedStatusCode: http.StatusUnauthorized, expectedResponseBody: nil, diff --git a/util/test/testutil.go b/util/test/testutil.go index a8e506300864d..61fa0e74616fe 100644 --- a/util/test/testutil.go +++ b/util/test/testutil.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/go-jose/go-jose/v3" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/require" ) From 9ea979bbcdc76223890388c4b83ced88505b95ce Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Fri, 3 Jan 2025 00:26:59 +0100 Subject: [PATCH 05/41] chore: enable use-any from revive (#21282) 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 ddd4555e2f5c8..d17541fc9fed4 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -21,6 +21,7 @@ linters: - ineffassign - misspell - perfsprint + - revive - staticcheck - testifylint - thelper @@ -70,6 +71,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 28c534ad5fd11..480222b8dd1f2 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 c0c039b88faca..7ee01e9d73e12 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 616b7ef9a7e74..cd8e38837f186 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 1df037c13a566..09bfab4a523cf 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 d7b35d1815454..bcc5c55f8473f 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 57aefe847604c..10c114f39dcae 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 4d9d95f9cf4b8..31bbd7cc5d92b 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 4ac24f094edd2..7cec658cf06c3 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 25e6b138da749..6a94890eb92eb 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 2c55fecad5403..a208e5781f264 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 d119824f40174..e2440980cfaed 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 cb7389ac6b0cf..50bb7536a1e8a 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 a43e3e9b8222f..6e56be37b2ace 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 83f364c1a2cb2..7ef4c73ce2a0d 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 5a3b1d88dd4f4..0869f3ea4dee6 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 80b0d8a7fc052..d3edc0558a962 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 dec0ab96b45c9..88187705d4c33 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 a7de3a1f6ab4a..2138d3599dc24 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 ad54debb37dce..1b76d7ca2857e 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 f2c7f1d4a9781..4bebfbd88eb07 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 5d65554db4355..d52e5c770b25d 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 c1fd1a1c5ebc4..fb9c46ee0f9ba 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 875c6cf73787e..557f419672b5d 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 cf476ceeba51d..3bbc8664c7016 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 a52f7e8159b86..f5ee8293e011d 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 a87e1fab9bdb1..a7b3f25b806b6 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 5b490233d5d7e..5de30be130672 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 1a4a86285a183..07e3565eeb75d 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 a38e17474e122..2799b99668ea5 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 175683c434d72..4064718c94662 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 a9b2daf7be43b..86d3c98129046 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 1f2be70edb428..5ee1ea303fc79 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 d01ddbb6185dd..7b40d99e8c103 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 79baa727a14b0..f82ac37ab711d 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 dde6db03c7c27..b8390883925fb 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 8cde366e2dfd8..c3ed07fc0bec7 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 0d71f20b50a83..42cd39b715f4f 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 be033175d61f9..679ea356cca2c 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 84ab870404f1a..f0985cf9de2bc 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 4bfca4971bada..51b7ae51c22e3 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 8d19a2cffa260..6c66186649ef3 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 a886cba7c47ef..5da70572172c2 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 c8715e57776e0..1d5ba90d0dddf 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 f674266738944..5bdde7e572bdb 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 85f59b5dee699..e46dd15f565d6 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 f8f54758d64d5..23d96778fdf44 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 71d59c56da94d..97344ced7b95e 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 0b7245def64cd..9a4ca5c977dbd 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 e7cc47fa8b76a..325af2b8d9df7 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 57aede02a5b49..c177b98a78611 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 3dcc905182258..64ed8d3b450e0 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 849b9a48f02b6..9b924e063b786 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 555f419563d42..fd4c8e690ec32 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 589064b240351..beb08617477f4 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 8c69c4195c3ad..ee7385d06d8f9 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 7eb61acf4cfbc..ba149c39d16df 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 30bd0a97bedc5..7120eb9f37e05 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 5d7eacd2fd35f..0fd2f56845862 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 22d737f985e60..8c10e040ef1b7 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 8c4c3b4d88341..1cfc623959711 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 266c6ab0fd6cc..0a95917df8785 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 635000e688ce3..619a07fc9d85a 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 db58d209f19b8..70a3ebeae7f45 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 70339499e0a13..7ddcf9eaea409 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 383cb0c0c3d5a..5410e274e386c 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 93fb8f66051e0..a03bf2eff28f0 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 08d7bcb6df646..b656c95a11a0e 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 b74d46c170326..c53ec4d8b8465 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 16c0022dd1cb1..4cce0b257965f 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 c39f4628a432c..a51c59eac9c87 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 247fadffd908c..88fdbadb459de 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 ca901cf2c1890..a1c7082a559d7 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 4769775f9671f..ed48b0d559824 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 370a84173997b..27aa579fe6f88 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 9d3c849c992b3..70fcafb805f7d 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 28492686a8003..e11b186964db7 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 8282ce5337d39..8aa6f92605d0f 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 1c0d6b76de703..e642e667933b6 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 b9f0f4a19fe6f..7da3573bbfbeb 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 f8279693c2afb..46039fa840746 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 1bbba4f27f1f1..18c5cf3fa49ba 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 10492971a1e73..9e611e65471b6 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 eb20c3195d21b..81dd6d7ea7e04 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 f7d78fbf63c15..915aff1080e74 100644 --- a/server/application/application.go +++ b/server/application/application.go @@ -154,7 +154,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, @@ -163,7 +163,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) @@ -193,7 +193,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) @@ -212,7 +212,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) @@ -1061,7 +1061,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) @@ -1111,8 +1111,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, }, }) @@ -2160,7 +2160,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, @@ -2177,7 +2177,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, @@ -2597,7 +2597,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 @@ -2605,7 +2605,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 4ec2fa8cfacff..12d8991205ce4 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 c8a562123ad19..75cf809b43743 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 ac2166d2ef481..b38f84fb7a7a2 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 7496b83eec6a4..9f9290b36bbac 100644 --- a/server/cluster/cluster_test.go +++ b/server/cluster/cluster_test.go @@ -128,7 +128,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 933dcde42decb..aad7c601dd243 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 cba62c3bb591c..cc40764642b82 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 c361d9d990882..9a057fda008da 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 2c3ad6755ab94..097e55624b251 100644 --- a/server/project/project_test.go +++ b/server/project/project_test.go @@ -713,7 +713,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 08bff84c30b7c..250be3fdea3f3 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 f1d3fe5ffd08b..60522b7497aed 100644 --- a/server/repository/repository_test.go +++ b/server/repository/repository_test.go @@ -964,7 +964,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 55f35fe818240..5e6769deeb1f1 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 c466e0fe9c629..f3e9fe5313168 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 1472116be7e93..3a923e57311a7 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 3ee4a30509cbb..ee30ff6118153 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 79bd890518603..ca55d319943e5 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 4d66534961a87..a8d28091a5f34 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 27adae8497d75..08c03bb4f872c 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 e88fb05d8a006..5137da6d8eada 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 5808383027888..a01c2312f9b8f 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 6181d75b90288..2c8a3fab1566c 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 68e674f9f8b36..54de570ffd63c 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 559c910144dd1..3e50a6c07009b 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 95437b9f2892d..0cf71f2a191af 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 3ad755bfdca69..e02fc5bc83908 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 30eb59b8ef49b..c599c18bb1528 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 dbfb4ef4741c2..5ee6415e10d74 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 3034a87858418..1ad6a65fb819a 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 3f4ef5d1842ee..51f655b28b7c9 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 f728128053f6b..145042963695d 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 32d133d6e8385..e236a71bff991 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 f96a366a75d6a..6fc45c6806afd 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 ea2a66ab9d6f8..432eaf5a9b883 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 f0c335abb9287..49a4bb3f290ae 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 2e8d0ad0e4bbe..240a940f14be3 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 f5bb7b9427507..3ef73dd9ffc4c 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 c46b02b942584..5f1544c20f4eb 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 2fdd9fc37f8be..fb468eb581d8b 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 2c938b6998bb7..5f0de926f7dd2 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 f221099844876..87d7100381c36 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 0ec1de7a60609..bcc3b54ea3e12 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 9674a2ef5bc00..35b33b9d8a0ff 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 38136d8c43dba..a1fd515dcf12e 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 480ca077dcb61..549d10c6c551a 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 c4413b626eea6..3bca3134bd917 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 2c98083273d5e..0ccd0c5a2a63c 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 5bfaf99e92921..a7e305dbddbc9 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 1bd3686fa2b10..0d323e4d1108e 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 cc4c6b46e03f6..bc6526a6f4739 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 93e8f9688b2bd..9852e526270cd 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 6b244e4b95695..6708092cf3602 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 4dfbaf1c2816e..b7d30b0c62d86 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 36739e7def1cb..45bd8f82ac7f2 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 bd7108b6d0085..ba016a1cd38d1 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 c71f5e1a8a6f2..a05d51c669499 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 fb557010c85a0..ec6f0e9bf604e 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 2d72a87745f25..a8957c177686a 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 e2ca9e92141e9..bb6770da333a1 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 aa96dfc4d3fff..6cd1378a2c71f 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 1836aa1613ff8..9aa5b5b1f2b51 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 27299495fd9be..eb0395fd0c7a9 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 dd583fb5a37ce..ad5fce46e38cf 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 4b7a06bf7dc7e..1447f146815d1 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 a1fdadafc0a0c..c2e4e6766343d 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 ed8067cc926a9..6f3501e31d7e0 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 ae26448bedb15..ec058d1635e23 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 f00f245dc9cb0..92f931b6b6278 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 df9943d41bf11..a141d50dd1b87 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 8b29430ddedef..de0617fca15fc 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 63aa31c3d3d13..24b79f57e3ec4 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 a450260bea399..7a178027b8461 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 04ade75159a88..7b1457923e8f9 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 b274300873d76..14c693014789c 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 6ada7349d090c..0c224ad7cd800 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 82f06367be9c1..2b35cef92697c 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 4b013edea0ba7..1a57d375d695c 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 1d0d6e8a87c4b..f9da179867322 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 f24b0be317f43..aa127d344551c 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 c27c92e0a3045..6deba84b5aa95 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 5ea3dcc0a6cc8..c48b76baf2a1f 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 e15ae4963fd8f..09a15ff08c3a5 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 f56a25a4c4217..208050602cdf8 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 9dd4695918e30..89dfb302ebf66 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. From 13235ad477e82723bc749f4410cf38cec3dda55b Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Fri, 3 Jan 2025 00:27:41 +0100 Subject: [PATCH 06/41] chore: use testify instead of testing.Fatal (#21258) Signed-off-by: Matthieu MOREL --- common/common_test.go | 5 ++--- controller/cache/cache_test.go | 5 ++--- controller/state_test.go | 4 +--- notification_controller/controller/controller_test.go | 8 ++------ 4 files changed, 7 insertions(+), 15 deletions(-) diff --git a/common/common_test.go b/common/common_test.go index 7ceb42f5e8605..65140ee9c7332 100644 --- a/common/common_test.go +++ b/common/common_test.go @@ -96,9 +96,8 @@ func TestSetOptionalRedisPasswordFromKubeConfig(t *testing.T) { redisOptions = &redis.Options{} ) if tc.secret != nil { - if _, err := kubeClient.CoreV1().Secrets(tc.namespace).Create(ctx, tc.secret, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create secret: %v", err) - } + _, err := kubeClient.CoreV1().Secrets(tc.namespace).Create(ctx, tc.secret, metav1.CreateOptions{}) + require.NoErrorf(t, err, "Failed to create secret") } err := SetOptionalRedisPasswordFromKubeConfig(ctx, kubeClient, tc.namespace, redisOptions) if tc.expectedErr != "" { diff --git a/controller/cache/cache_test.go b/controller/cache/cache_test.go index 652b4b5549ccc..feb78ec839363 100644 --- a/controller/cache/cache_test.go +++ b/controller/cache/cache_test.go @@ -12,6 +12,7 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -726,9 +727,7 @@ func TestShouldHashManifest(t *testing.T) { test.un.SetAnnotations(test.annotations) } got := shouldHashManifest(test.appName, test.gvk, test.un) - if test.want != got { - t.Fatalf("test=%v want %v got %v", test.name, test.want, got) - } + require.Equalf(t, test.want, got, "test=%v", test.name) }) } } diff --git a/controller/state_test.go b/controller/state_test.go index 9a410992366f5..c446176fea9e9 100644 --- a/controller/state_test.go +++ b/controller/state_test.go @@ -1564,9 +1564,7 @@ func TestUseDiffCache(t *testing.T) { } if a != nil { err := mergo.Merge(app, a, mergo.WithOverride, mergo.WithOverwriteWithEmptyValue) - if err != nil { - t.Fatalf("error merging app: %s", err) - } + require.NoErrorf(t, err, "error merging app") } if app.Spec.Destination.Name != "" && app.Spec.Destination.Server != "" { // Simulate the controller's process for populating both of these fields. diff --git a/notification_controller/controller/controller_test.go b/notification_controller/controller/controller_test.go index a1c7082a559d7..af79e2d9e7d34 100644 --- a/notification_controller/controller/controller_test.go +++ b/notification_controller/controller/controller_test.go @@ -105,9 +105,7 @@ func TestGetAppProj_invalidProjectNestedString(t *testing.T) { func TestInit(t *testing.T) { scheme := runtime.NewScheme() err := v1alpha1.SchemeBuilder.AddToScheme(scheme) - if err != nil { - t.Fatalf("Error registering the resource: %v", err) - } + require.NoErrorf(t, err, "Error registering the resource") dynamicClient := fake.NewSimpleDynamicClient(scheme) k8sClient := k8sfake.NewSimpleClientset() appLabelSelector := "app=test" @@ -141,9 +139,7 @@ func TestInit(t *testing.T) { func TestInitTimeout(t *testing.T) { scheme := runtime.NewScheme() err := v1alpha1.SchemeBuilder.AddToScheme(scheme) - if err != nil { - t.Fatalf("Error registering the resource: %v", err) - } + require.NoErrorf(t, err, "Error registering the resource") dynamicClient := fake.NewSimpleDynamicClient(scheme) k8sClient := k8sfake.NewSimpleClientset() appLabelSelector := "app=test" From 8200e3d315abd5f2a8cbf447bcc11585c8ddded9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 3 Jan 2025 11:05:07 -0500 Subject: [PATCH 07/41] chore(deps): bump github.com/go-git/go-git/v5 from 5.13.0 to 5.13.1 (#21352) Bumps [github.com/go-git/go-git/v5](https://github.com/go-git/go-git) from 5.13.0 to 5.13.1. - [Release notes](https://github.com/go-git/go-git/releases) - [Commits](https://github.com/go-git/go-git/compare/v5.13.0...v5.13.1) --- updated-dependencies: - dependency-name: github.com/go-git/go-git/v5 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 4 ++-- go.sum | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/go.mod b/go.mod index b2125cb037cb8..d56fb9459f331 100644 --- a/go.mod +++ b/go.mod @@ -29,7 +29,7 @@ require ( github.com/felixge/httpsnoop v1.0.4 github.com/fsnotify/fsnotify v1.8.0 github.com/gfleury/go-bitbucket-v1 v0.0.0-20220301131131-8e7ed04b843e - github.com/go-git/go-git/v5 v5.13.0 + github.com/go-git/go-git/v5 v5.13.1 github.com/go-jose/go-jose/v3 v3.0.3 github.com/go-logr/logr v1.4.2 github.com/go-openapi/loads v0.22.0 @@ -198,7 +198,7 @@ require ( github.com/ghodss/yaml v1.0.0 // indirect github.com/go-errors/errors v1.4.2 // indirect github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect - github.com/go-git/go-billy/v5 v5.6.0 // indirect + github.com/go-git/go-billy/v5 v5.6.1 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/analysis v0.23.0 // indirect github.com/go-openapi/errors v0.22.0 // indirect diff --git a/go.sum b/go.sum index 53fe0babfd7bd..e6ddf4e8e033c 100644 --- a/go.sum +++ b/go.sum @@ -233,8 +233,8 @@ github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5m github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= -github.com/elazarl/goproxy v1.2.1 h1:njjgvO6cRG9rIqN2ebkqy6cQz2Njkx7Fsfv/zIZqgug= -github.com/elazarl/goproxy v1.2.1/go.mod h1:YfEbZtqP4AetfO6d40vWchF3znWX7C7Vd6ZMfdL8z64= +github.com/elazarl/goproxy v1.2.3 h1:xwIyKHbaP5yfT6O9KIeYJR5549MXRQkoQMRXGztz8YQ= +github.com/elazarl/goproxy v1.2.3/go.mod h1:YfEbZtqP4AetfO6d40vWchF3znWX7C7Vd6ZMfdL8z64= github.com/emicklei/go-restful/v3 v3.8.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= @@ -291,12 +291,12 @@ github.com/go-fed/httpsig v1.1.0 h1:9M+hb0jkEICD8/cAiNqEB66R87tTINszBRTjwjQzWcI= github.com/go-fed/httpsig v1.1.0/go.mod h1:RCMrTZvN1bJYtofsG4rd5NaO5obxQ5xBkdiS7xsT7bM= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic= -github.com/go-git/go-billy/v5 v5.6.0 h1:w2hPNtoehvJIxR00Vb4xX94qHQi/ApZfX+nBE2Cjio8= -github.com/go-git/go-billy/v5 v5.6.0/go.mod h1:sFDq7xD3fn3E0GOwUSZqHo9lrkmx8xJhA0ZrfvjBRGM= +github.com/go-git/go-billy/v5 v5.6.1 h1:u+dcrgaguSSkbjzHwelEjc0Yj300NUevrrPphk/SoRA= +github.com/go-git/go-billy/v5 v5.6.1/go.mod h1:0AsLr1z2+Uksi4NlElmMblP5rPcDZNRCD8ujZCRR2BE= github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4= github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII= -github.com/go-git/go-git/v5 v5.13.0 h1:vLn5wlGIh/X78El6r3Jr+30W16Blk0CTcxTYcYPWi5E= -github.com/go-git/go-git/v5 v5.13.0/go.mod h1:Wjo7/JyVKtQgUNdXYXIepzWfJQkUEIGvkvVkiXRR/zw= +github.com/go-git/go-git/v5 v5.13.1 h1:DAQ9APonnlvSWpvolXWIuV6Q6zXy2wHbN4cVlNR5Q+M= +github.com/go-git/go-git/v5 v5.13.1/go.mod h1:qryJB4cSBoq3FRoBRf5A77joojuBcmPJ0qu3XXXVixc= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-jose/go-jose/v3 v3.0.3 h1:fFKWeig/irsp7XD2zBxvnmA/XaRWp5V3CBsZXJF7G7k= github.com/go-jose/go-jose/v3 v3.0.3/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= From 4723abd0b4911e39d7aa7c4ba721157436de15d8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 3 Jan 2025 11:05:35 -0500 Subject: [PATCH 08/41] chore(deps): bump github.com/bradleyfalzon/ghinstallation/v2 (#21353) Bumps [github.com/bradleyfalzon/ghinstallation/v2](https://github.com/bradleyfalzon/ghinstallation) from 2.12.0 to 2.13.0. - [Release notes](https://github.com/bradleyfalzon/ghinstallation/releases) - [Commits](https://github.com/bradleyfalzon/ghinstallation/compare/v2.12.0...v2.13.0) --- updated-dependencies: - dependency-name: github.com/bradleyfalzon/ghinstallation/v2 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 3 ++- go.sum | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index d56fb9459f331..dc66f9214e6cc 100644 --- a/go.mod +++ b/go.mod @@ -16,7 +16,7 @@ require ( github.com/aws/aws-sdk-go v1.55.5 github.com/bmatcuk/doublestar/v4 v4.7.1 github.com/bombsimon/logrusr/v2 v2.0.1 - github.com/bradleyfalzon/ghinstallation/v2 v2.12.0 + github.com/bradleyfalzon/ghinstallation/v2 v2.13.0 github.com/casbin/casbin/v2 v2.103.0 github.com/casbin/govaluate v1.3.0 github.com/cespare/xxhash/v2 v2.3.0 @@ -139,6 +139,7 @@ require ( github.com/go-jose/go-jose/v4 v4.0.2 // indirect github.com/golang-jwt/jwt/v4 v4.5.1 // indirect github.com/google/gnostic-models v0.6.8 // indirect + github.com/google/go-github/v68 v68.0.0 // indirect github.com/google/s2a-go v0.1.7 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect github.com/googleapis/gax-go/v2 v2.12.3 // indirect diff --git a/go.sum b/go.sum index e6ddf4e8e033c..d51e3f074767c 100644 --- a/go.sum +++ b/go.sum @@ -151,8 +151,8 @@ github.com/bmatcuk/doublestar/v4 v4.7.1 h1:fdDeAqgT47acgwd9bd9HxJRDmc9UAmPpc+2m0 github.com/bmatcuk/doublestar/v4 v4.7.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= github.com/bombsimon/logrusr/v2 v2.0.1 h1:1VgxVNQMCvjirZIYaT9JYn6sAVGVEcNtRE0y4mvaOAM= github.com/bombsimon/logrusr/v2 v2.0.1/go.mod h1:ByVAX+vHdLGAfdroiMg6q0zgq2FODY2lc5YJvzmOJio= -github.com/bradleyfalzon/ghinstallation/v2 v2.12.0 h1:k8oVjGhZel2qmCUsYwSE34jPNT9DL2wCBOtugsHv26g= -github.com/bradleyfalzon/ghinstallation/v2 v2.12.0/go.mod h1:V4gJcNyAftH0rXpRp1SUVUuh+ACxOH1xOk/ZzkRHltg= +github.com/bradleyfalzon/ghinstallation/v2 v2.13.0 h1:5FhjW93/YLQJDmPdeyMPw7IjAPzqsr+0jHPfrPz0sZI= +github.com/bradleyfalzon/ghinstallation/v2 v2.13.0/go.mod h1:EJ6fgedVEHa2kUyBTTvslJCXJafS/mhJNNKEOCspZXQ= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= @@ -437,6 +437,8 @@ github.com/google/go-github/v41 v41.0.0 h1:HseJrM2JFf2vfiZJ8anY2hqBjdfY1Vlj/K27u github.com/google/go-github/v41 v41.0.0/go.mod h1:XgmCA5H323A9rtgExdTcnDkcqp6S30AVACCBDOonIxg= github.com/google/go-github/v66 v66.0.0 h1:ADJsaXj9UotwdgK8/iFZtv7MLc8E8WBl62WLd/D/9+M= github.com/google/go-github/v66 v66.0.0/go.mod h1:+4SO9Zkuyf8ytMj0csN1NR/5OTR+MfqPp8P8dVlcvY4= +github.com/google/go-github/v68 v68.0.0 h1:ZW57zeNZiXTdQ16qrDiZ0k6XucrxZ2CGmoTvcCyQG6s= +github.com/google/go-github/v68 v68.0.0/go.mod h1:K9HAUBovM2sLwM408A18h+wd9vqdLOEqTUCbnRIcx68= github.com/google/go-jsonnet v0.20.0 h1:WG4TTSARuV7bSm4PMB4ohjxe33IHT5WVTrJSU33uT4g= github.com/google/go-jsonnet v0.20.0/go.mod h1:VbgWF9JX7ztlv770x/TolZNGGFfiHEVx9G6ca2eUmeA= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= From ceb758c8772ae70d73246fe224e5b9fd6484a0ac Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Fri, 3 Jan 2025 17:10:00 +0100 Subject: [PATCH 09/41] chore: import k8s.io/api/core/v1 as corev1 (#21345) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 2 + applicationset/generators/plugin_test.go | 54 ++++++------ cmd/argocd/commands/admin/admin.go | 10 +-- cmd/argocd/commands/admin/app.go | 4 +- cmd/argocd/commands/admin/backup_test.go | 4 +- .../commands/admin/generatespec_utils.go | 6 +- .../commands/admin/generatespec_utils_test.go | 4 +- cmd/argocd/commands/admin/repo.go | 4 +- .../commands/admin/settings_rbac_test.go | 6 +- cmd/argocd/commands/admin/settings_test.go | 6 +- cmd/argocd/commands/app_test.go | 36 ++++---- controller/appcontroller.go | 30 +++---- controller/cache/cache.go | 14 ++-- controller/cache/cache_test.go | 38 ++++----- controller/cache/info.go | 38 ++++----- controller/cache/info_test.go | 25 +++--- controller/clusterinfoupdater_test.go | 6 +- controller/sharding/sharding.go | 6 +- controller/sharding/sharding_test.go | 6 +- controller/state.go | 4 +- hack/dev-mounter/main.go | 4 +- hack/gen-catalog/main.go | 11 ++- .../generators/cluster_generator.go | 4 +- .../generators/repo_generator.go | 4 +- pkg/apis/application/v1alpha1/types.go | 24 +++--- server/account/account_test.go | 40 ++++----- server/application/application.go | 10 +-- server/application/application_test.go | 11 ++- server/application/terminal.go | 6 +- server/application/websocket_test.go | 6 +- server/applicationset/applicationset.go | 4 +- server/applicationset/applicationset_test.go | 6 +- server/deeplinks/deeplinks_test.go | 4 +- server/project/project.go | 6 +- server/server.go | 4 +- test/e2e/app_management_ns_test.go | 28 +++---- test/e2e/app_management_test.go | 34 ++++---- test/e2e/app_sync_options_test.go | 4 +- test/e2e/fixture/app/expectation.go | 12 +-- test/e2e/git_submodule_test.go | 13 ++- test/e2e/git_test.go | 9 +- test/e2e/helm_test.go | 12 +-- test/e2e/hook_test.go | 18 ++-- test/e2e/sync_waves_test.go | 11 ++- test/e2e/sync_with_impersonate_test.go | 4 +- test/testdata.go | 10 +-- util/argo/audit_logger.go | 8 +- .../argo/normalizers/knowntypes_normalizer.go | 4 +- util/db/certificate_test.go | 8 +- util/db/cluster.go | 28 +++---- util/db/cluster_norace_test.go | 10 +-- util/db/cluster_test.go | 44 +++++----- util/db/db.go | 6 +- util/db/db_test.go | 30 +++---- util/db/gpgkeys_test.go | 18 ++-- util/db/helmrepository.go | 6 +- util/db/repository.go | 4 +- util/db/repository_legacy.go | 18 ++-- util/db/secrets.go | 34 ++++---- util/helm/helm_test.go | 6 +- util/kube/kube_test.go | 6 +- util/kube/util.go | 12 +-- util/kube/util_test.go | 8 +- util/notification/settings/legacy.go | 4 +- util/notification/settings/legacy_test.go | 10 +-- util/notification/settings/settings.go | 12 +-- util/rbac/rbac.go | 14 ++-- util/rbac/rbac_norace_test.go | 4 +- util/rbac/rbac_test.go | 8 +- util/settings/accounts.go | 16 ++-- util/settings/accounts_test.go | 12 +-- util/settings/settings.go | 80 +++++++++--------- util/settings/settings_test.go | 83 +++++++++---------- util/util.go | 6 +- util/util_test.go | 18 ++-- 75 files changed, 555 insertions(+), 564 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index d17541fc9fed4..eb77d99d3012e 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -56,6 +56,8 @@ linters-settings: alias: - alias: jwtgo pkg: github.com/golang-jwt/jwt/v5 + - alias: corev1 + pkg: k8s.io/api/core/v1 - alias: metav1 pkg: k8s.io/apimachinery/pkg/apis/meta/v1 - alias: stderrors diff --git a/applicationset/generators/plugin_test.go b/applicationset/generators/plugin_test.go index d52e5c770b25d..f9ce9bdd48a5b 100644 --- a/applicationset/generators/plugin_test.go +++ b/applicationset/generators/plugin_test.go @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -27,8 +27,8 @@ import ( func TestPluginGenerateParams(t *testing.T) { testCases := []struct { name string - configmap *v1.ConfigMap - secret *v1.Secret + configmap *corev1.ConfigMap + secret *corev1.Secret inputParameters map[string]apiextensionsv1.JSON values map[string]string gotemplate bool @@ -38,7 +38,7 @@ func TestPluginGenerateParams(t *testing.T) { }{ { name: "simple case", - configmap: &v1.ConfigMap{ + configmap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "first-plugin-cm", Namespace: "default", @@ -48,7 +48,7 @@ func TestPluginGenerateParams(t *testing.T) { "token": "$plugin.token", }, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: "default", @@ -94,7 +94,7 @@ func TestPluginGenerateParams(t *testing.T) { }, { name: "simple case with values", - configmap: &v1.ConfigMap{ + configmap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "first-plugin-cm", Namespace: "default", @@ -104,7 +104,7 @@ func TestPluginGenerateParams(t *testing.T) { "token": "$plugin.token", }, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: "default", @@ -156,7 +156,7 @@ func TestPluginGenerateParams(t *testing.T) { }, { name: "simple case with gotemplate", - configmap: &v1.ConfigMap{ + configmap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "first-plugin-cm", Namespace: "default", @@ -166,7 +166,7 @@ func TestPluginGenerateParams(t *testing.T) { "token": "$plugin.token", }, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: "default", @@ -216,7 +216,7 @@ func TestPluginGenerateParams(t *testing.T) { }, { name: "simple case with appended params", - configmap: &v1.ConfigMap{ + configmap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "first-plugin-cm", Namespace: "default", @@ -226,7 +226,7 @@ func TestPluginGenerateParams(t *testing.T) { "token": "$plugin.token", }, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: "default", @@ -272,7 +272,7 @@ func TestPluginGenerateParams(t *testing.T) { }, { name: "no params", - configmap: &v1.ConfigMap{ + configmap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "first-plugin-cm", Namespace: "default", @@ -282,7 +282,7 @@ func TestPluginGenerateParams(t *testing.T) { "token": "$plugin.token", }, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: "default", @@ -322,7 +322,7 @@ func TestPluginGenerateParams(t *testing.T) { }, { name: "empty return", - configmap: &v1.ConfigMap{ + configmap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "first-plugin-cm", Namespace: "default", @@ -332,7 +332,7 @@ func TestPluginGenerateParams(t *testing.T) { "token": "$plugin.token", }, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: "default", @@ -349,7 +349,7 @@ func TestPluginGenerateParams(t *testing.T) { }, { name: "wrong return", - configmap: &v1.ConfigMap{ + configmap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "first-plugin-cm", Namespace: "default", @@ -359,7 +359,7 @@ func TestPluginGenerateParams(t *testing.T) { "token": "$plugin.token", }, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: "default", @@ -376,7 +376,7 @@ func TestPluginGenerateParams(t *testing.T) { }, { name: "external secret", - configmap: &v1.ConfigMap{ + configmap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "first-plugin-cm", Namespace: "default", @@ -386,7 +386,7 @@ func TestPluginGenerateParams(t *testing.T) { "token": "$plugin-secret:plugin.token", }, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "plugin-secret", Namespace: "default", @@ -432,7 +432,7 @@ func TestPluginGenerateParams(t *testing.T) { }, { name: "no secret", - configmap: &v1.ConfigMap{ + configmap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "first-plugin-cm", Namespace: "default", @@ -442,7 +442,7 @@ func TestPluginGenerateParams(t *testing.T) { "token": "$plugin.token", }, }, - secret: &v1.Secret{}, + secret: &corev1.Secret{}, inputParameters: map[string]apiextensionsv1.JSON{ "pkey1": {Raw: []byte(`"val1"`)}, "pkey2": {Raw: []byte(`"val2"`)}, @@ -480,8 +480,8 @@ func TestPluginGenerateParams(t *testing.T) { }, { name: "no configmap", - configmap: &v1.ConfigMap{}, - secret: &v1.Secret{ + configmap: &corev1.ConfigMap{}, + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: "default", @@ -527,7 +527,7 @@ func TestPluginGenerateParams(t *testing.T) { }, { name: "no baseUrl", - configmap: &v1.ConfigMap{ + configmap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "first-plugin-cm", Namespace: "default", @@ -536,7 +536,7 @@ func TestPluginGenerateParams(t *testing.T) { "token": "$plugin.token", }, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: "default", @@ -582,7 +582,7 @@ func TestPluginGenerateParams(t *testing.T) { }, { name: "no token", - configmap: &v1.ConfigMap{ + configmap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "first-plugin-cm", Namespace: "default", @@ -591,7 +591,7 @@ func TestPluginGenerateParams(t *testing.T) { "baseUrl": "http://127.0.0.1", }, }, - secret: &v1.Secret{}, + secret: &corev1.Secret{}, inputParameters: map[string]apiextensionsv1.JSON{ "pkey1": {Raw: []byte(`"val1"`)}, "pkey2": {Raw: []byte(`"val2"`)}, diff --git a/cmd/argocd/commands/admin/admin.go b/cmd/argocd/commands/admin/admin.go index 326f9a10e8c7a..18994f7a5db39 100644 --- a/cmd/argocd/commands/admin/admin.go +++ b/cmd/argocd/commands/admin/admin.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/spf13/cobra" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" @@ -98,7 +98,7 @@ func newArgoCDClientsets(config *rest.Config, namespace string) *argoCDClientset // getReferencedSecrets examines the argocd-cm config for any referenced repo secrets and returns a // map of all referenced secrets. func getReferencedSecrets(un unstructured.Unstructured) map[string]bool { - var cm apiv1.ConfigMap + var cm corev1.ConfigMap err := runtime.DefaultUnstructuredConverter.FromUnstructured(un.Object, &cm) errors.CheckError(err) referencedSecrets := make(map[string]bool) @@ -192,8 +192,8 @@ func isArgoCDConfigMap(name string) bool { func specsEqual(left, right unstructured.Unstructured) bool { leftAnnotation := left.GetAnnotations() rightAnnotation := right.GetAnnotations() - delete(leftAnnotation, apiv1.LastAppliedConfigAnnotation) - delete(rightAnnotation, apiv1.LastAppliedConfigAnnotation) + delete(leftAnnotation, corev1.LastAppliedConfigAnnotation) + delete(rightAnnotation, corev1.LastAppliedConfigAnnotation) if !reflect.DeepEqual(leftAnnotation, rightAnnotation) { return false } @@ -244,7 +244,7 @@ func getAdditionalNamespaces(ctx context.Context, argocdClientsets *argoCDClient un, err := argocdClientsets.configMaps.Get(ctx, common.ArgoCDCmdParamsConfigMapName, metav1.GetOptions{}) errors.CheckError(err) - var cm apiv1.ConfigMap + var cm corev1.ConfigMap err = runtime.DefaultUnstructuredConverter.FromUnstructured(un.Object, &cm) errors.CheckError(err) diff --git a/cmd/argocd/commands/admin/app.go b/cmd/argocd/commands/admin/app.go index 23d96778fdf44..c60484c6ffcbe 100644 --- a/cmd/argocd/commands/admin/app.go +++ b/cmd/argocd/commands/admin/app.go @@ -11,7 +11,7 @@ import ( "time" "github.com/spf13/cobra" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/util/runtime" @@ -453,5 +453,5 @@ func reconcileApplications( } func newLiveStateCache(argoDB db.ArgoDB, appInformer kubecache.SharedIndexInformer, settingsMgr *settings.SettingsManager, server *metrics.MetricsServer) cache.LiveStateCache { - return cache.NewLiveStateCache(argoDB, appInformer, settingsMgr, kubeutil.NewKubectl(), server, func(managedByApp map[string]bool, ref apiv1.ObjectReference) {}, &sharding.ClusterSharding{}, argo.NewResourceTracking()) + return cache.NewLiveStateCache(argoDB, appInformer, settingsMgr, kubeutil.NewKubectl(), server, func(managedByApp map[string]bool, ref corev1.ObjectReference) {}, &sharding.ClusterSharding{}, argo.NewResourceTracking()) } diff --git a/cmd/argocd/commands/admin/backup_test.go b/cmd/argocd/commands/admin/backup_test.go index b4fd07ad04c1a..3796b4c7540c7 100644 --- a/cmd/argocd/commands/admin/backup_test.go +++ b/cmd/argocd/commands/admin/backup_test.go @@ -5,7 +5,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/utils/kube" "github.com/stretchr/testify/assert" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -13,7 +13,7 @@ import ( ) func newBackupObject(trackingValue string, trackingLabel bool, trackingAnnotation bool) *unstructured.Unstructured { - cm := v1.ConfigMap{ + cm := corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "my-configmap", Namespace: "namespace", diff --git a/cmd/argocd/commands/admin/generatespec_utils.go b/cmd/argocd/commands/admin/generatespec_utils.go index 97344ced7b95e..a4109353af248 100644 --- a/cmd/argocd/commands/admin/generatespec_utils.go +++ b/cmd/argocd/commands/admin/generatespec_utils.go @@ -8,7 +8,7 @@ import ( "os" "github.com/argoproj/gitops-engine/pkg/utils/kube" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "sigs.k8s.io/yaml" ioutil "github.com/argoproj/argo-cd/v2/util/io" @@ -38,7 +38,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 ...any) error { for i, resource := range resources { - if secret, ok := resource.(*v1.Secret); ok { + if secret, ok := resource.(*corev1.Secret); ok { convertSecretData(secret) } filteredResource, err := omitFields(resource) @@ -97,7 +97,7 @@ func omitFields(resource any) (any, error) { } // convertSecretData converts kubernetes secret's data to stringData -func convertSecretData(secret *v1.Secret) { +func convertSecretData(secret *corev1.Secret) { secret.Kind = kube.SecretKind secret.APIVersion = "v1" secret.StringData = map[string]string{} diff --git a/cmd/argocd/commands/admin/generatespec_utils_test.go b/cmd/argocd/commands/admin/generatespec_utils_test.go index 13d946d2c7478..5019d386a52e1 100644 --- a/cmd/argocd/commands/admin/generatespec_utils_test.go +++ b/cmd/argocd/commands/admin/generatespec_utils_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -38,7 +38,7 @@ func TestGetOutWriter_InlineOn(t *testing.T) { func TestPrintResources_Secret_YAML(t *testing.T) { out := bytes.Buffer{} - err := PrintResources("yaml", &out, &v1.Secret{ + err := PrintResources("yaml", &out, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "my-secret"}, Data: map[string][]byte{"my-secret-key": []byte("my-secret-data")}, }) diff --git a/cmd/argocd/commands/admin/repo.go b/cmd/argocd/commands/admin/repo.go index 30e3578249e59..2248696ddcc6b 100644 --- a/cmd/argocd/commands/admin/repo.go +++ b/cmd/argocd/commands/admin/repo.go @@ -6,7 +6,7 @@ import ( log "github.com/sirupsen/logrus" "github.com/spf13/cobra" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" @@ -137,7 +137,7 @@ func NewGenRepoSpecCommand() *cobra.Command { repoOpts.Repo.Password = cli.PromptPassword(repoOpts.Repo.Password) } - argoCDCM := &apiv1.ConfigMap{ + argoCDCM := &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", APIVersion: "v1", diff --git a/cmd/argocd/commands/admin/settings_rbac_test.go b/cmd/argocd/commands/admin/settings_rbac_test.go index 7e052ea2c1f8d..10cc065b582b7 100644 --- a/cmd/argocd/commands/admin/settings_rbac_test.go +++ b/cmd/argocd/commands/admin/settings_rbac_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" restclient "k8s.io/client-go/rest" @@ -147,7 +147,7 @@ func Test_PolicyFromK8s(t *testing.T) { ctx := context.Background() require.NoError(t, err) - kubeclientset := fake.NewClientset(&v1.ConfigMap{ + kubeclientset := fake.NewClientset(&corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-rbac-cm", Namespace: "argocd", @@ -280,7 +280,7 @@ p, role:user, logs, get, .*/.*, allow p, role:user, exec, create, .*/.*, allow ` - kubeclientset := fake.NewClientset(&v1.ConfigMap{ + kubeclientset := fake.NewClientset(&corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-rbac-cm", Namespace: "argocd", diff --git a/cmd/argocd/commands/admin/settings_test.go b/cmd/argocd/commands/admin/settings_test.go index 1f9af47540e6c..66f3385b2d976 100644 --- a/cmd/argocd/commands/admin/settings_test.go +++ b/cmd/argocd/commands/admin/settings_test.go @@ -13,7 +13,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" ) @@ -44,7 +44,7 @@ func captureStdout(callback func()) (string, error) { func newSettingsManager(data map[string]string) *settings.SettingsManager { ctx := context.Background() - clientset := fake.NewClientset(&v1.ConfigMap{ + clientset := fake.NewClientset(&corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: "default", Name: common.ArgoCDConfigMapName, @@ -53,7 +53,7 @@ func newSettingsManager(data map[string]string) *settings.SettingsManager { }, }, Data: data, - }, &v1.Secret{ + }, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "default", Name: common.ArgoCDSecretName, diff --git a/cmd/argocd/commands/app_test.go b/cmd/argocd/commands/app_test.go index c177b98a78611..3dcbaa5d7a9db 100644 --- a/cmd/argocd/commands/app_test.go +++ b/cmd/argocd/commands/app_test.go @@ -12,13 +12,22 @@ import ( "testing" "time" + "github.com/argoproj/gitops-engine/pkg/health" + "github.com/argoproj/gitops-engine/pkg/utils/kube" + "github.com/coreos/go-oidc/v3/oidc" + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/oauth2" "google.golang.org/grpc" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/watch" - - "github.com/argoproj/argo-cd/v2/reposerver/apiclient" - - v1 "k8s.io/api/core/v1" - + k8swatch "k8s.io/apimachinery/pkg/watch" "sigs.k8s.io/yaml" argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient" @@ -37,20 +46,7 @@ import ( versionpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/version" "github.com/argoproj/argo-cd/v2/pkg/apis/application" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - - "github.com/argoproj/gitops-engine/pkg/health" - "github.com/argoproj/gitops-engine/pkg/utils/kube" - "github.com/coreos/go-oidc/v3/oidc" - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "golang.org/x/oauth2" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/intstr" - k8swatch "k8s.io/apimachinery/pkg/watch" + "github.com/argoproj/argo-cd/v2/reposerver/apiclient" ) func Test_getInfos(t *testing.T) { @@ -2071,7 +2067,7 @@ func (c *fakeAppServiceClient) List(ctx context.Context, in *applicationpkg.Appl return nil, nil } -func (c *fakeAppServiceClient) ListResourceEvents(ctx context.Context, in *applicationpkg.ApplicationResourceEventsQuery, opts ...grpc.CallOption) (*v1.EventList, error) { +func (c *fakeAppServiceClient) ListResourceEvents(ctx context.Context, in *applicationpkg.ApplicationResourceEventsQuery, opts ...grpc.CallOption) (*corev1.EventList, error) { return nil, nil } diff --git a/controller/appcontroller.go b/controller/appcontroller.go index 8c10e040ef1b7..479c84bdf6099 100644 --- a/controller/appcontroller.go +++ b/controller/appcontroller.go @@ -25,7 +25,7 @@ import ( jsonpatch "github.com/evanphx/json-patch" log "github.com/sirupsen/logrus" "golang.org/x/sync/semaphore" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -353,7 +353,7 @@ func (ctrl *ApplicationController) onKubectlRun(command string) (kube.CleanupFun }, nil } -func isSelfReferencedApp(app *appv1.Application, ref v1.ObjectReference) bool { +func isSelfReferencedApp(app *appv1.Application, ref corev1.ObjectReference) bool { gvk := ref.GroupVersionKind() return ref.UID == app.UID && ref.Name == app.Name && @@ -412,7 +412,7 @@ func (ctrl *ApplicationController) getAppProj(app *appv1.Application) (*appv1.Ap return proj, nil } -func (ctrl *ApplicationController) handleObjectUpdated(managedByApp map[string]bool, ref v1.ObjectReference) { +func (ctrl *ApplicationController) handleObjectUpdated(managedByApp map[string]bool, ref corev1.ObjectReference) { // if namespaced resource is not managed by any app it might be orphaned resource of some other apps if len(managedByApp) == 0 && ref.Namespace != "" { // retrieve applications which monitor orphaned resources in the same namespace and refresh them unless resource is denied in app project @@ -673,10 +673,10 @@ func (ctrl *ApplicationController) getAppHosts(a *appv1.Application, appNodes [] logCtx = logCtx.WithField("time_ms", time.Since(ts.StartTime).Milliseconds()) logCtx.Debug("Finished getting app hosts") }() - supportedResourceNames := map[v1.ResourceName]bool{ - v1.ResourceCPU: true, - v1.ResourceStorage: true, - v1.ResourceMemory: true, + supportedResourceNames := map[corev1.ResourceName]bool{ + corev1.ResourceCPU: true, + corev1.ResourceStorage: true, + corev1.ResourceMemory: true, } appPods := map[kube.ResourceKey]bool{} for _, node := range appNodes { @@ -716,7 +716,7 @@ func (ctrl *ApplicationController) getAppHosts(a *appv1.Application, appNodes [] neighbors := allPodsByNode[nodeName] - resources := map[v1.ResourceName]appv1.HostResourceInfo{} + resources := map[corev1.ResourceName]appv1.HostResourceInfo{} for name, resource := range node.Capacity { info := resources[name] info.ResourceName = name @@ -738,7 +738,7 @@ func (ctrl *ApplicationController) getAppHosts(a *appv1.Application, appNodes [] for _, pod := range neighbors { for name, resource := range pod.ResourceRequests { - if !supportedResourceNames[name] || pod.Phase == v1.PodSucceeded || pod.Phase == v1.PodFailed { + if !supportedResourceNames[name] || pod.Phase == corev1.PodSucceeded || pod.Phase == corev1.PodFailed { continue } info := resources[name] @@ -1029,7 +1029,7 @@ func (ctrl *ApplicationController) processAppOperationQueueItem() (processNext b Message: err.Error(), }) message := fmt.Sprintf("Unable to delete application resources: %v", err.Error()) - ctrl.logAppEvent(app, argo.EventInfo{Reason: argo.EventReasonStatusRefreshed, Type: v1.EventTypeWarning}, message, context.TODO()) + ctrl.logAppEvent(app, argo.EventInfo{Reason: argo.EventReasonStatusRefreshed, Type: corev1.EventTypeWarning}, message, context.TODO()) } ts.AddCheckpoint("finalize_application_deletion_ms") } @@ -1559,10 +1559,10 @@ func (ctrl *ApplicationController) setOperationState(app *appv1.Application, sta messages = append(messages, "to", state.SyncResult.Revision) } if state.Phase.Successful() { - eventInfo.Type = v1.EventTypeNormal + eventInfo.Type = corev1.EventTypeNormal messages = append(messages, "succeeded") } else { - eventInfo.Type = v1.EventTypeWarning + eventInfo.Type = corev1.EventTypeWarning messages = append(messages, "failed:", state.Message) } ctrl.logAppEvent(app, eventInfo, strings.Join(messages, " "), context.TODO()) @@ -1996,11 +1996,11 @@ func (ctrl *ApplicationController) persistAppStatus(orig *appv1.Application, new logCtx := getAppLog(orig) if orig.Status.Sync.Status != newStatus.Sync.Status { message := fmt.Sprintf("Updated sync status: %s -> %s", orig.Status.Sync.Status, newStatus.Sync.Status) - ctrl.logAppEvent(orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: v1.EventTypeNormal}, message, context.TODO()) + ctrl.logAppEvent(orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: corev1.EventTypeNormal}, message, context.TODO()) } if orig.Status.Health.Status != newStatus.Health.Status { message := fmt.Sprintf("Updated health status: %s -> %s", orig.Status.Health.Status, newStatus.Health.Status) - ctrl.logAppEvent(orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: v1.EventTypeNormal}, message, context.TODO()) + ctrl.logAppEvent(orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: corev1.EventTypeNormal}, message, context.TODO()) } var newAnnotations map[string]string if orig.GetAnnotations() != nil { @@ -2183,7 +2183,7 @@ func (ctrl *ApplicationController) autoSync(app *appv1.Application, syncStatus * target = desiredCommitSHA } message := fmt.Sprintf("Initiated automated sync to '%s'", target) - ctrl.logAppEvent(app, argo.EventInfo{Reason: argo.EventReasonOperationStarted, Type: v1.EventTypeNormal}, message, context.TODO()) + ctrl.logAppEvent(app, argo.EventInfo{Reason: argo.EventReasonOperationStarted, Type: corev1.EventTypeNormal}, message, context.TODO()) logCtx.Info(message) return nil, setOpTime } diff --git a/controller/cache/cache.go b/controller/cache/cache.go index 0a95917df8785..ceb21c3e7b19d 100644 --- a/controller/cache/cache.go +++ b/controller/cache/cache.go @@ -20,7 +20,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/utils/kube" log "github.com/sirupsen/logrus" "golang.org/x/sync/semaphore" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -155,18 +155,18 @@ type LiveStateCache interface { Init() error } -type ObjectUpdatedHandler = func(managedByApp map[string]bool, ref v1.ObjectReference) +type ObjectUpdatedHandler = func(managedByApp map[string]bool, ref corev1.ObjectReference) type PodInfo struct { NodeName string - ResourceRequests v1.ResourceList - Phase v1.PodPhase + ResourceRequests corev1.ResourceList + Phase corev1.PodPhase } type NodeInfo struct { Name string - Capacity v1.ResourceList - SystemInfo v1.NodeSystemInfo + Capacity corev1.ResourceList + SystemInfo corev1.NodeSystemInfo } type ResourceInfo struct { @@ -576,7 +576,7 @@ func (c *liveStateCache) getCluster(server string) (clustercache.ClusterCache, e _ = clusterCache.OnResourceUpdated(func(newRes *clustercache.Resource, oldRes *clustercache.Resource, namespaceResources map[kube.ResourceKey]*clustercache.Resource) { toNotify := make(map[string]bool) - var ref v1.ObjectReference + var ref corev1.ObjectReference if newRes != nil { ref = newRes.Ref } else { diff --git a/controller/cache/cache_test.go b/controller/cache/cache_test.go index feb78ec839363..92322c3c44848 100644 --- a/controller/cache/cache_test.go +++ b/controller/cache/cache_test.go @@ -9,11 +9,11 @@ import ( "testing" "time" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -72,7 +72,7 @@ func TestHandleModEvent_ClusterExcluded(t *testing.T) { clustersCache := liveStateCache{ db: nil, appInformer: nil, - onObjectUpdated: func(managedByApp map[string]bool, ref v1.ObjectReference) { + onObjectUpdated: func(managedByApp map[string]bool, ref corev1.ObjectReference) { }, kubectl: nil, settingsMgr: &argosettings.SettingsManager{}, @@ -279,7 +279,7 @@ func TestIsRetryableError(t *testing.T) { func Test_asResourceNode_owner_refs(t *testing.T) { resNode := asResourceNode(&cache.Resource{ ResourceVersion: "", - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ APIVersion: "v1", }, OwnerRefs: []metav1.OwnerReference{ @@ -335,7 +335,7 @@ func Test_getAppRecursive(t *testing.T) { { name: "ok: cm1->app1", r: &cache.Resource{ - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm1", }, OwnerRefs: []metav1.OwnerReference{ @@ -355,7 +355,7 @@ func Test_getAppRecursive(t *testing.T) { { name: "ok: cm1->cm2->app1", r: &cache.Resource{ - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm1", }, OwnerRefs: []metav1.OwnerReference{ @@ -364,7 +364,7 @@ func Test_getAppRecursive(t *testing.T) { }, ns: map[kube.ResourceKey]*cache.Resource{ kube.NewResourceKey("", "", "", "cm2"): { - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm2", }, OwnerRefs: []metav1.OwnerReference{ @@ -383,7 +383,7 @@ func Test_getAppRecursive(t *testing.T) { { name: "cm1->cm2->app1 & cm1->cm3->app1", r: &cache.Resource{ - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm1", }, OwnerRefs: []metav1.OwnerReference{ @@ -393,7 +393,7 @@ func Test_getAppRecursive(t *testing.T) { }, ns: map[kube.ResourceKey]*cache.Resource{ kube.NewResourceKey("", "", "", "cm2"): { - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm2", }, OwnerRefs: []metav1.OwnerReference{ @@ -401,7 +401,7 @@ func Test_getAppRecursive(t *testing.T) { }, }, kube.NewResourceKey("", "", "", "cm3"): { - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm3", }, OwnerRefs: []metav1.OwnerReference{ @@ -422,7 +422,7 @@ func Test_getAppRecursive(t *testing.T) { // Issue #11699, fixed #12667. name: "ok: cm1->cm2 & cm1->cm3->cm2 & cm1->cm3->app1", r: &cache.Resource{ - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm1", }, OwnerRefs: []metav1.OwnerReference{ @@ -432,12 +432,12 @@ func Test_getAppRecursive(t *testing.T) { }, ns: map[kube.ResourceKey]*cache.Resource{ kube.NewResourceKey("", "", "", "cm2"): { - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm2", }, }, kube.NewResourceKey("", "", "", "cm3"): { - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm3", }, OwnerRefs: []metav1.OwnerReference{ @@ -457,7 +457,7 @@ func Test_getAppRecursive(t *testing.T) { { name: "cycle: cm1<->cm2", r: &cache.Resource{ - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm1", }, OwnerRefs: []metav1.OwnerReference{ @@ -466,7 +466,7 @@ func Test_getAppRecursive(t *testing.T) { }, ns: map[kube.ResourceKey]*cache.Resource{ kube.NewResourceKey("", "", "", "cm1"): { - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm1", }, OwnerRefs: []metav1.OwnerReference{ @@ -474,7 +474,7 @@ func Test_getAppRecursive(t *testing.T) { }, }, kube.NewResourceKey("", "", "", "cm2"): { - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm2", }, OwnerRefs: []metav1.OwnerReference{ @@ -488,7 +488,7 @@ func Test_getAppRecursive(t *testing.T) { { name: "cycle: cm1->cm2->cm3->cm1", r: &cache.Resource{ - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm1", }, OwnerRefs: []metav1.OwnerReference{ @@ -497,7 +497,7 @@ func Test_getAppRecursive(t *testing.T) { }, ns: map[kube.ResourceKey]*cache.Resource{ kube.NewResourceKey("", "", "", "cm1"): { - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm1", }, OwnerRefs: []metav1.OwnerReference{ @@ -505,7 +505,7 @@ func Test_getAppRecursive(t *testing.T) { }, }, kube.NewResourceKey("", "", "", "cm2"): { - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm2", }, OwnerRefs: []metav1.OwnerReference{ @@ -513,7 +513,7 @@ func Test_getAppRecursive(t *testing.T) { }, }, kube.NewResourceKey("", "", "", "cm3"): { - Ref: v1.ObjectReference{ + Ref: corev1.ObjectReference{ Name: "cm3", }, OwnerRefs: []metav1.OwnerReference{ diff --git a/controller/cache/info.go b/controller/cache/info.go index 619a07fc9d85a..8dfa6e1c51bd5 100644 --- a/controller/cache/info.go +++ b/controller/cache/info.go @@ -6,12 +6,12 @@ import ( "strconv" "strings" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime/schema" "github.com/argoproj/gitops-engine/pkg/utils/kube" "github.com/argoproj/gitops-engine/pkg/utils/text" "github.com/cespare/xxhash/v2" - v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" resourcehelper "k8s.io/kubectl/pkg/util/resource" @@ -72,18 +72,18 @@ func populateNodeInfo(un *unstructured.Unstructured, res *ResourceInfo, customLa } } -func getIngress(un *unstructured.Unstructured) []v1.LoadBalancerIngress { +func getIngress(un *unstructured.Unstructured) []corev1.LoadBalancerIngress { ingress, ok, err := unstructured.NestedSlice(un.Object, "status", "loadBalancer", "ingress") if !ok || err != nil { return nil } - res := make([]v1.LoadBalancerIngress, 0) + res := make([]corev1.LoadBalancerIngress, 0) for _, item := range ingress { if lbIngress, ok := item.(map[string]any); ok { if hostname := lbIngress["hostname"]; hostname != nil { - res = append(res, v1.LoadBalancerIngress{Hostname: fmt.Sprintf("%s", hostname)}) + res = append(res, corev1.LoadBalancerIngress{Hostname: fmt.Sprintf("%s", hostname)}) } else if ip := lbIngress["ip"]; ip != nil { - res = append(res, v1.LoadBalancerIngress{IP: fmt.Sprintf("%s", ip)}) + res = append(res, corev1.LoadBalancerIngress{IP: fmt.Sprintf("%s", ip)}) } } } @@ -92,8 +92,8 @@ func getIngress(un *unstructured.Unstructured) []v1.LoadBalancerIngress { func populateServiceInfo(un *unstructured.Unstructured, res *ResourceInfo) { targetLabels, _, _ := unstructured.NestedStringMap(un.Object, "spec", "selector") - ingress := make([]v1.LoadBalancerIngress, 0) - if serviceType, ok, err := unstructured.NestedString(un.Object, "spec", "type"); ok && err == nil && serviceType == string(v1.ServiceTypeLoadBalancer) { + ingress := make([]corev1.LoadBalancerIngress, 0) + if serviceType, ok, err := unstructured.NestedString(un.Object, "spec", "type"); ok && err == nil && serviceType == string(corev1.ServiceTypeLoadBalancer) { ingress = getIngress(un) } @@ -296,18 +296,18 @@ func populateIstioServiceEntryInfo(un *unstructured.Unstructured, res *ResourceI } } -func isPodInitializedConditionTrue(status *v1.PodStatus) bool { +func isPodInitializedConditionTrue(status *corev1.PodStatus) bool { for _, condition := range status.Conditions { - if condition.Type != v1.PodInitialized { + if condition.Type != corev1.PodInitialized { continue } - return condition.Status == v1.ConditionTrue + return condition.Status == corev1.ConditionTrue } return false } -func isRestartableInitContainer(initContainer *v1.Container) bool { +func isRestartableInitContainer(initContainer *corev1.Container) bool { if initContainer == nil { return false } @@ -315,15 +315,15 @@ func isRestartableInitContainer(initContainer *v1.Container) bool { return false } - return *initContainer.RestartPolicy == v1.ContainerRestartPolicyAlways + return *initContainer.RestartPolicy == corev1.ContainerRestartPolicyAlways } -func isPodPhaseTerminal(phase v1.PodPhase) bool { - return phase == v1.PodFailed || phase == v1.PodSucceeded +func isPodPhaseTerminal(phase corev1.PodPhase) bool { + return phase == corev1.PodFailed || phase == corev1.PodSucceeded } func populatePodInfo(un *unstructured.Unstructured, res *ResourceInfo) { - pod := v1.Pod{} + pod := corev1.Pod{} err := runtime.DefaultUnstructuredConverter.FromUnstructured(un.Object, &pod) if err != nil { return @@ -353,12 +353,12 @@ func populatePodInfo(un *unstructured.Unstructured, res *ResourceInfo) { // If the Pod carries {type:PodScheduled, reason:SchedulingGated}, set reason to 'SchedulingGated'. for _, condition := range pod.Status.Conditions { - if condition.Type == v1.PodScheduled && condition.Reason == v1.PodReasonSchedulingGated { - reason = v1.PodReasonSchedulingGated + if condition.Type == corev1.PodScheduled && condition.Reason == corev1.PodReasonSchedulingGated { + reason = corev1.PodReasonSchedulingGated } } - initContainers := make(map[string]*v1.Container) + initContainers := make(map[string]*corev1.Container) for i := range pod.Spec.InitContainers { initContainers[pod.Spec.InitContainers[i].Name] = &pod.Spec.InitContainers[i] if isRestartableInitContainer(&pod.Spec.InitContainers[i]) { @@ -463,7 +463,7 @@ func populatePodInfo(un *unstructured.Unstructured, res *ResourceInfo) { } func populateHostNodeInfo(un *unstructured.Unstructured, res *ResourceInfo) { - node := v1.Node{} + node := corev1.Node{} err := runtime.DefaultUnstructuredConverter.FromUnstructured(un.Object, &node) if err != nil { return diff --git a/controller/cache/info_test.go b/controller/cache/info_test.go index 70a3ebeae7f45..9dbb506719333 100644 --- a/controller/cache/info_test.go +++ b/controller/cache/info_test.go @@ -5,13 +5,12 @@ import ( "strings" "testing" - "k8s.io/apimachinery/pkg/api/resource" - "github.com/argoproj/gitops-engine/pkg/utils/kube" "github.com/argoproj/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "sigs.k8s.io/yaml" @@ -310,7 +309,7 @@ func TestGetPodInfo(t *testing.T) { assert.Equal(t, []string{"bar"}, info.Images) assert.Equal(t, &PodInfo{ NodeName: "minikube", - ResourceRequests: v1.ResourceList{v1.ResourceMemory: resource.MustParse("128Mi")}, + ResourceRequests: corev1.ResourceList{corev1.ResourceMemory: resource.MustParse("128Mi")}, }, info.PodInfo) assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{Labels: map[string]string{"app": "guestbook"}}, info.NetworkingInfo) }) @@ -907,8 +906,8 @@ status: populateNodeInfo(node, info, []string{}) assert.Equal(t, &NodeInfo{ Name: "minikube", - Capacity: v1.ResourceList{v1.ResourceMemory: resource.MustParse("6091320Ki"), v1.ResourceCPU: resource.MustParse("6")}, - SystemInfo: v1.NodeSystemInfo{Architecture: "amd64", OperatingSystem: "linux", OSImage: "Ubuntu 20.04 LTS"}, + Capacity: corev1.ResourceList{corev1.ResourceMemory: resource.MustParse("6091320Ki"), corev1.ResourceCPU: resource.MustParse("6")}, + SystemInfo: corev1.NodeSystemInfo{Architecture: "amd64", OperatingSystem: "linux", OSImage: "Ubuntu 20.04 LTS"}, }, info.NodeInfo) } @@ -918,7 +917,7 @@ func TestGetServiceInfo(t *testing.T) { assert.Empty(t, info.Info) assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{ TargetLabels: map[string]string{"app": "guestbook"}, - Ingress: []v1.LoadBalancerIngress{{Hostname: "localhost"}}, + Ingress: []corev1.LoadBalancerIngress{{Hostname: "localhost"}}, }, info.NetworkingInfo) } @@ -928,7 +927,7 @@ func TestGetLinkAnnotatedServiceInfo(t *testing.T) { assert.Empty(t, info.Info) assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{ TargetLabels: map[string]string{"app": "guestbook"}, - Ingress: []v1.LoadBalancerIngress{{Hostname: "localhost"}}, + Ingress: []corev1.LoadBalancerIngress{{Hostname: "localhost"}}, ExternalURLs: []string{"http://my-grafana.example.com/pre-generated-link"}, }, info.NetworkingInfo) } @@ -986,7 +985,7 @@ func TestGetIngressInfo(t *testing.T) { return strings.Compare(info.NetworkingInfo.TargetRefs[j].Name, info.NetworkingInfo.TargetRefs[i].Name) < 0 }) assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{ - Ingress: []v1.LoadBalancerIngress{{IP: "107.178.210.11"}}, + Ingress: []corev1.LoadBalancerIngress{{IP: "107.178.210.11"}}, TargetRefs: []v1alpha1.ResourceRef{{ Namespace: "default", Group: "", @@ -1011,7 +1010,7 @@ func TestGetLinkAnnotatedIngressInfo(t *testing.T) { return strings.Compare(info.NetworkingInfo.TargetRefs[j].Name, info.NetworkingInfo.TargetRefs[i].Name) < 0 }) assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{ - Ingress: []v1.LoadBalancerIngress{{IP: "107.178.210.11"}}, + Ingress: []corev1.LoadBalancerIngress{{IP: "107.178.210.11"}}, TargetRefs: []v1alpha1.ResourceRef{{ Namespace: "default", Group: "", @@ -1035,7 +1034,7 @@ func TestGetIngressInfoWildCardPath(t *testing.T) { return strings.Compare(info.NetworkingInfo.TargetRefs[j].Name, info.NetworkingInfo.TargetRefs[i].Name) < 0 }) assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{ - Ingress: []v1.LoadBalancerIngress{{IP: "107.178.210.11"}}, + Ingress: []corev1.LoadBalancerIngress{{IP: "107.178.210.11"}}, TargetRefs: []v1alpha1.ResourceRef{{ Namespace: "default", Group: "", @@ -1059,7 +1058,7 @@ func TestGetIngressInfoWithoutTls(t *testing.T) { return strings.Compare(info.NetworkingInfo.TargetRefs[j].Name, info.NetworkingInfo.TargetRefs[i].Name) < 0 }) assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{ - Ingress: []v1.LoadBalancerIngress{{IP: "107.178.210.11"}}, + Ingress: []corev1.LoadBalancerIngress{{IP: "107.178.210.11"}}, TargetRefs: []v1alpha1.ResourceRef{{ Namespace: "default", Group: "", @@ -1101,7 +1100,7 @@ func TestGetIngressInfoWithHost(t *testing.T) { populateNodeInfo(ingress, info, []string{}) assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{ - Ingress: []v1.LoadBalancerIngress{{IP: "107.178.210.11"}}, + Ingress: []corev1.LoadBalancerIngress{{IP: "107.178.210.11"}}, TargetRefs: []v1alpha1.ResourceRef{{ Namespace: "default", Group: "", diff --git a/controller/clusterinfoupdater_test.go b/controller/clusterinfoupdater_test.go index 24b6ce6ca7c7f..4467f44b3c4bb 100644 --- a/controller/clusterinfoupdater_test.go +++ b/controller/clusterinfoupdater_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo-cd/v2/common" @@ -44,7 +44,7 @@ func TestClusterSecretUpdater(t *testing.T) { {&now, errors.New("sync failed"), v1alpha1.ConnectionStatusFailed}, } - emptyArgoCDConfigMap := &v1.ConfigMap{ + emptyArgoCDConfigMap := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: fakeNamespace, @@ -54,7 +54,7 @@ func TestClusterSecretUpdater(t *testing.T) { }, Data: map[string]string{}, } - argoCDSecret := &v1.Secret{ + argoCDSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: fakeNamespace, diff --git a/controller/sharding/sharding.go b/controller/sharding/sharding.go index dbd2ec191552e..5634cdea12ddf 100644 --- a/controller/sharding/sharding.go +++ b/controller/sharding/sharding.go @@ -14,7 +14,7 @@ import ( "time" slices "golang.org/x/exp/slices" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -420,8 +420,8 @@ func getOrUpdateShardNumberForController(shardMappingData []shardApplicationCont } // generateDefaultShardMappingCM creates a default shard mapping configMap. Assigns current controller to shard 0. -func generateDefaultShardMappingCM(namespace, hostname string, replicas, shard int) (*v1.ConfigMap, error) { - shardingCM := &v1.ConfigMap{ +func generateDefaultShardMappingCM(namespace, hostname string, replicas, shard int) (*corev1.ConfigMap, error) { + shardingCM := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDAppControllerShardConfigMapName, Namespace: namespace, diff --git a/controller/sharding/sharding_test.go b/controller/sharding/sharding_test.go index 446844b64a33f..3e7311c137b47 100644 --- a/controller/sharding/sharding_test.go +++ b/controller/sharding/sharding_test.go @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" kubefake "k8s.io/client-go/kubernetes/fake" @@ -497,7 +497,7 @@ func Test_generateDefaultShardMappingCM_NoPredefinedShard(t *testing.T) { expectedMappingCM, err := json.Marshal(expectedMapping) require.NoError(t, err) - expectedShadingCM := &v1.ConfigMap{ + expectedShadingCM := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDAppControllerShardConfigMapName, Namespace: "test", @@ -532,7 +532,7 @@ func Test_generateDefaultShardMappingCM_PredefinedShard(t *testing.T) { expectedMappingCM, err := json.Marshal(expectedMapping) require.NoError(t, err) - expectedShadingCM := &v1.ConfigMap{ + expectedShadingCM := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDAppControllerShardConfigMapName, Namespace: "test", diff --git a/controller/state.go b/controller/state.go index f9b8628d89d29..c981bb1cc0c81 100644 --- a/controller/state.go +++ b/controller/state.go @@ -11,7 +11,7 @@ import ( "time" synccommon "github.com/argoproj/gitops-engine/pkg/sync/common" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "github.com/argoproj/gitops-engine/pkg/diff" "github.com/argoproj/gitops-engine/pkg/health" @@ -664,7 +664,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1 // targetNsExists == true implies that it already exists as a target, so no need to add the namespace to the // targetObjs array. if isManagedNamespace(liveObj, app) && !targetNsExists { - nsSpec := &v1.Namespace{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: kubeutil.NamespaceKind}, ObjectMeta: metav1.ObjectMeta{Name: liveObj.GetName()}} + nsSpec := &corev1.Namespace{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: kubeutil.NamespaceKind}, ObjectMeta: metav1.ObjectMeta{Name: liveObj.GetName()}} managedNs, err := kubeutil.ToUnstructured(nsSpec) if err != nil { conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: err.Error(), LastTransitionTime: &now}) diff --git a/hack/dev-mounter/main.go b/hack/dev-mounter/main.go index c53ec4d8b8465..59f5fbb918ee6 100644 --- a/hack/dev-mounter/main.go +++ b/hack/dev-mounter/main.go @@ -12,7 +12,7 @@ import ( "github.com/argoproj/pkg/errors" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/cache" @@ -50,7 +50,7 @@ func newCommand() *cobra.Command { } handledConfigMap := func(obj any) { - cm, ok := obj.(*v1.ConfigMap) + cm, ok := obj.(*corev1.ConfigMap) if !ok { return } diff --git a/hack/gen-catalog/main.go b/hack/gen-catalog/main.go index 962ecc6a7e8c6..decc4a39eda26 100644 --- a/hack/gen-catalog/main.go +++ b/hack/gen-catalog/main.go @@ -9,19 +9,18 @@ import ( "path/filepath" "strings" - "github.com/spf13/cobra/doc" - - "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/admin" - "github.com/argoproj/notifications-engine/pkg/services" "github.com/argoproj/notifications-engine/pkg/triggers" "github.com/argoproj/notifications-engine/pkg/util/misc" "github.com/olekukonko/tablewriter" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" - v1 "k8s.io/api/core/v1" + "github.com/spf13/cobra/doc" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/yaml" + + "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/admin" ) func main() { @@ -44,7 +43,7 @@ func newCatalogCommand() *cobra.Command { return &cobra.Command{ Use: "catalog", Run: func(c *cobra.Command, args []string) { - cm := v1.ConfigMap{ + cm := corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", APIVersion: "v1", diff --git a/hack/gen-resources/generators/cluster_generator.go b/hack/gen-resources/generators/cluster_generator.go index 044bdcaa2f0fc..56f912ae1532d 100644 --- a/hack/gen-resources/generators/cluster_generator.go +++ b/hack/gen-resources/generators/cluster_generator.go @@ -10,7 +10,7 @@ import ( "time" "gopkg.in/yaml.v2" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" @@ -72,7 +72,7 @@ func (cg *ClusterGenerator) getClusterCredentials(namespace string, releaseSuffi } var stdout, stderr, stdin bytes.Buffer - option := &v1.PodExecOptions{ + option := &corev1.PodExecOptions{ Command: cmd, Container: "syncer", Stdin: true, diff --git a/hack/gen-resources/generators/repo_generator.go b/hack/gen-resources/generators/repo_generator.go index 09d16f27e8be3..815dfce99b8ec 100644 --- a/hack/gen-resources/generators/repo_generator.go +++ b/hack/gen-resources/generators/repo_generator.go @@ -9,7 +9,7 @@ import ( "log" "net/http" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo-cd/v2/hack/gen-resources/util" @@ -88,7 +88,7 @@ func (rg *RepoGenerator) Generate(opts *util.GenerateOpts) error { secrets := rg.clientSet.CoreV1().Secrets(opts.Namespace) rg.bar.NewOption(0, int64(len(repos))) for _, repo := range repos { - _, err = secrets.Create(context.TODO(), &v1.Secret{ + _, err = secrets.Create(context.TODO(), &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "repo-", Namespace: opts.Namespace, diff --git a/pkg/apis/application/v1alpha1/types.go b/pkg/apis/application/v1alpha1/types.go index 8aa6f92605d0f..ce731d88b6d8f 100644 --- a/pkg/apis/application/v1alpha1/types.go +++ b/pkg/apis/application/v1alpha1/types.go @@ -26,7 +26,7 @@ import ( log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" @@ -1790,29 +1790,29 @@ type InfoItem struct { // ResourceNetworkingInfo holds networking resource related information // TODO: describe members of this type type ResourceNetworkingInfo struct { - TargetLabels map[string]string `json:"targetLabels,omitempty" protobuf:"bytes,1,opt,name=targetLabels"` - TargetRefs []ResourceRef `json:"targetRefs,omitempty" protobuf:"bytes,2,opt,name=targetRefs"` - Labels map[string]string `json:"labels,omitempty" protobuf:"bytes,3,opt,name=labels"` - Ingress []v1.LoadBalancerIngress `json:"ingress,omitempty" protobuf:"bytes,4,opt,name=ingress"` + TargetLabels map[string]string `json:"targetLabels,omitempty" protobuf:"bytes,1,opt,name=targetLabels"` + TargetRefs []ResourceRef `json:"targetRefs,omitempty" protobuf:"bytes,2,opt,name=targetRefs"` + Labels map[string]string `json:"labels,omitempty" protobuf:"bytes,3,opt,name=labels"` + Ingress []corev1.LoadBalancerIngress `json:"ingress,omitempty" protobuf:"bytes,4,opt,name=ingress"` // ExternalURLs holds list of URLs which should be available externally. List is populated for ingress resources using rules hostnames. ExternalURLs []string `json:"externalURLs,omitempty" protobuf:"bytes,5,opt,name=externalURLs"` } // TODO: describe this type type HostResourceInfo struct { - ResourceName v1.ResourceName `json:"resourceName,omitempty" protobuf:"bytes,1,name=resourceName"` - RequestedByApp int64 `json:"requestedByApp,omitempty" protobuf:"bytes,2,name=requestedByApp"` - RequestedByNeighbors int64 `json:"requestedByNeighbors,omitempty" protobuf:"bytes,3,name=requestedByNeighbors"` - Capacity int64 `json:"capacity,omitempty" protobuf:"bytes,4,name=capacity"` + ResourceName corev1.ResourceName `json:"resourceName,omitempty" protobuf:"bytes,1,name=resourceName"` + RequestedByApp int64 `json:"requestedByApp,omitempty" protobuf:"bytes,2,name=requestedByApp"` + RequestedByNeighbors int64 `json:"requestedByNeighbors,omitempty" protobuf:"bytes,3,name=requestedByNeighbors"` + Capacity int64 `json:"capacity,omitempty" protobuf:"bytes,4,name=capacity"` } // HostInfo holds host name and resources metrics // TODO: describe purpose of this type // TODO: describe members of this type type HostInfo struct { - Name string `json:"name,omitempty" protobuf:"bytes,1,name=name"` - ResourcesInfo []HostResourceInfo `json:"resourcesInfo,omitempty" protobuf:"bytes,2,name=resourcesInfo"` - SystemInfo v1.NodeSystemInfo `json:"systemInfo,omitempty" protobuf:"bytes,3,opt,name=systemInfo"` + Name string `json:"name,omitempty" protobuf:"bytes,1,name=name"` + ResourcesInfo []HostResourceInfo `json:"resourcesInfo,omitempty" protobuf:"bytes,2,name=resourcesInfo"` + SystemInfo corev1.NodeSystemInfo `json:"systemInfo,omitempty" protobuf:"bytes,3,opt,name=systemInfo"` } // ApplicationTree holds nodes which belongs to the application diff --git a/server/account/account_test.go b/server/account/account_test.go index 81dd6d7ea7e04..3028171cd3289 100644 --- a/server/account/account_test.go +++ b/server/account/account_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" @@ -31,16 +31,16 @@ const ( ) // return an AccountServer which returns fake data -func newTestAccountServer(ctx context.Context, opts ...func(cm *v1.ConfigMap, secret *v1.Secret)) (*Server, *session.Server) { +func newTestAccountServer(ctx context.Context, opts ...func(cm *corev1.ConfigMap, secret *corev1.Secret)) (*Server, *session.Server) { return newTestAccountServerExt(ctx, func(claims jwt.Claims, rvals ...any) bool { return true }, opts...) } -func newTestAccountServerExt(ctx context.Context, enforceFn rbac.ClaimsEnforcerFunc, opts ...func(cm *v1.ConfigMap, secret *v1.Secret)) (*Server, *session.Server) { +func newTestAccountServerExt(ctx context.Context, enforceFn rbac.ClaimsEnforcerFunc, opts ...func(cm *corev1.ConfigMap, secret *corev1.Secret)) (*Server, *session.Server) { bcrypt, err := password.HashPassword("oldpassword") errors.CheckError(err) - cm := &v1.ConfigMap{ + cm := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-cm", Namespace: testNamespace, @@ -50,7 +50,7 @@ func newTestAccountServerExt(ctx context.Context, enforceFn rbac.ClaimsEnforcerF }, Data: map[string]string{}, } - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: testNamespace, @@ -140,7 +140,7 @@ func TestUpdatePassword(t *testing.T) { } func TestUpdatePassword_AdminUpdatesAnotherUser(t *testing.T) { - accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := adminContext(context.Background()) @@ -158,7 +158,7 @@ func TestUpdatePassword_DoesNotHavePermissions(t *testing.T) { } t.Run("LocalAccountUpdatesAnotherAccount", func(t *testing.T) { - accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := adminContext(context.Background()) @@ -175,7 +175,7 @@ func TestUpdatePassword_DoesNotHavePermissions(t *testing.T) { } func TestUpdatePassword_ProjectToken(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := projTokenContext(context.Background()) @@ -184,7 +184,7 @@ func TestUpdatePassword_ProjectToken(t *testing.T) { } func TestUpdatePassword_OldSSOToken(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := ssoAdminContext(context.Background(), time.Now().Add(-2*common.ChangePasswordSSOTokenMaxAge)) @@ -194,7 +194,7 @@ func TestUpdatePassword_OldSSOToken(t *testing.T) { } func TestUpdatePassword_SSOUserUpdatesAnotherUser(t *testing.T) { - accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := ssoAdminContext(context.Background(), time.Now()) @@ -217,7 +217,7 @@ func TestListAccounts_NoAccountsConfigured(t *testing.T) { func TestListAccounts_AccountsAreConfigured(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" cm.Data["accounts.account2"] = "login, apiKey" cm.Data["accounts.account2.enabled"] = "false" @@ -235,7 +235,7 @@ func TestListAccounts_AccountsAreConfigured(t *testing.T) { func TestGetAccount(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" }) @@ -255,7 +255,7 @@ func TestGetAccount(t *testing.T) { func TestCreateToken_SuccessfullyCreated(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" }) @@ -270,7 +270,7 @@ func TestCreateToken_SuccessfullyCreated(t *testing.T) { func TestCreateToken_DoesNotHaveCapability(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["accounts.account1"] = "login" }) @@ -280,7 +280,7 @@ func TestCreateToken_DoesNotHaveCapability(t *testing.T) { func TestCreateToken_UserSpecifiedID(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" }) @@ -294,7 +294,7 @@ func TestCreateToken_UserSpecifiedID(t *testing.T) { func TestDeleteToken_SuccessfullyRemoved(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" secret.Data["accounts.account1.tokens"] = []byte(`[{"id":"123","iat":1583789194,"exp":1583789194}]`) }) @@ -309,7 +309,7 @@ func TestDeleteToken_SuccessfullyRemoved(t *testing.T) { } func TestCanI_GetLogsAllowNoSwitch(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { }) ctx := projTokenContext(context.Background()) @@ -323,7 +323,7 @@ func TestCanI_GetLogsDenySwitchOn(t *testing.T) { return false } - accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["server.rbac.log.enforce.enable"] = "true" }) @@ -334,7 +334,7 @@ func TestCanI_GetLogsDenySwitchOn(t *testing.T) { } func TestCanI_GetLogsAllowSwitchOn(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["server.rbac.log.enforce.enable"] = "true" }) @@ -345,7 +345,7 @@ func TestCanI_GetLogsAllowSwitchOn(t *testing.T) { } func TestCanI_GetLogsAllowSwitchOff(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *v1.ConfigMap, secret *v1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { cm.Data["server.rbac.log.enforce.enable"] = "false" }) diff --git a/server/application/application.go b/server/application/application.go index 915aff1080e74..46ffe686a2075 100644 --- a/server/application/application.go +++ b/server/application/application.go @@ -22,7 +22,7 @@ import ( log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -811,7 +811,7 @@ func (s *Server) Get(ctx context.Context, q *application.ApplicationQuery) (*app } // ListResourceEvents returns a list of event resources -func (s *Server) ListResourceEvents(ctx context.Context, q *application.ApplicationResourceEventsQuery) (*v1.EventList, error) { +func (s *Server) ListResourceEvents(ctx context.Context, q *application.ApplicationResourceEventsQuery) (*corev1.EventList, error) { a, _, err := s.getApplicationEnforceRBACInformer(ctx, rbacpolicy.ActionGet, q.GetProject(), q.GetAppNamespace(), q.GetName()) if err != nil { return nil, err @@ -1762,7 +1762,7 @@ func (s *Server) PodLogs(q *application.ApplicationPodLogsQuery, ws application. var streams []chan logEntry for _, pod := range pods { - stream, err := kubeClientset.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &v1.PodLogOptions{ + stream, err := kubeClientset.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &corev1.PodLogOptions{ Container: q.GetContainer(), Follow: q.GetFollow(), Timestamps: true, @@ -2325,7 +2325,7 @@ func (s *Server) TerminateOperation(ctx context.Context, termOpReq *application. } func (s *Server) logAppEvent(a *appv1.Application, ctx context.Context, reason string, action string) { - eventInfo := argo.EventInfo{Type: v1.EventTypeNormal, Reason: reason} + eventInfo := argo.EventInfo{Type: corev1.EventTypeNormal, Reason: reason} user := session.Username(ctx) if user == "" { user = "Unknown user" @@ -2336,7 +2336,7 @@ func (s *Server) logAppEvent(a *appv1.Application, ctx context.Context, reason s } func (s *Server) logResourceEvent(res *appv1.ResourceNode, ctx context.Context, reason string, action string) { - eventInfo := argo.EventInfo{Type: v1.EventTypeNormal, Reason: reason} + eventInfo := argo.EventInfo{Type: corev1.EventTypeNormal, Reason: reason} user := session.Username(ctx) if user == "" { user = "Unknown user" diff --git a/server/application/application_test.go b/server/application/application_test.go index 12d8991205ce4..7633035fc69d3 100644 --- a/server/application/application_test.go +++ b/server/application/application_test.go @@ -27,7 +27,6 @@ import ( k8sappsv1 "k8s.io/api/apps/v1" k8sbatchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" @@ -169,7 +168,7 @@ func newTestAppServer(t *testing.T, objects ...runtime.Object) *Server { func newTestAppServerWithEnforcerConfigure(t *testing.T, f func(*rbac.Enforcer), additionalConfig map[string]string, objects ...runtime.Object) *Server { t.Helper() - kubeclientset := fake.NewClientset(&v1.ConfigMap{ + kubeclientset := fake.NewClientset(&corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: testNamespace, Name: "argocd-cm", @@ -178,7 +177,7 @@ func newTestAppServerWithEnforcerConfigure(t *testing.T, f func(*rbac.Enforcer), }, }, Data: additionalConfig, - }, &v1.Secret{ + }, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: testNamespace, @@ -334,7 +333,7 @@ func newTestAppServerWithBenchmark(b *testing.B, objects ...runtime.Object) *Ser func newTestAppServerWithEnforcerConfigureWithBenchmark(b *testing.B, f func(*rbac.Enforcer), objects ...runtime.Object) *Server { b.Helper() - kubeclientset := fake.NewClientset(&v1.ConfigMap{ + kubeclientset := fake.NewClientset(&corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: testNamespace, Name: "argocd-cm", @@ -342,7 +341,7 @@ func newTestAppServerWithEnforcerConfigureWithBenchmark(b *testing.B, f func(*rb "app.kubernetes.io/part-of": "argocd", }, }, - }, &v1.Secret{ + }, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: testNamespace, @@ -2226,7 +2225,7 @@ func createAppServerWithMaxLodLogs(t *testing.T, podNumber int, maxPodLogsToRend resources := make([]appsv1.ResourceStatus, podNumber) for i := 0; i < podNumber; i++ { - pod := v1.Pod{ + pod := corev1.Pod{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", Kind: "Pod", diff --git a/server/application/terminal.go b/server/application/terminal.go index 46884ce2ffa5e..814ea3ad15b8a 100644 --- a/server/application/terminal.go +++ b/server/application/terminal.go @@ -8,7 +8,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/utils/kube" log "github.com/sirupsen/logrus" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -216,7 +216,7 @@ func (s *terminalHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - if pod.Status.Phase != v1.PodRunning { + if pod.Status.Phase != corev1.PodRunning { http.Error(w, "Pod not running", http.StatusBadRequest) return } @@ -309,7 +309,7 @@ func startProcess(k8sClient kubernetes.Interface, cfg *rest.Config, namespace, p Namespace(namespace). SubResource("exec") - req.VersionedParams(&v1.PodExecOptions{ + req.VersionedParams(&corev1.PodExecOptions{ Container: containerName, Command: cmd, Stdin: true, diff --git a/server/application/websocket_test.go b/server/application/websocket_test.go index b38f84fb7a7a2..ab5011569bec0 100644 --- a/server/application/websocket_test.go +++ b/server/application/websocket_test.go @@ -8,7 +8,7 @@ import ( "strings" "testing" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" @@ -34,7 +34,7 @@ func newTestTerminalSession(w http.ResponseWriter, r *http.Request) terminalSess func newEnforcer() *rbac.Enforcer { additionalConfig := make(map[string]string, 0) - kubeclientset := fake.NewClientset(&v1.ConfigMap{ + kubeclientset := fake.NewClientset(&corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: testNamespace, Name: "argocd-cm", @@ -43,7 +43,7 @@ func newEnforcer() *rbac.Enforcer { }, }, Data: additionalConfig, - }, &v1.Secret{ + }, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: testNamespace, diff --git a/server/applicationset/applicationset.go b/server/applicationset/applicationset.go index 9807c515bc0ab..49e0a42fb9e05 100644 --- a/server/applicationset/applicationset.go +++ b/server/applicationset/applicationset.go @@ -15,7 +15,7 @@ import ( log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" @@ -496,7 +496,7 @@ func (s *Server) waitSync(appset *v1alpha1.ApplicationSet) { } func (s *Server) logAppSetEvent(a *v1alpha1.ApplicationSet, ctx context.Context, reason string, action string) { - eventInfo := argo.EventInfo{Type: v1.EventTypeNormal, Reason: reason} + eventInfo := argo.EventInfo{Type: corev1.EventTypeNormal, Reason: reason} user := session.Username(ctx) if user == "" { user = "Unknown user" diff --git a/server/applicationset/applicationset_test.go b/server/applicationset/applicationset_test.go index 8f16d415dec13..05c614eb45bd3 100644 --- a/server/applicationset/applicationset_test.go +++ b/server/applicationset/applicationset_test.go @@ -9,7 +9,7 @@ import ( "github.com/argoproj/pkg/sync" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -72,7 +72,7 @@ func newTestNamespacedAppSetServer(objects ...runtime.Object) *Server { } func newTestAppSetServerWithEnforcerConfigure(f func(*rbac.Enforcer), namespace string, objects ...runtime.Object) *Server { - kubeclientset := fake.NewClientset(&v1.ConfigMap{ + kubeclientset := fake.NewClientset(&corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: testNamespace, Name: "argocd-cm", @@ -80,7 +80,7 @@ func newTestAppSetServerWithEnforcerConfigure(f func(*rbac.Enforcer), namespace "app.kubernetes.io/part-of": "argocd", }, }, - }, &v1.Secret{ + }, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: testNamespace, diff --git a/server/deeplinks/deeplinks_test.go b/server/deeplinks/deeplinks_test.go index 217b8b93b7dbe..a01fe6900ddcf 100644 --- a/server/deeplinks/deeplinks_test.go +++ b/server/deeplinks/deeplinks_test.go @@ -8,7 +8,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/utils/kube" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/utils/ptr" @@ -43,7 +43,7 @@ func TestDeepLinks(t *testing.T) { }, }) require.NoError(t, err) - resourceObj, err := kube.ToUnstructured(&v1.ConfigMap{ + resourceObj, err := kube.ToUnstructured(&corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cm", Namespace: "test-cm", diff --git a/server/project/project.go b/server/project/project.go index 9a057fda008da..92c61d5dabb51 100644 --- a/server/project/project.go +++ b/server/project/project.go @@ -13,7 +13,7 @@ import ( log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" @@ -476,7 +476,7 @@ func (s *Server) Delete(ctx context.Context, q *project.ProjectQuery) (*project. return &project.EmptyResponse{}, err } -func (s *Server) ListEvents(ctx context.Context, q *project.ProjectQuery) (*v1.EventList, error) { +func (s *Server) ListEvents(ctx context.Context, q *project.ProjectQuery) (*corev1.EventList, error) { if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionGet, q.Name); err != nil { return nil, err } @@ -493,7 +493,7 @@ func (s *Server) ListEvents(ctx context.Context, q *project.ProjectQuery) (*v1.E } func (s *Server) logEvent(a *v1alpha1.AppProject, ctx context.Context, reason string, action string) { - eventInfo := argo.EventInfo{Type: v1.EventTypeNormal, Reason: reason} + eventInfo := argo.EventInfo{Type: corev1.EventTypeNormal, Reason: reason} user := session.Username(ctx) if user == "" { user = "Unknown user" diff --git a/server/server.go b/server/server.go index 5e6769deeb1f1..c3ef5ef0ea5c4 100644 --- a/server/server.go +++ b/server/server.go @@ -28,6 +28,7 @@ import ( // nolint:staticcheck golang_proto "github.com/golang/protobuf/proto" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" @@ -54,7 +55,6 @@ import ( "google.golang.org/grpc/reflection" "google.golang.org/grpc/status" "gopkg.in/yaml.v2" - v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" @@ -862,7 +862,7 @@ func (a *ArgoCDServer) watchSettings() { } func (a *ArgoCDServer) rbacPolicyLoader(ctx context.Context) { - err := a.enf.RunPolicyLoader(ctx, func(cm *v1.ConfigMap) error { + err := a.enf.RunPolicyLoader(ctx, func(cm *corev1.ConfigMap) error { var scopes []string if scopesStr, ok := cm.Data[rbac.ConfigMapScopesKey]; len(scopesStr) > 0 && ok { scopes = make([]string, 0) diff --git a/test/e2e/app_management_ns_test.go b/test/e2e/app_management_ns_test.go index 217d7e8559e57..f1cb7117dd98c 100644 --- a/test/e2e/app_management_ns_test.go +++ b/test/e2e/app_management_ns_test.go @@ -17,7 +17,7 @@ import ( log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -1488,7 +1488,7 @@ func TestNamespacedOrphanedResource(t *testing.T) { Expect(NoConditions()). When(). And(func() { - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "orphaned-configmap", }, @@ -1601,15 +1601,15 @@ func TestNamespacedNotPermittedResources(t *testing.T) { CheckError(KubeClientset.NetworkingV1().Ingresses(TestNamespace()).Delete(context.Background(), "sample-ingress", metav1.DeleteOptions{})) }() - svc := &v1.Service{ + svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "guestbook-ui", Annotations: map[string]string{ common.AnnotationKeyAppInstance: fmt.Sprintf("%s_%s:Service:%s/guesbook-ui", TestNamespace(), ctx.AppQualifiedName(), DeploymentNamespace()), }, }, - Spec: v1.ServiceSpec{ - Ports: []v1.ServicePort{{ + Spec: corev1.ServiceSpec{ + Ports: []corev1.ServicePort{{ Port: 80, TargetPort: intstr.IntOrString{Type: intstr.Int, IntVal: 80}, }}, @@ -1773,7 +1773,7 @@ func TestNamespacedListResource(t *testing.T) { Expect(NoConditions()). When(). And(func() { - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "orphaned-configmap", }, @@ -1898,7 +1898,7 @@ func TestNamespacedNamespaceAutoCreationWithMetadata(t *testing.T) { Sync(). Then(). Expect(Success("")). - Expect(Namespace(updatedNamespace, func(app *Application, ns *v1.Namespace) { + Expect(Namespace(updatedNamespace, func(app *Application, ns *corev1.Namespace) { assert.Empty(t, app.Status.Conditions) delete(ns.Labels, "kubernetes.io/metadata.name") @@ -1922,7 +1922,7 @@ func TestNamespacedNamespaceAutoCreationWithMetadata(t *testing.T) { Sync(). Then(). Expect(Success("")). - Expect(Namespace(updatedNamespace, func(app *Application, ns *v1.Namespace) { + Expect(Namespace(updatedNamespace, func(app *Application, ns *corev1.Namespace) { delete(ns.Labels, "kubernetes.io/metadata.name") delete(ns.Labels, "argocd.argoproj.io/tracking-id") delete(ns.Annotations, "kubectl.kubernetes.io/last-applied-configuration") @@ -1941,7 +1941,7 @@ func TestNamespacedNamespaceAutoCreationWithMetadata(t *testing.T) { Sync(). Then(). Expect(Success("")). - Expect(Namespace(updatedNamespace, func(app *Application, ns *v1.Namespace) { + Expect(Namespace(updatedNamespace, func(app *Application, ns *corev1.Namespace) { delete(ns.Labels, "kubernetes.io/metadata.name") delete(ns.Labels, "argocd.argoproj.io/tracking-id") delete(ns.Annotations, "argocd.argoproj.io/tracking-id") @@ -1992,7 +1992,7 @@ func TestNamespacedNamespaceAutoCreationWithMetadataAndNsManifest(t *testing.T) Sync(). Then(). Expect(Success("")). - Expect(Namespace(namespace, func(app *Application, ns *v1.Namespace) { + Expect(Namespace(namespace, func(app *Application, ns *corev1.Namespace) { delete(ns.Labels, "kubernetes.io/metadata.name") delete(ns.Labels, "argocd.argoproj.io/tracking-id") delete(ns.Labels, "kubectl.kubernetes.io/last-applied-configuration") @@ -2060,7 +2060,7 @@ metadata: } }). Then(). - Expect(Namespace(updatedNamespace, func(app *Application, ns *v1.Namespace) { + Expect(Namespace(updatedNamespace, func(app *Application, ns *corev1.Namespace) { assert.Empty(t, app.Status.Conditions) delete(ns.Labels, "kubernetes.io/metadata.name") @@ -2074,7 +2074,7 @@ metadata: Sync(). Then(). Expect(Success("")). - Expect(Namespace(updatedNamespace, func(app *Application, ns *v1.Namespace) { + Expect(Namespace(updatedNamespace, func(app *Application, ns *corev1.Namespace) { assert.Empty(t, app.Status.Conditions) delete(ns.Labels, "kubernetes.io/metadata.name") @@ -2093,7 +2093,7 @@ metadata: Sync(). Then(). Expect(Success("")). - Expect(Namespace(updatedNamespace, func(app *Application, ns *v1.Namespace) { + Expect(Namespace(updatedNamespace, func(app *Application, ns *corev1.Namespace) { assert.Empty(t, app.Status.Conditions) delete(ns.Labels, "kubernetes.io/metadata.name") @@ -2113,7 +2113,7 @@ metadata: Sync(). Then(). Expect(Success("")). - Expect(Namespace(updatedNamespace, func(app *Application, ns *v1.Namespace) { + Expect(Namespace(updatedNamespace, func(app *Application, ns *corev1.Namespace) { assert.Empty(t, app.Status.Conditions) delete(ns.Labels, "kubernetes.io/metadata.name") diff --git a/test/e2e/app_management_test.go b/test/e2e/app_management_test.go index db4272b823bc0..31137af8d54a1 100644 --- a/test/e2e/app_management_test.go +++ b/test/e2e/app_management_test.go @@ -15,7 +15,7 @@ import ( log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" rbacv1 "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -774,7 +774,7 @@ func assetSecretDataHidden(t *testing.T, manifest string) { var lastAppliedConfigAnnotation string annotations := secret.GetAnnotations() if annotations != nil { - lastAppliedConfigAnnotation = annotations[v1.LastAppliedConfigAnnotation] + lastAppliedConfigAnnotation = annotations[corev1.LastAppliedConfigAnnotation] } if lastAppliedConfigAnnotation != "" { assetSecretDataHidden(t, lastAppliedConfigAnnotation) @@ -1908,7 +1908,7 @@ func TestOrphanedResource(t *testing.T) { Expect(NoConditions()). When(). And(func() { - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "orphaned-configmap", }, @@ -2017,15 +2017,15 @@ func TestNotPermittedResources(t *testing.T) { CheckError(KubeClientset.NetworkingV1().Ingresses(TestNamespace()).Delete(context.Background(), "sample-ingress", metav1.DeleteOptions{})) }() - svc := &v1.Service{ + svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "guestbook-ui", Labels: map[string]string{ common.LabelKeyAppInstance: ctx.GetName(), }, }, - Spec: v1.ServiceSpec{ - Ports: []v1.ServicePort{{ + Spec: corev1.ServiceSpec{ + Ports: []corev1.ServicePort{{ Port: 80, TargetPort: intstr.IntOrString{Type: intstr.Int, IntVal: 80}, }}, @@ -2177,7 +2177,7 @@ func TestListResource(t *testing.T) { Expect(NoConditions()). When(). And(func() { - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "orphaned-configmap", }, @@ -2587,7 +2587,7 @@ func TestSwitchTrackingMethod(t *testing.T) { And(func() { // Add resource with tracking annotation. This should put the // application OutOfSync. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Annotations: map[string]string{ @@ -2621,7 +2621,7 @@ func TestSwitchTrackingMethod(t *testing.T) { // Add a resource with a tracking annotation. This should not // affect the application, because we now use the tracking method // "label". - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Annotations: map[string]string{ @@ -2638,7 +2638,7 @@ func TestSwitchTrackingMethod(t *testing.T) { And(func() { // Add a resource with the tracking label. The app should become // OutOfSync. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "extra-configmap", Labels: map[string]string{ @@ -2679,7 +2679,7 @@ func TestSwitchTrackingLabel(t *testing.T) { And(func() { // Add extra resource that carries the default tracking label // We expect the app to go out of sync. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Labels: map[string]string{ @@ -2713,7 +2713,7 @@ func TestSwitchTrackingLabel(t *testing.T) { And(func() { // Create resource with the new tracking label, the application // is expected to go out of sync - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Labels: map[string]string{ @@ -2740,7 +2740,7 @@ func TestSwitchTrackingLabel(t *testing.T) { // Add extra resource that carries the default tracking label // We expect the app to stay in sync, because the configured // label is different. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Labels: map[string]string{ @@ -2773,7 +2773,7 @@ func TestAnnotationTrackingExtraResources(t *testing.T) { And(func() { // Add a resource with an annotation that is not referencing the // resource. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "extra-configmap", Annotations: map[string]string{ @@ -2798,7 +2798,7 @@ func TestAnnotationTrackingExtraResources(t *testing.T) { And(func() { // Add a resource with an annotation that is self-referencing the // resource. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &v1.ConfigMap{ + FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Annotations: map[string]string{ @@ -2927,7 +2927,7 @@ func TestInstallationID(t *testing.T) { SetTrackingMethod(string(argo.TrackingMethodAnnotation)). And(func() { _, err := fixture.KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create( - context.Background(), &v1.ConfigMap{ + context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "test-configmap", Annotations: map[string]string{ @@ -2972,7 +2972,7 @@ func TestDeletionConfirmation(t *testing.T) { ctx. And(func() { _, err := fixture.KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create( - context.Background(), &v1.ConfigMap{ + context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "test-configmap", Labels: map[string]string{ diff --git a/test/e2e/app_sync_options_test.go b/test/e2e/app_sync_options_test.go index 7d0a0ffeabb99..96dde8804e2d7 100644 --- a/test/e2e/app_sync_options_test.go +++ b/test/e2e/app_sync_options_test.go @@ -6,7 +6,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/health" . "github.com/argoproj/gitops-engine/pkg/sync/common" "github.com/stretchr/testify/assert" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture" @@ -48,7 +48,7 @@ func TestNamespaceCreationWithSSA(t *testing.T) { Sync(). Then(). Expect(Success("")). - Expect(Namespace(namespace, func(app *Application, ns *v1.Namespace) { + Expect(Namespace(namespace, func(app *Application, ns *corev1.Namespace) { assert.NotContains(t, ns.Annotations, "kubectl.kubernetes.io/last-applied-configuration") })). Expect(SyncStatusIs(SyncStatusCodeSynced)). diff --git a/test/e2e/fixture/app/expectation.go b/test/e2e/fixture/app/expectation.go index 06b547aade3fd..9e66f2d6b711b 100644 --- a/test/e2e/fixture/app/expectation.go +++ b/test/e2e/fixture/app/expectation.go @@ -9,7 +9,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/health" . "github.com/argoproj/gitops-engine/pkg/sync/common" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" @@ -108,7 +108,7 @@ func StatusExists() Expectation { } } -func Namespace(name string, block func(app *Application, ns *v1.Namespace)) Expectation { +func Namespace(name string, block func(app *Application, ns *corev1.Namespace)) Expectation { return func(c *Consequences) (state, string) { ns, err := namespace(name) if err != nil { @@ -245,7 +245,7 @@ func DoesNotExistNow() Expectation { } } -func Pod(predicate func(p v1.Pod) bool) Expectation { +func Pod(predicate func(p corev1.Pod) bool) Expectation { return func(c *Consequences) (state, string) { pods, err := pods() if err != nil { @@ -260,7 +260,7 @@ func Pod(predicate func(p v1.Pod) bool) Expectation { } } -func NotPod(predicate func(p v1.Pod) bool) Expectation { +func NotPod(predicate func(p corev1.Pod) bool) Expectation { return func(c *Consequences) (state, string) { pods, err := pods() if err != nil { @@ -275,7 +275,7 @@ func NotPod(predicate func(p v1.Pod) bool) Expectation { } } -func pods() (*v1.PodList, error) { +func pods() (*corev1.PodList, error) { fixture.KubeClientset.CoreV1() pods, err := fixture.KubeClientset.CoreV1().Pods(fixture.DeploymentNamespace()).List(context.Background(), metav1.ListOptions{}) return pods, err @@ -292,7 +292,7 @@ func NoNamespace(name string) Expectation { } } -func namespace(name string) (*v1.Namespace, error) { +func namespace(name string) (*corev1.Namespace, error) { fixture.KubeClientset.CoreV1() return fixture.KubeClientset.CoreV1().Namespaces().Get(context.Background(), name, metav1.GetOptions{}) } diff --git a/test/e2e/git_submodule_test.go b/test/e2e/git_submodule_test.go index 525c13d4b35ef..73329d12234e8 100644 --- a/test/e2e/git_submodule_test.go +++ b/test/e2e/git_submodule_test.go @@ -3,11 +3,10 @@ package e2e import ( "testing" - v1 "k8s.io/api/core/v1" - - "github.com/argoproj/argo-cd/v2/test/e2e/fixture" + corev1 "k8s.io/api/core/v1" . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" + "github.com/argoproj/argo-cd/v2/test/e2e/fixture" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/app" ) @@ -23,7 +22,7 @@ func TestGitSubmoduleSSHSupport(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - Expect(Pod(func(p v1.Pod) bool { return p.Name == "pod-in-submodule" })) + Expect(Pod(func(p corev1.Pod) bool { return p.Name == "pod-in-submodule" })) } func TestGitSubmoduleHTTPSSupport(t *testing.T) { @@ -38,7 +37,7 @@ func TestGitSubmoduleHTTPSSupport(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - Expect(Pod(func(p v1.Pod) bool { return p.Name == "pod-in-submodule" })) + Expect(Pod(func(p corev1.Pod) bool { return p.Name == "pod-in-submodule" })) } func TestGitSubmoduleRemovalSupport(t *testing.T) { @@ -53,12 +52,12 @@ func TestGitSubmoduleRemovalSupport(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - Expect(Pod(func(p v1.Pod) bool { return p.Name == "pod-in-submodule" })). + Expect(Pod(func(p corev1.Pod) bool { return p.Name == "pod-in-submodule" })). When(). RemoveSubmodule(). Refresh(RefreshTypeNormal). Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - Expect(NotPod(func(p v1.Pod) bool { return p.Name == "pod-in-submodule" })) + Expect(NotPod(func(p corev1.Pod) bool { return p.Name == "pod-in-submodule" })) } diff --git a/test/e2e/git_test.go b/test/e2e/git_test.go index 7c92274dab56a..ef7bebb3cc43d 100644 --- a/test/e2e/git_test.go +++ b/test/e2e/git_test.go @@ -4,11 +4,10 @@ import ( "strings" "testing" - v1 "k8s.io/api/core/v1" - - "github.com/argoproj/argo-cd/v2/test/e2e/fixture" + corev1 "k8s.io/api/core/v1" . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" + "github.com/argoproj/argo-cd/v2/test/e2e/fixture" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/app" ) @@ -64,7 +63,7 @@ func TestGitSemverResolutionUsingConstraint(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - Expect(Pod(func(p v1.Pod) bool { return strings.HasPrefix(p.Name, "new-app") })) + Expect(Pod(func(p corev1.Pod) bool { return strings.HasPrefix(p.Name, "new-app") })) } func TestGitSemverResolutionUsingConstraintWithLeadingZero(t *testing.T) { @@ -89,5 +88,5 @@ func TestGitSemverResolutionUsingConstraintWithLeadingZero(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - Expect(Pod(func(p v1.Pod) bool { return strings.HasPrefix(p.Name, "new-app") })) + Expect(Pod(func(p corev1.Pod) bool { return strings.HasPrefix(p.Name, "new-app") })) } diff --git a/test/e2e/helm_test.go b/test/e2e/helm_test.go index 858626b4246ac..b507836841add 100644 --- a/test/e2e/helm_test.go +++ b/test/e2e/helm_test.go @@ -12,7 +12,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/health" . "github.com/argoproj/gitops-engine/pkg/sync/common" "github.com/stretchr/testify/assert" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -69,7 +69,7 @@ func TestHelmHookDeletePolicy(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(ResourceResultNumbering(2)). - Expect(NotPod(func(p v1.Pod) bool { return p.Name == "hook" })) + Expect(NotPod(func(p corev1.Pod) bool { return p.Name == "hook" })) } func TestDeclarativeHelm(t *testing.T) { @@ -522,10 +522,10 @@ func testHelmWithDependencies(t *testing.T, chartPath string, legacyRepo bool) { CheckError(fixture.SetHelmRepos(settings.HelmRepoCredentials{ URL: RepoURL(RepoURLTypeHelm), Name: "custom-repo", - KeySecret: &v1.SecretKeySelector{LocalObjectReference: v1.LocalObjectReference{Name: "helm-repo"}, Key: "keySecret"}, - CertSecret: &v1.SecretKeySelector{LocalObjectReference: v1.LocalObjectReference{Name: "helm-repo"}, Key: "certSecret"}, - UsernameSecret: &v1.SecretKeySelector{LocalObjectReference: v1.LocalObjectReference{Name: "helm-repo"}, Key: "username"}, - PasswordSecret: &v1.SecretKeySelector{LocalObjectReference: v1.LocalObjectReference{Name: "helm-repo"}, Key: "password"}, + KeySecret: &corev1.SecretKeySelector{LocalObjectReference: corev1.LocalObjectReference{Name: "helm-repo"}, Key: "keySecret"}, + CertSecret: &corev1.SecretKeySelector{LocalObjectReference: corev1.LocalObjectReference{Name: "helm-repo"}, Key: "certSecret"}, + UsernameSecret: &corev1.SecretKeySelector{LocalObjectReference: corev1.LocalObjectReference{Name: "helm-repo"}, Key: "username"}, + PasswordSecret: &corev1.SecretKeySelector{LocalObjectReference: corev1.LocalObjectReference{Name: "helm-repo"}, Key: "password"}, })) }) } else { diff --git a/test/e2e/hook_test.go b/test/e2e/hook_test.go index a538566986213..2d0958ed774e1 100644 --- a/test/e2e/hook_test.go +++ b/test/e2e/hook_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/gitops-engine/pkg/health" @@ -172,7 +172,7 @@ func TestPostSyncHookPodFailure(t *testing.T) { Expect(ResourceSyncStatusIs("Pod", "pod", SyncStatusCodeSynced)). Expect(ResourceHealthIs("Pod", "pod", health.HealthStatusDegraded)). Expect(ResourceResultNumbering(1)). - Expect(NotPod(func(p v1.Pod) bool { return p.Name == "hook" })) + Expect(NotPod(func(p corev1.Pod) bool { return p.Name == "hook" })) } func TestSyncFailHookPodFailure(t *testing.T) { @@ -264,7 +264,7 @@ func TestHookDeletePolicyHookSucceededHookExit0(t *testing.T) { Sync(). Then(). Expect(OperationPhaseIs(OperationSucceeded)). - Expect(NotPod(func(p v1.Pod) bool { return p.Name == "hook" })) + Expect(NotPod(func(p corev1.Pod) bool { return p.Name == "hook" })) } // make sure that we delete the hook on failure, if policy is set @@ -280,7 +280,7 @@ func TestHookDeletePolicyHookSucceededHookExit1(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationFailed)). Expect(ResourceResultNumbering(2)). - Expect(Pod(func(p v1.Pod) bool { return p.Name == "hook" })) + Expect(Pod(func(p corev1.Pod) bool { return p.Name == "hook" })) } // make sure that we do NOT delete the hook on success if failure policy is set @@ -294,7 +294,7 @@ func TestHookDeletePolicyHookFailedHookExit0(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(ResourceResultNumbering(2)). - Expect(Pod(func(p v1.Pod) bool { return p.Name == "hook" })) + Expect(Pod(func(p corev1.Pod) bool { return p.Name == "hook" })) } // make sure that we do delete the hook on failure if failure policy is set @@ -310,7 +310,7 @@ func TestHookDeletePolicyHookFailedHookExit1(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationFailed)). Expect(ResourceResultNumbering(2)). - Expect(NotPod(func(p v1.Pod) bool { return p.Name == "hook" })) + Expect(NotPod(func(p corev1.Pod) bool { return p.Name == "hook" })) } // make sure that we can run the hook twice @@ -328,7 +328,7 @@ func TestHookBeforeHookCreation(t *testing.T) { Expect(HealthIs(health.HealthStatusHealthy)). Expect(ResourceResultNumbering(2)). // the app will be in health+n-sync before this hook has run - Expect(Pod(func(p v1.Pod) bool { return p.Name == "hook" })). + Expect(Pod(func(p corev1.Pod) bool { return p.Name == "hook" })). And(func(_ *Application) { var err error creationTimestamp1, err = getCreationTimestamp() @@ -344,7 +344,7 @@ func TestHookBeforeHookCreation(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). Expect(ResourceResultNumbering(2)). - Expect(Pod(func(p v1.Pod) bool { return p.Name == "hook" })). + Expect(Pod(func(p corev1.Pod) bool { return p.Name == "hook" })). And(func(_ *Application) { creationTimestamp2, err := getCreationTimestamp() CheckError(err) @@ -389,7 +389,7 @@ func TestHookSkip(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(ResourceResultNumbering(1)). - Expect(NotPod(func(p v1.Pod) bool { return p.Name == "pod" })) + Expect(NotPod(func(p corev1.Pod) bool { return p.Name == "pod" })) } // make sure that we do NOT name non-hook resources in they are unnamed diff --git a/test/e2e/sync_waves_test.go b/test/e2e/sync_waves_test.go index 8beda162e5708..6b5894265b510 100644 --- a/test/e2e/sync_waves_test.go +++ b/test/e2e/sync_waves_test.go @@ -3,15 +3,14 @@ package e2e import ( "testing" + "github.com/argoproj/gitops-engine/pkg/health" + . "github.com/argoproj/gitops-engine/pkg/sync/common" + corev1 "k8s.io/api/core/v1" + . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/app" "github.com/argoproj/argo-cd/v2/util/errors" - - "github.com/argoproj/gitops-engine/pkg/health" - . "github.com/argoproj/gitops-engine/pkg/sync/common" - - v1 "k8s.io/api/core/v1" ) func TestFixingDegradedApp(t *testing.T) { @@ -143,6 +142,6 @@ func TestSyncPruneOrderWithSyncWaves(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - Expect(NotPod(func(p v1.Pod) bool { return p.Name == "pod-with-finalizers" })). + Expect(NotPod(func(p corev1.Pod) bool { return p.Name == "pod-with-finalizers" })). Expect(ResourceResultNumbering(4)) } diff --git a/test/e2e/sync_with_impersonate_test.go b/test/e2e/sync_with_impersonate_test.go index 4c7cf166f4a09..a0930163453bd 100644 --- a/test/e2e/sync_with_impersonate_test.go +++ b/test/e2e/sync_with_impersonate_test.go @@ -7,7 +7,7 @@ import ( "time" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" rbac "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -290,7 +290,7 @@ func createTestRoleBinding(roleName, serviceAccountName, namespace string) error // createTestServiceAccount creates a test ServiceAccount resource. func createTestServiceAccount(name, namespace string) error { - serviceAccount := &v1.ServiceAccount{ + serviceAccount := &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, diff --git a/test/testdata.go b/test/testdata.go index 2c5c6178317e3..a9b1cfa72ad17 100644 --- a/test/testdata.go +++ b/test/testdata.go @@ -6,7 +6,7 @@ import ( "github.com/alicebob/miniredis/v2" "github.com/argoproj/gitops-engine/pkg/utils/testing" "github.com/redis/go-redis/v9" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/labels" @@ -101,8 +101,8 @@ func NewConfigMap() *unstructured.Unstructured { return testing.Unstructured(ConfigMapManifest) } -func NewFakeConfigMap() *apiv1.ConfigMap { - cm := apiv1.ConfigMap{ +func NewFakeConfigMap() *corev1.ConfigMap { + cm := corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", APIVersion: "v1", @@ -119,8 +119,8 @@ func NewFakeConfigMap() *apiv1.ConfigMap { return &cm } -func NewFakeSecret(policy ...string) *apiv1.Secret { - secret := apiv1.Secret{ +func NewFakeSecret(policy ...string) *corev1.Secret { + secret := corev1.Secret{ TypeMeta: metav1.TypeMeta{ Kind: "Secret", APIVersion: "v1", diff --git a/util/argo/audit_logger.go b/util/argo/audit_logger.go index cffef2d64d75d..b220367bbbdcb 100644 --- a/util/argo/audit_logger.go +++ b/util/argo/audit_logger.go @@ -6,7 +6,7 @@ import ( "time" log "github.com/sirupsen/logrus" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" @@ -64,16 +64,16 @@ func (l *AuditLogger) logEvent(objMeta ObjectRef, gvk schema.GroupVersionKind, i logCtx = logCtx.WithField("name", objMeta.Name) } t := metav1.Time{Time: time.Now()} - event := v1.Event{ + event := corev1.Event{ ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("%v.%x", objMeta.Name, t.UnixNano()), Labels: eventLabels, Annotations: logFields, }, - Source: v1.EventSource{ + Source: corev1.EventSource{ Component: l.component, }, - InvolvedObject: v1.ObjectReference{ + InvolvedObject: corev1.ObjectReference{ Kind: gvk.Kind, Name: objMeta.Name, Namespace: objMeta.Namespace, diff --git a/util/argo/normalizers/knowntypes_normalizer.go b/util/argo/normalizers/knowntypes_normalizer.go index 6fc45c6806afd..9dc4f295be181 100644 --- a/util/argo/normalizers/knowntypes_normalizer.go +++ b/util/argo/normalizers/knowntypes_normalizer.go @@ -6,7 +6,7 @@ import ( "strings" log "github.com/sirupsen/logrus" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -63,7 +63,7 @@ func (n *knownTypesNormalizer) ensureDefaultCRDsConfigured() { n.typeFields[rolloutGK] = []knownTypeField{{ fieldPath: []string{"spec", "template", "spec"}, newFieldFn: func() any { - return &v1.PodSpec{} + return &corev1.PodSpec{} }, }} } diff --git a/util/db/certificate_test.go b/util/db/certificate_test.go index 62358bcd15b3b..74fd8bb0e1ca5 100644 --- a/util/db/certificate_test.go +++ b/util/db/certificate_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes/fake" @@ -245,7 +245,7 @@ const ( ) func getCertClientset() *fake.Clientset { - cm := v1.ConfigMap{ + cm := corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-cm", Namespace: testNamespace, @@ -256,7 +256,7 @@ func getCertClientset() *fake.Clientset { Data: nil, } - sshCM := v1.ConfigMap{ + sshCM := corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-ssh-known-hosts-cm", Namespace: testNamespace, @@ -269,7 +269,7 @@ func getCertClientset() *fake.Clientset { }, } - tlsCM := v1.ConfigMap{ + tlsCM := corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-tls-certs-cm", Namespace: testNamespace, diff --git a/util/db/cluster.go b/util/db/cluster.go index 4ce9bdbd37aa3..a76432ad1707a 100644 --- a/util/db/cluster.go +++ b/util/db/cluster.go @@ -13,7 +13,7 @@ import ( log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/watch" @@ -106,7 +106,7 @@ func (db *db) CreateCluster(ctx context.Context, c *appv1.Cluster) (*appv1.Clust return nil, err } - clusterSecret := &apiv1.Secret{ + clusterSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: secName, }, @@ -152,7 +152,7 @@ func (db *db) WatchClusters(ctx context.Context, ctx, common.LabelValueSecretTypeCluster, - func(secret *apiv1.Secret) { + func(secret *corev1.Secret) { cluster, err := SecretToCluster(secret) if err != nil { log.Errorf("could not unmarshal cluster secret %s", secret.Name) @@ -167,7 +167,7 @@ func (db *db) WatchClusters(ctx context.Context, handleAddEvent(cluster) }, - func(oldSecret *apiv1.Secret, newSecret *apiv1.Secret) { + func(oldSecret *corev1.Secret, newSecret *corev1.Secret) { oldCluster, err := SecretToCluster(oldSecret) if err != nil { log.Errorf("could not unmarshal cluster secret %s", oldSecret.Name) @@ -184,7 +184,7 @@ func (db *db) WatchClusters(ctx context.Context, handleModEvent(oldCluster, newCluster) }, - func(secret *apiv1.Secret) { + func(secret *corev1.Secret) { if string(secret.Data["server"]) == appv1.KubernetesInternalAPIServerAddr { // change local cluster event to modified or deleted, since it cannot be re-added or deleted handleModEvent(localCls, db.getLocalCluster()) @@ -198,7 +198,7 @@ func (db *db) WatchClusters(ctx context.Context, return err } -func (db *db) getClusterSecret(server string) (*apiv1.Secret, error) { +func (db *db) getClusterSecret(server string) (*corev1.Secret, error) { clusterSecrets, err := db.listSecretsByType(common.LabelValueSecretTypeCluster) if err != nil { return nil, err @@ -223,7 +223,7 @@ func (db *db) GetCluster(_ context.Context, server string) (*appv1.Cluster, erro return nil, err } if len(res) > 0 { - return SecretToCluster(res[0].(*apiv1.Secret)) + return SecretToCluster(res[0].(*corev1.Secret)) } if server == appv1.KubernetesInternalAPIServerAddr { return db.getLocalCluster(), nil @@ -244,7 +244,7 @@ func (db *db) GetProjectClusters(ctx context.Context, project string) ([]*appv1. } var res []*appv1.Cluster for i := range secrets { - cluster, err := SecretToCluster(secrets[i].(*apiv1.Secret)) + cluster, err := SecretToCluster(secrets[i].(*corev1.Secret)) if err != nil { return nil, fmt.Errorf("failed to convert secret to cluster: %w", err) } @@ -275,7 +275,7 @@ func (db *db) GetClusterServersByName(ctx context.Context, name string) ([]strin } var res []string for i := range secrets { - s := secrets[i].(*apiv1.Secret) + s := secrets[i].(*corev1.Secret) res = append(res, strings.TrimRight(string(s.Data["server"]), "/")) } return res, nil @@ -322,7 +322,7 @@ func (db *db) DeleteCluster(ctx context.Context, server string) error { } // clusterToSecret converts a cluster object to string data for serialization to a secret -func clusterToSecret(c *appv1.Cluster, secret *apiv1.Secret) error { +func clusterToSecret(c *appv1.Cluster, secret *corev1.Secret) error { data := make(map[string][]byte) data["server"] = []byte(strings.TrimRight(c.Server, "/")) if c.Name == "" { @@ -350,8 +350,8 @@ func clusterToSecret(c *appv1.Cluster, secret *apiv1.Secret) error { secret.Data = data secret.Labels = c.Labels - if c.Annotations != nil && c.Annotations[apiv1.LastAppliedConfigAnnotation] != "" { - return status.Errorf(codes.InvalidArgument, "annotation %s cannot be set", apiv1.LastAppliedConfigAnnotation) + if c.Annotations != nil && c.Annotations[corev1.LastAppliedConfigAnnotation] != "" { + return status.Errorf(codes.InvalidArgument, "annotation %s cannot be set", corev1.LastAppliedConfigAnnotation) } secret.Annotations = c.Annotations @@ -369,7 +369,7 @@ func clusterToSecret(c *appv1.Cluster, secret *apiv1.Secret) error { } // SecretToCluster converts a secret into a Cluster object -func SecretToCluster(s *apiv1.Secret) (*appv1.Cluster, error) { +func SecretToCluster(s *corev1.Secret) (*appv1.Cluster, error) { var config appv1.ClusterConfig if len(s.Data["config"]) > 0 { err := json.Unmarshal(s.Data["config"], &config) @@ -412,7 +412,7 @@ func SecretToCluster(s *apiv1.Secret) (*appv1.Cluster, error) { if s.Annotations != nil { annotations = maps.Clone(s.Annotations) // delete system annotations - delete(annotations, apiv1.LastAppliedConfigAnnotation) + delete(annotations, corev1.LastAppliedConfigAnnotation) delete(annotations, common.AnnotationKeyManagedBy) } diff --git a/util/db/cluster_norace_test.go b/util/db/cluster_norace_test.go index c26cfbf8b42f6..23b5beecef079 100644 --- a/util/db/cluster_norace_test.go +++ b/util/db/cluster_norace_test.go @@ -7,7 +7,7 @@ import ( "context" "testing" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo-cd/v2/common" @@ -23,7 +23,7 @@ func TestWatchClusters_CreateRemoveCluster(t *testing.T) { // !race: // Intermittent failure when running TestWatchClusters_LocalClusterModifications with -race, likely due to race condition // https://github.com/argoproj/argo-cd/issues/4755 - emptyArgoCDConfigMap := &v1.ConfigMap{ + emptyArgoCDConfigMap := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: fakeNamespace, @@ -33,7 +33,7 @@ func TestWatchClusters_CreateRemoveCluster(t *testing.T) { }, Data: map[string]string{}, } - argoCDSecret := &v1.Secret{ + argoCDSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: fakeNamespace, @@ -78,7 +78,7 @@ func TestWatchClusters_LocalClusterModifications(t *testing.T) { // !race: // Intermittent failure when running TestWatchClusters_LocalClusterModifications with -race, likely due to race condition // https://github.com/argoproj/argo-cd/issues/4755 - emptyArgoCDConfigMap := &v1.ConfigMap{ + emptyArgoCDConfigMap := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: fakeNamespace, @@ -88,7 +88,7 @@ func TestWatchClusters_LocalClusterModifications(t *testing.T) { }, Data: map[string]string{}, } - argoCDSecret := &v1.Secret{ + argoCDSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: fakeNamespace, diff --git a/util/db/cluster_test.go b/util/db/cluster_test.go index fc3da404e891a..b1eabfcc6f074 100644 --- a/util/db/cluster_test.go +++ b/util/db/cluster_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" @@ -52,7 +52,7 @@ func Test_URIToSecretName(t *testing.T) { func Test_secretToCluster(t *testing.T) { labels := map[string]string{"key1": "val1"} annotations := map[string]string{"key2": "val2"} - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster", Namespace: fakeNamespace, @@ -79,11 +79,11 @@ func Test_secretToCluster(t *testing.T) { } func Test_secretToCluster_LastAppliedConfigurationDropped(t *testing.T) { - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster", Namespace: fakeNamespace, - Annotations: map[string]string{v1.LastAppliedConfigAnnotation: "val2"}, + Annotations: map[string]string{corev1.LastAppliedConfigAnnotation: "val2"}, }, Data: map[string][]byte{ "name": []byte("test"), @@ -106,7 +106,7 @@ func TestClusterToSecret(t *testing.T) { Project: "project", Namespaces: []string{"default"}, } - s := &v1.Secret{} + s := &corev1.Secret{} err := clusterToSecret(cluster, s) require.NoError(t, err) @@ -121,20 +121,20 @@ func TestClusterToSecret(t *testing.T) { func TestClusterToSecret_LastAppliedConfigurationRejected(t *testing.T) { cluster := &appv1.Cluster{ Server: "server", - Annotations: map[string]string{v1.LastAppliedConfigAnnotation: "val2"}, + Annotations: map[string]string{corev1.LastAppliedConfigAnnotation: "val2"}, Name: "test", Config: v1alpha1.ClusterConfig{}, Project: "project", Namespaces: []string{"default"}, } - s := &v1.Secret{} + s := &corev1.Secret{} err := clusterToSecret(cluster, s) require.Error(t, err) require.Equal(t, codes.InvalidArgument, status.Code(err)) } func Test_secretToCluster_NoConfig(t *testing.T) { - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster", Namespace: fakeNamespace, @@ -155,7 +155,7 @@ func Test_secretToCluster_NoConfig(t *testing.T) { } func Test_secretToCluster_InvalidConfig(t *testing.T) { - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster", Namespace: fakeNamespace, @@ -172,7 +172,7 @@ func Test_secretToCluster_InvalidConfig(t *testing.T) { } func TestUpdateCluster(t *testing.T) { - kubeclientset := fake.NewClientset(&v1.Secret{ + kubeclientset := fake.NewClientset(&corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster", Namespace: fakeNamespace, @@ -202,7 +202,7 @@ func TestUpdateCluster(t *testing.T) { } func TestDeleteUnknownCluster(t *testing.T) { - kubeclientset := fake.NewClientset(&v1.Secret{ + kubeclientset := fake.NewClientset(&corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster", Namespace: fakeNamespace, @@ -221,7 +221,7 @@ func TestDeleteUnknownCluster(t *testing.T) { } func TestRejectCreationForInClusterWhenDisabled(t *testing.T) { - argoCDConfigMapWithInClusterServerAddressDisabled := &v1.ConfigMap{ + argoCDConfigMapWithInClusterServerAddressDisabled := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: fakeNamespace, @@ -231,7 +231,7 @@ func TestRejectCreationForInClusterWhenDisabled(t *testing.T) { }, Data: map[string]string{"cluster.inClusterEnabled": "false"}, } - argoCDSecret := &v1.Secret{ + argoCDSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: fakeNamespace, @@ -297,7 +297,7 @@ func runWatchTest(t *testing.T, db ArgoDB, actions []func(old *v1alpha1.Cluster, } func TestListClusters(t *testing.T) { - emptyArgoCDConfigMap := &v1.ConfigMap{ + emptyArgoCDConfigMap := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: fakeNamespace, @@ -307,7 +307,7 @@ func TestListClusters(t *testing.T) { }, Data: map[string]string{}, } - argoCDConfigMapWithInClusterServerAddressDisabled := &v1.ConfigMap{ + argoCDConfigMapWithInClusterServerAddressDisabled := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: fakeNamespace, @@ -317,7 +317,7 @@ func TestListClusters(t *testing.T) { }, Data: map[string]string{"cluster.inClusterEnabled": "false"}, } - argoCDSecret := &v1.Secret{ + argoCDSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: fakeNamespace, @@ -330,7 +330,7 @@ func TestListClusters(t *testing.T) { "server.secretkey": nil, }, } - secretForServerWithInClusterAddr := &v1.Secret{ + secretForServerWithInClusterAddr := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster1", Namespace: fakeNamespace, @@ -344,7 +344,7 @@ func TestListClusters(t *testing.T) { }, } - secretForServerWithExternalClusterAddr := &v1.Secret{ + secretForServerWithExternalClusterAddr := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster2", Namespace: fakeNamespace, @@ -358,7 +358,7 @@ func TestListClusters(t *testing.T) { }, } - invalidSecret := &v1.Secret{ + invalidSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster3", Namespace: fakeNamespace, @@ -426,7 +426,7 @@ func TestListClusters(t *testing.T) { // on the cluster secrets. The test isn't asserting anything because // before the fix it would cause a panic from concurrent map iteration and map write func TestClusterRaceConditionClusterSecrets(t *testing.T) { - clusterSecret := &v1.Secret{ + clusterSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster", Namespace: "default", @@ -440,7 +440,7 @@ func TestClusterRaceConditionClusterSecrets(t *testing.T) { }, } kubeClient := fake.NewClientset( - &v1.ConfigMap{ + &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -450,7 +450,7 @@ func TestClusterRaceConditionClusterSecrets(t *testing.T) { }, Data: map[string]string{}, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", diff --git a/util/db/db.go b/util/db/db.go index 0cd243c051458..92571c9514c7a 100644 --- a/util/db/db.go +++ b/util/db/db.go @@ -5,7 +5,7 @@ import ( "math" "strings" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" kubeerrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -136,7 +136,7 @@ func NewDB(namespace string, settingsMgr *settings.SettingsManager, kubeclientse } } -func (db *db) getSecret(name string, cache map[string]*v1.Secret) (*v1.Secret, error) { +func (db *db) getSecret(name string, cache map[string]*corev1.Secret) (*corev1.Secret, error) { if _, ok := cache[name]; !ok { secret, err := db.settingsMgr.GetSecretByName(name) if err != nil { @@ -147,7 +147,7 @@ func (db *db) getSecret(name string, cache map[string]*v1.Secret) (*v1.Secret, e return cache[name], nil } -func (db *db) unmarshalFromSecretsStr(secrets map[*SecretMaperValidation]*v1.SecretKeySelector, cache map[string]*v1.Secret) error { +func (db *db) unmarshalFromSecretsStr(secrets map[*SecretMaperValidation]*corev1.SecretKeySelector, cache map[string]*corev1.Secret) error { for dst, src := range secrets { if src != nil { secret, err := db.getSecret(src.Name, cache) diff --git a/util/db/db_test.go b/util/db/db_test.go index 8227f86964bcc..2ab263955dbbc 100644 --- a/util/db/db_test.go +++ b/util/db/db_test.go @@ -11,7 +11,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" appv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -27,7 +27,7 @@ const ( ) func getClientset(config map[string]string, objects ...runtime.Object) *fake.Clientset { - secret := v1.Secret{ + secret := corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-secret", Namespace: testNamespace, @@ -37,7 +37,7 @@ func getClientset(config map[string]string, objects ...runtime.Object) *fake.Cli "server.secretkey": []byte("test"), }, } - cm := v1.ConfigMap{ + cm := corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-cm", Namespace: testNamespace, @@ -292,8 +292,8 @@ func TestGetRepository(t *testing.T) { } } -func newManagedSecret() *v1.Secret { - return &v1.Secret{ +func newManagedSecret() *corev1.Secret { + return &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "managed-secret", Namespace: testNamespace, @@ -347,7 +347,7 @@ func TestDeleteRepositoryUnmanagedSecrets(t *testing.T) { key: password `, } - clientset := getClientset(config, &v1.Secret{ + clientset := getClientset(config, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "unmanaged-secret", Namespace: testNamespace, @@ -387,7 +387,7 @@ func TestUpdateRepositoryWithManagedSecrets(t *testing.T) { key: sshPrivateKey `, } - clientset := getClientset(config, &v1.Secret{ + clientset := getClientset(config, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "managed-secret", Namespace: testNamespace, @@ -447,7 +447,7 @@ func TestRepositorySecretsTrim(t *testing.T) { key: githubAppPrivateKey `, } - clientset := getClientset(config, &v1.Secret{ + clientset := getClientset(config, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "managed-secret", Namespace: testNamespace, @@ -505,7 +505,7 @@ func TestRepositorySecretsTrim(t *testing.T) { func TestGetClusterSuccessful(t *testing.T) { server := "my-cluster" name := "my-name" - clientset := getClientset(nil, &v1.Secret{ + clientset := getClientset(nil, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: testNamespace, Labels: map[string]string{ @@ -559,7 +559,7 @@ func TestDeleteClusterWithManagedSecret(t *testing.T) { clusterURL := "https://mycluster" clusterName := "cluster-mycluster-3274446258" - clientset := getClientset(nil, &v1.Secret{ + clientset := getClientset(nil, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: clusterName, Namespace: testNamespace, @@ -590,7 +590,7 @@ func TestDeleteClusterWithUnmanagedSecret(t *testing.T) { clusterURL := "https://mycluster" clusterName := "mycluster-443" - clientset := getClientset(nil, &v1.Secret{ + clientset := getClientset(nil, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: clusterName, Namespace: testNamespace, @@ -662,7 +662,7 @@ func TestListHelmRepositories(t *testing.T) { key: key `, } - clientset := getClientset(config, &v1.Secret{ + clientset := getClientset(config, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "test-secret", Namespace: testNamespace, @@ -710,7 +710,7 @@ func TestHelmRepositorySecretsTrim(t *testing.T) { key: key `, } - clientset := getClientset(config, &v1.Secret{ + clientset := getClientset(config, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "test-secret", Namespace: testNamespace, @@ -753,7 +753,7 @@ func TestHelmRepositorySecretsTrim(t *testing.T) { } func TestGetClusterServersByName(t *testing.T) { - clientset := getClientset(nil, &v1.Secret{ + clientset := getClientset(nil, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster-secret", Namespace: testNamespace, @@ -785,7 +785,7 @@ func TestGetClusterServersByName_InClusterNotConfigured(t *testing.T) { } func TestGetClusterServersByName_InClusterConfigured(t *testing.T) { - clientset := getClientset(nil, &v1.Secret{ + clientset := getClientset(nil, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster-secret", Namespace: testNamespace, diff --git a/util/db/gpgkeys_test.go b/util/db/gpgkeys_test.go index 731293b5b279b..4464e9b94cfad 100644 --- a/util/db/gpgkeys_test.go +++ b/util/db/gpgkeys_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes/fake" @@ -18,7 +18,7 @@ import ( ) // GPG config map with a single key and good mapping -var gpgCMEmpty = v1.ConfigMap{ +var gpgCMEmpty = corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDGPGKeysConfigMapName, Namespace: testNamespace, @@ -29,7 +29,7 @@ var gpgCMEmpty = v1.ConfigMap{ } // GPG config map with a single key and good mapping -var gpgCMSingleGoodPubkey = v1.ConfigMap{ +var gpgCMSingleGoodPubkey = corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDGPGKeysConfigMapName, Namespace: testNamespace, @@ -43,7 +43,7 @@ var gpgCMSingleGoodPubkey = v1.ConfigMap{ } // GPG config map with two keys and good mapping -var gpgCMMultiGoodPubkey = v1.ConfigMap{ +var gpgCMMultiGoodPubkey = corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDGPGKeysConfigMapName, Namespace: testNamespace, @@ -58,7 +58,7 @@ var gpgCMMultiGoodPubkey = v1.ConfigMap{ } // GPG config map with a single key and bad mapping -var gpgCMSingleKeyWrongId = v1.ConfigMap{ +var gpgCMSingleKeyWrongId = corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDGPGKeysConfigMapName, Namespace: testNamespace, @@ -72,7 +72,7 @@ var gpgCMSingleKeyWrongId = v1.ConfigMap{ } // GPG config map with a garbage pub key -var gpgCMGarbagePubkey = v1.ConfigMap{ +var gpgCMGarbagePubkey = corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDGPGKeysConfigMapName, Namespace: testNamespace, @@ -86,7 +86,7 @@ var gpgCMGarbagePubkey = v1.ConfigMap{ } // GPG config map with a wrong key -var gpgCMGarbageCMKey = v1.ConfigMap{ +var gpgCMGarbageCMKey = corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDGPGKeysConfigMapName, Namespace: testNamespace, @@ -100,8 +100,8 @@ var gpgCMGarbageCMKey = v1.ConfigMap{ } // Returns a fake client set for use in tests -func getGPGKeysClientset(gpgCM v1.ConfigMap) *fake.Clientset { - cm := v1.ConfigMap{ +func getGPGKeysClientset(gpgCM corev1.ConfigMap) *fake.Clientset { + cm := corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "argocd-cm", Namespace: testNamespace, diff --git a/util/db/helmrepository.go b/util/db/helmrepository.go index 0cc6bb2742572..012f93e5f20d4 100644 --- a/util/db/helmrepository.go +++ b/util/db/helmrepository.go @@ -7,7 +7,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/utils/ptr" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" @@ -35,12 +35,12 @@ func (db *db) getHelmRepo(repoURL string, helmRepositories []settings.HelmRepoCr Type: "helm", Name: repoInfo.Name, } - err := db.unmarshalFromSecretsStr(map[*SecretMaperValidation]*v1.SecretKeySelector{ + err := db.unmarshalFromSecretsStr(map[*SecretMaperValidation]*corev1.SecretKeySelector{ {Dest: &repo.Username, Transform: StripCRLFCharacter}: repoInfo.UsernameSecret, {Dest: &repo.Password, Transform: StripCRLFCharacter}: repoInfo.PasswordSecret, {Dest: &repo.TLSClientCertData, Transform: StripCRLFCharacter}: repoInfo.CertSecret, {Dest: &repo.TLSClientCertKey, Transform: StripCRLFCharacter}: repoInfo.KeySecret, - }, make(map[string]*v1.Secret)) + }, make(map[string]*corev1.Secret)) return repo, err } diff --git a/util/db/repository.go b/util/db/repository.go index f6e7a708d04df..db3f78f42558e 100644 --- a/util/db/repository.go +++ b/util/db/repository.go @@ -5,7 +5,7 @@ import ( "fmt" "hash/fnv" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" @@ -138,7 +138,7 @@ func (db *db) getRepositories(indexer, project string) ([]*appv1.Repository, err } var res []*appv1.Repository for i := range secrets { - repo, err := secretToRepository(secrets[i].(*apiv1.Secret)) + repo, err := secretToRepository(secrets[i].(*corev1.Secret)) if err != nil { return nil, err } diff --git a/util/db/repository_legacy.go b/util/db/repository_legacy.go index 4f570c653e15e..cbeaff56537bd 100644 --- a/util/db/repository_legacy.go +++ b/util/db/repository_legacy.go @@ -8,7 +8,7 @@ import ( log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -311,7 +311,7 @@ func (l *legacyRepositoryBackend) upsertSecret(name string, data map[string][]by if len(data) == 0 { return nil } - _, err = l.db.kubeclientset.CoreV1().Secrets(l.db.ns).Create(context.Background(), &apiv1.Secret{ + _, err = l.db.kubeclientset.CoreV1().Secrets(l.db.ns).Create(context.Background(), &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: name, Annotations: map[string]string{ @@ -387,7 +387,7 @@ func (l *legacyRepositoryBackend) credentialsToRepository(repoInfo settings.Repo GitHubAppEnterpriseBaseURL: repoInfo.GithubAppEnterpriseBaseURL, Proxy: repoInfo.Proxy, } - err := l.db.unmarshalFromSecretsStr(map[*SecretMaperValidation]*apiv1.SecretKeySelector{ + err := l.db.unmarshalFromSecretsStr(map[*SecretMaperValidation]*corev1.SecretKeySelector{ {Dest: &repo.Username, Transform: StripCRLFCharacter}: repoInfo.UsernameSecret, {Dest: &repo.Password, Transform: StripCRLFCharacter}: repoInfo.PasswordSecret, {Dest: &repo.SSHPrivateKey, Transform: StripCRLFCharacter}: repoInfo.SSHPrivateKeySecret, @@ -395,7 +395,7 @@ func (l *legacyRepositoryBackend) credentialsToRepository(repoInfo settings.Repo {Dest: &repo.TLSClientCertKey, Transform: StripCRLFCharacter}: repoInfo.TLSClientCertKeySecret, {Dest: &repo.GithubAppPrivateKey, Transform: StripCRLFCharacter}: repoInfo.GithubAppPrivateKeySecret, {Dest: &repo.GCPServiceAccountKey, Transform: StripCRLFCharacter}: repoInfo.GCPServiceAccountKey, - }, make(map[string]*apiv1.Secret)) + }, make(map[string]*corev1.Secret)) return repo, err } @@ -407,7 +407,7 @@ func (l *legacyRepositoryBackend) credentialsToRepositoryCredentials(repoInfo se GitHubAppEnterpriseBaseURL: repoInfo.GithubAppEnterpriseBaseURL, EnableOCI: repoInfo.EnableOCI, } - err := l.db.unmarshalFromSecretsStr(map[*SecretMaperValidation]*apiv1.SecretKeySelector{ + err := l.db.unmarshalFromSecretsStr(map[*SecretMaperValidation]*corev1.SecretKeySelector{ {Dest: &creds.Username}: repoInfo.UsernameSecret, {Dest: &creds.Password}: repoInfo.PasswordSecret, {Dest: &creds.SSHPrivateKey}: repoInfo.SSHPrivateKeySecret, @@ -415,17 +415,17 @@ func (l *legacyRepositoryBackend) credentialsToRepositoryCredentials(repoInfo se {Dest: &creds.TLSClientCertKey}: repoInfo.TLSClientCertKeySecret, {Dest: &creds.GithubAppPrivateKey}: repoInfo.GithubAppPrivateKeySecret, {Dest: &creds.GCPServiceAccountKey}: repoInfo.GCPServiceAccountKey, - }, make(map[string]*apiv1.Secret)) + }, make(map[string]*corev1.Secret)) return creds, err } // Set data to be stored in a given secret used for repository credentials and templates. // The name of the secret is a combination of the prefix given, and a calculated value // from the repository or template URL. -func (l *legacyRepositoryBackend) setSecretData(prefix string, url string, secretsData map[string]map[string][]byte, secretKey *apiv1.SecretKeySelector, value string, defaultKeyName string) *apiv1.SecretKeySelector { +func (l *legacyRepositoryBackend) setSecretData(prefix string, url string, secretsData map[string]map[string][]byte, secretKey *corev1.SecretKeySelector, value string, defaultKeyName string) *corev1.SecretKeySelector { if secretKey == nil && value != "" { - secretKey = &apiv1.SecretKeySelector{ - LocalObjectReference: apiv1.LocalObjectReference{Name: RepoURLToSecretName(prefix, url, "")}, + secretKey = &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: RepoURLToSecretName(prefix, url, "")}, Key: defaultKeyName, } } diff --git a/util/db/secrets.go b/util/db/secrets.go index a1fd515dcf12e..1ddf51d4f758f 100644 --- a/util/db/secrets.go +++ b/util/db/secrets.go @@ -11,7 +11,7 @@ import ( "time" log "github.com/sirupsen/logrus" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" @@ -23,7 +23,7 @@ import ( "github.com/argoproj/argo-cd/v2/util" ) -func (db *db) listSecretsByType(types ...string) ([]*apiv1.Secret, error) { +func (db *db) listSecretsByType(types ...string) ([]*corev1.Secret, error) { labelSelector := labels.NewSelector() req, err := labels.NewRequirement(common.LabelKeySecretType, selection.Equals, types) if err != nil { @@ -46,7 +46,7 @@ func (db *db) listSecretsByType(types ...string) ([]*apiv1.Secret, error) { return secrets, nil } -func boolOrFalse(secret *apiv1.Secret, key string) (bool, error) { +func boolOrFalse(secret *corev1.Secret, key string) (bool, error) { val, present := secret.Data[key] if !present { return false, nil @@ -55,7 +55,7 @@ func boolOrFalse(secret *apiv1.Secret, key string) (bool, error) { return strconv.ParseBool(string(val)) } -func intOrZero(secret *apiv1.Secret, key string) (int64, error) { +func intOrZero(secret *corev1.Secret, key string) (int64, error) { val, present := secret.Data[key] if !present { return 0, nil @@ -64,29 +64,29 @@ func intOrZero(secret *apiv1.Secret, key string) (int64, error) { return strconv.ParseInt(string(val), 10, 64) } -func updateSecretBool(secret *apiv1.Secret, key string, value bool) { +func updateSecretBool(secret *corev1.Secret, key string, value bool) { if _, present := secret.Data[key]; present || value { secret.Data[key] = []byte(strconv.FormatBool(value)) } } -func updateSecretInt(secret *apiv1.Secret, key string, value int64) { +func updateSecretInt(secret *corev1.Secret, key string, value int64) { if _, present := secret.Data[key]; present || value != 0 { secret.Data[key] = []byte(strconv.FormatInt(value, 10)) } } -func updateSecretString(secret *apiv1.Secret, key, value string) { +func updateSecretString(secret *corev1.Secret, key, value string) { if _, present := secret.Data[key]; present || len(value) > 0 { secret.Data[key] = []byte(value) } } -func (db *db) createSecret(ctx context.Context, secret *apiv1.Secret) (*apiv1.Secret, error) { +func (db *db) createSecret(ctx context.Context, secret *corev1.Secret) (*corev1.Secret, error) { return db.kubeclientset.CoreV1().Secrets(db.ns).Create(ctx, secret, metav1.CreateOptions{}) } -func addSecretMetadata(secret *apiv1.Secret, secretType string) { +func addSecretMetadata(secret *corev1.Secret, secretType string) { if secret.Annotations == nil { secret.Annotations = map[string]string{} } @@ -98,7 +98,7 @@ func addSecretMetadata(secret *apiv1.Secret, secretType string) { secret.Labels[common.LabelKeySecretType] = secretType } -func (db *db) deleteSecret(ctx context.Context, secret *apiv1.Secret) error { +func (db *db) deleteSecret(ctx context.Context, secret *corev1.Secret) error { var err error canDelete := secret.Annotations != nil && secret.Annotations[common.AnnotationKeyManagedBy] == common.AnnotationValueManagedByArgoCD @@ -114,9 +114,9 @@ func (db *db) deleteSecret(ctx context.Context, secret *apiv1.Secret) error { func (db *db) watchSecrets(ctx context.Context, secretType string, - handleAddEvent func(secret *apiv1.Secret), - handleModEvent func(oldSecret *apiv1.Secret, newSecret *apiv1.Secret), - handleDeleteEvent func(secret *apiv1.Secret), + handleAddEvent func(secret *corev1.Secret), + handleModEvent func(oldSecret *corev1.Secret, newSecret *corev1.Secret), + handleDeleteEvent func(secret *corev1.Secret), ) { secretListOptions := func(options *metav1.ListOptions) { labelSelector := fields.ParseSelectorOrDie(common.LabelKeySecretType + "=" + secretType) @@ -124,18 +124,18 @@ func (db *db) watchSecrets(ctx context.Context, } secretEventHandler := cache.ResourceEventHandlerFuncs{ AddFunc: func(obj any) { - if secretObj, ok := obj.(*apiv1.Secret); ok { + if secretObj, ok := obj.(*corev1.Secret); ok { handleAddEvent(secretObj) } }, DeleteFunc: func(obj any) { - if secretObj, ok := obj.(*apiv1.Secret); ok { + if secretObj, ok := obj.(*corev1.Secret); ok { handleDeleteEvent(secretObj) } }, UpdateFunc: func(oldObj, newObj any) { - if oldSecretObj, ok := oldObj.(*apiv1.Secret); ok { - if newSecretObj, ok := newObj.(*apiv1.Secret); ok { + if oldSecretObj, ok := oldObj.(*corev1.Secret); ok { + if newSecretObj, ok := newObj.(*corev1.Secret); ok { handleModEvent(oldSecretObj, newSecretObj) } } diff --git a/util/helm/helm_test.go b/util/helm/helm_test.go index a8957c177686a..b648fba0c47d3 100644 --- a/util/helm/helm_test.go +++ b/util/helm/helm_test.go @@ -11,7 +11,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/utils/kube" "github.com/stretchr/testify/assert" appsv1 "k8s.io/api/apps/v1" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) @@ -43,10 +43,10 @@ func TestHelmTemplateParams(t *testing.T) { for _, obj := range objs { if obj.GetKind() == "Service" && obj.GetName() == "test-minio" { - var svc apiv1.Service + var svc corev1.Service err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, &svc) require.NoError(t, err) - assert.Equal(t, apiv1.ServiceTypeLoadBalancer, svc.Spec.Type) + assert.Equal(t, corev1.ServiceTypeLoadBalancer, svc.Spec.Type) assert.Equal(t, int32(1234), svc.Spec.Ports[0].TargetPort.IntVal) assert.Equal(t, "true", svc.ObjectMeta.Annotations["prometheus.io/scrape"]) } diff --git a/util/kube/kube_test.go b/util/kube/kube_test.go index 51474359bde5e..4513cde7a28c0 100644 --- a/util/kube/kube_test.go +++ b/util/kube/kube_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" extv1beta1 "k8s.io/api/extensions/v1beta1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "sigs.k8s.io/yaml" @@ -147,7 +147,7 @@ func TestSetSvcLabel(t *testing.T) { require.NoError(t, err) log.Println(string(manifestBytes)) - var s apiv1.Service + var s corev1.Service err = json.Unmarshal(manifestBytes, &s) require.NoError(t, err) @@ -176,7 +176,7 @@ func TestSetAppInstanceAnnotation(t *testing.T) { require.NoError(t, err) log.Println(string(manifestBytes)) - var s apiv1.Service + var s corev1.Service err = json.Unmarshal(manifestBytes, &s) require.NoError(t, err) diff --git a/util/kube/util.go b/util/kube/util.go index 81c7c0d44ce57..97ae94a6bf1b6 100644 --- a/util/kube/util.go +++ b/util/kube/util.go @@ -3,7 +3,7 @@ package kube import ( "context" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -18,7 +18,7 @@ type kubeUtil struct { // updateFn will be called to set data for secret s. new will be true if the // secret was created by the caller, or false if it has existed before. -type updateFn func(s *apiv1.Secret, new bool) error +type updateFn func(s *corev1.Secret, new bool) error // NewKubeUtil NewUtil returns a new kubeUtil receiver func NewKubeUtil(client kubernetes.Interface, ctx context.Context) *kubeUtil { @@ -30,7 +30,7 @@ func NewKubeUtil(client kubernetes.Interface, ctx context.Context) *kubeUtil { // the receiver. If the secret is updated, labels and annotations will not be // touched. func (ku *kubeUtil) CreateOrUpdateSecret(ns string, name string, update updateFn) error { - var s *apiv1.Secret + var s *corev1.Secret var err error var new bool @@ -43,7 +43,7 @@ func (ku *kubeUtil) CreateOrUpdateSecret(ns string, name string, update updateFn } if new { - s = &apiv1.Secret{ + s = &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: ns, @@ -70,7 +70,7 @@ func (ku *kubeUtil) CreateOrUpdateSecret(ns string, name string, update updateFn // CreateOrUpdateSecretField creates or updates a secret name in namespace ns, with given value for given field func (ku *kubeUtil) CreateOrUpdateSecretField(ns string, name string, field string, value string) error { - err := ku.CreateOrUpdateSecret(ns, name, func(s *apiv1.Secret, new bool) error { + err := ku.CreateOrUpdateSecret(ns, name, func(s *corev1.Secret, new bool) error { s.Data[field] = []byte(value) return nil }) @@ -80,7 +80,7 @@ func (ku *kubeUtil) CreateOrUpdateSecretField(ns string, name string, field stri // CreateOrUpdateSecretData creates or updates a secret name in namespace ns, with given data. // If merge is true, merges data with the existing data, otherwise overwrites it. func (ku *kubeUtil) CreateOrUpdateSecretData(ns string, name string, data map[string][]byte, merge bool) error { - err := ku.CreateOrUpdateSecret(ns, name, func(s *apiv1.Secret, new bool) error { + err := ku.CreateOrUpdateSecret(ns, name, func(s *corev1.Secret, new bool) error { if !merge || new { s.Data = data } else { diff --git a/util/kube/util_test.go b/util/kube/util_test.go index ac3e5a35276e4..7ced9b6ef745a 100644 --- a/util/kube/util_test.go +++ b/util/kube/util_test.go @@ -6,14 +6,14 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" ) // nolint:unparam -func getSecret(client kubernetes.Interface, ns, name string) (*apiv1.Secret, error) { +func getSecret(client kubernetes.Interface, ns, name string) (*corev1.Secret, error) { s, err := client.CoreV1().Secrets(ns).Get(context.TODO(), name, metav1.GetOptions{}) if err != nil { return nil, err @@ -22,7 +22,7 @@ func getSecret(client kubernetes.Interface, ns, name string) (*apiv1.Secret, err } func Test_CreateOrUpdateSecretField(t *testing.T) { - secret := &apiv1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "test-secret", Namespace: "test", @@ -113,7 +113,7 @@ func Test_CreateOrUpdateSecretField(t *testing.T) { } func Test_CreateOrUpdateSecretData(t *testing.T) { - secret := &apiv1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "test-secret", Namespace: "test", diff --git a/util/notification/settings/legacy.go b/util/notification/settings/legacy.go index 7b1457923e8f9..12e3a6a9c3da6 100644 --- a/util/notification/settings/legacy.go +++ b/util/notification/settings/legacy.go @@ -12,7 +12,7 @@ import ( "github.com/argoproj/notifications-engine/pkg/util/text" jsonpatch "github.com/evanphx/json-patch" log "github.com/sirupsen/logrus" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "sigs.k8s.io/yaml" ) @@ -157,7 +157,7 @@ func (c *legacyServicesConfig) merge(cfg *api.Config) { } // ApplyLegacyConfig settings specified using deprecated config map and secret keys -func ApplyLegacyConfig(cfg *api.Config, context map[string]string, cm *v1.ConfigMap, secret *v1.Secret) error { +func ApplyLegacyConfig(cfg *api.Config, context map[string]string, cm *corev1.ConfigMap, secret *corev1.Secret) error { if notifiersData, ok := secret.Data["notifiers.yaml"]; ok && len(notifiersData) > 0 { log.Warn("Key 'notifiers.yaml' in Secret is deprecated, please migrate to new settings") legacyServices := &legacyServicesConfig{} diff --git a/util/notification/settings/legacy_test.go b/util/notification/settings/legacy_test.go index 00565767c38a5..1a77f87410d1f 100644 --- a/util/notification/settings/legacy_test.go +++ b/util/notification/settings/legacy_test.go @@ -9,7 +9,7 @@ import ( "github.com/argoproj/notifications-engine/pkg/triggers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/labels" ) @@ -36,8 +36,8 @@ triggers: ` err := ApplyLegacyConfig(&cfg, context, - &v1.ConfigMap{Data: map[string]string{"config.yaml": configYAML}}, - &v1.Secret{Data: map[string][]byte{}}, + &corev1.ConfigMap{Data: map[string]string{"config.yaml": configYAML}}, + &corev1.Secret{Data: map[string][]byte{}}, ) require.NoError(t, err) assert.Equal(t, []string{"my-trigger1"}, cfg.DefaultTriggers) @@ -82,8 +82,8 @@ slack: token: my-token ` err := ApplyLegacyConfig(&cfg, context, - &v1.ConfigMap{Data: map[string]string{"config.yaml": configYAML}}, - &v1.Secret{Data: map[string][]byte{"notifiers.yaml": []byte(notifiersYAML)}}, + &corev1.ConfigMap{Data: map[string]string{"config.yaml": configYAML}}, + &corev1.Secret{Data: map[string][]byte{"notifiers.yaml": []byte(notifiersYAML)}}, ) require.NoError(t, err) diff --git a/util/notification/settings/settings.go b/util/notification/settings/settings.go index 14c693014789c..50ef860b3aef3 100644 --- a/util/notification/settings/settings.go +++ b/util/notification/settings/settings.go @@ -5,7 +5,7 @@ import ( "github.com/argoproj/notifications-engine/pkg/api" "github.com/argoproj/notifications-engine/pkg/services" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "sigs.k8s.io/yaml" @@ -18,7 +18,7 @@ func GetFactorySettings(argocdService service.Service, secretName, configMapName return api.Settings{ SecretName: secretName, ConfigMapName: configMapName, - InitGetVars: func(cfg *api.Config, configMap *v1.ConfigMap, secret *v1.Secret) (api.GetVars, error) { + InitGetVars: func(cfg *api.Config, configMap *corev1.ConfigMap, secret *corev1.Secret) (api.GetVars, error) { if selfServiceNotificationEnabled { return initGetVarsWithoutSecret(argocdService, cfg, configMap, secret) } @@ -32,7 +32,7 @@ func GetFactorySettingsForCLI(argocdService *service.Service, secretName, config return api.Settings{ SecretName: secretName, ConfigMapName: configMapName, - InitGetVars: func(cfg *api.Config, configMap *v1.ConfigMap, secret *v1.Secret) (api.GetVars, error) { + InitGetVars: func(cfg *api.Config, configMap *corev1.ConfigMap, secret *corev1.Secret) (api.GetVars, error) { if *argocdService == nil { return nil, errors.New("argocdService is not initialized") } @@ -45,7 +45,7 @@ func GetFactorySettingsForCLI(argocdService *service.Service, secretName, config } } -func getContext(cfg *api.Config, configMap *v1.ConfigMap, secret *v1.Secret) (map[string]string, error) { +func getContext(cfg *api.Config, configMap *corev1.ConfigMap, secret *corev1.Secret) (map[string]string, error) { context := map[string]string{} if contextYaml, ok := configMap.Data["context"]; ok { if err := yaml.Unmarshal([]byte(contextYaml), &context); err != nil { @@ -58,7 +58,7 @@ func getContext(cfg *api.Config, configMap *v1.ConfigMap, secret *v1.Secret) (ma return context, nil } -func initGetVarsWithoutSecret(argocdService service.Service, cfg *api.Config, configMap *v1.ConfigMap, secret *v1.Secret) (api.GetVars, error) { +func initGetVarsWithoutSecret(argocdService service.Service, cfg *api.Config, configMap *corev1.ConfigMap, secret *corev1.Secret) (api.GetVars, error) { context, err := getContext(cfg, configMap, secret) if err != nil { return nil, err @@ -72,7 +72,7 @@ func initGetVarsWithoutSecret(argocdService service.Service, cfg *api.Config, co }, nil } -func initGetVars(argocdService service.Service, cfg *api.Config, configMap *v1.ConfigMap, secret *v1.Secret) (api.GetVars, error) { +func initGetVars(argocdService service.Service, cfg *api.Config, configMap *corev1.ConfigMap, secret *corev1.Secret) (api.GetVars, error) { context, err := getContext(cfg, configMap, secret) if err != nil { return nil, err diff --git a/util/rbac/rbac.go b/util/rbac/rbac.go index f9da179867322..29ff77e0ae4a6 100644 --- a/util/rbac/rbac.go +++ b/util/rbac/rbac.go @@ -23,7 +23,7 @@ import ( log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" @@ -345,7 +345,7 @@ func (e *Enforcer) newInformer() cache.SharedIndexInformer { } // RunPolicyLoader runs the policy loader which watches policy updates from the configmap and reloads them -func (e *Enforcer) RunPolicyLoader(ctx context.Context, onUpdated func(cm *apiv1.ConfigMap) error) error { +func (e *Enforcer) RunPolicyLoader(ctx context.Context, onUpdated func(cm *corev1.ConfigMap) error) error { cm, err := e.clientset.CoreV1().ConfigMaps(e.namespace).Get(ctx, e.configmap, metav1.GetOptions{}) if err != nil { if !apierr.IsNotFound(err) { @@ -361,12 +361,12 @@ func (e *Enforcer) RunPolicyLoader(ctx context.Context, onUpdated func(cm *apiv1 return nil } -func (e *Enforcer) runInformer(ctx context.Context, onUpdated func(cm *apiv1.ConfigMap) error) { +func (e *Enforcer) runInformer(ctx context.Context, onUpdated func(cm *corev1.ConfigMap) error) { cmInformer := e.newInformer() _, err := cmInformer.AddEventHandler( cache.ResourceEventHandlerFuncs{ AddFunc: func(obj any) { - if cm, ok := obj.(*apiv1.ConfigMap); ok { + if cm, ok := obj.(*corev1.ConfigMap); ok { err := e.syncUpdate(cm, onUpdated) if err != nil { log.Error(err) @@ -376,8 +376,8 @@ func (e *Enforcer) runInformer(ctx context.Context, onUpdated func(cm *apiv1.Con } }, UpdateFunc: func(old, new any) { - oldCM := old.(*apiv1.ConfigMap) - newCM := new.(*apiv1.ConfigMap) + oldCM := old.(*corev1.ConfigMap) + newCM := new.(*corev1.ConfigMap) if oldCM.ResourceVersion == newCM.ResourceVersion { return } @@ -430,7 +430,7 @@ func PolicyCSV(data map[string]string) string { } // syncUpdate updates the enforcer -func (e *Enforcer) syncUpdate(cm *apiv1.ConfigMap, onUpdated func(cm *apiv1.ConfigMap) error) error { +func (e *Enforcer) syncUpdate(cm *corev1.ConfigMap, onUpdated func(cm *corev1.ConfigMap) error) error { e.SetDefaultRole(cm.Data[ConfigMapPolicyDefaultKey]) e.SetMatchMode(cm.Data[ConfigMapMatchModeKey]) policyCSV := PolicyCSV(cm.Data) diff --git a/util/rbac/rbac_norace_test.go b/util/rbac/rbac_norace_test.go index 80314d04f3420..a35d29ceba64d 100644 --- a/util/rbac/rbac_norace_test.go +++ b/util/rbac/rbac_norace_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes/fake" ) @@ -32,7 +32,7 @@ func TestPolicyInformer(t *testing.T) { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() - go enf.runInformer(ctx, func(cm *apiv1.ConfigMap) error { + go enf.runInformer(ctx, func(cm *corev1.ConfigMap) error { return nil }) diff --git a/util/rbac/rbac_test.go b/util/rbac/rbac_test.go index aa127d344551c..8e8b54f44ce0b 100644 --- a/util/rbac/rbac_test.go +++ b/util/rbac/rbac_test.go @@ -10,7 +10,7 @@ import ( log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" @@ -22,12 +22,12 @@ const ( fakeNamespace = "fake-ns" ) -var noOpUpdate = func(cm *apiv1.ConfigMap) error { +var noOpUpdate = func(cm *corev1.ConfigMap) error { return nil } -func fakeConfigMap() *apiv1.ConfigMap { - cm := apiv1.ConfigMap{ +func fakeConfigMap() *corev1.ConfigMap { + cm := corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", APIVersion: "v1", diff --git a/util/settings/accounts.go b/util/settings/accounts.go index f172b6c83b19c..e3408b20e7a8a 100644 --- a/util/settings/accounts.go +++ b/util/settings/accounts.go @@ -10,7 +10,7 @@ import ( log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/util/retry" "github.com/argoproj/argo-cd/v2/common" @@ -95,8 +95,8 @@ func (a *Account) HasCapability(capability AccountCapability) bool { } func (mgr *SettingsManager) saveAccount(name string, account Account) error { - return mgr.updateSecret(func(secret *v1.Secret) error { - return mgr.updateConfigMap(func(cm *v1.ConfigMap) error { + return mgr.updateSecret(func(secret *corev1.Secret) error { + return mgr.updateConfigMap(func(cm *corev1.ConfigMap) error { return saveAccount(secret, cm, name, account) }) }) @@ -156,7 +156,7 @@ func (mgr *SettingsManager) GetAccounts() (map[string]Account, error) { return parseAccounts(secret, cm) } -func updateAccountMap(cm *v1.ConfigMap, key string, val string, defVal string) { +func updateAccountMap(cm *corev1.ConfigMap, key string, val string, defVal string) { existingVal := cm.Data[key] if existingVal != val { if val == "" || val == defVal { @@ -167,7 +167,7 @@ func updateAccountMap(cm *v1.ConfigMap, key string, val string, defVal string) { } } -func updateAccountSecret(secret *v1.Secret, key string, val string, defVal string) { +func updateAccountSecret(secret *corev1.Secret, key string, val string, defVal string) { existingVal := string(secret.Data[key]) if existingVal != val { if val == "" || val == defVal { @@ -178,7 +178,7 @@ func updateAccountSecret(secret *v1.Secret, key string, val string, defVal strin } } -func saveAccount(secret *v1.Secret, cm *v1.ConfigMap, name string, account Account) error { +func saveAccount(secret *corev1.Secret, cm *corev1.ConfigMap, name string, account Account) error { tokens, err := json.Marshal(account.Tokens) if err != nil { return err @@ -198,7 +198,7 @@ func saveAccount(secret *v1.Secret, cm *v1.ConfigMap, name string, account Accou return nil } -func parseAdminAccount(secret *v1.Secret, cm *v1.ConfigMap) (*Account, error) { +func parseAdminAccount(secret *corev1.Secret, cm *corev1.ConfigMap) (*Account, error) { adminAccount := &Account{Enabled: true, Capabilities: []AccountCapability{AccountCapabilityLogin}} if adminPasswordHash, ok := secret.Data[settingAdminPasswordHashKey]; ok { adminAccount.PasswordHash = string(adminPasswordHash) @@ -227,7 +227,7 @@ func parseAdminAccount(secret *v1.Secret, cm *v1.ConfigMap) (*Account, error) { return adminAccount, nil } -func parseAccounts(secret *v1.Secret, cm *v1.ConfigMap) (map[string]Account, error) { +func parseAccounts(secret *corev1.Secret, cm *corev1.ConfigMap) (map[string]Account, error) { adminAccount, err := parseAdminAccount(secret, cm) if err != nil { return nil, err diff --git a/util/settings/accounts_test.go b/util/settings/accounts_test.go index 2ab477ba6a963..03121a38c73b8 100644 --- a/util/settings/accounts_test.go +++ b/util/settings/accounts_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo-cd/v2/common" @@ -26,7 +26,7 @@ func TestGetAccounts_NoAccountsConfigured(t *testing.T) { } func TestGetAccounts_HasConfiguredAccounts(t *testing.T) { - _, settingsManager := fixtures(map[string]string{"accounts.test": "apiKey"}, func(secret *v1.Secret) { + _, settingsManager := fixtures(map[string]string{"accounts.test": "apiKey"}, func(secret *corev1.Secret) { secret.Data["accounts.test.tokens"] = []byte(`[{"id":"123","iat":1583789194,"exp":1583789194}]`) }) accounts, err := settingsManager.GetAccounts() @@ -77,13 +77,13 @@ func TestGetAccount_WithInvalidToken(t *testing.T) { "accounts.invaliduser": "apiKey", "accounts.user2": "apiKey", }, - func(secret *v1.Secret) { + func(secret *corev1.Secret) { secret.Data["accounts.user1.tokens"] = []byte(`[{"id":"1","iat":158378932,"exp":1583789194}]`) }, - func(secret *v1.Secret) { + func(secret *corev1.Secret) { secret.Data["accounts.invaliduser.tokens"] = []byte("Invalid token") }, - func(secret *v1.Secret) { + func(secret *corev1.Secret) { secret.Data["accounts.user2.tokens"] = []byte(`[{"id":"2","iat":1583789194,"exp":1583784545}]`) }, ) @@ -94,7 +94,7 @@ func TestGetAccount_WithInvalidToken(t *testing.T) { func TestGetAdminAccount(t *testing.T) { mTime := time.Now().Format(time.RFC3339) - _, settingsManager := fixtures(nil, func(secret *v1.Secret) { + _, settingsManager := fixtures(nil, func(secret *corev1.Secret) { secret.Data["admin.password"] = []byte("admin-password") secret.Data["admin.passwordMtime"] = []byte(mTime) }) diff --git a/util/settings/settings.go b/util/settings/settings.go index c48b76baf2a1f..168ea8ff434bf 100644 --- a/util/settings/settings.go +++ b/util/settings/settings.go @@ -20,7 +20,7 @@ import ( "time" log "github.com/sirupsen/logrus" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -202,12 +202,12 @@ type OIDCConfig struct { // DEPRECATED. Helm repository credentials are now managed using RepoCredentials type HelmRepoCredentials struct { - URL string `json:"url,omitempty"` - Name string `json:"name,omitempty"` - UsernameSecret *apiv1.SecretKeySelector `json:"usernameSecret,omitempty"` - PasswordSecret *apiv1.SecretKeySelector `json:"passwordSecret,omitempty"` - CertSecret *apiv1.SecretKeySelector `json:"certSecret,omitempty"` - KeySecret *apiv1.SecretKeySelector `json:"keySecret,omitempty"` + URL string `json:"url,omitempty"` + Name string `json:"name,omitempty"` + UsernameSecret *corev1.SecretKeySelector `json:"usernameSecret,omitempty"` + PasswordSecret *corev1.SecretKeySelector `json:"passwordSecret,omitempty"` + CertSecret *corev1.SecretKeySelector `json:"certSecret,omitempty"` + KeySecret *corev1.SecretKeySelector `json:"keySecret,omitempty"` } // KustomizeVersion holds information about additional Kustomize version @@ -229,7 +229,7 @@ type KustomizeSettings struct { var ( ByClusterURLIndexer = "byClusterURL" byClusterURLIndexerFunc = func(obj any) ([]string, error) { - s, ok := obj.(*apiv1.Secret) + s, ok := obj.(*corev1.Secret) if !ok { return nil, nil } @@ -246,7 +246,7 @@ var ( } ByClusterNameIndexer = "byClusterName" byClusterNameIndexerFunc = func(obj any) ([]string, error) { - s, ok := obj.(*apiv1.Secret) + s, ok := obj.(*corev1.Secret) if !ok { return nil, nil } @@ -266,7 +266,7 @@ var ( ByProjectRepoWriteIndexer = "byProjectRepoWrite" byProjectIndexerFunc = func(secretType string) func(obj any) ([]string, error) { return func(obj any) ([]string, error) { - s, ok := obj.(*apiv1.Secret) + s, ok := obj.(*corev1.Secret) if !ok { return nil, nil } @@ -318,11 +318,11 @@ type Repository struct { // helm only Name string `json:"name,omitempty"` // Name of the secret storing the username used to access the repo - UsernameSecret *apiv1.SecretKeySelector `json:"usernameSecret,omitempty"` + UsernameSecret *corev1.SecretKeySelector `json:"usernameSecret,omitempty"` // Name of the secret storing the password used to access the repo - PasswordSecret *apiv1.SecretKeySelector `json:"passwordSecret,omitempty"` + PasswordSecret *corev1.SecretKeySelector `json:"passwordSecret,omitempty"` // Name of the secret storing the SSH private key used to access the repo. Git only - SSHPrivateKeySecret *apiv1.SecretKeySelector `json:"sshPrivateKeySecret,omitempty"` + SSHPrivateKeySecret *corev1.SecretKeySelector `json:"sshPrivateKeySecret,omitempty"` // Whether to connect the repository in an insecure way (deprecated) InsecureIgnoreHostKey bool `json:"insecureIgnoreHostKey,omitempty"` // Whether to connect the repository in an insecure way @@ -330,13 +330,13 @@ type Repository struct { // Whether the repo is git-lfs enabled. Git only. EnableLFS bool `json:"enableLfs,omitempty"` // Name of the secret storing the TLS client cert data - TLSClientCertDataSecret *apiv1.SecretKeySelector `json:"tlsClientCertDataSecret,omitempty"` + TLSClientCertDataSecret *corev1.SecretKeySelector `json:"tlsClientCertDataSecret,omitempty"` // Name of the secret storing the TLS client cert's key data - TLSClientCertKeySecret *apiv1.SecretKeySelector `json:"tlsClientCertKeySecret,omitempty"` + TLSClientCertKeySecret *corev1.SecretKeySelector `json:"tlsClientCertKeySecret,omitempty"` // Whether the repo is helm-oci enabled. Git only. EnableOci bool `json:"enableOci,omitempty"` // Github App Private Key PEM data - GithubAppPrivateKeySecret *apiv1.SecretKeySelector `json:"githubAppPrivateKeySecret,omitempty"` + GithubAppPrivateKeySecret *corev1.SecretKeySelector `json:"githubAppPrivateKeySecret,omitempty"` // Github App ID of the app used to access the repo GithubAppId int64 `json:"githubAppID,omitempty"` // Github App Installation ID of the installed GitHub App @@ -348,7 +348,7 @@ type Repository struct { // NoProxy specifies a list of targets where the proxy isn't used, applies only in cases where the proxy is applied NoProxy string `json:"noProxy,omitempty"` // GCPServiceAccountKey specifies the service account key in JSON format to be used for getting credentials to Google Cloud Source repos - GCPServiceAccountKey *apiv1.SecretKeySelector `json:"gcpServiceAccountKey,omitempty"` + GCPServiceAccountKey *corev1.SecretKeySelector `json:"gcpServiceAccountKey,omitempty"` // ForceHttpBasicAuth determines whether Argo CD should force use of basic auth for HTTP connected repositories ForceHttpBasicAuth bool `json:"forceHttpBasicAuth,omitempty"` } @@ -358,17 +358,17 @@ type RepositoryCredentials struct { // The URL pattern the repository URL has to match URL string `json:"url,omitempty"` // Name of the secret storing the username used to access the repo - UsernameSecret *apiv1.SecretKeySelector `json:"usernameSecret,omitempty"` + UsernameSecret *corev1.SecretKeySelector `json:"usernameSecret,omitempty"` // Name of the secret storing the password used to access the repo - PasswordSecret *apiv1.SecretKeySelector `json:"passwordSecret,omitempty"` + PasswordSecret *corev1.SecretKeySelector `json:"passwordSecret,omitempty"` // Name of the secret storing the SSH private key used to access the repo. Git only - SSHPrivateKeySecret *apiv1.SecretKeySelector `json:"sshPrivateKeySecret,omitempty"` + SSHPrivateKeySecret *corev1.SecretKeySelector `json:"sshPrivateKeySecret,omitempty"` // Name of the secret storing the TLS client cert data - TLSClientCertDataSecret *apiv1.SecretKeySelector `json:"tlsClientCertDataSecret,omitempty"` + TLSClientCertDataSecret *corev1.SecretKeySelector `json:"tlsClientCertDataSecret,omitempty"` // Name of the secret storing the TLS client cert's key data - TLSClientCertKeySecret *apiv1.SecretKeySelector `json:"tlsClientCertKeySecret,omitempty"` + TLSClientCertKeySecret *corev1.SecretKeySelector `json:"tlsClientCertKeySecret,omitempty"` // Github App Private Key PEM data - GithubAppPrivateKeySecret *apiv1.SecretKeySelector `json:"githubAppPrivateKeySecret,omitempty"` + GithubAppPrivateKeySecret *corev1.SecretKeySelector `json:"githubAppPrivateKeySecret,omitempty"` // Github App ID of the app used to access the repo GithubAppId int64 `json:"githubAppID,omitempty"` // Github App Installation ID of the installed GitHub App @@ -380,7 +380,7 @@ type RepositoryCredentials struct { // the type of the repositoryCredentials, "git" or "helm", assumed to be "git" if empty or absent Type string `json:"type,omitempty"` // GCPServiceAccountKey specifies the service account key in JSON format to be used for getting credentials to Google Cloud Source repos - GCPServiceAccountKey *apiv1.SecretKeySelector `json:"gcpServiceAccountKey,omitempty"` + GCPServiceAccountKey *corev1.SecretKeySelector `json:"gcpServiceAccountKey,omitempty"` // ForceHttpBasicAuth determines whether Argo CD should force use of basic auth for HTTP connected repositories ForceHttpBasicAuth bool `json:"forceHttpBasicAuth,omitempty"` } @@ -638,14 +638,14 @@ func (mgr *SettingsManager) GetSecretsInformer() (cache.SharedIndexInformer, err return mgr.secretsInformer, nil } -func (mgr *SettingsManager) updateSecret(callback func(*apiv1.Secret) error) error { +func (mgr *SettingsManager) updateSecret(callback func(*corev1.Secret) error) error { argoCDSecret, err := mgr.getSecret() createSecret := false if err != nil { if !apierr.IsNotFound(err) { return err } - argoCDSecret = &apiv1.Secret{ + argoCDSecret = &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, }, @@ -676,14 +676,14 @@ func (mgr *SettingsManager) updateSecret(callback func(*apiv1.Secret) error) err return mgr.ResyncInformers() } -func (mgr *SettingsManager) updateConfigMap(callback func(*apiv1.ConfigMap) error) error { +func (mgr *SettingsManager) updateConfigMap(callback func(*corev1.ConfigMap) error) error { argoCDCM, err := mgr.getConfigMap() createCM := false if err != nil { if !apierr.IsNotFound(err) { return err } - argoCDCM = &apiv1.ConfigMap{ + argoCDCM = &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, }, @@ -716,14 +716,14 @@ func (mgr *SettingsManager) updateConfigMap(callback func(*apiv1.ConfigMap) erro return mgr.ResyncInformers() } -func (mgr *SettingsManager) getConfigMap() (*apiv1.ConfigMap, error) { +func (mgr *SettingsManager) getConfigMap() (*corev1.ConfigMap, error) { return mgr.GetConfigMapByName(common.ArgoCDConfigMapName) } // Returns the ConfigMap with the given name from the cluster. // The ConfigMap must be labeled with "app.kubernetes.io/part-of: argocd" in // order to be retrievable. -func (mgr *SettingsManager) GetConfigMapByName(configMapName string) (*apiv1.ConfigMap, error) { +func (mgr *SettingsManager) GetConfigMapByName(configMapName string) (*corev1.ConfigMap, error) { err := mgr.ensureSynced(false) if err != nil { return nil, err @@ -739,12 +739,12 @@ func (mgr *SettingsManager) GetConfigMapByName(configMapName string) (*apiv1.Con return cmCopy, err } -func (mgr *SettingsManager) getSecret() (*apiv1.Secret, error) { +func (mgr *SettingsManager) getSecret() (*corev1.Secret, error) { return mgr.GetSecretByName(common.ArgoCDSecretName) } // Returns the Secret with the given name from the cluster. -func (mgr *SettingsManager) GetSecretByName(secretName string) (*apiv1.Secret, error) { +func (mgr *SettingsManager) GetSecretByName(secretName string) (*corev1.Secret, error) { err := mgr.ensureSynced(false) if err != nil { return nil, err @@ -760,7 +760,7 @@ func (mgr *SettingsManager) GetSecretByName(secretName string) (*apiv1.Secret, e return secretCopy, err } -func (mgr *SettingsManager) getSecrets() ([]*apiv1.Secret, error) { +func (mgr *SettingsManager) getSecrets() ([]*corev1.Secret, error) { err := mgr.ensureSynced(false) if err != nil { return nil, err @@ -1256,7 +1256,7 @@ func (mgr *SettingsManager) GetRepositories() ([]Repository, error) { } func (mgr *SettingsManager) SaveRepositories(repos []Repository) error { - return mgr.updateConfigMap(func(argoCDCM *apiv1.ConfigMap) error { + return mgr.updateConfigMap(func(argoCDCM *corev1.ConfigMap) error { if len(repos) > 0 { yamlStr, err := yaml.Marshal(repos) if err != nil { @@ -1271,7 +1271,7 @@ func (mgr *SettingsManager) SaveRepositories(repos []Repository) error { } func (mgr *SettingsManager) SaveRepositoryCredentials(creds []RepositoryCredentials) error { - return mgr.updateConfigMap(func(argoCDCM *apiv1.ConfigMap) error { + return mgr.updateConfigMap(func(argoCDCM *corev1.ConfigMap) error { if len(creds) > 0 { yamlStr, err := yaml.Marshal(creds) if err != nil { @@ -1489,7 +1489,7 @@ func (mgr *SettingsManager) ensureSynced(forceResync bool) error { return mgr.initialize(ctx) } -func getDownloadBinaryUrlsFromConfigMap(argoCDCM *apiv1.ConfigMap) map[string]string { +func getDownloadBinaryUrlsFromConfigMap(argoCDCM *corev1.ConfigMap) map[string]string { binaryUrls := map[string]string{} for _, archType := range []string{"darwin-amd64", "darwin-arm64", "windows-amd64", "linux-amd64", "linux-arm64", "linux-ppc64le", "linux-s390x"} { if val, ok := argoCDCM.Data[settingsBinaryUrlsKey+"."+archType]; ok { @@ -1500,7 +1500,7 @@ func getDownloadBinaryUrlsFromConfigMap(argoCDCM *apiv1.ConfigMap) map[string]st } // updateSettingsFromConfigMap transfers settings from a Kubernetes configmap into an ArgoCDSettings struct. -func updateSettingsFromConfigMap(settings *ArgoCDSettings, argoCDCM *apiv1.ConfigMap) { +func updateSettingsFromConfigMap(settings *ArgoCDSettings, argoCDCM *corev1.ConfigMap) { settings.DexConfig = argoCDCM.Data[settingDexConfigKey] settings.OIDCConfigRAW = argoCDCM.Data[settingsOIDCConfigKey] settings.KustomizeBuildOptions = argoCDCM.Data[kustomizeBuildOptionsKey] @@ -1592,7 +1592,7 @@ func validateExternalURL(u string) error { } // updateSettingsFromSecret transfers settings from a Kubernetes secret into an ArgoCDSettings struct. -func (mgr *SettingsManager) updateSettingsFromSecret(settings *ArgoCDSettings, argoCDSecret *apiv1.Secret, secrets []*apiv1.Secret) error { +func (mgr *SettingsManager) updateSettingsFromSecret(settings *ArgoCDSettings, argoCDSecret *corev1.Secret, secrets []*corev1.Secret) error { var errs []error secretKey, ok := argoCDSecret.Data[settingServerSignatureKey] if ok { @@ -1675,7 +1675,7 @@ func (mgr *SettingsManager) externalServerTLSCertificate() (*tls.Certificate, er // SaveSettings serializes ArgoCDSettings and upserts it into K8s secret/configmap func (mgr *SettingsManager) SaveSettings(settings *ArgoCDSettings) error { - err := mgr.updateConfigMap(func(argoCDCM *apiv1.ConfigMap) error { + err := mgr.updateConfigMap(func(argoCDCM *corev1.ConfigMap) error { if settings.URL != "" { argoCDCM.Data[settingURLKey] = settings.URL } else { @@ -1710,7 +1710,7 @@ func (mgr *SettingsManager) SaveSettings(settings *ArgoCDSettings) error { return err } - return mgr.updateSecret(func(argoCDSecret *apiv1.Secret) error { + return mgr.updateSecret(func(argoCDSecret *corev1.Secret) error { argoCDSecret.Data[settingServerSignatureKey] = settings.ServerSignature if settings.WebhookGitHubSecret != "" { argoCDSecret.Data[settingsWebhookGitHubSecretKey] = []byte(settings.WebhookGitHubSecret) diff --git a/util/settings/settings_test.go b/util/settings/settings_test.go index 8822793364038..95d07fce97abe 100644 --- a/util/settings/settings_test.go +++ b/util/settings/settings_test.go @@ -12,22 +12,21 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/client-go/kubernetes/fake" "github.com/argoproj/argo-cd/v2/common" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" testutil "github.com/argoproj/argo-cd/v2/test" "github.com/argoproj/argo-cd/v2/util/test" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - v1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes/fake" ) -func fixtures(data map[string]string, opts ...func(secret *v1.Secret)) (*fake.Clientset, *SettingsManager) { - cm := &v1.ConfigMap{ +func fixtures(data map[string]string, opts ...func(secret *corev1.Secret)) (*fake.Clientset, *SettingsManager) { + cm := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -37,7 +36,7 @@ func fixtures(data map[string]string, opts ...func(secret *v1.Secret)) (*fake.Cl }, Data: data, } - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -57,7 +56,7 @@ func fixtures(data map[string]string, opts ...func(secret *v1.Secret)) (*fake.Cl } func TestDocumentedArgoCDConfigMapIsValid(t *testing.T) { - var argocdCM *v1.ConfigMap + var argocdCM *corev1.ConfigMap settings := ArgoCDSettings{} data, err := os.ReadFile("../../docs/operator-manual/argocd-cm.yaml") require.NoError(t, err) @@ -86,7 +85,7 @@ func TestGetConfigMapByName(t *testing.T) { func TestGetSecretByName(t *testing.T) { t.Run("data is never nil", func(t *testing.T) { - _, settingsManager := fixtures(nil, func(secret *v1.Secret) { secret.Data = nil }) + _, settingsManager := fixtures(nil, func(secret *corev1.Secret) { secret.Data = nil }) secret, err := settingsManager.GetSecretByName(common.ArgoCDSecretName) require.NoError(t, err) assert.NotNil(t, secret.Data) @@ -235,7 +234,7 @@ func TestInClusterServerAddressEnabled(t *testing.T) { func TestInClusterServerAddressEnabledByDefault(t *testing.T) { kubeClient := fake.NewClientset( - &v1.ConfigMap{ + &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -245,7 +244,7 @@ func TestInClusterServerAddressEnabledByDefault(t *testing.T) { }, Data: map[string]string{}, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -957,7 +956,7 @@ func TestSettingsManager_GetHelp(t *testing.T) { func TestSettingsManager_GetSettings(t *testing.T) { t.Run("UserSessionDurationNotProvided", func(t *testing.T) { kubeClient := fake.NewClientset( - &v1.ConfigMap{ + &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -967,7 +966,7 @@ func TestSettingsManager_GetSettings(t *testing.T) { }, Data: nil, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -987,7 +986,7 @@ func TestSettingsManager_GetSettings(t *testing.T) { }) t.Run("UserSessionDurationInvalidFormat", func(t *testing.T) { kubeClient := fake.NewClientset( - &v1.ConfigMap{ + &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -999,7 +998,7 @@ func TestSettingsManager_GetSettings(t *testing.T) { "users.session.duration": "10hh", }, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -1019,7 +1018,7 @@ func TestSettingsManager_GetSettings(t *testing.T) { }) t.Run("UserSessionDurationProvided", func(t *testing.T) { kubeClient := fake.NewClientset( - &v1.ConfigMap{ + &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -1031,7 +1030,7 @@ func TestSettingsManager_GetSettings(t *testing.T) { "users.session.duration": "10h", }, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -1053,7 +1052,7 @@ func TestSettingsManager_GetSettings(t *testing.T) { func TestGetOIDCConfig(t *testing.T) { kubeClient := fake.NewClientset( - &v1.ConfigMap{ + &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -1065,7 +1064,7 @@ func TestGetOIDCConfig(t *testing.T) { "oidc.config": "\n requestedIDTokenClaims: {\"groups\": {\"essential\": true}}\n", }, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -1133,7 +1132,7 @@ func Test_validateExternalURL(t *testing.T) { func TestGetOIDCSecretTrim(t *testing.T) { kubeClient := fake.NewClientset( - &v1.ConfigMap{ + &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -1145,7 +1144,7 @@ func TestGetOIDCSecretTrim(t *testing.T) { "oidc.config": "\n name: Okta\n clientSecret: test-secret\r\n \n clientID: aaaabbbbccccddddeee\n", }, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -1179,7 +1178,7 @@ func getCNFromCertificate(cert *tls.Certificate) string { func Test_GetTLSConfiguration(t *testing.T) { t.Run("Valid external TLS secret with success", func(t *testing.T) { kubeClient := fake.NewClientset( - &v1.ConfigMap{ + &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -1191,7 +1190,7 @@ func Test_GetTLSConfiguration(t *testing.T) { "oidc.config": "\n name: Okta\n clientSecret: test-secret\r\n \n clientID: aaaabbbbccccddddeee\n", }, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -1204,7 +1203,7 @@ func Test_GetTLSConfiguration(t *testing.T) { "server.secretkey": nil, }, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: externalServerTLSSecretName, Namespace: "default", @@ -1225,7 +1224,7 @@ func Test_GetTLSConfiguration(t *testing.T) { t.Run("Valid external TLS secret overrides argocd-secret", func(t *testing.T) { kubeClient := fake.NewClientset( - &v1.ConfigMap{ + &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -1237,7 +1236,7 @@ func Test_GetTLSConfiguration(t *testing.T) { "oidc.config": "\n name: Okta\n clientSecret: test-secret\r\n \n clientID: aaaabbbbccccddddeee\n", }, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -1252,7 +1251,7 @@ func Test_GetTLSConfiguration(t *testing.T) { "tls.key": []byte(testutil.MustLoadFileToString("../../test/fixture/certs/argocd-e2e-server.key")), }, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: externalServerTLSSecretName, Namespace: "default", @@ -1272,7 +1271,7 @@ func Test_GetTLSConfiguration(t *testing.T) { }) t.Run("Invalid external TLS secret", func(t *testing.T) { kubeClient := fake.NewClientset( - &v1.ConfigMap{ + &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -1284,7 +1283,7 @@ func Test_GetTLSConfiguration(t *testing.T) { "oidc.config": "\n name: Okta\n clientSecret: test-secret\r\n \n clientID: aaaabbbbccccddddeee\n", }, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -1297,7 +1296,7 @@ func Test_GetTLSConfiguration(t *testing.T) { "server.secretkey": nil, }, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: externalServerTLSSecretName, Namespace: "default", @@ -1315,7 +1314,7 @@ func Test_GetTLSConfiguration(t *testing.T) { }) t.Run("No external TLS secret", func(t *testing.T) { kubeClient := fake.NewClientset( - &v1.ConfigMap{ + &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -1327,7 +1326,7 @@ func Test_GetTLSConfiguration(t *testing.T) { "oidc.config": "\n name: Okta\n clientSecret: test-secret\r\n \n clientID: aaaabbbbccccddddeee\n", }, }, - &v1.Secret{ + &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -1386,7 +1385,7 @@ requestedScopes: ["openid", "profile", "email"] # Optional set of OIDC claims to request on the ID token. requestedIDTokenClaims: {"groups": {"essential": true}}`, } - cm := &v1.ConfigMap{ + cm := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -1396,7 +1395,7 @@ requestedIDTokenClaims: {"groups": {"essential": true}}`, }, Data: data, } - argocdSecret := &v1.Secret{ + argocdSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -1407,7 +1406,7 @@ requestedIDTokenClaims: {"groups": {"essential": true}}`, "webhook.github.secret": []byte("$ext:webhook.github.secret"), }, } - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "ext", Namespace: "default", @@ -1458,7 +1457,7 @@ func TestGetEnableManifestGeneration(t *testing.T) { for i := range testCases { tc := testCases[i] t.Run(tc.name, func(t *testing.T) { - cm := &v1.ConfigMap{ + cm := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -1468,7 +1467,7 @@ func TestGetEnableManifestGeneration(t *testing.T) { }, Data: tc.data, } - argocdSecret := &v1.Secret{ + argocdSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -1516,7 +1515,7 @@ func TestGetHelmSettings(t *testing.T) { for i := range testCases { tc := testCases[i] t.Run(tc.name, func(t *testing.T) { - cm := &v1.ConfigMap{ + cm := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDConfigMapName, Namespace: "default", @@ -1526,7 +1525,7 @@ func TestGetHelmSettings(t *testing.T) { }, Data: tc.data, } - argocdSecret := &v1.Secret{ + argocdSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: common.ArgoCDSecretName, Namespace: "default", @@ -1536,7 +1535,7 @@ func TestGetHelmSettings(t *testing.T) { "server.secretkey": nil, }, } - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "acme", Namespace: "default", diff --git a/util/util.go b/util/util.go index 862d3848984ba..2f3a458f9979b 100644 --- a/util/util.go +++ b/util/util.go @@ -4,7 +4,7 @@ import ( "crypto/rand" "encoding/base64" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" ) // MakeSignature generates a cryptographically-secure pseudo-random token, based on a given number of random bytes, for signing purposes. @@ -23,8 +23,8 @@ func MakeSignature(size int) ([]byte, error) { // // This function takes a slice of pointers to Secrets and returns a new slice // containing deep copies of the original secrets. -func SecretCopy(secrets []*apiv1.Secret) []*apiv1.Secret { - secretsCopy := make([]*apiv1.Secret, len(secrets)) +func SecretCopy(secrets []*corev1.Secret) []*corev1.Secret { + secretsCopy := make([]*corev1.Secret, len(secrets)) for i, secret := range secrets { secretsCopy[i] = secret.DeepCopy() } diff --git a/util/util_test.go b/util/util_test.go index 1edafb9350491..e166646541c75 100644 --- a/util/util_test.go +++ b/util/util_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - apiv1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo-cd/v2/util" @@ -44,31 +44,31 @@ func TestParseRevision(t *testing.T) { func TestSecretCopy(t *testing.T) { type args struct { - secrets []*apiv1.Secret + secrets []*corev1.Secret } tests := []struct { name string args args - want []*apiv1.Secret + want []*corev1.Secret }{ - {name: "nil", args: args{secrets: nil}, want: []*apiv1.Secret{}}, + {name: "nil", args: args{secrets: nil}, want: []*corev1.Secret{}}, { - name: "Three", args: args{secrets: []*apiv1.Secret{ + name: "Three", args: args{secrets: []*corev1.Secret{ {ObjectMeta: metav1.ObjectMeta{Name: "one"}}, {ObjectMeta: metav1.ObjectMeta{Name: "two"}}, {ObjectMeta: metav1.ObjectMeta{Name: "three"}}, }}, - want: []*apiv1.Secret{ + want: []*corev1.Secret{ {ObjectMeta: metav1.ObjectMeta{Name: "one"}}, {ObjectMeta: metav1.ObjectMeta{Name: "two"}}, {ObjectMeta: metav1.ObjectMeta{Name: "three"}}, }, }, { - name: "One", args: args{secrets: []*apiv1.Secret{{ObjectMeta: metav1.ObjectMeta{Name: "one"}}}}, - want: []*apiv1.Secret{{ObjectMeta: metav1.ObjectMeta{Name: "one"}}}, + name: "One", args: args{secrets: []*corev1.Secret{{ObjectMeta: metav1.ObjectMeta{Name: "one"}}}}, + want: []*corev1.Secret{{ObjectMeta: metav1.ObjectMeta{Name: "one"}}}, }, - {name: "Zero", args: args{secrets: []*apiv1.Secret{}}, want: []*apiv1.Secret{}}, + {name: "Zero", args: args{secrets: []*corev1.Secret{}}, want: []*corev1.Secret{}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { From ef55ba549bd7893d80223c19a16fb1d1368d3f0c Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Fri, 3 Jan 2025 17:10:24 +0100 Subject: [PATCH 10/41] chore: use dario.cat/mergo instead of github.com/imdario/mergo (#21274) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 4 ++++ applicationset/generators/generator_spec_processor.go | 2 +- applicationset/generators/matrix.go | 2 +- applicationset/generators/merge.go | 2 +- controller/state_test.go | 2 +- go.mod | 4 ++-- 6 files changed, 10 insertions(+), 6 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index eb77d99d3012e..2c67b56154f2f 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -49,6 +49,10 @@ linters-settings: - github.com/golang-jwt/jwt/v4: recommendations: - github.com/golang-jwt/jwt/v5 + - github.com/imdario/mergo: + recommendations: + - dario.cat/mergo + reason: "`github.com/imdario/mergo` has been renamed." - github.com/pkg/errors: recommendations: - errors diff --git a/applicationset/generators/generator_spec_processor.go b/applicationset/generators/generator_spec_processor.go index 6a94890eb92eb..822f29f340662 100644 --- a/applicationset/generators/generator_spec_processor.go +++ b/applicationset/generators/generator_spec_processor.go @@ -13,7 +13,7 @@ import ( argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - "github.com/imdario/mergo" + "dario.cat/mergo" log "github.com/sirupsen/logrus" ) diff --git a/applicationset/generators/matrix.go b/applicationset/generators/matrix.go index d3edc0558a962..2ddf87f9d6cdd 100644 --- a/applicationset/generators/matrix.go +++ b/applicationset/generators/matrix.go @@ -5,7 +5,7 @@ import ( "fmt" "time" - "github.com/imdario/mergo" + "dario.cat/mergo" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/argoproj/argo-cd/v2/applicationset/utils" diff --git a/applicationset/generators/merge.go b/applicationset/generators/merge.go index 2138d3599dc24..7532716775ce1 100644 --- a/applicationset/generators/merge.go +++ b/applicationset/generators/merge.go @@ -6,7 +6,7 @@ import ( "fmt" "time" - "github.com/imdario/mergo" + "dario.cat/mergo" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/argoproj/argo-cd/v2/applicationset/utils" diff --git a/controller/state_test.go b/controller/state_test.go index c446176fea9e9..aeab4ad0574a7 100644 --- a/controller/state_test.go +++ b/controller/state_test.go @@ -7,11 +7,11 @@ import ( "testing" "time" + "dario.cat/mergo" "github.com/argoproj/gitops-engine/pkg/health" synccommon "github.com/argoproj/gitops-engine/pkg/sync/common" "github.com/argoproj/gitops-engine/pkg/utils/kube" . "github.com/argoproj/gitops-engine/pkg/utils/testing" - "github.com/imdario/mergo" "github.com/sirupsen/logrus" logrustest "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/assert" diff --git a/go.mod b/go.mod index dc66f9214e6cc..fa24962628d0c 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.22.0 require ( code.gitea.io/sdk/gitea v0.19.0 + dario.cat/mergo v1.0.1 github.com/Azure/kubelogin v0.1.6 github.com/Masterminds/semver/v3 v3.3.1 github.com/Masterminds/sprig/v3 v3.3.0 @@ -54,7 +55,6 @@ require ( github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/hashicorp/go-retryablehttp v0.7.7 - github.com/imdario/mergo v0.3.16 github.com/improbable-eng/grpc-web v0.15.0 github.com/itchyny/gojq v0.12.17 github.com/jeremywohl/flatten v1.0.1 @@ -113,7 +113,6 @@ require ( ) require ( - dario.cat/mergo v1.0.1 // indirect github.com/Azure/azure-sdk-for-go/sdk/azcore v1.14.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect @@ -143,6 +142,7 @@ require ( github.com/google/s2a-go v0.1.7 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect github.com/googleapis/gax-go/v2 v2.12.3 // indirect + github.com/imdario/mergo v0.3.16 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect From 5508d1fedaf56be03d74f8d5bed8cd82eb46e10f Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Fri, 3 Jan 2025 18:09:37 +0100 Subject: [PATCH 11/41] chore: enable importas for k8s.io/apimachinery/pkg/api/errors (#21262) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 2 ++ .../controllers/applicationset_controller.go | 8 ++--- cmd/argocd/commands/admin/backup.go | 16 ++++----- .../commands/admin/redis_initial_password.go | 4 +-- controller/appcontroller.go | 14 ++++---- controller/appcontroller_test.go | 4 +-- controller/cache/cache.go | 22 ++++++------ controller/cache/cache_test.go | 12 +++---- controller/sharding/sharding.go | 6 ++-- server/application/application.go | 22 ++++++------ server/application/terminal.go | 4 +-- server/applicationset/applicationset.go | 8 ++--- server/notification/notification.go | 8 ++--- server/project/project.go | 6 ++-- server/repository/repository.go | 4 +-- test/e2e/fixture/app/expectation.go | 6 ++-- .../fixture/applicationsets/utils/fixture.go | 10 +++--- util/argo/argo.go | 6 ++-- util/clusterauth/clusterauth.go | 14 ++++---- util/clusterauth/clusterauth_test.go | 4 +-- util/db/cluster.go | 4 +-- util/db/db.go | 4 +-- util/db/repository_legacy.go | 4 +-- util/db/repository_secrets.go | 8 ++--- util/db/repository_secrets_test.go | 6 ++-- util/grpc/errors.go | 28 +++++++-------- util/grpc/errors_test.go | 34 +++++++++---------- util/rbac/rbac.go | 4 +-- util/settings/settings.go | 7 ++-- 29 files changed, 139 insertions(+), 140 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 2c67b56154f2f..307792b0cb251 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -62,6 +62,8 @@ linters-settings: pkg: github.com/golang-jwt/jwt/v5 - alias: corev1 pkg: k8s.io/api/core/v1 + - alias: apierrors + pkg: k8s.io/apimachinery/pkg/api/errors - alias: metav1 pkg: k8s.io/apimachinery/pkg/apis/meta/v1 - alias: stderrors diff --git a/applicationset/controllers/applicationset_controller.go b/applicationset/controllers/applicationset_controller.go index c0545222817fa..63baafaa64114 100644 --- a/applicationset/controllers/applicationset_controller.go +++ b/applicationset/controllers/applicationset_controller.go @@ -28,7 +28,7 @@ import ( "github.com/google/go-cmp/cmp/cmpopts" log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" @@ -465,7 +465,7 @@ func (r *ApplicationSetReconciler) setApplicationSetStatusCondition(ctx context. updatedAppset.DeepCopyInto(applicationSet) return nil }) - if err != nil && !apierr.IsNotFound(err) { + if err != nil && !apierrors.IsNotFound(err) { return fmt.Errorf("unable to set application set condition: %w", err) } } @@ -489,7 +489,7 @@ func (r *ApplicationSetReconciler) validateGeneratedApplications(ctx context.Con appProject := &argov1alpha1.AppProject{} err := r.Client.Get(ctx, types.NamespacedName{Name: app.Spec.Project, Namespace: r.ArgoCDNamespace}, appProject) if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { errorsByIndex[i] = fmt.Errorf("application references project %s which does not exist", app.Spec.Project) continue } @@ -1302,7 +1302,7 @@ func (r *ApplicationSetReconciler) migrateStatus(ctx context.Context, appset *ar updatedAppset.DeepCopyInto(appset) return nil }) - if err != nil && !apierr.IsNotFound(err) { + if err != nil && !apierrors.IsNotFound(err) { return fmt.Errorf("unable to set application set condition: %w", err) } } diff --git a/cmd/argocd/commands/admin/backup.go b/cmd/argocd/commands/admin/backup.go index 9e9efc9d576c4..7b58cd49fae8d 100644 --- a/cmd/argocd/commands/admin/backup.go +++ b/cmd/argocd/commands/admin/backup.go @@ -9,7 +9,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/utils/kube" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/client-go/dynamic" @@ -106,8 +106,8 @@ func NewExportCommand() *cobra.Command { } } applicationSets, err := acdClients.applicationSets.List(ctx, metav1.ListOptions{}) - if err != nil && !apierr.IsNotFound(err) { - if apierr.IsForbidden(err) { + if err != nil && !apierrors.IsNotFound(err) { + if apierrors.IsForbidden(err) { log.Warn(err) } else { errors.CheckError(err) @@ -222,7 +222,7 @@ func NewImportCommand() *cobra.Command { pruneObjects[kube.ResourceKey{Group: application.Group, Kind: application.AppProjectKind, Name: proj.GetName(), Namespace: proj.GetNamespace()}] = proj } applicationSets, err := acdClients.applicationSets.List(ctx, metav1.ListOptions{}) - if apierr.IsForbidden(err) || apierr.IsNotFound(err) { + if apierrors.IsForbidden(err) || apierrors.IsNotFound(err) { log.Warnf("argoproj.io/ApplicationSet: %v\n", err) } else { errors.CheckError(err) @@ -279,7 +279,7 @@ func NewImportCommand() *cobra.Command { isForbidden := false if !dryRun { _, err = dynClient.Create(ctx, bakObj, metav1.CreateOptions{}) - if apierr.IsForbidden(err) || apierr.IsNotFound(err) { + if apierrors.IsForbidden(err) || apierrors.IsNotFound(err) { isForbidden = true log.Warnf("%s/%s %s: %v", gvk.Group, gvk.Kind, bakObj.GetName(), err) } else { @@ -298,7 +298,7 @@ func NewImportCommand() *cobra.Command { if !dryRun { newLive := updateLive(bakObj, &liveObj, stopOperation) _, err = dynClient.Update(ctx, newLive, metav1.UpdateOptions{}) - if apierr.IsForbidden(err) || apierr.IsNotFound(err) { + if apierrors.IsForbidden(err) || apierrors.IsNotFound(err) { isForbidden = true log.Warnf("%s/%s %s: %v", gvk.Group, gvk.Kind, bakObj.GetName(), err) } else { @@ -329,7 +329,7 @@ func NewImportCommand() *cobra.Command { newLive := liveObj.DeepCopy() newLive.SetFinalizers(nil) _, err = dynClient.Update(ctx, newLive, metav1.UpdateOptions{}) - if err != nil && !apierr.IsNotFound(err) { + if err != nil && !apierrors.IsNotFound(err) { errors.CheckError(err) } } @@ -345,7 +345,7 @@ func NewImportCommand() *cobra.Command { canPrune := promptUtil.Confirm(fmt.Sprintf("Are you sure you want to prune %s/%s %s ? [y/n]", key.Group, key.Kind, key.Name)) if canPrune { err = dynClient.Delete(ctx, key.Name, metav1.DeleteOptions{}) - if apierr.IsForbidden(err) || apierr.IsNotFound(err) { + if apierrors.IsForbidden(err) || apierrors.IsNotFound(err) { isForbidden = true log.Warnf("%s/%s %s: %v\n", key.Group, key.Kind, key.Name, err) } else { diff --git a/cmd/argocd/commands/admin/redis_initial_password.go b/cmd/argocd/commands/admin/redis_initial_password.go index a0f0a9845cbb6..82085f9ec6771 100644 --- a/cmd/argocd/commands/admin/redis_initial_password.go +++ b/cmd/argocd/commands/admin/redis_initial_password.go @@ -8,7 +8,7 @@ import ( "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" @@ -74,7 +74,7 @@ func NewRedisInitialPasswordCommand() *cobra.Command { Type: corev1.SecretTypeOpaque, } _, err = kubeClientset.CoreV1().Secrets(namespace).Create(context.Background(), secret, metav1.CreateOptions{}) - if err != nil && !apierr.IsAlreadyExists(err) { + if err != nil && !apierrors.IsAlreadyExists(err) { errors.CheckError(err) } diff --git a/controller/appcontroller.go b/controller/appcontroller.go index 479c84bdf6099..910f4fc1ae06d 100644 --- a/controller/appcontroller.go +++ b/controller/appcontroller.go @@ -26,7 +26,7 @@ import ( log "github.com/sirupsen/logrus" "golang.org/x/sync/semaphore" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/labels" @@ -60,8 +60,6 @@ import ( "github.com/argoproj/argo-cd/v2/util/env" "github.com/argoproj/argo-cd/v2/util/stats" - kubeerrors "k8s.io/apimachinery/pkg/api/errors" - "github.com/argoproj/argo-cd/v2/pkg/ratelimiter" appstatecache "github.com/argoproj/argo-cd/v2/util/cache/appstate" "github.com/argoproj/argo-cd/v2/util/db" @@ -277,7 +275,7 @@ func NewApplicationController( applicationControllerName := env.StringFromEnv(common.EnvAppControllerName, common.DefaultApplicationControllerName) appControllerDeployment, err := deploymentInformer.Lister().Deployments(settingsMgr.GetNamespace()).Get(applicationControllerName) if err != nil { - if kubeerrors.IsNotFound(err) { + if apierrors.IsNotFound(err) { appControllerDeployment = nil } else { return fmt.Errorf("error retrieving Application Controller Deployment: %w", err) @@ -400,7 +398,7 @@ func (ctrl *ApplicationController) getAppProj(app *appv1.Application) (*appv1.Ap } proj, err := projCache.(*appProjCache).GetAppProject(context.TODO()) if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil, err } else { return nil, fmt.Errorf("could not retrieve AppProject '%s' from cache: %w", app.Spec.Project, err) @@ -1180,7 +1178,7 @@ func (ctrl *ApplicationController) finalizeApplicationDeletion(app *appv1.Applic // Get refreshed application info, since informer app copy might be stale app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(app.Namespace).Get(context.Background(), app.Name, metav1.GetOptions{}) if err != nil { - if !apierr.IsNotFound(err) { + if !apierrors.IsNotFound(err) { logCtx.Errorf("Unable to get refreshed application info prior deleting resources: %v", err) } return nil @@ -1535,7 +1533,7 @@ func (ctrl *ApplicationController) setOperationState(app *appv1.Application, sta _, err := ctrl.PatchAppWithWriteBack(context.Background(), app.Name, app.Namespace, types.MergePatchType, patchJSON, metav1.PatchOptions{}) if err != nil { // Stop retrying updating deleted application - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil } // kube.RetryUntilSucceed logs failed attempts at "debug" level, but we want to know if this fails. Log a @@ -2449,7 +2447,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar func (ctrl *ApplicationController) projectErrorToCondition(err error, app *appv1.Application) appv1.ApplicationCondition { var condition appv1.ApplicationCondition - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { condition = appv1.ApplicationCondition{ Type: appv1.ApplicationConditionInvalidSpecError, Message: fmt.Sprintf("Application referencing project %s which does not exist", app.Spec.Project), diff --git a/controller/appcontroller_test.go b/controller/appcontroller_test.go index 1cfc623959711..75b6fd5bfd860 100644 --- a/controller/appcontroller_test.go +++ b/controller/appcontroller_test.go @@ -30,7 +30,7 @@ import ( "github.com/stretchr/testify/mock" v1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" @@ -1309,7 +1309,7 @@ func TestSetOperationStateOnDeletedApp(t *testing.T) { patched := false fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true - return true, &v1alpha1.Application{}, apierr.NewNotFound(schema.GroupResource{}, "my-app") + return true, &v1alpha1.Application{}, apierrors.NewNotFound(schema.GroupResource{}, "my-app") }) ctrl.setOperationState(newFakeApp(), &v1alpha1.OperationState{Phase: synccommon.OperationSucceeded}) assert.True(t, patched) diff --git a/controller/cache/cache.go b/controller/cache/cache.go index ceb21c3e7b19d..08682c41d5078 100644 --- a/controller/cache/cache.go +++ b/controller/cache/cache.go @@ -21,7 +21,7 @@ import ( log "github.com/sirupsen/logrus" "golang.org/x/sync/semaphore" corev1 "k8s.io/api/core/v1" - kerrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" @@ -409,14 +409,14 @@ func isRetryableError(err error) bool { if err == nil { return false } - return kerrors.IsInternalError(err) || - kerrors.IsInvalid(err) || - kerrors.IsTooManyRequests(err) || - kerrors.IsServerTimeout(err) || - kerrors.IsServiceUnavailable(err) || - kerrors.IsTimeout(err) || - kerrors.IsUnexpectedObjectError(err) || - kerrors.IsUnexpectedServerError(err) || + return apierrors.IsInternalError(err) || + apierrors.IsInvalid(err) || + apierrors.IsTooManyRequests(err) || + apierrors.IsServerTimeout(err) || + apierrors.IsServiceUnavailable(err) || + apierrors.IsTimeout(err) || + apierrors.IsUnexpectedObjectError(err) || + apierrors.IsUnexpectedServerError(err) || isResourceQuotaConflictErr(err) || isTransientNetworkErr(err) || isExceededQuotaErr(err) || @@ -429,11 +429,11 @@ func isHTTP2GoawayErr(err error) bool { } func isExceededQuotaErr(err error) bool { - return kerrors.IsForbidden(err) && strings.Contains(err.Error(), "exceeded quota") + return apierrors.IsForbidden(err) && strings.Contains(err.Error(), "exceeded quota") } func isResourceQuotaConflictErr(err error) bool { - return kerrors.IsConflict(err) && strings.Contains(err.Error(), "Operation cannot be fulfilled on resourcequota") + return apierrors.IsConflict(err) && strings.Contains(err.Error(), "Operation cannot be fulfilled on resourcequota") } func isTransientNetworkErr(err error) bool { diff --git a/controller/cache/cache_test.go b/controller/cache/cache_test.go index 92322c3c44848..31bffd5c1502b 100644 --- a/controller/cache/cache_test.go +++ b/controller/cache/cache_test.go @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -239,15 +239,15 @@ func TestIsRetryableError(t *testing.T) { assert.False(t, isRetryableError(nil)) }) t.Run("ResourceQuotaConflictErr", func(t *testing.T) { - assert.False(t, isRetryableError(apierr.NewConflict(schema.GroupResource{}, "", nil))) - assert.True(t, isRetryableError(apierr.NewConflict(schema.GroupResource{Group: "v1", Resource: "resourcequotas"}, "", nil))) + assert.False(t, isRetryableError(apierrors.NewConflict(schema.GroupResource{}, "", nil))) + assert.True(t, isRetryableError(apierrors.NewConflict(schema.GroupResource{Group: "v1", Resource: "resourcequotas"}, "", nil))) }) t.Run("ExceededQuotaErr", func(t *testing.T) { - assert.False(t, isRetryableError(apierr.NewForbidden(schema.GroupResource{}, "", nil))) - assert.True(t, isRetryableError(apierr.NewForbidden(schema.GroupResource{Group: "v1", Resource: "pods"}, "", errors.New("exceeded quota")))) + assert.False(t, isRetryableError(apierrors.NewForbidden(schema.GroupResource{}, "", nil))) + assert.True(t, isRetryableError(apierrors.NewForbidden(schema.GroupResource{Group: "v1", Resource: "pods"}, "", errors.New("exceeded quota")))) }) t.Run("TooManyRequestsDNS", func(t *testing.T) { - assert.True(t, isRetryableError(apierr.NewTooManyRequests("", 0))) + assert.True(t, isRetryableError(apierrors.NewTooManyRequests("", 0))) }) t.Run("DNSError", func(t *testing.T) { assert.True(t, isRetryableError(&net.DNSError{})) diff --git a/controller/sharding/sharding.go b/controller/sharding/sharding.go index 5634cdea12ddf..d883b6839a277 100644 --- a/controller/sharding/sharding.go +++ b/controller/sharding/sharding.go @@ -23,7 +23,7 @@ import ( "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" log "github.com/sirupsen/logrus" - kubeerrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "github.com/argoproj/argo-cd/v2/util/db" "github.com/argoproj/argo-cd/v2/util/env" @@ -313,7 +313,7 @@ func GetOrUpdateShardFromConfigMap(kubeClient kubernetes.Interface, settingsMgr shardMappingCM, err := kubeClient.CoreV1().ConfigMaps(settingsMgr.GetNamespace()).Get(context.Background(), common.ArgoCDAppControllerShardConfigMapName, metav1.GetOptions{}) if err != nil { - if !kubeerrors.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return -1, fmt.Errorf("error getting sharding config map: %w", err) } log.Infof("shard mapping configmap %s not found. Creating default shard mapping configmap.", common.ArgoCDAppControllerShardConfigMapName) @@ -487,7 +487,7 @@ func GetClusterSharding(kubeClient kubernetes.Interface, settingsMgr *settings.S // If we still see conflicts after the retries, wait for next iteration of heartbeat process. for i := 0; i <= common.AppControllerHeartbeatUpdateRetryCount; i++ { shardNumber, err = GetOrUpdateShardFromConfigMap(kubeClient, settingsMgr, replicasCount, shardNumber) - if err != nil && !kubeerrors.IsConflict(err) { + if err != nil && !apierrors.IsConflict(err) { err = fmt.Errorf("unable to get shard due to error updating the sharding config map: %w", err) break } diff --git a/server/application/application.go b/server/application/application.go index 46ffe686a2075..9a12da04f1be2 100644 --- a/server/application/application.go +++ b/server/application/application.go @@ -23,7 +23,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/fields" @@ -176,10 +176,10 @@ func (s *Server) getAppEnforceRBAC(ctx context.Context, action, project, namespa } a, err := getApp() if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { if project != "" { // We know that the user was allowed to get the Application, but the Application does not exist. Return 404. - return nil, nil, status.Error(codes.NotFound, apierr.NewNotFound(schema.GroupResource{Group: "argoproj.io", Resource: "applications"}, name).Error()) + return nil, nil, status.Error(codes.NotFound, apierrors.NewNotFound(schema.GroupResource{Group: "argoproj.io", Resource: "applications"}, name).Error()) } // We don't know if the user was allowed to get the Application, and we don't want to leak information about // the Application's existence. Return 403. @@ -201,7 +201,7 @@ func (s *Server) getAppEnforceRBAC(ctx context.Context, action, project, namespa // The user specified a project. We would have returned a 404 if the user had access to the app, but the app // did not exist. So we have to return a 404 when the app does exist, but the user does not have access. // Otherwise, they could infer that the app exists based on the error code. - return nil, nil, status.Error(codes.NotFound, apierr.NewNotFound(schema.GroupResource{Group: "argoproj.io", Resource: "applications"}, name).Error()) + return nil, nil, status.Error(codes.NotFound, apierrors.NewNotFound(schema.GroupResource{Group: "argoproj.io", Resource: "applications"}, name).Error()) } // The user didn't specify a project. We always return permission denied for both lack of access and lack of // existence. @@ -218,7 +218,7 @@ func (s *Server) getAppEnforceRBAC(ctx context.Context, action, project, namespa }).Warnf("user tried to %s application in project %s, but the application is in project %s", action, project, effectiveProject) // The user has access to the app, but the app is in a different project. Return 404, meaning "app doesn't // exist in that project". - return nil, nil, status.Error(codes.NotFound, apierr.NewNotFound(schema.GroupResource{Group: "argoproj.io", Resource: "applications"}, name).Error()) + return nil, nil, status.Error(codes.NotFound, apierrors.NewNotFound(schema.GroupResource{Group: "argoproj.io", Resource: "applications"}, name).Error()) } // Get the app's associated project, and make sure all project restrictions are enforced. proj, err := s.getAppProject(ctx, a, logCtx) @@ -357,7 +357,7 @@ func (s *Server) Create(ctx context.Context, q *application.ApplicationCreateReq s.waitSync(created) return created, nil } - if !apierr.IsAlreadyExists(err) { + if !apierrors.IsAlreadyExists(err) { return nil, fmt.Errorf("error creating application: %w", err) } @@ -949,7 +949,7 @@ func (s *Server) updateApp(app *appv1.Application, newApp *appv1.Application, ct s.waitSync(res) return res, nil } - if !apierr.IsConflict(err) { + if !apierrors.IsConflict(err) { return nil, err } @@ -1055,7 +1055,7 @@ func (s *Server) getAppProject(ctx context.Context, a *appv1.Application, logCtx // If there's a permission issue or the app doesn't exist, return a vague error to avoid letting the user enumerate project names. vagueError := status.Errorf(codes.InvalidArgument, "app is not allowed in project %q, or the project does not exist", a.Spec.Project) - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil, vagueError } @@ -1247,7 +1247,7 @@ func (s *Server) validateAndNormalizeApp(ctx context.Context, app *appv1.Applica appNs := s.appNamespaceOrDefault(app.Namespace) currApp, err := s.appclientset.ArgoprojV1alpha1().Applications(appNs).Get(ctx, app.Name, metav1.GetOptions{}) if err != nil { - if !apierr.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return fmt.Errorf("error getting application by name: %w", err) } // Kubernetes go-client will return a pointer to a zero-value app instead of nil, even @@ -2311,7 +2311,7 @@ func (s *Server) TerminateOperation(ctx context.Context, termOpReq *application. s.logAppEvent(a, ctx, argo.EventReasonResourceUpdated, "terminated running operation") return &application.OperationTerminateResponse{}, nil } - if !apierr.IsConflict(err) { + if !apierrors.IsConflict(err) { return nil, fmt.Errorf("error updating application: %w", err) } log.Warnf("failed to set operation for app %q due to update conflict. retrying again...", *termOpReq.Name) @@ -2548,7 +2548,7 @@ func (s *Server) patchResource(ctx context.Context, config *rest.Config, liveObj if statusPatch != nil { _, err = s.kubectl.PatchResource(ctx, config, newObj.GroupVersionKind(), newObj.GetName(), newObj.GetNamespace(), types.MergePatchType, diffBytes, "status") if err != nil { - if !apierr.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return nil, fmt.Errorf("error patching resource: %w", err) } // K8s API server returns 404 NotFound when the CRD does not support the status subresource diff --git a/server/application/terminal.go b/server/application/terminal.go index 814ea3ad15b8a..ecfc20f85c090 100644 --- a/server/application/terminal.go +++ b/server/application/terminal.go @@ -9,7 +9,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/utils/kube" log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" @@ -170,7 +170,7 @@ func (s *terminalHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { a, err := s.appLister.Applications(ns).Get(app) if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { http.Error(w, "App not found", http.StatusNotFound) return } diff --git a/server/applicationset/applicationset.go b/server/applicationset/applicationset.go index 49e0a42fb9e05..1b00fea5ebd3e 100644 --- a/server/applicationset/applicationset.go +++ b/server/applicationset/applicationset.go @@ -16,7 +16,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/dynamic" @@ -230,7 +230,7 @@ func (s *Server) Create(ctx context.Context, q *applicationset.ApplicationSetCre return created, nil } - if !apierr.IsAlreadyExists(err) { + if !apierrors.IsAlreadyExists(err) { return nil, fmt.Errorf("error creating ApplicationSet: %w", err) } // act idempotent if existing spec matches new spec @@ -314,7 +314,7 @@ func (s *Server) updateAppSet(appset *v1alpha1.ApplicationSet, newAppset *v1alph s.waitSync(res) return res, nil } - if !apierr.IsConflict(err) { + if !apierrors.IsConflict(err) { return nil, err } @@ -453,7 +453,7 @@ func (s *Server) checkCreatePermissions(ctx context.Context, appset *v1alpha1.Ap _, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(ctx, projectName, metav1.GetOptions{}) if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { return status.Errorf(codes.InvalidArgument, "ApplicationSet references project %s which does not exist", projectName) } return fmt.Errorf("error getting ApplicationSet's project %q: %w", projectName, err) diff --git a/server/notification/notification.go b/server/notification/notification.go index 7b8f6589fcfbf..e34520e97513e 100644 --- a/server/notification/notification.go +++ b/server/notification/notification.go @@ -4,7 +4,7 @@ import ( "context" "github.com/argoproj/notifications-engine/pkg/api" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/utils/ptr" "github.com/argoproj/argo-cd/v2/pkg/apiclient/notification" @@ -25,7 +25,7 @@ func NewServer(apiFactory api.Factory) notification.NotificationServiceServer { func (s *Server) ListTriggers(ctx context.Context, q *notification.TriggersListRequest) (*notification.TriggerList, error) { api, err := s.apiFactory.GetAPI() if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { return ¬ification.TriggerList{}, nil } } @@ -40,7 +40,7 @@ func (s *Server) ListTriggers(ctx context.Context, q *notification.TriggersListR func (s *Server) ListServices(ctx context.Context, q *notification.ServicesListRequest) (*notification.ServiceList, error) { api, err := s.apiFactory.GetAPI() if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { return ¬ification.ServiceList{}, nil } return nil, err @@ -56,7 +56,7 @@ func (s *Server) ListServices(ctx context.Context, q *notification.ServicesListR func (s *Server) ListTemplates(ctx context.Context, q *notification.TemplatesListRequest) (*notification.TemplateList, error) { api, err := s.apiFactory.GetAPI() if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { return ¬ification.TemplateList{}, nil } return nil, err diff --git a/server/project/project.go b/server/project/project.go index 92c61d5dabb51..ac0d0cf27f191 100644 --- a/server/project/project.go +++ b/server/project/project.go @@ -14,7 +14,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/client-go/kubernetes" @@ -260,7 +260,7 @@ func (s *Server) Create(ctx context.Context, q *project.ProjectCreateRequest) (* return nil, fmt.Errorf("error validating project: %w", err) } res, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Create(ctx, q.Project, metav1.CreateOptions{}) - if apierr.IsAlreadyExists(err) { + if apierrors.IsAlreadyExists(err) { existing, getErr := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(ctx, q.Project.Name, metav1.GetOptions{}) if getErr != nil { return nil, status.Errorf(codes.Internal, "unable to check existing project details: %v", getErr) @@ -539,7 +539,7 @@ func (s *Server) NormalizeProjs() error { log.Infof("Successfully normalized project %s.", proj.Name) break } - if !apierr.IsConflict(err) { + if !apierrors.IsConflict(err) { log.Warnf("Failed normalize project %s", proj.Name) break } diff --git a/server/repository/repository.go b/server/repository/repository.go index 02f20463c0ca8..0e91811e929b4 100644 --- a/server/repository/repository.go +++ b/server/repository/repository.go @@ -12,7 +12,7 @@ import ( log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/tools/cache" @@ -330,7 +330,7 @@ func (s *Server) GetAppDetails(ctx context.Context, q *repositorypkg.RepoAppDeta if err := s.enf.EnforceErr(claims, rbacpolicy.ResourceApplications, rbacpolicy.ActionGet, appRBACObj); err != nil { return nil, err } - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { // app doesn't exist since it still is being formulated. verify they can create the app // before we reveal repo details if err := s.enf.EnforceErr(claims, rbacpolicy.ResourceApplications, rbacpolicy.ActionCreate, appRBACObj); err != nil { diff --git a/test/e2e/fixture/app/expectation.go b/test/e2e/fixture/app/expectation.go index 9e66f2d6b711b..02365ba69662b 100644 --- a/test/e2e/fixture/app/expectation.go +++ b/test/e2e/fixture/app/expectation.go @@ -10,7 +10,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/health" . "github.com/argoproj/gitops-engine/pkg/sync/common" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" @@ -223,7 +223,7 @@ func DoesNotExist() Expectation { return func(c *Consequences) (state, string) { _, err := c.get() if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { return succeeded, "app does not exist" } return failed, err.Error() @@ -236,7 +236,7 @@ func DoesNotExistNow() Expectation { return func(c *Consequences) (state, string) { _, err := c.get() if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { return succeeded, "app does not exist" } return failed, err.Error() diff --git a/test/e2e/fixture/applicationsets/utils/fixture.go b/test/e2e/fixture/applicationsets/utils/fixture.go index a01c2312f9b8f..cbdd223e00ac8 100644 --- a/test/e2e/fixture/applicationsets/utils/fixture.go +++ b/test/e2e/fixture/applicationsets/utils/fixture.go @@ -14,7 +14,7 @@ import ( log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/api/equality" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" @@ -118,7 +118,7 @@ func EnsureCleanState(t *testing.T) { func() error { // Delete the applicationset-e2e namespace, if it exists err := fixtureClient.KubeClientset.CoreV1().Namespaces().Delete(context.Background(), ApplicationsResourcesNamespace, metav1.DeleteOptions{PropagationPolicy: &policy}) - if err != nil && !apierr.IsNotFound(err) { // 'not found' error is expected + if err != nil && !apierrors.IsNotFound(err) { // 'not found' error is expected return err } return nil @@ -126,7 +126,7 @@ func EnsureCleanState(t *testing.T) { func() error { // Delete the argocd-e2e-external namespace, if it exists err := fixtureClient.KubeClientset.CoreV1().Namespaces().Delete(context.Background(), string(ArgoCDExternalNamespace), metav1.DeleteOptions{PropagationPolicy: &policy}) - if err != nil && !apierr.IsNotFound(err) { // 'not found' error is expected + if err != nil && !apierrors.IsNotFound(err) { // 'not found' error is expected return err } return nil @@ -134,7 +134,7 @@ func EnsureCleanState(t *testing.T) { func() error { // Delete the argocd-e2e-external namespace, if it exists err := fixtureClient.KubeClientset.CoreV1().Namespaces().Delete(context.Background(), string(ArgoCDExternalNamespace2), metav1.DeleteOptions{PropagationPolicy: &policy}) - if err != nil && !apierr.IsNotFound(err) { // 'not found' error is expected + if err != nil && !apierrors.IsNotFound(err) { // 'not found' error is expected return err } return nil @@ -276,7 +276,7 @@ func cleanUpNamespace(fixtureClient *E2EFixtureK8sClient, namespace string) erro msg = fmt.Sprintf("namespace '%s' still exists, after delete", namespace) } - if msg == "" && err != nil && apierr.IsNotFound(err) { + if msg == "" && err != nil && apierrors.IsNotFound(err) { // Success is an error containing 'applicationset-e2e' not found. return nil } diff --git a/util/argo/argo.go b/util/argo/argo.go index c599c18bb1528..7ff14f76d235f 100644 --- a/util/argo/argo.go +++ b/util/argo/argo.go @@ -17,7 +17,7 @@ import ( log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -244,7 +244,7 @@ func RefreshApp(appIf v1alpha1.ApplicationInterface, name string, refreshType ar for attempt := 0; attempt < 5; attempt++ { app, err := appIf.Patch(context.Background(), name, types.MergePatchType, patch, metav1.PatchOptions{}) if err != nil { - if !apierr.IsConflict(err) { + if !apierrors.IsConflict(err) { return nil, fmt.Errorf("error patching annotations in application %q: %w", name, err) } } else { @@ -881,7 +881,7 @@ func SetAppOperation(appIf v1alpha1.ApplicationInterface, appName string, op *ar if err == nil { return a, nil } - if !apierr.IsConflict(err) { + if !apierrors.IsConflict(err) { return nil, fmt.Errorf("error updating application %q: %w", appName, err) } log.Warnf("Failed to set operation for app '%s' due to update conflict. Retrying again...", appName) diff --git a/util/clusterauth/clusterauth.go b/util/clusterauth/clusterauth.go index bcc3b54ea3e12..7e139104b5613 100644 --- a/util/clusterauth/clusterauth.go +++ b/util/clusterauth/clusterauth.go @@ -11,7 +11,7 @@ import ( log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" @@ -67,7 +67,7 @@ func CreateServiceAccount( } _, err := clientset.CoreV1().ServiceAccounts(namespace).Create(context.Background(), &serviceAccount, metav1.CreateOptions{}) if err != nil { - if !apierr.IsAlreadyExists(err) { + if !apierrors.IsAlreadyExists(err) { return fmt.Errorf("Failed to create service account %q in namespace %q: %w", serviceAccountName, namespace, err) } log.Infof("ServiceAccount %q already exists in namespace %q", serviceAccountName, namespace) @@ -80,7 +80,7 @@ func CreateServiceAccount( func upsert(kind string, name string, create func() (any, error), update func() (any, error)) error { _, err := create() if err != nil { - if !apierr.IsAlreadyExists(err) { + if !apierrors.IsAlreadyExists(err) { return fmt.Errorf("Failed to create %s %q: %w", kind, name, err) } _, err = update() @@ -339,7 +339,7 @@ func UninstallClusterManagerRBAC(clientset kubernetes.Interface) error { // UninstallRBAC uninstalls RBAC related resources for a binding, role, and service account func UninstallRBAC(clientset kubernetes.Interface, namespace, bindingName, roleName, serviceAccount string) error { if err := clientset.RbacV1().ClusterRoleBindings().Delete(context.Background(), bindingName, metav1.DeleteOptions{}); err != nil { - if !apierr.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return fmt.Errorf("Failed to delete ClusterRoleBinding: %w", err) } log.Infof("ClusterRoleBinding %q not found", bindingName) @@ -348,7 +348,7 @@ func UninstallRBAC(clientset kubernetes.Interface, namespace, bindingName, roleN } if err := clientset.RbacV1().ClusterRoles().Delete(context.Background(), roleName, metav1.DeleteOptions{}); err != nil { - if !apierr.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return fmt.Errorf("Failed to delete ClusterRole: %w", err) } log.Infof("ClusterRole %q not found", roleName) @@ -357,7 +357,7 @@ func UninstallRBAC(clientset kubernetes.Interface, namespace, bindingName, roleN } if err := clientset.CoreV1().ServiceAccounts(namespace).Delete(context.Background(), serviceAccount, metav1.DeleteOptions{}); err != nil { - if !apierr.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return fmt.Errorf("Failed to delete ServiceAccount: %w", err) } log.Infof("ServiceAccount %q in namespace %q not found", serviceAccount, namespace) @@ -456,7 +456,7 @@ func RotateServiceAccountSecrets(clientset kubernetes.Interface, claims *Service // 2. delete existing secret object secretsClient := clientset.CoreV1().Secrets(claims.Namespace) err = secretsClient.Delete(context.Background(), claims.SecretName, metav1.DeleteOptions{}) - if !apierr.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return err } return nil diff --git a/util/clusterauth/clusterauth_test.go b/util/clusterauth/clusterauth_test.go index 8f21f39bd22b4..748519697b160 100644 --- a/util/clusterauth/clusterauth_test.go +++ b/util/clusterauth/clusterauth_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -224,7 +224,7 @@ func TestRotateServiceAccountSecrets(t *testing.T) { }, sa.Secrets) secretsClient := kubeclientset.CoreV1().Secrets(testClaims.Namespace) _, err = secretsClient.Get(context.Background(), testClaims.SecretName, metav1.GetOptions{}) - assert.True(t, apierr.IsNotFound(err)) + assert.True(t, apierrors.IsNotFound(err)) } func TestGetServiceAccountBearerToken(t *testing.T) { diff --git a/util/db/cluster.go b/util/db/cluster.go index a76432ad1707a..a17f72d2840b8 100644 --- a/util/db/cluster.go +++ b/util/db/cluster.go @@ -14,7 +14,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/watch" "k8s.io/utils/ptr" @@ -118,7 +118,7 @@ func (db *db) CreateCluster(ctx context.Context, c *appv1.Cluster) (*appv1.Clust clusterSecret, err = db.createSecret(ctx, clusterSecret) if err != nil { - if apierr.IsAlreadyExists(err) { + if apierrors.IsAlreadyExists(err) { return nil, status.Errorf(codes.AlreadyExists, "cluster %q already exists", c.Server) } return nil, err diff --git a/util/db/db.go b/util/db/db.go index 92571c9514c7a..4114450631d8d 100644 --- a/util/db/db.go +++ b/util/db/db.go @@ -6,7 +6,7 @@ import ( "strings" corev1 "k8s.io/api/core/v1" - kubeerrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -176,7 +176,7 @@ func (db *db) GetApplicationControllerReplicas() int { appControllerDeployment, err := db.kubeclientset.AppsV1().Deployments(db.settingsMgr.GetNamespace()).Get(context.Background(), applicationControllerName, metav1.GetOptions{}) if err != nil { appControllerDeployment = nil - if !kubeerrors.IsNotFound(err) { + if !apierrors.IsNotFound(err) { log.Warnf("error retrieveing Argo CD controller deployment: %s", err) } } diff --git a/util/db/repository_legacy.go b/util/db/repository_legacy.go index cbeaff56537bd..d0bfaf4321a05 100644 --- a/util/db/repository_legacy.go +++ b/util/db/repository_legacy.go @@ -9,7 +9,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo-cd/v2/common" @@ -307,7 +307,7 @@ func (l *legacyRepositoryBackend) updateCredentialsSecret(credsInfo *settings.Re func (l *legacyRepositoryBackend) upsertSecret(name string, data map[string][]byte) error { secret, err := l.db.kubeclientset.CoreV1().Secrets(l.db.ns).Get(context.Background(), name, metav1.GetOptions{}) if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { if len(data) == 0 { return nil } diff --git a/util/db/repository_secrets.go b/util/db/repository_secrets.go index 1897e54d6dcf3..6d5d0ad3a21bf 100644 --- a/util/db/repository_secrets.go +++ b/util/db/repository_secrets.go @@ -9,7 +9,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo-cd/v2/common" @@ -38,7 +38,7 @@ func (s *secretsRepositoryBackend) CreateRepository(ctx context.Context, reposit _, err := s.db.createSecret(ctx, repositorySecret) if err != nil { - if apierr.IsAlreadyExists(err) { + if apierrors.IsAlreadyExists(err) { hasLabel, err := s.hasRepoTypeLabel(secName) if err != nil { return nil, status.Error(codes.Internal, err.Error()) @@ -63,7 +63,7 @@ func (s *secretsRepositoryBackend) hasRepoTypeLabel(secretName string) (bool, er noCache := make(map[string]*corev1.Secret) sec, err := s.db.getSecret(secretName, noCache) if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { return false, nil } return false, err @@ -192,7 +192,7 @@ func (s *secretsRepositoryBackend) CreateRepoCreds(ctx context.Context, repoCred _, err := s.db.createSecret(ctx, repoCredsSecret) if err != nil { - if apierr.IsAlreadyExists(err) { + if apierrors.IsAlreadyExists(err) { return nil, status.Errorf(codes.AlreadyExists, "repository credentials %q already exists", repoCreds.URL) } return nil, err diff --git a/util/db/repository_secrets_test.go b/util/db/repository_secrets_test.go index e484999f884e7..1d91dd32937a0 100644 --- a/util/db/repository_secrets_test.go +++ b/util/db/repository_secrets_test.go @@ -10,7 +10,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -93,7 +93,7 @@ func TestSecretsRepositoryBackend_CreateRepository(t *testing.T) { Group: "v1", Resource: "secrets", } - return true, nil, k8serrors.NewAlreadyExists(gr, "already exists") + return true, nil, apierrors.NewAlreadyExists(gr, "already exists") }) // when @@ -130,7 +130,7 @@ func TestSecretsRepositoryBackend_CreateRepository(t *testing.T) { Group: "v1", Resource: "secrets", } - return true, nil, k8serrors.NewAlreadyExists(gr, "already exists") + return true, nil, apierrors.NewAlreadyExists(gr, "already exists") }) watcher := watch.NewFakeWithChanSize(1, true) watcher.Add(secret) diff --git a/util/grpc/errors.go b/util/grpc/errors.go index 0d323e4d1108e..755e9bae89d1a 100644 --- a/util/grpc/errors.go +++ b/util/grpc/errors.go @@ -8,7 +8,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" ) func rewrapError(err error, code codes.Code) error { @@ -66,31 +66,31 @@ func kubeErrToGRPC(err error) error { */ switch { - case apierr.IsNotFound(err): + case apierrors.IsNotFound(err): err = rewrapError(err, codes.NotFound) - case apierr.IsAlreadyExists(err): + case apierrors.IsAlreadyExists(err): err = rewrapError(err, codes.AlreadyExists) - case apierr.IsInvalid(err): + case apierrors.IsInvalid(err): err = rewrapError(err, codes.InvalidArgument) - case apierr.IsMethodNotSupported(err): + case apierrors.IsMethodNotSupported(err): err = rewrapError(err, codes.Unimplemented) - case apierr.IsServiceUnavailable(err): + case apierrors.IsServiceUnavailable(err): err = rewrapError(err, codes.Unavailable) - case apierr.IsBadRequest(err): + case apierrors.IsBadRequest(err): err = rewrapError(err, codes.FailedPrecondition) - case apierr.IsUnauthorized(err): + case apierrors.IsUnauthorized(err): err = rewrapError(err, codes.Unauthenticated) - case apierr.IsForbidden(err): + case apierrors.IsForbidden(err): err = rewrapError(err, codes.PermissionDenied) - case apierr.IsTimeout(err): + case apierrors.IsTimeout(err): err = rewrapError(err, codes.DeadlineExceeded) - case apierr.IsServerTimeout(err): + case apierrors.IsServerTimeout(err): err = rewrapError(err, codes.Unavailable) - case apierr.IsConflict(err): + case apierrors.IsConflict(err): err = rewrapError(err, codes.Aborted) - case apierr.IsTooManyRequests(err): + case apierrors.IsTooManyRequests(err): err = rewrapError(err, codes.ResourceExhausted) - case apierr.IsInternalError(err): + case apierrors.IsInternalError(err): err = rewrapError(err, codes.Internal) default: // This is necessary as GRPC Status don't support wrapped errors: diff --git a/util/grpc/errors_test.go b/util/grpc/errors_test.go index 5b9dddd8b41b7..5e6bfd7b69b57 100644 --- a/util/grpc/errors_test.go +++ b/util/grpc/errors_test.go @@ -7,7 +7,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime/schema" "github.com/stretchr/testify/assert" @@ -51,10 +51,10 @@ func Test_kubeErrToGRPC(t *testing.T) { Group: "apps", Resource: "Deployment", } - return apierr.NewForbidden(gr, "some-app", errors.New("authentication error")) + return apierrors.NewForbidden(gr, "some-app", errors.New("authentication error")) } newUnauthorizedError := func() error { - return apierr.NewUnauthorized("unauthenticated") + return apierrors.NewUnauthorized("unauthenticated") } cases := []*testCase{ { @@ -80,7 +80,7 @@ func Test_kubeErrToGRPC(t *testing.T) { expectedGRPCStatus: status.New(codes.NotFound, "Not found"), }, { - name: "will return permission denied if apierr.IsForbidden", + name: "will return permission denied if apierrors.IsForbidden", givenErrFn: func() error { return newForbiddenError() }, @@ -92,7 +92,7 @@ func Test_kubeErrToGRPC(t *testing.T) { expectedGRPCStatus: status.New(codes.PermissionDenied, newForbiddenError().Error()), }, { - name: "will return unauthenticated if apierr.IsUnauthorized", + name: "will return unauthenticated if apierrors.IsUnauthorized", givenErrFn: func() error { return newUnauthorizedError() }, @@ -104,40 +104,40 @@ func Test_kubeErrToGRPC(t *testing.T) { expectedGRPCStatus: status.New(codes.Unauthenticated, newUnauthorizedError().Error()), }, { - name: "will return Unavailable if apierr.IsServerTimeout", + name: "will return Unavailable if apierrors.IsServerTimeout", givenErrFn: func() error { - return apierr.NewServerTimeout(schema.GroupResource{}, "update", 1) + return apierrors.NewServerTimeout(schema.GroupResource{}, "update", 1) }, expectedErrFn: func() error { - err := apierr.NewServerTimeout(schema.GroupResource{}, "update", 1) + err := apierrors.NewServerTimeout(schema.GroupResource{}, "update", 1) grpcStatus := status.New(codes.Unavailable, err.Error()) return grpcStatus.Err() }, - expectedGRPCStatus: status.New(codes.Unavailable, apierr.NewServerTimeout(schema.GroupResource{}, "update", 1).Error()), + expectedGRPCStatus: status.New(codes.Unavailable, apierrors.NewServerTimeout(schema.GroupResource{}, "update", 1).Error()), }, { - name: "will return Aborted if apierr.IsConflict", + name: "will return Aborted if apierrors.IsConflict", givenErrFn: func() error { - return apierr.NewConflict(schema.GroupResource{}, "foo", errors.New("foo")) + return apierrors.NewConflict(schema.GroupResource{}, "foo", errors.New("foo")) }, expectedErrFn: func() error { - err := apierr.NewConflict(schema.GroupResource{}, "foo", errors.New("foo")) + err := apierrors.NewConflict(schema.GroupResource{}, "foo", errors.New("foo")) grpcStatus := status.New(codes.Aborted, err.Error()) return grpcStatus.Err() }, - expectedGRPCStatus: status.New(codes.Aborted, apierr.NewConflict(schema.GroupResource{}, "foo", errors.New("foo")).Error()), + expectedGRPCStatus: status.New(codes.Aborted, apierrors.NewConflict(schema.GroupResource{}, "foo", errors.New("foo")).Error()), }, { - name: "will return ResourceExhausted if apierr.IsTooManyRequests", + name: "will return ResourceExhausted if apierrors.IsTooManyRequests", givenErrFn: func() error { - return apierr.NewTooManyRequests("foo", 1) + return apierrors.NewTooManyRequests("foo", 1) }, expectedErrFn: func() error { - err := apierr.NewTooManyRequests("foo", 1) + err := apierrors.NewTooManyRequests("foo", 1) grpcStatus := status.New(codes.ResourceExhausted, err.Error()) return grpcStatus.Err() }, - expectedGRPCStatus: status.New(codes.ResourceExhausted, apierr.NewTooManyRequests("foo", 1).Error()), + expectedGRPCStatus: status.New(codes.ResourceExhausted, apierrors.NewTooManyRequests("foo", 1).Error()), }, } for _, c := range cases { diff --git a/util/rbac/rbac.go b/util/rbac/rbac.go index 29ff77e0ae4a6..05d5cf61b2fd3 100644 --- a/util/rbac/rbac.go +++ b/util/rbac/rbac.go @@ -24,7 +24,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" v1 "k8s.io/client-go/informers/core/v1" @@ -348,7 +348,7 @@ func (e *Enforcer) newInformer() cache.SharedIndexInformer { func (e *Enforcer) RunPolicyLoader(ctx context.Context, onUpdated func(cm *corev1.ConfigMap) error) error { cm, err := e.clientset.CoreV1().ConfigMaps(e.namespace).Get(ctx, e.configmap, metav1.GetOptions{}) if err != nil { - if !apierr.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return err } } else { diff --git a/util/settings/settings.go b/util/settings/settings.go index 168ea8ff434bf..96af75b0f4e8f 100644 --- a/util/settings/settings.go +++ b/util/settings/settings.go @@ -21,7 +21,6 @@ import ( log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" - apierr "k8s.io/apimachinery/pkg/api/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" @@ -642,7 +641,7 @@ func (mgr *SettingsManager) updateSecret(callback func(*corev1.Secret) error) er argoCDSecret, err := mgr.getSecret() createSecret := false if err != nil { - if !apierr.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return err } argoCDSecret = &corev1.Secret{ @@ -680,7 +679,7 @@ func (mgr *SettingsManager) updateConfigMap(callback func(*corev1.ConfigMap) err argoCDCM, err := mgr.getConfigMap() createCM := false if err != nil { - if !apierr.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return err } argoCDCM = &corev1.ConfigMap{ @@ -1658,7 +1657,7 @@ func (mgr *SettingsManager) externalServerTLSCertificate() (*tls.Certificate, er var cert tls.Certificate secret, err := mgr.GetSecretByName(externalServerTLSSecretName) if err != nil { - if apierr.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil, nil } } From acb47b418ca3270ad4b24a754fd3292988aaa5b1 Mon Sep 17 00:00:00 2001 From: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> Date: Fri, 3 Jan 2025 16:51:31 -0500 Subject: [PATCH 12/41] chore: add script to bump major version (#21363) * chore: add script to bump major version Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * add workflow to automatically bump the version Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * better PR Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * use new output mechanism Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * fix incorrect message Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> --------- Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> --- .github/workflows/bump-major-version.yaml | 46 +++++++++++++++++++++++ hack/bump-major-version.sh | 31 +++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 .github/workflows/bump-major-version.yaml create mode 100755 hack/bump-major-version.sh diff --git a/.github/workflows/bump-major-version.yaml b/.github/workflows/bump-major-version.yaml new file mode 100644 index 0000000000000..b9dc0d77f7cb2 --- /dev/null +++ b/.github/workflows/bump-major-version.yaml @@ -0,0 +1,46 @@ +name: Bump major version +on: + workflow_dispatch: {} + +permissions: {} + +jobs: + prepare-release: + permissions: + contents: write # for peter-evans/create-pull-request to create branch + pull-requests: write # for peter-evans/create-pull-request to create a PR + name: Automatically update major version + runs-on: ubuntu-22.04 + steps: + - name: Checkout code + uses: actions/checkout@8410ad0602e1e429cee44a835ae9f77f654a6694 # v4.0.0 + with: + fetch-depth: 0 + token: ${{ secrets.GITHUB_TOKEN }} + + # Get the current major version from go.mod and save it as a variable. + - name: Get target version + id: get-target-version + run: | + set -ue + CURRENT_VERSION=$(grep 'module github.com/argoproj/argo-cd' go.mod | awk '{print $2}' | sed 's/.*\/v//') + echo "TARGET_VERSION=$((CURRENT_VERSION + 1))" >> $GITHUB_OUTPUT + + - name: Run script to bump the version + run: | + hack/bump-major-version.sh + + - name: Create pull request + uses: peter-evans/create-pull-request@5e914681df9dc83aa4e4905692ca88beb2f9e91f # v7.0.5 + with: + commit-message: "Bump major version to ${{ steps.get-target-version.outputs.TARGET_VERSION }}" + title: "Bump major version to ${{ steps.get-target-version.outputs.TARGET_VERSION }}" + body: | + Congrats! You've just bumped the major version to ${{ steps.get-target-version.outputs.TARGET_VERSION }}. + + Next steps: + - [ ] Merge this PR + - [ ] Add an upgrade guide to the docs for this version + branch: bump-major-version + branch-suffix: random + signoff: true diff --git a/hack/bump-major-version.sh b/hack/bump-major-version.sh new file mode 100755 index 0000000000000..5575d1f2da4da --- /dev/null +++ b/hack/bump-major-version.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash + +# This script bumps the major version of Argo CD. Before cutting a new major release, run this script and open a PR. + +# Get the current version from go.mod. +CURRENT_VERSION=$(grep 'module github.com/argoproj/argo-cd' go.mod | awk '{print $2}' | sed 's/.*\/v//') + +echo "Upgrading from v${CURRENT_VERSION} to v$((CURRENT_VERSION + 1))..." + +# sed commands in this script use -i.bak for compatibility with both GNU sed and BSD sed. + +for file in .golangci.yaml .goreleaser.yaml .mockery.yaml Makefile Procfile; do + echo "Incrementing the major version in $file..." + sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" "$file" && rm "$file.bak" +done + +for file in hack/generate-proto.sh hack/update-codegen.sh hack/update-openapi.sh; do + echo "Incrementing the major version in $file..." + sed -i.bak "s/v${CURRENT_VERSION}/v$((CURRENT_VERSION + 1))/g" "$file" && rm "$file.bak" +done + +echo "Incrementing the major version in proto files..." +find . -name '*.proto' -exec sed -i.bak "s/github.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" {} \; -exec sed -i.bak "s/github\.com.\argoproj\.argo_cd\.v${CURRENT_VERSION}/github\.com.\argoproj\.argo_cd\.v$((CURRENT_VERSION + 1))/g" {} \; -exec rm {}.bak \; + +echo "Incrementing the major version in go files..." +find . -name '*.go' -exec sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" {} \; -exec rm {}.bak \; + +echo "Incrementing the major version in go.mod..." +sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" go.mod && rm go.mod.bak + +echo 'Finished! Now run `make codegen-local && make lint-local && make test-local` to ensure everything is working as expected.' From 8245cd90b35ebd179f592d06d34570cb767c2176 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 3 Jan 2025 22:40:05 +0000 Subject: [PATCH 13/41] chore(deps): update module github.com/golangci/golangci-lint to v1.63.4 (#21368) Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci-build.yaml | 2 +- hack/installers/install-lint-tools.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci-build.yaml b/.github/workflows/ci-build.yaml index 578fb1d511d46..fda8d23ff6f99 100644 --- a/.github/workflows/ci-build.yaml +++ b/.github/workflows/ci-build.yaml @@ -112,7 +112,7 @@ jobs: uses: golangci/golangci-lint-action@971e284b6050e8a5849b72094c50ab08da042db8 # v6.1.1 with: # renovate: datasource=go packageName=github.com/golangci/golangci-lint versioning=regex:^v(?\d+)\.(?\d+)\.(?\d+)?$ - version: v1.63.3 + version: v1.63.4 args: --verbose test-go: diff --git a/hack/installers/install-lint-tools.sh b/hack/installers/install-lint-tools.sh index 4f371866128e3..c038e02cb7c3b 100755 --- a/hack/installers/install-lint-tools.sh +++ b/hack/installers/install-lint-tools.sh @@ -2,6 +2,6 @@ set -eux -o pipefail # renovate: datasource=go packageName=github.com/golangci/golangci-lint -GOLANGCI_LINT_VERSION=1.63.3 +GOLANGCI_LINT_VERSION=1.63.4 GO111MODULE=on go install "github.com/golangci/golangci-lint/cmd/golangci-lint@v${GOLANGCI_LINT_VERSION}" From 4e5db16fbfce29ba0c20a58ac99294658339e975 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Fri, 3 Jan 2025 23:45:03 +0100 Subject: [PATCH 14/41] chore: enable increment-decrement from revive (#21366) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 1 - applicationset/controllers/applicationset_controller.go | 6 +++--- applicationset/generators/merge.go | 2 +- applicationset/utils/utils.go | 4 ++-- controller/clusterinfoupdater.go | 2 +- hack/gen-resources/util/progress_bar.go | 2 +- reposerver/gpgwatcher.go | 2 +- test/e2e/cluster_test.go | 2 +- util/cert/cert.go | 8 ++++---- util/gpg/gpg.go | 8 ++++---- util/session/sessionmanager.go | 4 ++-- 11 files changed, 20 insertions(+), 21 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 307792b0cb251..ae8b18c759ebd 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -108,7 +108,6 @@ linters-settings: - 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 diff --git a/applicationset/controllers/applicationset_controller.go b/applicationset/controllers/applicationset_controller.go index 63baafaa64114..f3c771327affa 100644 --- a/applicationset/controllers/applicationset_controller.go +++ b/applicationset/controllers/applicationset_controller.go @@ -1162,10 +1162,10 @@ func (r *ApplicationSetReconciler) updateApplicationSetApplicationStatusProgress // populate updateCountMap with counts of existing Pending and Progressing Applications for _, appStatus := range applicationSet.Status.ApplicationStatus { - totalCountMap[appStepMap[appStatus.Application]] += 1 + totalCountMap[appStepMap[appStatus.Application]]++ if appStatus.Status == "Pending" || appStatus.Status == "Progressing" { - updateCountMap[appStepMap[appStatus.Application]] += 1 + updateCountMap[appStepMap[appStatus.Application]]++ } } @@ -1201,7 +1201,7 @@ func (r *ApplicationSetReconciler) updateApplicationSetApplicationStatusProgress appStatus.Message = "Application moved to Pending status, watching for the Application resource to start Progressing." appStatus.Step = strconv.Itoa(getAppStep(appStatus.Application, appStepMap)) - updateCountMap[appStepMap[appStatus.Application]] += 1 + updateCountMap[appStepMap[appStatus.Application]]++ } appStatuses = append(appStatuses, appStatus) diff --git a/applicationset/generators/merge.go b/applicationset/generators/merge.go index 7532716775ce1..dfd826ab2df7e 100644 --- a/applicationset/generators/merge.go +++ b/applicationset/generators/merge.go @@ -99,7 +99,7 @@ func (m *MergeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Appl i := 0 for _, mergedParamSet := range baseParamSetsByMergeKey { mergedParamSets[i] = mergedParamSet - i += 1 + i++ } return mergedParamSets, nil diff --git a/applicationset/utils/utils.go b/applicationset/utils/utils.go index 51b7ae51c22e3..08bb77c53219d 100644 --- a/applicationset/utils/utils.go +++ b/applicationset/utils/utils.go @@ -131,7 +131,7 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri // If it is a struct we translate each field case reflect.Struct: - for i := 0; i < original.NumField(); i += 1 { + for i := 0; i < original.NumField(); i++ { currentType := fmt.Sprintf("%s.%s", original.Type().Field(i).Name, original.Type().PkgPath()) // specific case time if currentType == "time.Time" { @@ -173,7 +173,7 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri copyValueIntoUnexported(copy, reflect.MakeSlice(original.Type(), original.Len(), original.Cap())) } - for i := 0; i < original.Len(); i += 1 { + for i := 0; i < original.Len(); i++ { if err := r.deeplyReplace(copy.Index(i), original.Index(i), replaceMap, useGoTemplate, goTemplateOptions); err != nil { // Not wrapping the error, since this is a recursive function. Avoids excessively long error messages. return err diff --git a/controller/clusterinfoupdater.go b/controller/clusterinfoupdater.go index 655ff6a59b759..d60e06d4890de 100644 --- a/controller/clusterinfoupdater.go +++ b/controller/clusterinfoupdater.go @@ -136,7 +136,7 @@ func (c *clusterInfoUpdater) getUpdatedClusterInfo(ctx context.Context, apps []* continue } if a.Spec.Destination.Server == cluster.Server { - appCount += 1 + appCount++ } } clusterInfo := appv1.ClusterInfo{ diff --git a/hack/gen-resources/util/progress_bar.go b/hack/gen-resources/util/progress_bar.go index 66eda264c77e5..d12f64eb34549 100644 --- a/hack/gen-resources/util/progress_bar.go +++ b/hack/gen-resources/util/progress_bar.go @@ -30,7 +30,7 @@ func (bar *Bar) getPercent() int64 { } func (bar *Bar) Increment() { - bar.cur += 1 + bar.cur++ } func (bar *Bar) Play() { diff --git a/reposerver/gpgwatcher.go b/reposerver/gpgwatcher.go index d2fdcbb62ded3..35495c36086c3 100644 --- a/reposerver/gpgwatcher.go +++ b/reposerver/gpgwatcher.go @@ -47,7 +47,7 @@ func StartGPGWatcher(sourcePath string) error { if err != nil { log.Errorf("Error re-creating watcher on %s: %v", sourcePath, err) if attempt < maxRecreateRetries { - attempt += 1 + attempt++ log.Infof("Retrying to re-create watcher, attempt %d of %d", attempt, maxRecreateRetries) time.Sleep(1 * time.Second) continue diff --git a/test/e2e/cluster_test.go b/test/e2e/cluster_test.go index a79772614580f..c0beb74c88312 100644 --- a/test/e2e/cluster_test.go +++ b/test/e2e/cluster_test.go @@ -38,7 +38,7 @@ https://kubernetes.default.svc in-cluster %v Successful `, GetVe CreateApp() tries := 25 - for i := 0; i <= tries; i += 1 { + for i := 0; i <= tries; i++ { clusterFixture.GivenWithSameState(t). When(). List(). diff --git a/util/cert/cert.go b/util/cert/cert.go index 04cdadc37bfce..27e4231cf5e8c 100644 --- a/util/cert/cert.go +++ b/util/cert/cert.go @@ -159,7 +159,7 @@ func ParseTLSCertificatesFromStream(stream io.Reader) ([]string, error) { // TODO: Implement error heuristics for scanner.Scan() { - curLine += 1 + curLine++ if !inCertData { if strings.HasPrefix(scanner.Text(), CertificateBeginMarker) { certLine = 1 @@ -167,7 +167,7 @@ func ParseTLSCertificatesFromStream(stream io.Reader) ([]string, error) { pemData += scanner.Text() + "\n" } } else { - certLine += 1 + certLine++ pemData += scanner.Text() + "\n" if strings.HasPrefix(scanner.Text(), CertificateEndMarker) { inCertData = false @@ -215,10 +215,10 @@ func ParseSSHKnownHostsFromStream(stream io.Reader) ([]string, error) { numEntries := 0 for scanner.Scan() { - curLine += 1 + curLine++ lineData := scanner.Text() if IsValidSSHKnownHostsEntry(lineData) { - numEntries += 1 + numEntries++ knownHostsLists = append(knownHostsLists, lineData) } } diff --git a/util/gpg/gpg.go b/util/gpg/gpg.go index a7e305dbddbc9..bea324024eecc 100644 --- a/util/gpg/gpg.go +++ b/util/gpg/gpg.go @@ -597,7 +597,7 @@ func ParseGitCommitVerification(signature string) PGPVerifyResult { scanner := bufio.NewScanner(strings.NewReader(signature)) for scanner.Scan() && linesParsed < MaxVerificationLinesToParse { - linesParsed += 1 + linesParsed++ // Indicating the beginning of a signature start := verificationStartMatch.FindStringSubmatch(scanner.Text()) @@ -607,7 +607,7 @@ func ParseGitCommitVerification(signature string) PGPVerifyResult { return unknownResult("Unexpected end-of-file while parsing commit verification output.") } - linesParsed += 1 + linesParsed++ // What key has made the signature? keyID := verificationKeyIDMatch.FindStringSubmatch(scanner.Text()) @@ -626,7 +626,7 @@ func ParseGitCommitVerification(signature string) PGPVerifyResult { return unknownResult("Unexpected end-of-file while parsing commit verification output.") } - linesParsed += 1 + linesParsed++ // Skip additional fields for verificationAdditionalFields.MatchString(scanner.Text()) { @@ -634,7 +634,7 @@ func ParseGitCommitVerification(signature string) PGPVerifyResult { return unknownResult("Unexpected end-of-file while parsing commit verification output.") } - linesParsed += 1 + linesParsed++ } if strings.HasPrefix(scanner.Text(), "gpg: Can't check signature: ") { diff --git a/util/session/sessionmanager.go b/util/session/sessionmanager.go index 6deba84b5aa95..dfb0053bfea74 100644 --- a/util/session/sessionmanager.go +++ b/util/session/sessionmanager.go @@ -303,7 +303,7 @@ func expireOldFailedAttempts(maxAge time.Duration, failures map[string]LoginAtte expiredCount := 0 for key, attempt := range failures { if time.Since(attempt.LastFailed) > maxAge*time.Second { - expiredCount += 1 + expiredCount++ delete(failures, key) } } @@ -362,7 +362,7 @@ func (mgr *SessionManager) updateFailureCount(username string, failed bool) { // On login failure, increase fail count and update last failed timestamp. // On login success, remove the entry from the cache. if failed { - attempt.FailCount += 1 + attempt.FailCount++ attempt.LastFailed = time.Now() failures[username] = attempt log.Warnf("User %s failed login %d time(s)", username, attempt.FailCount) From e66068c11b5a00be03bc9b012801635202ed30ad Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Sat, 4 Jan 2025 00:44:23 +0100 Subject: [PATCH 15/41] chore: enable var-declaration from revive (#21370) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 1 - .../commands/applicationset_controller.go | 3 +-- cmd/argocd/commands/cluster.go | 2 +- controller/cache/cache.go | 4 ++-- controller/cache/cache_test.go | 6 +++--- controller/sync.go | 2 +- hack/known_types/main.go | 2 +- pkg/apis/application/v1alpha1/types.go | 2 +- reposerver/server.go | 2 +- server/badge/badge.go | 2 +- util/argo/audit_logger_test.go | 2 +- util/cache/cache.go | 2 +- util/db/certificate.go | 6 +++--- util/db/certificate_test.go | 8 ++++---- util/db/gpgkeys.go | 2 +- util/git/creds.go | 2 +- util/gpg/gpg.go | 2 +- util/io/path/resolved_test.go | 2 +- util/lua/custom_actions_test.go | 2 +- 19 files changed, 26 insertions(+), 28 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index ae8b18c759ebd..0e85608e22332 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -137,7 +137,6 @@ linters-settings: - 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 diff --git a/cmd/argocd-applicationset-controller/commands/applicationset_controller.go b/cmd/argocd-applicationset-controller/commands/applicationset_controller.go index abc4d55035f72..ffd925a8c09ee 100644 --- a/cmd/argocd-applicationset-controller/commands/applicationset_controller.go +++ b/cmd/argocd-applicationset-controller/commands/applicationset_controller.go @@ -120,8 +120,7 @@ func NewCommand() *cobra.Command { } // By default, watch all namespaces - var watchedNamespace string = "" - + var watchedNamespace string // If the applicationset-namespaces contains only one namespace it corresponds to the current namespace if len(applicationSetNamespaces) == 1 { watchedNamespace = (applicationSetNamespaces)[0] diff --git a/cmd/argocd/commands/cluster.go b/cmd/argocd/commands/cluster.go index da8447c7f9c02..165b162356fe2 100644 --- a/cmd/argocd/commands/cluster.go +++ b/cmd/argocd/commands/cluster.go @@ -404,7 +404,7 @@ argocd cluster rm cluster-name`, conn, clusterIf := headless.NewClientOrDie(clientOpts, c).NewClusterClientOrDie() defer io.Close(conn) numOfClusters := len(args) - var isConfirmAll bool = false + var isConfirmAll bool for _, clusterSelector := range args { clusterQuery := getQueryBySelector(clusterSelector) diff --git a/controller/cache/cache.go b/controller/cache/cache.go index 08682c41d5078..b4c9819184e88 100644 --- a/controller/cache/cache.go +++ b/controller/cache/cache.go @@ -108,10 +108,10 @@ var ( clusterCacheAttemptLimit int32 = 1 // clusterCacheRetryUseBackoff specifies whether to use a backoff strategy on cluster cache sync, if retry is enabled - clusterCacheRetryUseBackoff bool = false + clusterCacheRetryUseBackoff = false // clusterCacheBatchEventsProcessing specifies whether to enable batch events processing - clusterCacheBatchEventsProcessing bool = false + clusterCacheBatchEventsProcessing = false // clusterCacheEventProcessingInterval specifies the interval between processing events when BatchEventsProcessing is enabled clusterCacheEventProcessingInterval = 100 * time.Millisecond diff --git a/controller/cache/cache_test.go b/controller/cache/cache_test.go index 31bffd5c1502b..076633444ee49 100644 --- a/controller/cache/cache_test.go +++ b/controller/cache/cache_test.go @@ -536,9 +536,9 @@ func Test_getAppRecursive(t *testing.T) { func TestSkipResourceUpdate(t *testing.T) { var ( - hash1_x string = "x" - hash2_y string = "y" - hash3_x string = "x" + hash1_x = "x" + hash2_y = "y" + hash3_x = "x" ) info := &ResourceInfo{ manifestHash: hash1_x, diff --git a/controller/sync.go b/controller/sync.go index a03bf2eff28f0..9910254acf40a 100644 --- a/controller/sync.go +++ b/controller/sync.go @@ -38,7 +38,7 @@ import ( "github.com/argoproj/argo-cd/v2/util/rand" ) -var syncIdPrefix uint64 = 0 +var syncIdPrefix uint64 const ( // EnvVarSyncWaveDelay is an environment variable which controls the delay in seconds between diff --git a/hack/known_types/main.go b/hack/known_types/main.go index 88fdbadb459de..ca2cf23a380f7 100644 --- a/hack/known_types/main.go +++ b/hack/known_types/main.go @@ -23,7 +23,7 @@ const ( ) func newCommand() *cobra.Command { - var docsOutputPath string = "" + var docsOutputPath string command := &cobra.Command{ Use: "go run github.com/argoproj/argo-cd/hack/known_types ALIAS PACKAGE_PATH OUTPUT_PATH", Example: "go run github.com/argoproj/argo-cd/hack/known_types corev1 k8s.io/api/core/v1 corev1_known_types.go", diff --git a/pkg/apis/application/v1alpha1/types.go b/pkg/apis/application/v1alpha1/types.go index ce731d88b6d8f..db61be5c888ff 100644 --- a/pkg/apis/application/v1alpha1/types.go +++ b/pkg/apis/application/v1alpha1/types.go @@ -1124,7 +1124,7 @@ func (d *ApplicationDestination) SetIsServerInferred(inferred bool) { type ResourceHealthLocation string var ( - ResourceHealthLocationInline ResourceHealthLocation = "" + ResourceHealthLocationInline ResourceHealthLocation ResourceHealthLocationAppTree ResourceHealthLocation = "appTree" ) diff --git a/reposerver/server.go b/reposerver/server.go index 56ed69b99b06a..709428d2d22b3 100644 --- a/reposerver/server.go +++ b/reposerver/server.go @@ -45,7 +45,7 @@ type ArgoCDRepoServer struct { } // The hostnames to generate self-signed issues with -var tlsHostList []string = []string{"localhost", "reposerver"} +var tlsHostList = []string{"localhost", "reposerver"} // NewServer returns a new instance of the Argo CD Repo server func NewServer(metricsServer *metrics.MetricsServer, cache *reposervercache.Cache, tlsConfCustomizer tlsutil.ConfigCustomizer, initConstants repository.RepoServerInitConstants, gitCredsStore git.CredsStore) (*ArgoCDRepoServer, error) { diff --git a/server/badge/badge.go b/server/badge/badge.go index 58278f8c9c0cb..62afa5b030c89 100644 --- a/server/badge/badge.go +++ b/server/badge/badge.go @@ -242,7 +242,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if displayAppName && applicationName != "" { titleRectWidth := len(applicationName) * widthPerChar - var longerWidth int = max(titleRectWidth, svgWidth) + longerWidth := max(titleRectWidth, svgWidth) rightRectWidth := longerWidth - leftRectWidth badge = titleRectWidthPattern.ReplaceAllString(badge, fmt.Sprintf(`$1"%d"`, longerWidth)) badge = rightRectWidthPattern.ReplaceAllString(badge, fmt.Sprintf(`$1"%d"`, rightRectWidth)) diff --git a/util/argo/audit_logger_test.go b/util/argo/audit_logger_test.go index 6327dd9a938bd..5f147f906cb03 100644 --- a/util/argo/audit_logger_test.go +++ b/util/argo/audit_logger_test.go @@ -19,7 +19,7 @@ const ( _test = "test" ) -var testEnableEventLog []string = []string{_somecomponent, _test} +var testEnableEventLog = []string{_somecomponent, _test} // Helper to capture log entries generated by the logger and return it as string func captureLogEntries(run func()) string { diff --git a/util/cache/cache.go b/util/cache/cache.go index 240a940f14be3..8ffe21b93a0e5 100644 --- a/util/cache/cache.go +++ b/util/cache/cache.go @@ -179,7 +179,7 @@ func AddCacheFlagsToCmd(cmd *cobra.Command, opts ...Options) func() (*Cache, err redisCACertificate := redisCACertificateSrc() compressionStr := compressionStrSrc() - var tlsConfig *tls.Config = nil + var tlsConfig *tls.Config if redisUseTLS { tlsConfig = &tls.Config{} if redisClientCertificate != "" { diff --git a/util/db/certificate.go b/util/db/certificate.go index 401094316cc41..978c29f964eeb 100644 --- a/util/db/certificate.go +++ b/util/db/certificate.go @@ -151,8 +151,8 @@ func (db *db) GetRepoCertificate(ctx context.Context, serverType string, serverN // actually created. func (db *db) CreateRepoCertificate(ctx context.Context, certificates *appsv1.RepositoryCertificateList, upsert bool) (*appsv1.RepositoryCertificateList, error) { var ( - saveSSHData bool = false - saveTLSData bool = false + saveSSHData = false + saveTLSData = false ) sshKnownHostsList, err := db.getSSHKnownHostsData() @@ -243,7 +243,7 @@ func (db *db) CreateRepoCertificate(ctx context.Context, certificates *appsv1.Re saveSSHData = true } } else if certificate.CertType == "https" { - var tlsCertificate *TLSCertificate = nil + var tlsCertificate *TLSCertificate newEntry := true upserted := false pemCreated := make([]string, 0) diff --git a/util/db/certificate_test.go b/util/db/certificate_test.go index 74fd8bb0e1ca5..0075781dbd75e 100644 --- a/util/db/certificate_test.go +++ b/util/db/certificate_test.go @@ -20,7 +20,7 @@ const ( Test_Cert2CN = "CN=bar.example.com,OU=Testsuite,O=Testing Corp,L=Hanover,ST=Lower Saxony,C=DE" ) -var Test_TLS_Subjects []string = []string{ +var Test_TLS_Subjects = []string{ "CN=foo.example.com,OU=SpecOps,O=Capone\\, Inc,L=Chicago,ST=IL,C=US", "CN=bar.example.com,OU=Testsuite,O=Testing Corp,L=Hanover,ST=Lower Saxony,C=DE", } @@ -213,7 +213,7 @@ ssh.dev.azure.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7Hr1oTWqNqOlzGJOfGJ4Nak vs-ssh.visualstudio.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7Hr1oTWqNqOlzGJOfGJ4NakVyIzf1rXYd4d7wo6jBlkLvCA4odBlL0mDUyZ0/QUfTTqeu+tm22gOsv+VrVTMk6vwRU75gY/y9ut5Mb3bR5BV58dKXyq9A9UeB5Cakehn5Zgm6x1mKoVyf+FFn26iYqXJRgzIZZcZ5V6hrE0Qg39kZm4az48o0AUbf6Sp4SLdvnuMa2sVNwHBboS7EJkm57XQPVU3/QpyNLHbWDdzwtrlS+ez30S3AdYhLKEOxAG8weOnyrtLJAUen9mTkol8oII1edf7mWWbWVf0nBmly21+nZcmCTISQBtdcyPaEno7fFQMDD26/s0lfKob4Kw8H ` -var Test_SSH_Hostname_Entries []string = []string{ +var Test_SSH_Hostname_Entries = []string{ "bitbucket.org", "github.com", "gitlab.com", @@ -223,7 +223,7 @@ var Test_SSH_Hostname_Entries []string = []string{ "vs-ssh.visualstudio.com", } -var Test_SSH_Subtypes []string = []string{ +var Test_SSH_Subtypes = []string{ "ssh-rsa", "ssh-rsa", "ecdsa-sha2-nistp256", @@ -233,7 +233,7 @@ var Test_SSH_Subtypes []string = []string{ "ssh-rsa", } -var Test_TLS_Hostnames []string = []string{ +var Test_TLS_Hostnames = []string{ "test.example.com", "test.example.com", "github.com", diff --git a/util/db/gpgkeys.go b/util/db/gpgkeys.go index ddb985101a6e7..add5b4f4222b3 100644 --- a/util/db/gpgkeys.go +++ b/util/db/gpgkeys.go @@ -42,7 +42,7 @@ func validatePGPKey(keyData string) (*appsv1.GnuPGPublicKey, error) { return nil, errors.New("More than one key found in input data") } - var retKey *appsv1.GnuPGPublicKey = nil + var retKey *appsv1.GnuPGPublicKey // Is there a better way to get the first element from a map without knowing its key? for _, k := range parsed { retKey = k diff --git a/util/git/creds.go b/util/git/creds.go index 19308112c9c29..aea82574934d6 100644 --- a/util/git/creds.go +++ b/util/git/creds.go @@ -285,7 +285,7 @@ func (f sshPrivateKeyFile) Close() error { // Remove a list of files that have been created as temp files while creating // HTTPCreds object above. func (f authFilePaths) Close() error { - var retErr error = nil + var retErr error for _, path := range f { err := os.Remove(path) if err != nil { diff --git a/util/gpg/gpg.go b/util/gpg/gpg.go index bea324024eecc..6b8cefbeea82f 100644 --- a/util/gpg/gpg.go +++ b/util/gpg/gpg.go @@ -502,7 +502,7 @@ func GetInstalledPGPKeys(kids []string) ([]*appsv1.GnuPGPublicKey, error) { } scanner := bufio.NewScanner(strings.NewReader(out)) - var curKey *appsv1.GnuPGPublicKey = nil + var curKey *appsv1.GnuPGPublicKey for scanner.Scan() { if strings.HasPrefix(scanner.Text(), "pub ") { // This is the beginning of a new key, time to store the previously parsed one in our list and start fresh. diff --git a/util/io/path/resolved_test.go b/util/io/path/resolved_test.go index 36472e8788716..c5168c5b39951 100644 --- a/util/io/path/resolved_test.go +++ b/util/io/path/resolved_test.go @@ -48,7 +48,7 @@ func Test_isURLSchemeAllowed(t *testing.T) { allowed []string expected bool } - var tts []testdata = []testdata{ + tts := []testdata{ { name: "Allowed scheme matches", scheme: "http", diff --git a/util/lua/custom_actions_test.go b/util/lua/custom_actions_test.go index 1447f146815d1..aee5c59a9ac0d 100644 --- a/util/lua/custom_actions_test.go +++ b/util/lua/custom_actions_test.go @@ -239,7 +239,7 @@ func getExpectedObjectList(t *testing.T, path string) *unstructured.Unstructured } func findFirstMatchingItem(items []unstructured.Unstructured, f func(unstructured.Unstructured) bool) *unstructured.Unstructured { - var matching *unstructured.Unstructured = nil + var matching *unstructured.Unstructured for _, item := range items { if f(item) { matching = &item From b3e31ed1f4fb54b3523a19c2b4efa65b33d8b16a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Jan 2025 09:22:59 -0500 Subject: [PATCH 16/41] chore(deps): bump github.com/coreos/go-oidc/v3 from 3.11.0 to 3.12.0 (#21383) Bumps [github.com/coreos/go-oidc/v3](https://github.com/coreos/go-oidc) from 3.11.0 to 3.12.0. - [Release notes](https://github.com/coreos/go-oidc/releases) - [Commits](https://github.com/coreos/go-oidc/compare/v3.11.0...v3.12.0) --- updated-dependencies: - dependency-name: github.com/coreos/go-oidc/v3 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index fa24962628d0c..06f5362b7c0bc 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,7 @@ require ( github.com/casbin/govaluate v1.3.0 github.com/cespare/xxhash/v2 v2.3.0 github.com/chainguard-dev/git-urls v1.0.2 - github.com/coreos/go-oidc/v3 v3.11.0 + github.com/coreos/go-oidc/v3 v3.12.0 github.com/cyphar/filepath-securejoin v0.3.6 github.com/dustin/go-humanize v1.0.1 github.com/evanphx/json-patch v5.9.0+incompatible diff --git a/go.sum b/go.sum index d51e3f074767c..f57af02ca51f6 100644 --- a/go.sum +++ b/go.sum @@ -195,8 +195,8 @@ github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:z github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= github.com/codeskyblue/go-sh v0.0.0-20190412065543-76bd3d59ff27/go.mod h1:VQx0hjo2oUeQkQUET7wRwradO6f+fN5jzXgB/zROxxE= -github.com/coreos/go-oidc/v3 v3.11.0 h1:Ia3MxdwpSw702YW0xgfmP1GVCMA9aEFWu12XUZ3/OtI= -github.com/coreos/go-oidc/v3 v3.11.0/go.mod h1:gE3LgjOgFoHi9a4ce4/tJczr0Ai2/BoDhf0r5lltWI0= +github.com/coreos/go-oidc/v3 v3.12.0 h1:sJk+8G2qq94rDI6ehZ71Bol3oUHy63qNYmkiSjrc/Jo= +github.com/coreos/go-oidc/v3 v3.12.0/go.mod h1:gE3LgjOgFoHi9a4ce4/tJczr0Ai2/BoDhf0r5lltWI0= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= From 1bf2ab5dc0479fbf36dfe1ab5bceb738e8a5ed8f Mon Sep 17 00:00:00 2001 From: Keith Chong Date: Mon, 6 Jan 2025 09:24:42 -0500 Subject: [PATCH 17/41] test: Update ui test to fix logic for headless mode, add logs (#21361) (#21362) Signed-off-by: Keith Chong --- ui-test/src/UiTestUtilities.ts | 11 +++--- .../application-create-panel.ts | 39 ++++++++++++------- .../applications-list/applications-list.ts | 14 +++---- .../applications-sync-panel.ts | 4 +- ui-test/src/navigation.ts | 8 ++-- 5 files changed, 43 insertions(+), 33 deletions(-) diff --git a/ui-test/src/UiTestUtilities.ts b/ui-test/src/UiTestUtilities.ts index ac38790ca1e4e..bdc1e201e10bc 100644 --- a/ui-test/src/UiTestUtilities.ts +++ b/ui-test/src/UiTestUtilities.ts @@ -49,21 +49,20 @@ export default class UiTestUtilities { */ public static async init(): Promise { const options = new chrome.Options(); - if (process.env.IS_HEADLESS) { + UiTestUtilities.log('Env var IS_HEADLESS = ' + process.env.IS_HEADLESS); + if (process.env.IS_HEADLESS !== 'false') { + UiTestUtilities.log('Adding headless option'); options.addArguments('headless'); } options.addArguments('window-size=1400x1200'); - const driver = await new Builder() - .forBrowser('chrome') - .setChromeOptions(options) - .build(); + const driver = await new Builder().forBrowser('chrome').setChromeOptions(options).build(); UiTestUtilities.log('Environment variables are:'); UiTestUtilities.log(require('dotenv').config({path: __dirname + '/../.env'})); // Navigate to the ArgoCD URL await driver.get(Configuration.ARGOCD_URL); - + UiTestUtilities.log('Navigate to Argo CD URL successful: driver.get'); return new Navigation(driver); } diff --git a/ui-test/src/application-create-panel/application-create-panel.ts b/ui-test/src/application-create-panel/application-create-panel.ts index a153611aa47bd..713845c2dfabc 100644 --- a/ui-test/src/application-create-panel/application-create-panel.ts +++ b/ui-test/src/application-create-panel/application-create-panel.ts @@ -31,7 +31,8 @@ export class ApplicationCreatePanel extends Base { try { const appNameField = await UiTestUtilities.findUiElement(this.driver, CREATE_APPLICATION_FIELD_APP_NAME); await appNameField.sendKeys(appName); - } catch (err) { + } catch (err: any) { + UiTestUtilities.log('Error caught while setting app name: ' + err); throw new Error(err); } } @@ -40,7 +41,8 @@ export class ApplicationCreatePanel extends Base { try { const project = await UiTestUtilities.findUiElement(this.driver, CREATE_APPLICATION_FIELD_PROJECT); await project.sendKeys(projectName); - } catch (err) { + } catch (err: any) { + UiTestUtilities.log('Error caught while setting project name: ' + err); throw new Error(err); } } @@ -49,7 +51,8 @@ export class ApplicationCreatePanel extends Base { try { const reposUrl = await UiTestUtilities.findUiElement(this.driver, CREATE_APPLICATION_FIELD_REPOSITORY_URL); await reposUrl.sendKeys(sourceRepoUrl); - } catch (err) { + } catch (err: any) { + UiTestUtilities.log('Error caught while setting source repo URL: ' + err); throw new Error(err); } } @@ -58,7 +61,8 @@ export class ApplicationCreatePanel extends Base { try { const path = await UiTestUtilities.findUiElement(this.driver, CREATE_APPLICATION_FIELD_REPOSITORY_PATH); await path.sendKeys(sourceRepoPath); - } catch (err) { + } catch (err: any) { + UiTestUtilities.log('Error caught while setting source repo path: ' + err); throw new Error(err); } } @@ -78,7 +82,8 @@ export class ApplicationCreatePanel extends Base { if (destinationClusterFieldValue) { await this.setDestinationClusterUrl(destinationClusterFieldValue); } - } catch (err) { + } catch (err: any) { + UiTestUtilities.log('Error caught while selecting destination cluster URL menu: ' + err); throw new Error(err); } } @@ -98,7 +103,8 @@ export class ApplicationCreatePanel extends Base { if (destinationClusterFieldValue) { await this.setDestinationClusterName(destinationClusterFieldValue); } - } catch (err) { + } catch (err: any) { + UiTestUtilities.log('Error caught while selecting destination cluster name menu: ' + err); throw new Error(err); } } @@ -108,7 +114,8 @@ export class ApplicationCreatePanel extends Base { const clusterName = await UiTestUtilities.findUiElement(this.driver, CREATE_APPLICATION_FIELD_CLUSTER_NAME); await clusterName.sendKeys(destinationClusterName); // await clusterName.sendKeys('\r'); - } catch (err) { + } catch (err: any) { + UiTestUtilities.log('Error caught while setting destination cluster name: ' + err); throw new Error(err); } } @@ -117,7 +124,8 @@ export class ApplicationCreatePanel extends Base { try { const clusterUrl = await UiTestUtilities.findUiElement(this.driver, CREATE_APPLICATION_FIELD_CLUSTER_URL); await clusterUrl.sendKeys(destinationClusterUrl); - } catch (err) { + } catch (err: any) { + UiTestUtilities.log('Error caught while setting destination cluster URL: ' + err); throw new Error(err); } } @@ -126,7 +134,8 @@ export class ApplicationCreatePanel extends Base { try { const namespace = await UiTestUtilities.findUiElement(this.driver, CREATE_APPLICATION_FIELD_CLUSTER_NAMESPACE); await namespace.sendKeys(destinationNamespace); - } catch (err) { + } catch (err: any) { + UiTestUtilities.log('Error caught while setting destination namespace: ' + err); throw new Error(err); } } @@ -140,12 +149,13 @@ export class ApplicationCreatePanel extends Base { await createButton.click(); // Wait until the Create Application Sliding Panel disappears - await this.driver.wait(until.elementIsNotVisible(createButton), Const.TEST_SLIDING_PANEL_TIMEOUT).catch(e => { + await this.driver.wait(until.elementIsNotVisible(createButton), Const.TEST_SLIDING_PANEL_TIMEOUT).catch((e) => { UiTestUtilities.logError('The Create Application Sliding Panel did not disappear'); throw e; }); await this.driver.sleep(1000); - } catch (err) { + } catch (err: any) { + UiTestUtilities.log('Error caught while clicking Create button: ' + err); throw new Error(err); } } @@ -159,11 +169,12 @@ export class ApplicationCreatePanel extends Base { await cancelButton.click(); // Wait until the Create Application Sliding Panel disappears - await this.driver.wait(until.elementIsNotVisible(cancelButton), Const.TEST_SLIDING_PANEL_TIMEOUT).catch(e => { + await this.driver.wait(until.elementIsNotVisible(cancelButton), Const.TEST_SLIDING_PANEL_TIMEOUT).catch((e) => { UiTestUtilities.logError('The Create Application Sliding Panel did not disappear'); throw e; }); - } catch (err) { + } catch (err: any) { + UiTestUtilities.log('Error caught while clicking Cancel button: ' + err); throw new Error(err); } } @@ -198,7 +209,7 @@ export class ApplicationCreatePanel extends Base { await this.selectDestinationClusterNameMenu(destinationClusterName); await this.setDestinationNamespace(destinationNamespace); await this.clickCreateButton(); - } catch (err) { + } catch (err: any) { throw new Error(err); } } diff --git a/ui-test/src/applications-list/applications-list.ts b/ui-test/src/applications-list/applications-list.ts index ae76b9d80c045..90dfb791a93cb 100644 --- a/ui-test/src/applications-list/applications-list.ts +++ b/ui-test/src/applications-list/applications-list.ts @@ -27,7 +27,7 @@ export class ApplicationsList extends Base { try { const tile = await UiTestUtilities.findUiElement(this.driver, this.getApplicationTileLocator(appName)); await tile.click(); - } catch (err) { + } catch (err: any) { throw new Error(err); } } @@ -39,7 +39,7 @@ export class ApplicationsList extends Base { try { const newAppButton = await UiTestUtilities.findUiElement(this.driver, NEW_APP_BUTTON); await newAppButton.click(); - } catch (err) { + } catch (err: any) { throw new Error(err); } return this.applicationCreatePanel; @@ -57,7 +57,7 @@ export class ApplicationsList extends Base { // Wait until the Synchronize sliding panel appears const synchronizeButton = await this.driver.wait(until.elementLocated(SYNC_PANEL_SYNCHRONIZE_BUTTON), Const.TEST_TIMEOUT); await this.driver.wait(until.elementIsVisible(synchronizeButton), Const.TEST_TIMEOUT); - } catch (err) { + } catch (err: any) { throw new Error(err); } return this.applicationsSyncPanel; @@ -72,7 +72,7 @@ export class ApplicationsList extends Base { try { const deleteButton = await UiTestUtilities.findUiElement(this.driver, this.getDeleteButtonLocatorForApp(appName)); await deleteButton.click(); - } catch (err) { + } catch (err: any) { throw new Error(err); } return this.popupManager; @@ -95,7 +95,7 @@ export class ApplicationsList extends Base { const refreshButton = await UiTestUtilities.findUiElement(this.driver, this.getRefreshButtonLocatorForApp(appName)); await this.driver.wait(until.elementIsVisible(refreshButton), Const.TEST_TIMEOUT); await refreshButton.click(); - } catch (err) { + } catch (err: any) { throw new Error(err); } } @@ -111,7 +111,7 @@ export class ApplicationsList extends Base { await this.driver.wait(async () => { return UiTestUtilities.untilAttributeIs(healthStatusElement, 'title', 'Healthy'); }, Const.TEST_TIMEOUT); - } catch (err) { + } catch (err: any) { throw new Error(err); } } @@ -127,7 +127,7 @@ export class ApplicationsList extends Base { await this.driver.wait(async () => { return UiTestUtilities.untilAttributeIs(statusElement, 'title', 'Synced'); }, Const.TEST_TIMEOUT); - } catch (err) { + } catch (err: any) { throw new Error(err); } } diff --git a/ui-test/src/applications-sync-panel/applications-sync-panel.ts b/ui-test/src/applications-sync-panel/applications-sync-panel.ts index 9a5f266de58f3..dfd4b8c6010d3 100644 --- a/ui-test/src/applications-sync-panel/applications-sync-panel.ts +++ b/ui-test/src/applications-sync-panel/applications-sync-panel.ts @@ -23,12 +23,12 @@ export class ApplicationsSyncPanel extends Base { await this.driver.wait(until.elementIsEnabled(synchronizeButton), Const.TEST_TIMEOUT); await synchronizeButton.click(); - await this.driver.wait(until.elementIsNotVisible(synchronizeButton), Const.TEST_SLIDING_PANEL_TIMEOUT).catch(e => { + await this.driver.wait(until.elementIsNotVisible(synchronizeButton), Const.TEST_SLIDING_PANEL_TIMEOUT).catch((e) => { UiTestUtilities.logError('The Synchronization Sliding Panel did not disappear'); throw e; }); UiTestUtilities.log('Synchronize sliding panel disappeared'); - } catch (err) { + } catch (err: any) { throw new Error(err); } } diff --git a/ui-test/src/navigation.ts b/ui-test/src/navigation.ts index 8baaff37e4d38..79618405f3761 100644 --- a/ui-test/src/navigation.ts +++ b/ui-test/src/navigation.ts @@ -31,7 +31,7 @@ export class Navigation extends Base { try { const navBarButton = await UiTestUtilities.findUiElement(this.driver, NAVBAR_APPLICATIONS_BUTTON); await navBarButton.click(); - } catch (err) { + } catch (err: any) { throw new Error(err); } return this.applicationsList; @@ -45,7 +45,7 @@ export class Navigation extends Base { try { const navBarButton = await UiTestUtilities.findUiElement(this.driver, NAVBAR_SETTINGS_BUTTON); await navBarButton.click(); - } catch (err) { + } catch (err: any) { throw new Error(err); } } @@ -58,7 +58,7 @@ export class Navigation extends Base { try { const navBarButton = await UiTestUtilities.findUiElement(this.driver, NAVBAR_USER_INFO_BUTTON); await navBarButton.click(); - } catch (err) { + } catch (err: any) { throw new Error(err); } } @@ -71,7 +71,7 @@ export class Navigation extends Base { try { const navBarButton = await UiTestUtilities.findUiElement(this.driver, NAVBAR_DOCS_BUTTON); await navBarButton.click(); - } catch (err) { + } catch (err: any) { throw new Error(err); } } From 38ad4f465332b2fd5ce06d84352bba35ac176e3e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Jan 2025 09:25:17 -0500 Subject: [PATCH 18/41] chore(deps): bump golang.org/x/term from 0.27.0 to 0.28.0 (#21382) Bumps [golang.org/x/term](https://github.com/golang/term) from 0.27.0 to 0.28.0. - [Commits](https://github.com/golang/term/compare/v0.27.0...v0.28.0) --- updated-dependencies: - dependency-name: golang.org/x/term dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 4 ++-- go.sum | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index 06f5362b7c0bc..f9d876b28ba3e 100644 --- a/go.mod +++ b/go.mod @@ -88,7 +88,7 @@ require ( golang.org/x/net v0.33.0 golang.org/x/oauth2 v0.24.0 golang.org/x/sync v0.10.0 - golang.org/x/term v0.27.0 + golang.org/x/term v0.28.0 golang.org/x/time v0.8.0 google.golang.org/genproto/googleapis/api v0.0.0-20241104194629-dd2ea8efbc28 google.golang.org/grpc v1.69.2 @@ -152,7 +152,7 @@ require ( go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0 // indirect go.starlark.net v0.0.0-20230525235612-a134d8f9ddca // indirect golang.org/x/mod v0.22.0 // indirect - golang.org/x/sys v0.28.0 // indirect + golang.org/x/sys v0.29.0 // indirect golang.org/x/text v0.21.0 // indirect golang.org/x/tools v0.27.0 // indirect google.golang.org/api v0.171.0 // indirect diff --git a/go.sum b/go.sum index f57af02ca51f6..107e6e1820571 100644 --- a/go.sum +++ b/go.sum @@ -1232,8 +1232,8 @@ golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= -golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= +golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/telemetry v0.0.0-20240208230135-b75ee8823808/go.mod h1:KG1lNk5ZFNssSZLrpVb4sMXKMpGwGXOxSG3rnu2gZQQ= golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= @@ -1258,8 +1258,8 @@ golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk= golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0= -golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= -golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= +golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg= +golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= From 41dec01c7c7a993e6287128f4cbc928a52c8c48a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Jan 2025 09:56:26 -0500 Subject: [PATCH 19/41] chore(deps-dev): bump @types/node from 22.10.2 to 22.10.5 in /ui-test (#21381) Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 22.10.2 to 22.10.5. - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) --- updated-dependencies: - dependency-name: "@types/node" dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- ui-test/package.json | 2 +- ui-test/yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ui-test/package.json b/ui-test/package.json index 44612099be8c6..424425b0b091e 100644 --- a/ui-test/package.json +++ b/ui-test/package.json @@ -19,7 +19,7 @@ }, "devDependencies": { "@types/mocha": "^10.0.10", - "@types/node": "^22.10.2", + "@types/node": "^22.10.5", "dotenv": "^16.4.7", "mocha": "^11.0.1", "prettier": "^2.8.8", diff --git a/ui-test/yarn.lock b/ui-test/yarn.lock index 0a38218816a27..e2d66b0771791 100644 --- a/ui-test/yarn.lock +++ b/ui-test/yarn.lock @@ -60,10 +60,10 @@ resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-10.0.10.tgz#91f62905e8d23cbd66225312f239454a23bebfa0" integrity sha512-xPyYSz1cMPnJQhl0CLMH68j3gprKZaTjG3s5Vi+fDgx+uhG9NOXwbVt52eFS8ECyXhyKcjDLCBEqBExKuiZb7Q== -"@types/node@*", "@types/node@^22.10.2": - version "22.10.2" - resolved "https://registry.yarnpkg.com/@types/node/-/node-22.10.2.tgz#a485426e6d1fdafc7b0d4c7b24e2c78182ddabb9" - integrity sha512-Xxr6BBRCAOQixvonOye19wnzyDiUtTeqldOOmj3CkeblonbccA12PFwlufvRdrpjXxqnmUaeiU5EOA+7s5diUQ== +"@types/node@*", "@types/node@^22.10.5": + version "22.10.5" + resolved "https://registry.yarnpkg.com/@types/node/-/node-22.10.5.tgz#95af89a3fb74a2bb41ef9927f206e6472026e48b" + integrity sha512-F8Q+SeGimwOo86fiovQh8qiXfFEh2/ocYv7tU5pJ3EXMSSxk1Joj5wefpFK2fHTf/N6HKGSxIDBT9f3gCxXPkQ== dependencies: undici-types "~6.20.0" From 9f0dc9402fb8245d95834b29f19397ff758147db Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Mon, 6 Jan 2025 17:30:42 +0100 Subject: [PATCH 20/41] chore: enable redundant-import-alias from revive (#21386) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 14 + applicationset/metrics/metrics_test.go | 16 +- .../services/pull_request/azure_devops.go | 4 +- .../pull_request/azure_devops_test.go | 2 +- cmd/argocd/commands/admin/notifications.go | 2 +- cmd/argocd/commands/app_actions.go | 2 +- controller/appcontroller_test.go | 8 +- controller/sharding/sharding.go | 2 +- controller/state_test.go | 8 +- pkg/apis/application/v1alpha1/values.go | 4 +- reposerver/apiclient/mocks/Clientset.go | 5 +- reposerver/repository/repository_test.go | 6 +- server/application/application_test.go | 377 +++++++++--------- server/badge/badge.go | 2 +- test/e2e/fixture/admin/utils/backup.go | 2 +- test/e2e/fixture/applicationsets/actions.go | 12 +- test/e2e/sync_with_impersonate_test.go | 18 +- util/db/db_test.go | 6 +- util/db/secrets.go | 4 +- util/notification/k8s/informers.go | 6 +- util/rbac/rbac.go | 4 +- util/settings/settings.go | 6 +- 22 files changed, 259 insertions(+), 251 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 0e85608e22332..59d71984efa37 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -60,12 +60,18 @@ linters-settings: alias: - alias: jwtgo pkg: github.com/golang-jwt/jwt/v5 + - alias: appsv1 + pkg: k8s.io/api/apps/v1 - alias: corev1 pkg: k8s.io/api/core/v1 + - alias: rbacv1 + pkg: k8s.io/api/rbac/v1 - alias: apierrors pkg: k8s.io/apimachinery/pkg/api/errors - alias: metav1 pkg: k8s.io/apimachinery/pkg/apis/meta/v1 + - alias: informersv1 + pkg: k8s.io/client-go/informers/core/v1 - alias: stderrors pkg: errors perfsprint: @@ -106,19 +112,24 @@ linters-settings: disabled: true # report when replacing `errors.New(fmt.Sprintf())` with `fmt.Errorf()` is possible - name: errorf + disabled: false # incrementing an integer variable by 1 is recommended to be done using the `++` operator - name: increment-decrement + disabled: false # 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 + disabled: false # 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 + - name: redundant-import-alias + disabled: false # redundant else-blocks that can be eliminated from the code. - name: superfluous-else disabled: true @@ -130,13 +141,16 @@ linters-settings: disabled: true # spots and proposes to remove unreachable code. also helps to spot errors - name: unreachable-code + disabled: false # 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 + disabled: false # report when a variable declaration can be simplified - name: var-declaration + disabled: false # warns when initialism, variable or package naming conventions are not followed. - name: var-naming disabled: true diff --git a/applicationset/metrics/metrics_test.go b/applicationset/metrics/metrics_test.go index 13457ca03d37f..f3e5b25fcf7cc 100644 --- a/applicationset/metrics/metrics_test.go +++ b/applicationset/metrics/metrics_test.go @@ -7,23 +7,19 @@ import ( "testing" "time" - "github.com/argoproj/argo-cd/v2/applicationset/utils" - argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/runtime" ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" - fake "sigs.k8s.io/controller-runtime/pkg/client/fake" - - prometheus "github.com/prometheus/client_golang/prometheus" - - metricsutil "github.com/argoproj/argo-cd/v2/util/metrics" - + "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/metrics" - "sigs.k8s.io/yaml" + + "github.com/argoproj/argo-cd/v2/applicationset/utils" + argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" + metricsutil "github.com/argoproj/argo-cd/v2/util/metrics" ) var ( diff --git a/applicationset/services/pull_request/azure_devops.go b/applicationset/services/pull_request/azure_devops.go index 1d263212cdea1..78cf29f01aa7f 100644 --- a/applicationset/services/pull_request/azure_devops.go +++ b/applicationset/services/pull_request/azure_devops.go @@ -6,8 +6,8 @@ import ( "strings" "github.com/microsoft/azure-devops-go-api/azuredevops" - core "github.com/microsoft/azure-devops-go-api/azuredevops/core" - git "github.com/microsoft/azure-devops-go-api/azuredevops/git" + "github.com/microsoft/azure-devops-go-api/azuredevops/core" + "github.com/microsoft/azure-devops-go-api/azuredevops/git" ) const AZURE_DEVOPS_DEFAULT_URL = "https://dev.azure.com" diff --git a/applicationset/services/pull_request/azure_devops_test.go b/applicationset/services/pull_request/azure_devops_test.go index 24453c93a2195..d5291c710c923 100644 --- a/applicationset/services/pull_request/azure_devops_test.go +++ b/applicationset/services/pull_request/azure_devops_test.go @@ -7,7 +7,7 @@ import ( "github.com/microsoft/azure-devops-go-api/azuredevops/webapi" "github.com/microsoft/azure-devops-go-api/azuredevops/core" - git "github.com/microsoft/azure-devops-go-api/azuredevops/git" + "github.com/microsoft/azure-devops-go-api/azuredevops/git" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/cmd/argocd/commands/admin/notifications.go b/cmd/argocd/commands/admin/notifications.go index 0442e5b5f02f0..8b0f50bbdbb0b 100644 --- a/cmd/argocd/commands/admin/notifications.go +++ b/cmd/argocd/commands/admin/notifications.go @@ -11,7 +11,7 @@ import ( "github.com/argoproj/argo-cd/v2/reposerver/apiclient" "github.com/argoproj/argo-cd/v2/util/env" service "github.com/argoproj/argo-cd/v2/util/notification/argocd" - settings "github.com/argoproj/argo-cd/v2/util/notification/settings" + "github.com/argoproj/argo-cd/v2/util/notification/settings" "github.com/argoproj/argo-cd/v2/util/tls" "github.com/argoproj/notifications-engine/pkg/cmd" diff --git a/cmd/argocd/commands/app_actions.go b/cmd/argocd/commands/app_actions.go index f795585d07b8c..69a36683dd357 100644 --- a/cmd/argocd/commands/app_actions.go +++ b/cmd/argocd/commands/app_actions.go @@ -21,7 +21,7 @@ import ( argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient" applicationpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" "github.com/argoproj/argo-cd/v2/pkg/apis/application" - v1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" + "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/util/argo" "github.com/argoproj/argo-cd/v2/util/errors" "github.com/argoproj/argo-cd/v2/util/io" diff --git a/controller/appcontroller_test.go b/controller/appcontroller_test.go index 75b6fd5bfd860..350fa959c3c39 100644 --- a/controller/appcontroller_test.go +++ b/controller/appcontroller_test.go @@ -28,7 +28,7 @@ import ( "github.com/argoproj/gitops-engine/pkg/utils/kube" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" - v1 "k8s.io/api/apps/v1" + appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -1696,7 +1696,7 @@ func TestUpdateReconciledAt(t *testing.T) { } func TestUpdateHealthStatusTransitionTime(t *testing.T) { - deployment := kube.MustToUnstructured(&v1.Deployment{ + deployment := kube.MustToUnstructured(&appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: "apps/v1", Kind: "Deployment", @@ -1798,7 +1798,7 @@ apps/Deployment: func TestUpdateHealthStatusProgression(t *testing.T) { app := newFakeAppWithHealthAndTime(health.HealthStatusDegraded, testTimestamp) - deployment := kube.MustToUnstructured(&v1.Deployment{ + deployment := kube.MustToUnstructured(&appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: "apps/v1", Kind: "Deployment", @@ -1807,7 +1807,7 @@ func TestUpdateHealthStatusProgression(t *testing.T) { Name: "demo", Namespace: "default", }, - Status: v1.DeploymentStatus{ + Status: appsv1.DeploymentStatus{ ObservedGeneration: 0, }, }) diff --git a/controller/sharding/sharding.go b/controller/sharding/sharding.go index d883b6839a277..1ae2052efd56f 100644 --- a/controller/sharding/sharding.go +++ b/controller/sharding/sharding.go @@ -8,12 +8,12 @@ import ( "hash/fnv" "math" "os" + "slices" "sort" "strconv" "strings" "time" - slices "golang.org/x/exp/slices" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" diff --git a/controller/state_test.go b/controller/state_test.go index aeab4ad0574a7..af66e54cf169d 100644 --- a/controller/state_test.go +++ b/controller/state_test.go @@ -16,7 +16,7 @@ import ( logrustest "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - v1 "k8s.io/api/apps/v1" + appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -684,7 +684,7 @@ func TestCompareAppStateWithManifestGeneratePath(t *testing.T) { func TestSetHealth(t *testing.T) { app := newFakeApp() - deployment := kube.MustToUnstructured(&v1.Deployment{ + deployment := kube.MustToUnstructured(&appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: "apps/v1", Kind: "Deployment", @@ -721,7 +721,7 @@ func TestSetHealth(t *testing.T) { func TestPreserveStatusTimestamp(t *testing.T) { timestamp := metav1.Now() app := newFakeAppWithHealthAndTime(health.HealthStatusHealthy, timestamp) - deployment := kube.MustToUnstructured(&v1.Deployment{ + deployment := kube.MustToUnstructured(&appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: "apps/v1", Kind: "Deployment", @@ -758,7 +758,7 @@ func TestPreserveStatusTimestamp(t *testing.T) { func TestSetHealthSelfReferencedApp(t *testing.T) { app := newFakeApp() unstructuredApp := kube.MustToUnstructured(app) - deployment := kube.MustToUnstructured(&v1.Deployment{ + deployment := kube.MustToUnstructured(&appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: "apps/v1", Kind: "Deployment", diff --git a/pkg/apis/application/v1alpha1/values.go b/pkg/apis/application/v1alpha1/values.go index e642e667933b6..e900a5d3d61c6 100644 --- a/pkg/apis/application/v1alpha1/values.go +++ b/pkg/apis/application/v1alpha1/values.go @@ -3,10 +3,10 @@ package v1alpha1 import ( "encoding/json" "fmt" - reflect "reflect" + "reflect" "strings" - runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/yaml" ) diff --git a/reposerver/apiclient/mocks/Clientset.go b/reposerver/apiclient/mocks/Clientset.go index 292b0de5d3651..edd32c1931f06 100644 --- a/reposerver/apiclient/mocks/Clientset.go +++ b/reposerver/apiclient/mocks/Clientset.go @@ -1,9 +1,8 @@ package mocks import ( - apiclient "github.com/argoproj/argo-cd/v2/reposerver/apiclient" - - io "github.com/argoproj/argo-cd/v2/util/io" + "github.com/argoproj/argo-cd/v2/reposerver/apiclient" + "github.com/argoproj/argo-cd/v2/util/io" ) type Clientset struct { diff --git a/reposerver/repository/repository_test.go b/reposerver/repository/repository_test.go index 9e611e65471b6..7ccadd6af84f7 100644 --- a/reposerver/repository/repository_test.go +++ b/reposerver/repository/repository_test.go @@ -29,7 +29,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" - v1 "k8s.io/api/apps/v1" + appsv1 "k8s.io/api/apps/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/yaml" @@ -1113,7 +1113,7 @@ func TestGenerateHelmWithValues(t *testing.T) { require.NoError(t, err) if obj.GetKind() == "Deployment" && obj.GetName() == "test-redis-slave" { - var dep v1.Deployment + var dep appsv1.Deployment err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, &dep) require.NoError(t, err) assert.Equal(t, int32(2), *dep.Spec.Replicas) @@ -1175,7 +1175,7 @@ func TestGenerateHelmWithEnvVars(t *testing.T) { require.NoError(t, err) if obj.GetKind() == "Deployment" && obj.GetName() == "production-redis-slave" { - var dep v1.Deployment + var dep appsv1.Deployment err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, &dep) require.NoError(t, err) assert.Equal(t, int32(3), *dep.Spec.Replicas) diff --git a/server/application/application_test.go b/server/application/application_test.go index 7633035fc69d3..a3e26d52a6028 100644 --- a/server/application/application_test.go +++ b/server/application/application_test.go @@ -24,7 +24,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" - k8sappsv1 "k8s.io/api/apps/v1" + appsv1 "k8s.io/api/apps/v1" k8sbatchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -41,8 +41,7 @@ import ( "github.com/argoproj/argo-cd/v2/common" "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" - appsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" + "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" apps "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned/fake" appinformer "github.com/argoproj/argo-cd/v2/pkg/client/informers/externalversions" "github.com/argoproj/argo-cd/v2/reposerver/apiclient" @@ -73,13 +72,13 @@ type broadcasterMock struct { objects []runtime.Object } -func (b broadcasterMock) Subscribe(ch chan *appv1.ApplicationWatchEvent, filters ...func(event *appv1.ApplicationWatchEvent) bool) func() { +func (b broadcasterMock) Subscribe(ch chan *v1alpha1.ApplicationWatchEvent, filters ...func(event *v1alpha1.ApplicationWatchEvent) bool) func() { // Simulate the broadcaster notifying the subscriber of an application update. // The second parameter to Subscribe is filters. For the purposes of tests, we ignore the filters. Future tests // might require implementing those. go func() { for _, obj := range b.objects { - app, ok := obj.(*appsv1.Application) + app, ok := obj.(*v1alpha1.Application) if ok { oldVersion, err := strconv.Atoi(app.ResourceVersion) if err != nil { @@ -87,7 +86,7 @@ func (b broadcasterMock) Subscribe(ch chan *appv1.ApplicationWatchEvent, filters } clonedApp := app.DeepCopy() clonedApp.ResourceVersion = strconv.Itoa(oldVersion + 1) - ch <- &appsv1.ApplicationWatchEvent{Type: watch.Added, Application: *clonedApp} + ch <- &v1alpha1.ApplicationWatchEvent{Type: watch.Added, Application: *clonedApp} } } }() @@ -98,17 +97,17 @@ func (broadcasterMock) OnAdd(any, bool) {} func (broadcasterMock) OnUpdate(any, any) {} func (broadcasterMock) OnDelete(any) {} -func fakeRepo() *appsv1.Repository { - return &appsv1.Repository{ +func fakeRepo() *v1alpha1.Repository { + return &v1alpha1.Repository{ Repo: fakeRepoURL, } } -func fakeCluster() *appsv1.Cluster { - return &appsv1.Cluster{ +func fakeCluster() *v1alpha1.Cluster { + return &v1alpha1.Cluster{ Server: "https://cluster-api.example.com", Name: "fake-cluster", - Config: appsv1.ClusterConfig{}, + Config: v1alpha1.ClusterConfig{}, } } @@ -140,12 +139,12 @@ func fakeRepoServerClient(isHelm bool) *mocks.RepoServerServiceClient { mockRepoServiceClient.On("GenerateManifest", mock.Anything, mock.Anything).Return(&apiclient.ManifestResponse{}, nil) mockRepoServiceClient.On("GetAppDetails", mock.Anything, mock.Anything).Return(&apiclient.RepoAppDetailsResponse{}, nil) mockRepoServiceClient.On("TestRepository", mock.Anything, mock.Anything).Return(&apiclient.TestRepositoryResponse{}, nil) - mockRepoServiceClient.On("GetRevisionMetadata", mock.Anything, mock.Anything).Return(&appsv1.RevisionMetadata{}, nil) + mockRepoServiceClient.On("GetRevisionMetadata", mock.Anything, mock.Anything).Return(&v1alpha1.RevisionMetadata{}, nil) mockWithFilesClient := &mocks.RepoServerService_GenerateManifestWithFilesClient{} mockWithFilesClient.On("Send", mock.Anything).Return(nil) mockWithFilesClient.On("CloseAndRecv").Return(&apiclient.ManifestResponse{}, nil) mockRepoServiceClient.On("GenerateManifestWithFiles", mock.Anything, mock.Anything).Return(mockWithFilesClient, nil) - mockRepoServiceClient.On("GetRevisionChartDetails", mock.Anything, mock.Anything).Return(&appsv1.ChartDetails{}, nil) + mockRepoServiceClient.On("GetRevisionChartDetails", mock.Anything, mock.Anything).Return(&v1alpha1.ChartDetails{}, nil) if isHelm { mockRepoServiceClient.On("ResolveRevision", mock.Anything, mock.Anything).Return(fakeResolveRevisionResponseHelm(), nil) @@ -196,30 +195,30 @@ func newTestAppServerWithEnforcerConfigure(t *testing.T, f func(*rbac.Enforcer), mockRepoClient := &mocks.Clientset{RepoServerServiceClient: fakeRepoServerClient(false)} - defaultProj := &appsv1.AppProject{ + defaultProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "default", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, }, } - myProj := &appsv1.AppProject{ + myProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "my-proj", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, }, } - projWithSyncWindows := &appsv1.AppProject{ + projWithSyncWindows := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "proj-maint", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, - SyncWindows: appsv1.SyncWindows{}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + SyncWindows: v1alpha1.SyncWindows{}, }, } - matchingWindow := &appsv1.SyncWindow{ + matchingWindow := &v1alpha1.SyncWindow{ Kind: "allow", Schedule: "* * * * *", Duration: "1h", @@ -261,16 +260,16 @@ func newTestAppServerWithEnforcerConfigure(t *testing.T, f func(*rbac.Enforcer), appStateCache := appstate.NewCache(cache.NewCache(cache.NewInMemoryCache(time.Hour)), time.Hour) // pre-populate the app cache for _, obj := range objects { - app, ok := obj.(*appsv1.Application) + app, ok := obj.(*v1alpha1.Application) if ok { - err := appStateCache.SetAppManagedResources(app.Name, []*appsv1.ResourceDiff{}) + err := appStateCache.SetAppManagedResources(app.Name, []*v1alpha1.ResourceDiff{}) require.NoError(t, err) // Pre-populate the resource tree based on the app's resources. - nodes := make([]appsv1.ResourceNode, len(app.Status.Resources)) + nodes := make([]v1alpha1.ResourceNode, len(app.Status.Resources)) for i, res := range app.Status.Resources { - nodes[i] = appsv1.ResourceNode{ - ResourceRef: appsv1.ResourceRef{ + nodes[i] = v1alpha1.ResourceNode{ + ResourceRef: v1alpha1.ResourceRef{ Group: res.Group, Kind: res.Kind, Version: res.Version, @@ -280,7 +279,7 @@ func newTestAppServerWithEnforcerConfigure(t *testing.T, f func(*rbac.Enforcer), }, } } - err = appStateCache.SetAppResourcesTree(app.Name, &appsv1.ApplicationTree{ + err = appStateCache.SetAppResourcesTree(app.Name, &v1alpha1.ApplicationTree{ Nodes: nodes, }) require.NoError(t, err) @@ -360,29 +359,29 @@ func newTestAppServerWithEnforcerConfigureWithBenchmark(b *testing.B, f func(*rb mockRepoClient := &mocks.Clientset{RepoServerServiceClient: fakeRepoServerClient(false)} - defaultProj := &appsv1.AppProject{ + defaultProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "default", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, }, } - myProj := &appsv1.AppProject{ + myProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "my-proj", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, }, } - projWithSyncWindows := &appsv1.AppProject{ + projWithSyncWindows := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "proj-maint", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, - SyncWindows: appsv1.SyncWindows{}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + SyncWindows: v1alpha1.SyncWindows{}, }, } - matchingWindow := &appsv1.SyncWindow{ + matchingWindow := &v1alpha1.SyncWindow{ Kind: "allow", Schedule: "* * * * *", Duration: "1h", @@ -423,16 +422,16 @@ func newTestAppServerWithEnforcerConfigureWithBenchmark(b *testing.B, f func(*rb appStateCache := appstate.NewCache(cache.NewCache(cache.NewInMemoryCache(time.Hour)), time.Hour) // pre-populate the app cache for _, obj := range objects { - app, ok := obj.(*appsv1.Application) + app, ok := obj.(*v1alpha1.Application) if ok { - err := appStateCache.SetAppManagedResources(app.Name, []*appsv1.ResourceDiff{}) + err := appStateCache.SetAppManagedResources(app.Name, []*v1alpha1.ResourceDiff{}) require.NoError(b, err) // Pre-populate the resource tree based on the app's resources. - nodes := make([]appsv1.ResourceNode, len(app.Status.Resources)) + nodes := make([]v1alpha1.ResourceNode, len(app.Status.Resources)) for i, res := range app.Status.Resources { - nodes[i] = appsv1.ResourceNode{ - ResourceRef: appsv1.ResourceRef{ + nodes[i] = v1alpha1.ResourceNode{ + ResourceRef: v1alpha1.ResourceRef{ Group: res.Group, Kind: res.Kind, Version: res.Version, @@ -442,7 +441,7 @@ func newTestAppServerWithEnforcerConfigureWithBenchmark(b *testing.B, f func(*rb }, } } - err = appStateCache.SetAppResourcesTree(app.Name, &appsv1.ApplicationTree{ + err = appStateCache.SetAppResourcesTree(app.Name, &v1alpha1.ApplicationTree{ Nodes: nodes, }) require.NoError(b, err) @@ -539,20 +538,20 @@ spec: server: https://cluster-api.example.com ` -func newTestAppWithDestName(opts ...func(app *appsv1.Application)) *appsv1.Application { +func newTestAppWithDestName(opts ...func(app *v1alpha1.Application)) *v1alpha1.Application { return createTestApp(fakeAppWithDestName, opts...) } -func newTestApp(opts ...func(app *appsv1.Application)) *appsv1.Application { +func newTestApp(opts ...func(app *v1alpha1.Application)) *v1alpha1.Application { return createTestApp(fakeApp, opts...) } -func newTestAppWithAnnotations(opts ...func(app *appsv1.Application)) *appsv1.Application { +func newTestAppWithAnnotations(opts ...func(app *v1alpha1.Application)) *v1alpha1.Application { return createTestApp(fakeAppWithAnnotations, opts...) } -func createTestApp(testApp string, opts ...func(app *appsv1.Application)) *appsv1.Application { - var app appsv1.Application +func createTestApp(testApp string, opts ...func(app *v1alpha1.Application)) *v1alpha1.Application { + var app v1alpha1.Application err := yaml.Unmarshal([]byte(testApp), &app) if err != nil { panic(err) @@ -618,7 +617,7 @@ type TestResourceTreeServer struct { ctx context.Context } -func (t *TestResourceTreeServer) Send(tree *appsv1.ApplicationTree) error { +func (t *TestResourceTreeServer) Send(tree *v1alpha1.ApplicationTree) error { return nil } @@ -692,7 +691,7 @@ func TestNoAppEnumeration(t *testing.T) { _ = enf.SetBuiltinPolicy(assets.BuiltinPolicyCSV) enf.SetDefaultRole("role:none") } - deployment := k8sappsv1.Deployment{ + deployment := appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: "apps/v1", Kind: "Deployment", @@ -702,9 +701,9 @@ func TestNoAppEnumeration(t *testing.T) { Namespace: "test", }, } - testApp := newTestApp(func(app *appsv1.Application) { + testApp := newTestApp(func(app *v1alpha1.Application) { app.Name = "test" - app.Status.Resources = []appsv1.ResourceStatus{ + app.Status.Resources = []v1alpha1.ResourceStatus{ { Group: deployment.GroupVersionKind().Group, Kind: deployment.GroupVersionKind().Kind, @@ -714,20 +713,20 @@ func TestNoAppEnumeration(t *testing.T) { Status: "Synced", }, } - app.Status.History = []appsv1.RevisionHistory{ + app.Status.History = []v1alpha1.RevisionHistory{ { ID: 0, - Source: appsv1.ApplicationSource{ + Source: v1alpha1.ApplicationSource{ TargetRevision: "something-old", }, }, } }) - testHelmApp := newTestApp(func(app *appsv1.Application) { + testHelmApp := newTestApp(func(app *v1alpha1.Application) { app.Name = "test-helm" app.Spec.Source.Path = "" app.Spec.Source.Chart = "test" - app.Status.Resources = []appsv1.ResourceStatus{ + app.Status.Resources = []v1alpha1.ResourceStatus{ { Group: deployment.GroupVersionKind().Group, Kind: deployment.GroupVersionKind().Kind, @@ -737,26 +736,26 @@ func TestNoAppEnumeration(t *testing.T) { Status: "Synced", }, } - app.Status.History = []appsv1.RevisionHistory{ + app.Status.History = []v1alpha1.RevisionHistory{ { ID: 0, - Source: appsv1.ApplicationSource{ + Source: v1alpha1.ApplicationSource{ TargetRevision: "something-old", }, }, } }) - testAppMulti := newTestApp(func(app *appsv1.Application) { + testAppMulti := newTestApp(func(app *v1alpha1.Application) { app.Name = "test-multi" - app.Spec.Sources = appsv1.ApplicationSources{ - appsv1.ApplicationSource{ + app.Spec.Sources = v1alpha1.ApplicationSources{ + v1alpha1.ApplicationSource{ TargetRevision: "something-old", }, - appsv1.ApplicationSource{ + v1alpha1.ApplicationSource{ TargetRevision: "something-old", }, } - app.Status.Resources = []appsv1.ResourceStatus{ + app.Status.Resources = []v1alpha1.ResourceStatus{ { Group: deployment.GroupVersionKind().Group, Kind: deployment.GroupVersionKind().Kind, @@ -766,14 +765,14 @@ func TestNoAppEnumeration(t *testing.T) { Status: "Synced", }, } - app.Status.History = []appsv1.RevisionHistory{ + app.Status.History = []v1alpha1.RevisionHistory{ { ID: 1, - Sources: appsv1.ApplicationSources{ - appsv1.ApplicationSource{ + Sources: v1alpha1.ApplicationSources{ + v1alpha1.ApplicationSource{ TargetRevision: "something-old", }, - appsv1.ApplicationSource{ + v1alpha1.ApplicationSource{ TargetRevision: "something-old", }, }, @@ -825,24 +824,24 @@ func TestNoAppEnumeration(t *testing.T) { }) t.Run("UpdateSpec", func(t *testing.T) { - _, err := appServer.UpdateSpec(adminCtx, &application.ApplicationUpdateSpecRequest{Name: ptr.To("test"), Spec: &appsv1.ApplicationSpec{ - Destination: appsv1.ApplicationDestination{Namespace: "default", Server: "https://cluster-api.example.com"}, - Source: &appsv1.ApplicationSource{RepoURL: "https://some-fake-source", Path: "."}, + _, err := appServer.UpdateSpec(adminCtx, &application.ApplicationUpdateSpecRequest{Name: ptr.To("test"), Spec: &v1alpha1.ApplicationSpec{ + Destination: v1alpha1.ApplicationDestination{Namespace: "default", Server: "https://cluster-api.example.com"}, + Source: &v1alpha1.ApplicationSource{RepoURL: "https://some-fake-source", Path: "."}, }}) require.NoError(t, err) - _, err = appServer.UpdateSpec(noRoleCtx, &application.ApplicationUpdateSpecRequest{Name: ptr.To("test"), Spec: &appsv1.ApplicationSpec{ - Destination: appsv1.ApplicationDestination{Namespace: "default", Server: "https://cluster-api.example.com"}, - Source: &appsv1.ApplicationSource{RepoURL: "https://some-fake-source", Path: "."}, + _, err = appServer.UpdateSpec(noRoleCtx, &application.ApplicationUpdateSpecRequest{Name: ptr.To("test"), Spec: &v1alpha1.ApplicationSpec{ + Destination: v1alpha1.ApplicationDestination{Namespace: "default", Server: "https://cluster-api.example.com"}, + Source: &v1alpha1.ApplicationSource{RepoURL: "https://some-fake-source", Path: "."}, }}) require.EqualError(t, err, common.PermissionDeniedAPIError.Error(), "error message must be _only_ the permission error, to avoid leaking information about app existence") - _, err = appServer.UpdateSpec(adminCtx, &application.ApplicationUpdateSpecRequest{Name: ptr.To("doest-not-exist"), Spec: &appsv1.ApplicationSpec{ - Destination: appsv1.ApplicationDestination{Namespace: "default", Server: "https://cluster-api.example.com"}, - Source: &appsv1.ApplicationSource{RepoURL: "https://some-fake-source", Path: "."}, + _, err = appServer.UpdateSpec(adminCtx, &application.ApplicationUpdateSpecRequest{Name: ptr.To("doest-not-exist"), Spec: &v1alpha1.ApplicationSpec{ + Destination: v1alpha1.ApplicationDestination{Namespace: "default", Server: "https://cluster-api.example.com"}, + Source: &v1alpha1.ApplicationSource{RepoURL: "https://some-fake-source", Path: "."}, }}) require.EqualError(t, err, common.PermissionDeniedAPIError.Error(), "error message must be _only_ the permission error, to avoid leaking information about app existence") - _, err = appServer.UpdateSpec(adminCtx, &application.ApplicationUpdateSpecRequest{Name: ptr.To("doest-not-exist"), Project: ptr.To("test"), Spec: &appsv1.ApplicationSpec{ - Destination: appsv1.ApplicationDestination{Namespace: "default", Server: "https://cluster-api.example.com"}, - Source: &appsv1.ApplicationSource{RepoURL: "https://some-fake-source", Path: "."}, + _, err = appServer.UpdateSpec(adminCtx, &application.ApplicationUpdateSpecRequest{Name: ptr.To("doest-not-exist"), Project: ptr.To("test"), Spec: &v1alpha1.ApplicationSpec{ + Destination: v1alpha1.ApplicationDestination{Namespace: "default", Server: "https://cluster-api.example.com"}, + Source: &v1alpha1.ApplicationSource{RepoURL: "https://some-fake-source", Path: "."}, }}) assert.EqualError(t, err, "rpc error: code = NotFound desc = applications.argoproj.io \"doest-not-exist\" not found", "when the request specifies a project, we can return the standard k8s error message") }) @@ -1090,7 +1089,7 @@ func setSyncRunningOperationState(t *testing.T, appServer *Server) { app, err := appIf.Get(context.Background(), "test", metav1.GetOptions{}) require.NoError(t, err) // This sets the status that would be set by the controller usually. - app.Status.OperationState = &appsv1.OperationState{Phase: synccommon.OperationRunning, Operation: appsv1.Operation{Sync: &appsv1.SyncOperation{}}} + app.Status.OperationState = &v1alpha1.OperationState{Phase: synccommon.OperationRunning, Operation: v1alpha1.Operation{Sync: &v1alpha1.SyncOperation{}}} _, err = appIf.Update(context.Background(), app, metav1.UpdateOptions{}) require.NoError(t, err) } @@ -1108,15 +1107,15 @@ func unsetSyncRunningOperationState(t *testing.T, appServer *Server) { } func TestListAppsInNamespaceWithLabels(t *testing.T) { - appServer := newTestAppServer(t, newTestApp(func(app *appsv1.Application) { + appServer := newTestAppServer(t, newTestApp(func(app *v1alpha1.Application) { app.Name = "App1" app.ObjectMeta.Namespace = "test-namespace" app.SetLabels(map[string]string{"key1": "value1", "key2": "value1"}) - }), newTestApp(func(app *appsv1.Application) { + }), newTestApp(func(app *v1alpha1.Application) { app.Name = "App2" app.ObjectMeta.Namespace = "test-namespace" app.SetLabels(map[string]string{"key1": "value2"}) - }), newTestApp(func(app *appsv1.Application) { + }), newTestApp(func(app *v1alpha1.Application) { app.Name = "App3" app.ObjectMeta.Namespace = "test-namespace" app.SetLabels(map[string]string{"key1": "value3"}) @@ -1129,13 +1128,13 @@ func TestListAppsInNamespaceWithLabels(t *testing.T) { } func TestListAppsInDefaultNSWithLabels(t *testing.T) { - appServer := newTestAppServer(t, newTestApp(func(app *appsv1.Application) { + appServer := newTestAppServer(t, newTestApp(func(app *v1alpha1.Application) { app.Name = "App1" app.SetLabels(map[string]string{"key1": "value1", "key2": "value1"}) - }), newTestApp(func(app *appsv1.Application) { + }), newTestApp(func(app *v1alpha1.Application) { app.Name = "App2" app.SetLabels(map[string]string{"key1": "value2"}) - }), newTestApp(func(app *appsv1.Application) { + }), newTestApp(func(app *v1alpha1.Application) { app.Name = "App3" app.SetLabels(map[string]string{"key1": "value3"}) })) @@ -1227,13 +1226,13 @@ func testListAppsWithLabels(t *testing.T, appQuery application.ApplicationQuery, } func TestListAppWithProjects(t *testing.T) { - appServer := newTestAppServer(t, newTestApp(func(app *appsv1.Application) { + appServer := newTestAppServer(t, newTestApp(func(app *v1alpha1.Application) { app.Name = "App1" app.Spec.Project = "test-project1" - }), newTestApp(func(app *appsv1.Application) { + }), newTestApp(func(app *v1alpha1.Application) { app.Name = "App2" app.Spec.Project = "test-project2" - }), newTestApp(func(app *appsv1.Application) { + }), newTestApp(func(app *v1alpha1.Application) { app.Name = "App3" app.Spec.Project = "test-project3" })) @@ -1278,11 +1277,11 @@ func TestListAppWithProjects(t *testing.T) { } func TestListApps(t *testing.T) { - appServer := newTestAppServer(t, newTestApp(func(app *appsv1.Application) { + appServer := newTestAppServer(t, newTestApp(func(app *v1alpha1.Application) { app.Name = "bcd" - }), newTestApp(func(app *appsv1.Application) { + }), newTestApp(func(app *v1alpha1.Application) { app.Name = "abc" - }), newTestApp(func(app *appsv1.Application) { + }), newTestApp(func(app *v1alpha1.Application) { app.Name = "def" })) @@ -1308,7 +1307,7 @@ func TestCoupleAppsListApps(t *testing.T) { for projectId := 0; projectId < 100; projectId++ { projectName := fmt.Sprintf("proj-%d", projectId) for appId := 0; appId < 100; appId++ { - objects = append(objects, newTestApp(func(app *appsv1.Application) { + objects = append(objects, newTestApp(func(app *v1alpha1.Application) { app.Name = fmt.Sprintf("app-%d-%d", projectId, appId) app.Spec.Project = projectName })) @@ -1338,10 +1337,10 @@ g, group-49, role:test3 assert.Len(t, names, 300) } -func generateTestApp(num int) []*appsv1.Application { - apps := []*appsv1.Application{} +func generateTestApp(num int) []*v1alpha1.Application { + apps := []*v1alpha1.Application{} for i := 0; i < num; i++ { - apps = append(apps, newTestApp(func(app *appsv1.Application) { + apps = append(apps, newTestApp(func(app *v1alpha1.Application) { app.Name = fmt.Sprintf("test-app%.6d", i) })) } @@ -1498,8 +1497,8 @@ func TestCreateAppWithDestName(t *testing.T) { func TestCreateAppWithOperation(t *testing.T) { appServer := newTestAppServer(t) testApp := newTestAppWithDestName() - testApp.Operation = &appsv1.Operation{ - Sync: &appsv1.SyncOperation{ + testApp.Operation = &v1alpha1.Operation{ + Sync: &v1alpha1.SyncOperation{ Manifests: []string{ "test", }, @@ -1567,7 +1566,7 @@ func TestDeleteApp(t *testing.T) { return true, nil, nil }) fakeAppCs.AddReactor("get", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { - return true, &appsv1.Application{Spec: appsv1.ApplicationSpec{Source: &appsv1.ApplicationSource{}}}, nil + return true, &v1alpha1.Application{Spec: v1alpha1.ApplicationSpec{Source: &v1alpha1.ApplicationSource{}}}, nil }) appServer.appclientset = fakeAppCs @@ -1778,7 +1777,7 @@ func TestSyncAndTerminate(t *testing.T) { assert.Regexp(t, ".*initiated sync to HEAD \\([0-9A-Fa-f]{40}\\).*", event.Message) // set status.operationState to pretend that an operation has started by controller - app.Status.OperationState = &appsv1.OperationState{ + app.Status.OperationState = &v1alpha1.OperationState{ Operation: *app.Operation, Phase: synccommon.OperationRunning, StartedAt: metav1.NewTime(time.Now()), @@ -1850,7 +1849,7 @@ func TestSyncGit(t *testing.T) { func TestRollbackApp(t *testing.T) { testApp := newTestApp() - testApp.Status.History = []appsv1.RevisionHistory{{ + testApp.Status.History = []v1alpha1.RevisionHistory{{ ID: 1, Revision: "abc", Source: *testApp.Spec.Source.DeepCopy(), @@ -2008,7 +2007,7 @@ func TestGetCachedAppState(t *testing.T) { testApp := newTestApp() testApp.ObjectMeta.ResourceVersion = "1" testApp.Spec.Project = "test-proj" - testProj := &appsv1.AppProject{ + testProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{ Name: "test-proj", Namespace: testNamespace, @@ -2017,7 +2016,7 @@ func TestGetCachedAppState(t *testing.T) { appServer := newTestAppServer(t, testApp, testProj) fakeClientSet := appServer.appclientset.(*apps.Clientset) fakeClientSet.AddReactor("get", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { - return true, &appsv1.Application{Spec: appsv1.ApplicationSpec{Source: &appsv1.ApplicationSource{}}}, nil + return true, &v1alpha1.Application{Spec: v1alpha1.ApplicationSpec{Source: &v1alpha1.ApplicationSource{}}}, nil }) t.Run("NoError", func(t *testing.T) { err := appServer.getCachedAppState(context.Background(), testApp, func() error { @@ -2043,7 +2042,7 @@ func TestGetCachedAppState(t *testing.T) { return true, testApp, nil }) fakeClientSet.AddReactor("get", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { - return true, &appsv1.Application{Spec: appsv1.ApplicationSpec{Source: &appsv1.ApplicationSource{}}}, nil + return true, &v1alpha1.Application{Spec: v1alpha1.ApplicationSpec{Source: &v1alpha1.ApplicationSource{}}}, nil }) fakeClientSet.Unlock() fakeClientSet.AddWatchReactor("applications", func(action kubetesting.Action) (handled bool, ret watch.Interface, err error) { @@ -2105,14 +2104,14 @@ func TestSplitStatusPatch(t *testing.T) { } func TestLogsGetSelectedPod(t *testing.T) { - deployment := appsv1.ResourceRef{Group: "", Version: "v1", Kind: "Deployment", Name: "deployment", UID: "1"} - rs := appsv1.ResourceRef{Group: "", Version: "v1", Kind: "ReplicaSet", Name: "rs", UID: "2"} - podRS := appsv1.ResourceRef{Group: "", Version: "v1", Kind: "Pod", Name: "podrs", UID: "3"} - pod := appsv1.ResourceRef{Group: "", Version: "v1", Kind: "Pod", Name: "pod", UID: "4"} - treeNodes := []appsv1.ResourceNode{ + deployment := v1alpha1.ResourceRef{Group: "", Version: "v1", Kind: "Deployment", Name: "deployment", UID: "1"} + rs := v1alpha1.ResourceRef{Group: "", Version: "v1", Kind: "ReplicaSet", Name: "rs", UID: "2"} + podRS := v1alpha1.ResourceRef{Group: "", Version: "v1", Kind: "Pod", Name: "podrs", UID: "3"} + pod := v1alpha1.ResourceRef{Group: "", Version: "v1", Kind: "Pod", Name: "pod", UID: "4"} + treeNodes := []v1alpha1.ResourceNode{ {ResourceRef: deployment, ParentRefs: nil}, - {ResourceRef: rs, ParentRefs: []appsv1.ResourceRef{deployment}}, - {ResourceRef: podRS, ParentRefs: []appsv1.ResourceRef{rs}}, + {ResourceRef: rs, ParentRefs: []v1alpha1.ResourceRef{deployment}}, + {ResourceRef: podRS, ParentRefs: []v1alpha1.ResourceRef{rs}}, {ResourceRef: pod, ParentRefs: nil}, } appName := "appName" @@ -2222,7 +2221,7 @@ func TestMaxPodLogsRender(t *testing.T) { func createAppServerWithMaxLodLogs(t *testing.T, podNumber int, maxPodLogsToRender ...int64) (*Server, context.Context) { t.Helper() runtimeObjects := make([]runtime.Object, podNumber+1) - resources := make([]appsv1.ResourceStatus, podNumber) + resources := make([]v1alpha1.ResourceStatus, podNumber) for i := 0; i < podNumber; i++ { pod := corev1.Pod{ @@ -2235,7 +2234,7 @@ func createAppServerWithMaxLodLogs(t *testing.T, podNumber int, maxPodLogsToRend Namespace: "test", }, } - resources[i] = appsv1.ResourceStatus{ + resources[i] = v1alpha1.ResourceStatus{ Group: pod.GroupVersionKind().Group, Kind: pod.GroupVersionKind().Kind, Version: pod.GroupVersionKind().Version, @@ -2246,7 +2245,7 @@ func createAppServerWithMaxLodLogs(t *testing.T, podNumber int, maxPodLogsToRend runtimeObjects[i] = kube.MustToUnstructured(&pod) } - testApp := newTestApp(func(app *appsv1.Application) { + testApp := newTestApp(func(app *v1alpha1.Application) { app.Name = "test" app.Status.Resources = resources }) @@ -2278,7 +2277,7 @@ func refreshAnnotationRemover(t *testing.T, ctx context.Context, patched *int32, a, err := appServer.appLister.Applications(appNs).Get(aName) require.NoError(t, err) a = a.DeepCopy() - if a.GetAnnotations() != nil && a.GetAnnotations()[appsv1.AnnotationKeyRefresh] != "" { + if a.GetAnnotations() != nil && a.GetAnnotations()[v1alpha1.AnnotationKeyRefresh] != "" { a.SetAnnotations(map[string]string{}) a.SetResourceVersion("999") _, err = appServer.appclientset.ArgoprojV1alpha1().Applications(a.Namespace).Update( @@ -2306,7 +2305,7 @@ func TestGetAppRefresh_NormalRefresh(t *testing.T) { _, err := appServer.Get(context.Background(), &application.ApplicationQuery{ Name: &testApp.Name, - Refresh: ptr.To(string(appsv1.RefreshTypeNormal)), + Refresh: ptr.To(string(v1alpha1.RefreshTypeNormal)), }) require.NoError(t, err) @@ -2341,7 +2340,7 @@ func TestGetAppRefresh_HardRefresh(t *testing.T) { _, err := appServer.Get(context.Background(), &application.ApplicationQuery{ Name: &testApp.Name, - Refresh: ptr.To(string(appsv1.RefreshTypeHard)), + Refresh: ptr.To(string(v1alpha1.RefreshTypeHard)), }) require.NoError(t, err) require.NotNil(t, getAppDetailsQuery) @@ -2361,8 +2360,8 @@ func TestInferResourcesStatusHealth(t *testing.T) { cacheClient := cacheutil.NewCache(cacheutil.NewInMemoryCache(1 * time.Hour)) testApp := newTestApp() - testApp.Status.ResourceHealthSource = appsv1.ResourceHealthLocationAppTree - testApp.Status.Resources = []appsv1.ResourceStatus{{ + testApp.Status.ResourceHealthSource = v1alpha1.ResourceHealthLocationAppTree + testApp.Status.Resources = []v1alpha1.ResourceStatus{{ Group: "apps", Kind: "Deployment", Name: "guestbook", @@ -2375,14 +2374,14 @@ func TestInferResourcesStatusHealth(t *testing.T) { }} appServer := newTestAppServer(t, testApp) appStateCache := appstate.NewCache(cacheClient, time.Minute) - err := appStateCache.SetAppResourcesTree(testApp.Name, &appsv1.ApplicationTree{Nodes: []appsv1.ResourceNode{{ - ResourceRef: appsv1.ResourceRef{ + err := appStateCache.SetAppResourcesTree(testApp.Name, &v1alpha1.ApplicationTree{Nodes: []v1alpha1.ResourceNode{{ + ResourceRef: v1alpha1.ResourceRef{ Group: "apps", Kind: "Deployment", Name: "guestbook", Namespace: "default", }, - Health: &appsv1.HealthStatus{ + Health: &v1alpha1.HealthStatus{ Status: health.HealthStatusDegraded, }, }}}) @@ -2408,7 +2407,7 @@ func TestRunNewStyleResourceAction(t *testing.T) { action := "create-job" uid := "1" - resources := []appsv1.ResourceStatus{{ + resources := []v1alpha1.ResourceStatus{{ Group: group, Kind: kind, Name: resourceName, @@ -2418,8 +2417,8 @@ func TestRunNewStyleResourceAction(t *testing.T) { appStateCache := appstate.NewCache(cacheClient, time.Minute) - nodes := []appsv1.ResourceNode{{ - ResourceRef: appsv1.ResourceRef{ + nodes := []v1alpha1.ResourceNode{{ + ResourceRef: v1alpha1.ResourceRef{ Group: group, Kind: kind, Version: version, @@ -2429,11 +2428,11 @@ func TestRunNewStyleResourceAction(t *testing.T) { }, }} - createJobDenyingProj := &appsv1.AppProject{ + createJobDenyingProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "createJobDenyingProj", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, NamespaceResourceWhitelist: []metav1.GroupKind{{Group: "never", Kind: "mind"}}, }, } @@ -2475,13 +2474,13 @@ func TestRunNewStyleResourceAction(t *testing.T) { t.Run("CreateOperationNotPermitted", func(t *testing.T) { testApp := newTestApp() testApp.Spec.Project = "createJobDenyingProj" - testApp.Status.ResourceHealthSource = appsv1.ResourceHealthLocationAppTree + testApp.Status.ResourceHealthSource = v1alpha1.ResourceHealthLocationAppTree testApp.Status.Resources = resources appServer := newTestAppServer(t, testApp, createJobDenyingProj, kube.MustToUnstructured(&cronJob)) appServer.cache = servercache.NewCache(appStateCache, time.Minute, time.Minute, time.Minute) - err := appStateCache.SetAppResourcesTree(testApp.Name, &appsv1.ApplicationTree{Nodes: nodes}) + err := appStateCache.SetAppResourcesTree(testApp.Name, &v1alpha1.ApplicationTree{Nodes: nodes}) require.NoError(t, err) appResponse, runErr := appServer.RunResourceAction(context.Background(), &application.ResourceActionRunRequest{ @@ -2501,13 +2500,13 @@ func TestRunNewStyleResourceAction(t *testing.T) { t.Run("CreateOperationPermitted", func(t *testing.T) { testApp := newTestApp() - testApp.Status.ResourceHealthSource = appsv1.ResourceHealthLocationAppTree + testApp.Status.ResourceHealthSource = v1alpha1.ResourceHealthLocationAppTree testApp.Status.Resources = resources appServer := newTestAppServer(t, testApp, kube.MustToUnstructured(&cronJob)) appServer.cache = servercache.NewCache(appStateCache, time.Minute, time.Minute, time.Minute) - err := appStateCache.SetAppResourcesTree(testApp.Name, &appsv1.ApplicationTree{Nodes: nodes}) + err := appStateCache.SetAppResourcesTree(testApp.Name, &v1alpha1.ApplicationTree{Nodes: nodes}) require.NoError(t, err) appResponse, runErr := appServer.RunResourceAction(context.Background(), &application.ResourceActionRunRequest{ @@ -2537,7 +2536,7 @@ func TestRunOldStyleResourceAction(t *testing.T) { action := "pause" uid := "2" - resources := []appsv1.ResourceStatus{{ + resources := []v1alpha1.ResourceStatus{{ Group: group, Kind: kind, Name: resourceName, @@ -2547,8 +2546,8 @@ func TestRunOldStyleResourceAction(t *testing.T) { appStateCache := appstate.NewCache(cacheClient, time.Minute) - nodes := []appsv1.ResourceNode{{ - ResourceRef: appsv1.ResourceRef{ + nodes := []v1alpha1.ResourceNode{{ + ResourceRef: v1alpha1.ResourceRef{ Group: group, Kind: kind, Version: version, @@ -2558,7 +2557,7 @@ func TestRunOldStyleResourceAction(t *testing.T) { }, }} - deployment := k8sappsv1.Deployment{ + deployment := appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: "apps/v1", Kind: "Deployment", @@ -2571,14 +2570,14 @@ func TestRunOldStyleResourceAction(t *testing.T) { t.Run("DefaultPatchOperation", func(t *testing.T) { testApp := newTestApp() - testApp.Status.ResourceHealthSource = appsv1.ResourceHealthLocationAppTree + testApp.Status.ResourceHealthSource = v1alpha1.ResourceHealthLocationAppTree testApp.Status.Resources = resources // appServer := newTestAppServer(t, testApp, returnDeployment()) appServer := newTestAppServer(t, testApp, kube.MustToUnstructured(&deployment)) appServer.cache = servercache.NewCache(appStateCache, time.Minute, time.Minute, time.Minute) - err := appStateCache.SetAppResourcesTree(testApp.Name, &appsv1.ApplicationTree{Nodes: nodes}) + err := appStateCache.SetAppResourcesTree(testApp.Name, &v1alpha1.ApplicationTree{Nodes: nodes}) require.NoError(t, err) appResponse, runErr := appServer.RunResourceAction(context.Background(), &application.ResourceActionRunRequest{ @@ -2720,11 +2719,11 @@ func TestAppNamespaceRestrictions(t *testing.T) { testApp := newTestApp() testApp.Namespace = "argocd-1" testApp.Spec.Project = "other-ns" - otherNsProj := &appsv1.AppProject{ + otherNsProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "other-ns", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, SourceNamespaces: []string{"argocd-1"}, }, } @@ -2744,11 +2743,11 @@ func TestAppNamespaceRestrictions(t *testing.T) { testApp := newTestApp() testApp.Namespace = "argocd-1" testApp.Spec.Project = "other-ns" - otherNsProj := &appsv1.AppProject{ + otherNsProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "other-ns", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, SourceNamespaces: []string{"argocd-2"}, }, } @@ -2767,11 +2766,11 @@ func TestAppNamespaceRestrictions(t *testing.T) { testApp := newTestApp() testApp.Namespace = "argocd-1" testApp.Spec.Project = "other-ns" - otherNsProj := &appsv1.AppProject{ + otherNsProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "other-ns", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, SourceNamespaces: []string{"argocd-1"}, }, } @@ -2791,11 +2790,11 @@ func TestAppNamespaceRestrictions(t *testing.T) { testApp := newTestApp() testApp.Namespace = "argocd-1" testApp.Spec.Project = "other-ns" - otherNsProj := &appsv1.AppProject{ + otherNsProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "other-ns", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, SourceNamespaces: []string{}, }, } @@ -2814,11 +2813,11 @@ func TestAppNamespaceRestrictions(t *testing.T) { testApp := newTestApp() testApp.Namespace = "argocd-1" testApp.Spec.Project = "other-ns" - otherNsProj := &appsv1.AppProject{ + otherNsProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "other-ns", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, SourceNamespaces: []string{"argocd-1"}, }, } @@ -2836,11 +2835,11 @@ func TestAppNamespaceRestrictions(t *testing.T) { testApp := newTestApp() testApp.Namespace = "argocd-1" testApp.Spec.Project = "other-ns" - otherNsProj := &appsv1.AppProject{ + otherNsProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "other-ns", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, SourceNamespaces: []string{"argocd-1"}, }, } @@ -2855,11 +2854,11 @@ func TestAppNamespaceRestrictions(t *testing.T) { testApp := newTestApp() testApp.Namespace = "argocd-1" testApp.Spec.Project = "other-ns" - otherNsProj := &appsv1.AppProject{ + otherNsProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "other-ns", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, SourceNamespaces: []string{"argocd-2"}, }, } @@ -2875,11 +2874,11 @@ func TestAppNamespaceRestrictions(t *testing.T) { testApp := newTestApp() testApp.Namespace = "argocd-1" testApp.Spec.Project = "other-ns" - otherNsProj := &appsv1.AppProject{ + otherNsProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "other-ns", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, SourceNamespaces: []string{"argocd-2"}, }, } @@ -2898,11 +2897,11 @@ func TestAppNamespaceRestrictions(t *testing.T) { testApp := newTestApp() testApp.Namespace = "argocd-1" testApp.Spec.Project = "other-ns" - otherNsProj := &appsv1.AppProject{ + otherNsProj := &v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{Name: "other-ns", Namespace: "default"}, - Spec: appsv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []appsv1.ApplicationDestination{{Server: "*", Namespace: "*"}}, + Destinations: []v1alpha1.ApplicationDestination{{Server: "*", Namespace: "*"}}, SourceNamespaces: []string{"argocd-1"}, }, } @@ -2918,9 +2917,9 @@ func TestAppNamespaceRestrictions(t *testing.T) { } func TestGetAmbiguousRevision_MultiSource(t *testing.T) { - app := &appv1.Application{ - Spec: appv1.ApplicationSpec{ - Sources: []appv1.ApplicationSource{ + app := &v1alpha1.Application{ + Spec: v1alpha1.ApplicationSpec{ + Sources: []v1alpha1.ApplicationSource{ { TargetRevision: "revision1", }, @@ -2946,8 +2945,8 @@ func TestGetAmbiguousRevision_MultiSource(t *testing.T) { assert.Equal(t, expected, result, "Expected ambiguous revision to be %s, but got %s", expected, result) // Test when app.Spec.HasMultipleSources() is false - app.Spec = appv1.ApplicationSpec{ - Source: &appv1.ApplicationSource{ + app.Spec = v1alpha1.ApplicationSpec{ + Source: &v1alpha1.ApplicationSource{ TargetRevision: "revision3", }, Sources: nil, @@ -2961,9 +2960,9 @@ func TestGetAmbiguousRevision_MultiSource(t *testing.T) { } func TestGetAmbiguousRevision_SingleSource(t *testing.T) { - app := &appv1.Application{ - Spec: appv1.ApplicationSpec{ - Source: &appv1.ApplicationSource{ + app := &v1alpha1.Application{ + Spec: v1alpha1.ApplicationSpec{ + Source: &v1alpha1.ApplicationSource{ TargetRevision: "revision1", }, }, @@ -2983,9 +2982,9 @@ func TestServer_ResolveSourceRevisions_MultiSource(t *testing.T) { s := newTestAppServer(t) ctx := context.Background() - a := &appv1.Application{ - Spec: appv1.ApplicationSpec{ - Sources: []appv1.ApplicationSource{ + a := &v1alpha1.Application{ + Spec: v1alpha1.ApplicationSpec{ + Sources: []v1alpha1.ApplicationSource{ { RepoURL: "https://github.com/example/repo.git", }, @@ -3011,9 +3010,9 @@ func TestServer_ResolveSourceRevisions_SingleSource(t *testing.T) { s := newTestAppServer(t) ctx := context.Background() - a := &appv1.Application{ - Spec: appv1.ApplicationSpec{ - Source: &appv1.ApplicationSource{ + a := &v1alpha1.Application{ + Spec: v1alpha1.ApplicationSpec{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/example/repo.git", }, }, @@ -3037,8 +3036,8 @@ func Test_RevisionMetadata(t *testing.T) { singleSourceApp := newTestApp() singleSourceApp.Name = "single-source-app" - singleSourceApp.Spec = appv1.ApplicationSpec{ - Source: &appv1.ApplicationSource{ + singleSourceApp.Spec = v1alpha1.ApplicationSpec{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", Path: "helm-guestbook", TargetRevision: "HEAD", @@ -3047,8 +3046,8 @@ func Test_RevisionMetadata(t *testing.T) { multiSourceApp := newTestApp() multiSourceApp.Name = "multi-source-app" - multiSourceApp.Spec = appv1.ApplicationSpec{ - Sources: []appv1.ApplicationSource{ + multiSourceApp.Spec = v1alpha1.ApplicationSpec{ + Sources: []v1alpha1.ApplicationSource{ { RepoURL: "https://github.com/argoproj/argocd-example-apps.git", Path: "helm-guestbook", @@ -3062,14 +3061,14 @@ func Test_RevisionMetadata(t *testing.T) { }, } - singleSourceHistory := []appv1.RevisionHistory{ + singleSourceHistory := []v1alpha1.RevisionHistory{ { ID: 1, Source: singleSourceApp.Spec.GetSource(), Revision: "a", }, } - multiSourceHistory := []appv1.RevisionHistory{ + multiSourceHistory := []v1alpha1.RevisionHistory{ { ID: 1, Sources: multiSourceApp.Spec.GetSources(), diff --git a/server/badge/badge.go b/server/badge/badge.go index 62afa5b030c89..df14c51d819b1 100644 --- a/server/badge/badge.go +++ b/server/badge/badge.go @@ -10,7 +10,7 @@ import ( healthutil "github.com/argoproj/gitops-engine/pkg/health" "k8s.io/apimachinery/pkg/api/errors" - validation "k8s.io/apimachinery/pkg/api/validation" + "k8s.io/apimachinery/pkg/api/validation" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" diff --git a/test/e2e/fixture/admin/utils/backup.go b/test/e2e/fixture/admin/utils/backup.go index ca55d319943e5..e6a96c1b92072 100644 --- a/test/e2e/fixture/admin/utils/backup.go +++ b/test/e2e/fixture/admin/utils/backup.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - kube "github.com/argoproj/gitops-engine/pkg/utils/kube" + "github.com/argoproj/gitops-engine/pkg/utils/kube" yaml "gopkg.in/yaml.v3" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) diff --git a/test/e2e/fixture/applicationsets/actions.go b/test/e2e/fixture/applicationsets/actions.go index 08c03bb4f872c..81892a8fcee2d 100644 --- a/test/e2e/fixture/applicationsets/actions.go +++ b/test/e2e/fixture/applicationsets/actions.go @@ -11,7 +11,7 @@ import ( log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" - v1 "k8s.io/api/rbac/v1" + rbacv1 "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" @@ -242,9 +242,9 @@ func (a *Actions) CreatePlacementRoleAndRoleBinding() *Actions { var err error - _, err = fixtureClient.KubeClientset.RbacV1().Roles(fixture.TestNamespace()).Create(context.Background(), &v1.Role{ + _, err = fixtureClient.KubeClientset.RbacV1().Roles(fixture.TestNamespace()).Create(context.Background(), &rbacv1.Role{ ObjectMeta: metav1.ObjectMeta{Name: "placement-role", Namespace: fixture.TestNamespace()}, - Rules: []v1.PolicyRule{ + Rules: []rbacv1.PolicyRule{ { Verbs: []string{"get", "list", "watch"}, APIGroups: []string{"cluster.open-cluster-management.io"}, @@ -258,16 +258,16 @@ func (a *Actions) CreatePlacementRoleAndRoleBinding() *Actions { if err == nil { _, err = fixtureClient.KubeClientset.RbacV1().RoleBindings(fixture.TestNamespace()).Create(context.Background(), - &v1.RoleBinding{ + &rbacv1.RoleBinding{ ObjectMeta: metav1.ObjectMeta{Name: "placement-role-binding", Namespace: fixture.TestNamespace()}, - Subjects: []v1.Subject{ + Subjects: []rbacv1.Subject{ { Name: "argocd-applicationset-controller", Namespace: fixture.TestNamespace(), Kind: "ServiceAccount", }, }, - RoleRef: v1.RoleRef{ + RoleRef: rbacv1.RoleRef{ Kind: "Role", APIGroup: "rbac.authorization.k8s.io", Name: "placement-role", diff --git a/test/e2e/sync_with_impersonate_test.go b/test/e2e/sync_with_impersonate_test.go index a0930163453bd..38dd73550b172 100644 --- a/test/e2e/sync_with_impersonate_test.go +++ b/test/e2e/sync_with_impersonate_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" - rbac "k8s.io/api/rbac/v1" + rbacv1 "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -78,7 +78,7 @@ func TestSyncWithImpersonateWithSyncServiceAccount(t *testing.T) { require.NoError(t, err) err = createTestAppProject(projectName, fixture.TestNamespace(), destinationServiceAccounts) require.NoError(t, err) - err = createTestRole(roleName, fixture.DeploymentNamespace(), []rbac.PolicyRule{ + err = createTestRole(roleName, fixture.DeploymentNamespace(), []rbacv1.PolicyRule{ { APIGroups: []string{"apps", ""}, Resources: []string{"deployments"}, @@ -132,7 +132,7 @@ func TestSyncWithMissingServiceAccount(t *testing.T) { require.NoError(t, err) err = createTestAppProject(projectName, fixture.TestNamespace(), destinationServiceAccounts) require.NoError(t, err) - err = createTestRole(roleName, fixture.DeploymentNamespace(), []rbac.PolicyRule{ + err = createTestRole(roleName, fixture.DeploymentNamespace(), []rbacv1.PolicyRule{ { APIGroups: []string{"apps", ""}, Resources: []string{"deployments"}, @@ -182,7 +182,7 @@ func TestSyncWithValidSAButDisallowedDestination(t *testing.T) { require.NoError(t, err) err = createTestAppProject(projectName, fixture.TestNamespace(), destinationServiceAccounts) require.NoError(t, err) - err = createTestRole(roleName, fixture.DeploymentNamespace(), []rbac.PolicyRule{ + err = createTestRole(roleName, fixture.DeploymentNamespace(), []rbacv1.PolicyRule{ { APIGroups: []string{"apps", ""}, Resources: []string{"deployments"}, @@ -251,8 +251,8 @@ func createTestAppProject(name, namespace string, destinationServiceAccounts []v } // createTestRole creates a test Role resource. -func createTestRole(roleName, namespace string, rules []rbac.PolicyRule) error { - role := &rbac.Role{ +func createTestRole(roleName, namespace string, rules []rbacv1.PolicyRule) error { + role := &rbacv1.Role{ ObjectMeta: metav1.ObjectMeta{ Name: roleName, Namespace: namespace, @@ -266,18 +266,18 @@ func createTestRole(roleName, namespace string, rules []rbac.PolicyRule) error { // createTestRoleBinding creates a test RoleBinding resource. func createTestRoleBinding(roleName, serviceAccountName, namespace string) error { - roleBinding := &rbac.RoleBinding{ + roleBinding := &rbacv1.RoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: roleName + "-binding", }, - Subjects: []rbac.Subject{ + Subjects: []rbacv1.Subject{ { Kind: "ServiceAccount", Name: serviceAccountName, Namespace: namespace, }, }, - RoleRef: rbac.RoleRef{ + RoleRef: rbacv1.RoleRef{ Kind: "Role", Name: roleName, APIGroup: "rbac.authorization.k8s.io", diff --git a/util/db/db_test.go b/util/db/db_test.go index 2ab263955dbbc..518a77577e468 100644 --- a/util/db/db_test.go +++ b/util/db/db_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - appv1 "k8s.io/api/apps/v1" + appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -817,12 +817,12 @@ func TestGetApplicationControllerReplicas(t *testing.T) { assert.Equal(t, int(expectedReplicas), replicas) expectedReplicas = int32(3) - clientset = getClientset(nil, &appv1.Deployment{ + clientset = getClientset(nil, &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: common.ApplicationController, Namespace: testNamespace, }, - Spec: appv1.DeploymentSpec{ + Spec: appsv1.DeploymentSpec{ Replicas: &expectedReplicas, }, }) diff --git a/util/db/secrets.go b/util/db/secrets.go index 1ddf51d4f758f..729d8d5617209 100644 --- a/util/db/secrets.go +++ b/util/db/secrets.go @@ -16,7 +16,7 @@ import ( "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" - informerv1 "k8s.io/client-go/informers/core/v1" + informersv1 "k8s.io/client-go/informers/core/v1" "k8s.io/client-go/tools/cache" "github.com/argoproj/argo-cd/v2/common" @@ -143,7 +143,7 @@ func (db *db) watchSecrets(ctx context.Context, } indexers := cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc} - clusterSecretInformer := informerv1.NewFilteredSecretInformer(db.kubeclientset, db.ns, 3*time.Minute, indexers, secretListOptions) + clusterSecretInformer := informersv1.NewFilteredSecretInformer(db.kubeclientset, db.ns, 3*time.Minute, indexers, secretListOptions) _, err := clusterSecretInformer.AddEventHandler(secretEventHandler) if err != nil { log.Error(err) diff --git a/util/notification/k8s/informers.go b/util/notification/k8s/informers.go index 361453da0dfc0..2980ccfb38be3 100644 --- a/util/notification/k8s/informers.go +++ b/util/notification/k8s/informers.go @@ -4,7 +4,7 @@ import ( "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - corev1 "k8s.io/client-go/informers/core/v1" + informersv1 "k8s.io/client-go/informers/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/cache" ) @@ -14,13 +14,13 @@ const ( ) func NewSecretInformer(clientset kubernetes.Interface, namespace string, secretName string) cache.SharedIndexInformer { - return corev1.NewFilteredSecretInformer(clientset, namespace, settingsResyncDuration, cache.Indexers{}, func(options *metav1.ListOptions) { + return informersv1.NewFilteredSecretInformer(clientset, namespace, settingsResyncDuration, cache.Indexers{}, func(options *metav1.ListOptions) { options.FieldSelector = "metadata.name=" + secretName }) } func NewConfigMapInformer(clientset kubernetes.Interface, namespace string, configMapName string) cache.SharedIndexInformer { - return corev1.NewFilteredConfigMapInformer(clientset, namespace, settingsResyncDuration, cache.Indexers{}, func(options *metav1.ListOptions) { + return informersv1.NewFilteredConfigMapInformer(clientset, namespace, settingsResyncDuration, cache.Indexers{}, func(options *metav1.ListOptions) { options.FieldSelector = "metadata.name=" + configMapName }) } diff --git a/util/rbac/rbac.go b/util/rbac/rbac.go index 05d5cf61b2fd3..f977e092074cf 100644 --- a/util/rbac/rbac.go +++ b/util/rbac/rbac.go @@ -27,7 +27,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" - v1 "k8s.io/client-go/informers/core/v1" + informersv1 "k8s.io/client-go/informers/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/cache" ) @@ -341,7 +341,7 @@ func (e *Enforcer) newInformer() cache.SharedIndexInformer { options.FieldSelector = cmFieldSelector.String() } indexers := cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc} - return v1.NewFilteredConfigMapInformer(e.clientset, e.namespace, defaultRBACSyncPeriod, indexers, tweakConfigMap) + return informersv1.NewFilteredConfigMapInformer(e.clientset, e.namespace, defaultRBACSyncPeriod, indexers, tweakConfigMap) } // RunPolicyLoader runs the policy loader which watches policy updates from the configmap and reloads them diff --git a/util/settings/settings.go b/util/settings/settings.go index 96af75b0f4e8f..29ec6bfc2874c 100644 --- a/util/settings/settings.go +++ b/util/settings/settings.go @@ -25,7 +25,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" - v1 "k8s.io/client-go/informers/core/v1" + informersv1 "k8s.io/client-go/informers/core/v1" "k8s.io/client-go/kubernetes" v1listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" @@ -1407,8 +1407,8 @@ func (mgr *SettingsManager) initialize(ctx context.Context) error { ByProjectRepoIndexer: byProjectIndexerFunc(common.LabelValueSecretTypeRepository), ByProjectRepoWriteIndexer: byProjectIndexerFunc(common.LabelValueSecretTypeRepositoryWrite), } - cmInformer := v1.NewFilteredConfigMapInformer(mgr.clientset, mgr.namespace, 3*time.Minute, indexers, tweakConfigMap) - secretsInformer := v1.NewSecretInformer(mgr.clientset, mgr.namespace, 3*time.Minute, indexers) + cmInformer := informersv1.NewFilteredConfigMapInformer(mgr.clientset, mgr.namespace, 3*time.Minute, indexers, tweakConfigMap) + secretsInformer := informersv1.NewSecretInformer(mgr.clientset, mgr.namespace, 3*time.Minute, indexers) _, err := cmInformer.AddEventHandler(eventHandler) if err != nil { log.Error(err) From 0c1d218d88f3dbcae596c89ce48d6f91f7a7eb3d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Jan 2025 11:31:40 -0500 Subject: [PATCH 21/41] chore(deps): bump golang.org/x/oauth2 from 0.24.0 to 0.25.0 (#21384) Bumps [golang.org/x/oauth2](https://github.com/golang/oauth2) from 0.24.0 to 0.25.0. - [Commits](https://github.com/golang/oauth2/compare/v0.24.0...v0.25.0) --- updated-dependencies: - dependency-name: golang.org/x/oauth2 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index f9d876b28ba3e..97acc1ee49c16 100644 --- a/go.mod +++ b/go.mod @@ -86,7 +86,7 @@ require ( golang.org/x/crypto v0.31.0 golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f golang.org/x/net v0.33.0 - golang.org/x/oauth2 v0.24.0 + golang.org/x/oauth2 v0.25.0 golang.org/x/sync v0.10.0 golang.org/x/term v0.28.0 golang.org/x/time v0.8.0 diff --git a/go.sum b/go.sum index 107e6e1820571..008d7103981d7 100644 --- a/go.sum +++ b/go.sum @@ -1144,8 +1144,8 @@ golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4Iltr golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.20.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= golang.org/x/oauth2 v0.21.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= -golang.org/x/oauth2 v0.24.0 h1:KTBBxWqUa0ykRPLtV69rRto9TLXcqYkeswu48x/gvNE= -golang.org/x/oauth2 v0.24.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= +golang.org/x/oauth2 v0.25.0 h1:CY4y7XT9v0cRI9oupztF8AgiIu99L/ksR/Xp/6jrZ70= +golang.org/x/oauth2 v0.25.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= From c80325737efd30acca2ccbcd5cd68d6134ad38ca Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Mon, 6 Jan 2025 17:34:32 +0100 Subject: [PATCH 22/41] chore: enable duplicated-imports from revive (#21378) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 3 + applicationset/generators/git_test.go | 139 ++-- applicationset/generators/matrix_test.go | 213 +++--- cmd/argocd/commands/app_test.go | 5 +- controller/state_test.go | 275 ++++--- reposerver/cache/cache_test.go | 49 +- reposerver/repository/repository.go | 21 +- reposerver/repository/repository_test.go | 631 ++++++++-------- server/application/application.go | 230 +++--- server/application/application_test.go | 7 +- server/application/terminal.go | 8 +- server/cluster/cluster_test.go | 102 ++- server/repository/repository.go | 69 +- server/repository/repository_test.go | 3 +- server/server_test.go | 3 +- test/e2e/app_management_ns_test.go | 471 ++++++------ test/e2e/app_management_test.go | 408 +++++----- test/e2e/applicationset_test.go | 703 +++++++++--------- test/e2e/cluster_generator_test.go | 169 +++-- test/e2e/cluster_test.go | 71 +- test/e2e/clusterdecisiongenerator_e2e_test.go | 117 ++- test/e2e/custom_tool_test.go | 57 +- test/e2e/graceful_restart_test.go | 7 +- test/e2e/helm_test.go | 67 +- test/e2e/kustomize_test.go | 12 +- test/e2e/matrix_e2e_test.go | 85 ++- test/e2e/merge_e2e_test.go | 65 +- test/e2e/selective_sync_test.go | 9 +- util/argo/resource_tracking.go | 27 +- util/db/cluster_test.go | 11 +- util/db/repository.go | 69 +- util/localconfig/localconfig.go | 13 +- 32 files changed, 2042 insertions(+), 2077 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 59d71984efa37..54a58363ef87f 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -99,6 +99,9 @@ linters-settings: # Importing with `.` makes the programs much harder to understand - name: dot-imports disabled: true + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#duplicated-imports + - name: duplicated-imports + disabled: false # Empty blocks make code less readable and could be a symptom of a bug or unfinished refactoring. - name: empty-block disabled: true diff --git a/applicationset/generators/git_test.go b/applicationset/generators/git_test.go index 50bb7536a1e8a..588a9de6c378a 100644 --- a/applicationset/generators/git_test.go +++ b/applicationset/generators/git_test.go @@ -14,7 +14,6 @@ import ( "github.com/argoproj/argo-cd/v2/applicationset/services/mocks" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" ) func Test_generateParamsFromGitFile(t *testing.T) { @@ -182,7 +181,7 @@ foo: func TestGitGenerateParamsFromDirectories(t *testing.T) { cases := []struct { name string - directories []argoprojiov1alpha1.GitDirectoryGeneratorItem + directories []v1alpha1.GitDirectoryGeneratorItem pathParamPrefix string repoApps []string repoError error @@ -192,7 +191,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { }{ { name: "happy flow - created apps", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, repoApps: []string{ "app1", "app2", @@ -209,7 +208,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { }, { name: "It prefixes path parameters with PathParamPrefix", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, pathParamPrefix: "myRepo", repoApps: []string{ "app1", @@ -227,7 +226,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { }, { name: "It filters application according to the paths", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*"}, {Path: "p1/*/*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*"}, {Path: "p1/*/*"}}, repoApps: []string{ "app1", "p1/app2", @@ -243,7 +242,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { }, { name: "It filters application according to the paths with Exclude", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*", Exclude: true}, {Path: "*"}, {Path: "*/*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*", Exclude: true}, {Path: "*"}, {Path: "*/*"}}, repoApps: []string{ "app1", "app2", @@ -261,7 +260,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { }, { name: "Expecting same exclude behavior with different order", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}, {Path: "p1/*", Exclude: true}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}, {Path: "p1/*", Exclude: true}}, repoApps: []string{ "app1", "app2", @@ -279,7 +278,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { }, { name: "Value variable interpolation", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}}, repoApps: []string{ "app1", "p1/app2", @@ -298,7 +297,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { }, { name: "handles empty response from repo server", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, repoApps: []string{}, repoError: nil, expected: []map[string]any{}, @@ -306,7 +305,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { }, { name: "handles error from repo server", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, repoApps: []string{}, repoError: errors.New("error"), expected: []map[string]any{}, @@ -325,13 +324,13 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { argoCDServiceMock.On("GetDirectories", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(testCaseCopy.repoApps, testCaseCopy.repoError) gitGenerator := NewGitGenerator(&argoCDServiceMock, "") - applicationSetInfo := argoprojiov1alpha1.ApplicationSet{ + applicationSetInfo := v1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ Name: "set", }, - Spec: argoprojiov1alpha1.ApplicationSetSpec{ - Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{ - Git: &argoprojiov1alpha1.GitGenerator{ + Spec: v1alpha1.ApplicationSetSpec{ + Generators: []v1alpha1.ApplicationSetGenerator{{ + Git: &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", Directories: testCaseCopy.directories, @@ -345,7 +344,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { scheme := runtime.NewScheme() err := v1alpha1.AddToScheme(scheme) require.NoError(t, err) - appProject := argoprojiov1alpha1.AppProject{} + appProject := v1alpha1.AppProject{} client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build() @@ -366,7 +365,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) { func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { cases := []struct { name string - directories []argoprojiov1alpha1.GitDirectoryGeneratorItem + directories []v1alpha1.GitDirectoryGeneratorItem pathParamPrefix string repoApps []string repoError error @@ -375,7 +374,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }{ { name: "happy flow - created apps", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, repoApps: []string{ "app1", "app2", @@ -419,7 +418,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, { name: "It prefixes path parameters with PathParamPrefix", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, pathParamPrefix: "myRepo", repoApps: []string{ "app1", @@ -470,7 +469,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, { name: "It filters application according to the paths", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*"}, {Path: "p1/*/*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*"}, {Path: "p1/*/*"}}, repoApps: []string{ "app1", "p1/app2", @@ -507,7 +506,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, { name: "It filters application according to the paths with Exclude", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*", Exclude: true}, {Path: "*"}, {Path: "*/*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*", Exclude: true}, {Path: "*"}, {Path: "*/*"}}, repoApps: []string{ "app1", "app2", @@ -553,7 +552,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, { name: "Expecting same exclude behavior with different order", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}, {Path: "p1/*", Exclude: true}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}, {Path: "p1/*", Exclude: true}}, repoApps: []string{ "app1", "app2", @@ -599,7 +598,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, { name: "handles empty response from repo server", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, repoApps: []string{}, repoError: nil, expected: []map[string]any{}, @@ -607,7 +606,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { }, { name: "handles error from repo server", - directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, repoApps: []string{}, repoError: errors.New("error"), expected: []map[string]any{}, @@ -626,14 +625,14 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { argoCDServiceMock.On("GetDirectories", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(testCaseCopy.repoApps, testCaseCopy.repoError) gitGenerator := NewGitGenerator(&argoCDServiceMock, "") - applicationSetInfo := argoprojiov1alpha1.ApplicationSet{ + applicationSetInfo := v1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ Name: "set", }, - Spec: argoprojiov1alpha1.ApplicationSetSpec{ + Spec: v1alpha1.ApplicationSetSpec{ GoTemplate: true, - Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{ - Git: &argoprojiov1alpha1.GitGenerator{ + Generators: []v1alpha1.ApplicationSetGenerator{{ + Git: &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", Directories: testCaseCopy.directories, @@ -646,7 +645,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) { scheme := runtime.NewScheme() err := v1alpha1.AddToScheme(scheme) require.NoError(t, err) - appProject := argoprojiov1alpha1.AppProject{} + appProject := v1alpha1.AppProject{} client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build() @@ -668,7 +667,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { cases := []struct { name string // files is the list of paths/globs to match - files []argoprojiov1alpha1.GitFileGeneratorItem + files []v1alpha1.GitFileGeneratorItem // repoFileContents maps repo path to the literal contents of that path repoFileContents map[string][]byte // if repoPathsError is non-nil, the call to GetPaths(...) will return this error value @@ -679,7 +678,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { }{ { name: "happy flow: create params from git files", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, repoFileContents: map[string][]byte{ "cluster-config/production/config.json": []byte(`{ "cluster": { @@ -739,7 +738,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { }, { name: "Value variable interpolation", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, repoFileContents: map[string][]byte{ "cluster-config/production/config.json": []byte(`{ "cluster": { @@ -807,7 +806,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { }, { name: "handles error during getting repo paths", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, repoFileContents: map[string][]byte{}, repoPathsError: errors.New("paths error"), expected: []map[string]any{}, @@ -815,7 +814,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { }, { name: "test invalid JSON file returns error", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, repoFileContents: map[string][]byte{ "cluster-config/production/config.json": []byte(`invalid json file`), }, @@ -825,7 +824,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { }, { name: "test JSON array", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, repoFileContents: map[string][]byte{ "cluster-config/production/config.json": []byte(` [ @@ -880,7 +879,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) { }, { name: "Test YAML flow", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}}, repoFileContents: map[string][]byte{ "cluster-config/production/config.yaml": []byte(` cluster: @@ -934,7 +933,7 @@ cluster: }, { name: "test YAML array", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}}, repoFileContents: map[string][]byte{ "cluster-config/production/config.yaml": []byte(` - cluster: @@ -991,13 +990,13 @@ cluster: Return(testCaseCopy.repoFileContents, testCaseCopy.repoPathsError) gitGenerator := NewGitGenerator(&argoCDServiceMock, "") - applicationSetInfo := argoprojiov1alpha1.ApplicationSet{ + applicationSetInfo := v1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ Name: "set", }, - Spec: argoprojiov1alpha1.ApplicationSetSpec{ - Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{ - Git: &argoprojiov1alpha1.GitGenerator{ + Spec: v1alpha1.ApplicationSetSpec{ + Generators: []v1alpha1.ApplicationSetGenerator{{ + Git: &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", Files: testCaseCopy.files, @@ -1010,7 +1009,7 @@ cluster: scheme := runtime.NewScheme() err := v1alpha1.AddToScheme(scheme) require.NoError(t, err) - appProject := argoprojiov1alpha1.AppProject{} + appProject := v1alpha1.AppProject{} client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build() @@ -1033,7 +1032,7 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { cases := []struct { name string // files is the list of paths/globs to match - files []argoprojiov1alpha1.GitFileGeneratorItem + files []v1alpha1.GitFileGeneratorItem // repoFileContents maps repo path to the literal contents of that path repoFileContents map[string][]byte // if repoPathsError is non-nil, the call to GetPaths(...) will return this error value @@ -1043,7 +1042,7 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { }{ { name: "happy flow: create params from git files", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, repoFileContents: map[string][]byte{ "cluster-config/production/config.json": []byte(`{ "cluster": { @@ -1119,7 +1118,7 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { }, { name: "handles error during getting repo paths", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, repoFileContents: map[string][]byte{}, repoPathsError: errors.New("paths error"), expected: []map[string]any{}, @@ -1127,7 +1126,7 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { }, { name: "test invalid JSON file returns error", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, repoFileContents: map[string][]byte{ "cluster-config/production/config.json": []byte(`invalid json file`), }, @@ -1137,7 +1136,7 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { }, { name: "test JSON array", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}}, repoFileContents: map[string][]byte{ "cluster-config/production/config.json": []byte(` [ @@ -1206,7 +1205,7 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) { }, { name: "Test YAML flow", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}}, repoFileContents: map[string][]byte{ "cluster-config/production/config.yaml": []byte(` cluster: @@ -1276,7 +1275,7 @@ cluster: }, { name: "test YAML array", - files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}}, + files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}}, repoFileContents: map[string][]byte{ "cluster-config/production/config.yaml": []byte(` - cluster: @@ -1347,14 +1346,14 @@ cluster: Return(testCaseCopy.repoFileContents, testCaseCopy.repoPathsError) gitGenerator := NewGitGenerator(&argoCDServiceMock, "") - applicationSetInfo := argoprojiov1alpha1.ApplicationSet{ + applicationSetInfo := v1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ Name: "set", }, - Spec: argoprojiov1alpha1.ApplicationSetSpec{ + Spec: v1alpha1.ApplicationSetSpec{ GoTemplate: true, - Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{ - Git: &argoprojiov1alpha1.GitGenerator{ + Generators: []v1alpha1.ApplicationSetGenerator{{ + Git: &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", Files: testCaseCopy.files, @@ -1366,7 +1365,7 @@ cluster: scheme := runtime.NewScheme() err := v1alpha1.AddToScheme(scheme) require.NoError(t, err) - appProject := argoprojiov1alpha1.AppProject{} + appProject := v1alpha1.AppProject{} client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build() @@ -1388,7 +1387,7 @@ cluster: func TestGitGenerator_GenerateParams(t *testing.T) { cases := []struct { name string - directories []argoprojiov1alpha1.GitDirectoryGeneratorItem + directories []v1alpha1.GitDirectoryGeneratorItem pathParamPrefix string repoApps []string repoPathsError error @@ -1396,7 +1395,7 @@ func TestGitGenerator_GenerateParams(t *testing.T) { values map[string]string expected []map[string]any expectedError error - appset argoprojiov1alpha1.ApplicationSet + appset v1alpha1.ApplicationSet callGetDirectories bool }{ { @@ -1405,25 +1404,25 @@ func TestGitGenerator_GenerateParams(t *testing.T) { "app1", }, repoPathsError: nil, - appset: argoprojiov1alpha1.ApplicationSet{ + appset: v1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ Name: "set", Namespace: "namespace", }, - Spec: argoprojiov1alpha1.ApplicationSetSpec{ - Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{ - Git: &argoprojiov1alpha1.GitGenerator{ + Spec: v1alpha1.ApplicationSetSpec{ + Generators: []v1alpha1.ApplicationSetGenerator{{ + Git: &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", - Directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, PathParamPrefix: "", Values: map[string]string{ "foo": "bar", }, }, }}, - Template: argoprojiov1alpha1.ApplicationSetTemplate{ - Spec: argoprojiov1alpha1.ApplicationSpec{ + Template: v1alpha1.ApplicationSetTemplate{ + Spec: v1alpha1.ApplicationSpec{ Project: "{{.project}}", }, }, @@ -1439,25 +1438,25 @@ func TestGitGenerator_GenerateParams(t *testing.T) { "app1", }, repoPathsError: nil, - appset: argoprojiov1alpha1.ApplicationSet{ + appset: v1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ Name: "set", Namespace: "namespace", }, - Spec: argoprojiov1alpha1.ApplicationSetSpec{ - Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{ - Git: &argoprojiov1alpha1.GitGenerator{ + Spec: v1alpha1.ApplicationSetSpec{ + Generators: []v1alpha1.ApplicationSetGenerator{{ + Git: &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", - Directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, PathParamPrefix: "", Values: map[string]string{ "foo": "bar", }, }, }}, - Template: argoprojiov1alpha1.ApplicationSetTemplate{ - Spec: argoprojiov1alpha1.ApplicationSpec{ + Template: v1alpha1.ApplicationSetTemplate{ + Spec: v1alpha1.ApplicationSpec{ Project: "project", }, }, @@ -1479,7 +1478,7 @@ func TestGitGenerator_GenerateParams(t *testing.T) { scheme := runtime.NewScheme() err := v1alpha1.AddToScheme(scheme) require.NoError(t, err) - appProject := argoprojiov1alpha1.AppProject{} + appProject := v1alpha1.AppProject{} client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build() diff --git a/applicationset/generators/matrix_test.go b/applicationset/generators/matrix_test.go index 88187705d4c33..fb597e86a5365 100644 --- a/applicationset/generators/matrix_test.go +++ b/applicationset/generators/matrix_test.go @@ -20,29 +20,28 @@ import ( apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" ) func TestMatrixGenerate(t *testing.T) { - gitGenerator := &argoprojiov1alpha1.GitGenerator{ + gitGenerator := &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", - Directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, } - listGenerator := &argoprojiov1alpha1.ListGenerator{ + listGenerator := &v1alpha1.ListGenerator{ Elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "Cluster","url": "Url", "templated": "test-{{path.basenameNormalized}}"}`)}}, } testCases := []struct { name string - baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator + baseGenerators []v1alpha1.ApplicationSetNestedGenerator expectedErr error expected []map[string]any }{ { name: "happy flow - generate params", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, }, @@ -57,9 +56,9 @@ func TestMatrixGenerate(t *testing.T) { }, { name: "happy flow - generate params from two lists", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { - List: &argoprojiov1alpha1.ListGenerator{ + List: &v1alpha1.ListGenerator{ Elements: []apiextensionsv1.JSON{ {Raw: []byte(`{"a": "1"}`)}, {Raw: []byte(`{"a": "2"}`)}, @@ -67,7 +66,7 @@ func TestMatrixGenerate(t *testing.T) { }, }, { - List: &argoprojiov1alpha1.ListGenerator{ + List: &v1alpha1.ListGenerator{ Elements: []apiextensionsv1.JSON{ {Raw: []byte(`{"b": "1"}`)}, {Raw: []byte(`{"b": "2"}`)}, @@ -84,7 +83,7 @@ func TestMatrixGenerate(t *testing.T) { }, { name: "returns error if there is less than two base generators", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, }, @@ -93,7 +92,7 @@ func TestMatrixGenerate(t *testing.T) { }, { name: "returns error if there is more than two base generators", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { List: listGenerator, }, @@ -108,7 +107,7 @@ func TestMatrixGenerate(t *testing.T) { }, { name: "returns error if there is more than one inner generator in the first base generator", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, List: listGenerator, @@ -121,7 +120,7 @@ func TestMatrixGenerate(t *testing.T) { }, { name: "returns error if there is more than one inner generator in the second base generator", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { List: listGenerator, }, @@ -139,15 +138,15 @@ func TestMatrixGenerate(t *testing.T) { t.Run(testCaseCopy.name, func(t *testing.T) { genMock := &generatorMock{} - appSet := &argoprojiov1alpha1.ApplicationSet{ + appSet := &v1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ Name: "set", }, - Spec: argoprojiov1alpha1.ApplicationSetSpec{}, + Spec: v1alpha1.ApplicationSetSpec{}, } for _, g := range testCaseCopy.baseGenerators { - gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{ + gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{ Git: g.Git, List: g.List, } @@ -165,7 +164,7 @@ func TestMatrixGenerate(t *testing.T) { }, nil) genMock.On("GetTemplate", &gitGeneratorSpec). - Return(&argoprojiov1alpha1.ApplicationSetTemplate{}) + Return(&v1alpha1.ApplicationSetTemplate{}) } matrixGenerator := NewMatrixGenerator( @@ -175,10 +174,10 @@ func TestMatrixGenerate(t *testing.T) { }, ) - got, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{ - Matrix: &argoprojiov1alpha1.MatrixGenerator{ + got, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{ + Matrix: &v1alpha1.MatrixGenerator{ Generators: testCaseCopy.baseGenerators, - Template: argoprojiov1alpha1.ApplicationSetTemplate{}, + Template: v1alpha1.ApplicationSetTemplate{}, }, }, appSet, nil) @@ -193,25 +192,25 @@ func TestMatrixGenerate(t *testing.T) { } func TestMatrixGenerateGoTemplate(t *testing.T) { - gitGenerator := &argoprojiov1alpha1.GitGenerator{ + gitGenerator := &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", - Directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, } - listGenerator := &argoprojiov1alpha1.ListGenerator{ + listGenerator := &v1alpha1.ListGenerator{ Elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "Cluster","url": "Url"}`)}}, } testCases := []struct { name string - baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator + baseGenerators []v1alpha1.ApplicationSetNestedGenerator expectedErr error expected []map[string]any }{ { name: "happy flow - generate params", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, }, @@ -242,9 +241,9 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { }, { name: "happy flow - generate params from two lists", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { - List: &argoprojiov1alpha1.ListGenerator{ + List: &v1alpha1.ListGenerator{ Elements: []apiextensionsv1.JSON{ {Raw: []byte(`{"a": "1"}`)}, {Raw: []byte(`{"a": "2"}`)}, @@ -252,7 +251,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { }, }, { - List: &argoprojiov1alpha1.ListGenerator{ + List: &v1alpha1.ListGenerator{ Elements: []apiextensionsv1.JSON{ {Raw: []byte(`{"b": "1"}`)}, {Raw: []byte(`{"b": "2"}`)}, @@ -269,16 +268,16 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { }, { name: "parameter override: first list elements take precedence", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { - List: &argoprojiov1alpha1.ListGenerator{ + List: &v1alpha1.ListGenerator{ Elements: []apiextensionsv1.JSON{ {Raw: []byte(`{"booleanFalse": false, "booleanTrue": true, "stringFalse": "false", "stringTrue": "true"}`)}, }, }, }, { - List: &argoprojiov1alpha1.ListGenerator{ + List: &v1alpha1.ListGenerator{ Elements: []apiextensionsv1.JSON{ {Raw: []byte(`{"booleanFalse": true, "booleanTrue": false, "stringFalse": "true", "stringTrue": "false"}`)}, }, @@ -291,7 +290,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { }, { name: "returns error if there is less than two base generators", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, }, @@ -300,7 +299,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { }, { name: "returns error if there is more than two base generators", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { List: listGenerator, }, @@ -315,7 +314,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { }, { name: "returns error if there is more than one inner generator in the first base generator", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, List: listGenerator, @@ -328,7 +327,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { }, { name: "returns error if there is more than one inner generator in the second base generator", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { List: listGenerator, }, @@ -346,17 +345,17 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { t.Run(testCaseCopy.name, func(t *testing.T) { genMock := &generatorMock{} - appSet := &argoprojiov1alpha1.ApplicationSet{ + appSet := &v1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ Name: "set", }, - Spec: argoprojiov1alpha1.ApplicationSetSpec{ + Spec: v1alpha1.ApplicationSetSpec{ GoTemplate: true, }, } for _, g := range testCaseCopy.baseGenerators { - gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{ + gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{ Git: g.Git, List: g.List, } @@ -378,7 +377,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { }, nil) genMock.On("GetTemplate", &gitGeneratorSpec). - Return(&argoprojiov1alpha1.ApplicationSetTemplate{}) + Return(&v1alpha1.ApplicationSetTemplate{}) } matrixGenerator := NewMatrixGenerator( @@ -388,10 +387,10 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { }, ) - got, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{ - Matrix: &argoprojiov1alpha1.MatrixGenerator{ + got, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{ + Matrix: &v1alpha1.MatrixGenerator{ Generators: testCaseCopy.baseGenerators, - Template: argoprojiov1alpha1.ApplicationSetTemplate{}, + Template: v1alpha1.ApplicationSetTemplate{}, }, }, appSet, nil) @@ -406,31 +405,31 @@ func TestMatrixGenerateGoTemplate(t *testing.T) { } func TestMatrixGetRequeueAfter(t *testing.T) { - gitGenerator := &argoprojiov1alpha1.GitGenerator{ + gitGenerator := &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", - Directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, + Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}}, } - listGenerator := &argoprojiov1alpha1.ListGenerator{ + listGenerator := &v1alpha1.ListGenerator{ Elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "Cluster","url": "Url"}`)}}, } - pullRequestGenerator := &argoprojiov1alpha1.PullRequestGenerator{} + pullRequestGenerator := &v1alpha1.PullRequestGenerator{} - scmGenerator := &argoprojiov1alpha1.SCMProviderGenerator{} + scmGenerator := &v1alpha1.SCMProviderGenerator{} - duckTypeGenerator := &argoprojiov1alpha1.DuckTypeGenerator{} + duckTypeGenerator := &v1alpha1.DuckTypeGenerator{} testCases := []struct { name string - baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator + baseGenerators []v1alpha1.ApplicationSetNestedGenerator gitGetRequeueAfter time.Duration expected time.Duration }{ { name: "return NoRequeueAfter if all the inner baseGenerators returns it", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, }, @@ -443,7 +442,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) { }, { name: "returns the minimal time", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, }, @@ -456,7 +455,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) { }, { name: "returns the minimal time for pull request", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, }, @@ -469,7 +468,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) { }, { name: "returns the default time if no requeueAfterSeconds is provided", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, }, @@ -481,7 +480,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) { }, { name: "returns the default time for duck type generator", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, }, @@ -493,7 +492,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) { }, { name: "returns the default time for scm generator", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, }, @@ -512,7 +511,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) { mock := &generatorMock{} for _, g := range testCaseCopy.baseGenerators { - gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{ + gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{ Git: g.Git, List: g.List, PullRequest: g.PullRequest, @@ -532,10 +531,10 @@ func TestMatrixGetRequeueAfter(t *testing.T) { }, ) - got := matrixGenerator.GetRequeueAfter(&argoprojiov1alpha1.ApplicationSetGenerator{ - Matrix: &argoprojiov1alpha1.MatrixGenerator{ + got := matrixGenerator.GetRequeueAfter(&v1alpha1.ApplicationSetGenerator{ + Matrix: &v1alpha1.MatrixGenerator{ Generators: testCaseCopy.baseGenerators, - Template: argoprojiov1alpha1.ApplicationSetTemplate{}, + Template: v1alpha1.ApplicationSetTemplate{}, }, }) @@ -545,16 +544,16 @@ func TestMatrixGetRequeueAfter(t *testing.T) { } func TestInterpolatedMatrixGenerate(t *testing.T) { - interpolatedGitGenerator := &argoprojiov1alpha1.GitGenerator{ + interpolatedGitGenerator := &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", - Files: []argoprojiov1alpha1.GitFileGeneratorItem{ + Files: []v1alpha1.GitFileGeneratorItem{ {Path: "examples/git-generator-files-discovery/cluster-config/dev/config.json"}, {Path: "examples/git-generator-files-discovery/cluster-config/prod/config.json"}, }, } - interpolatedClusterGenerator := &argoprojiov1alpha1.ClusterGenerator{ + interpolatedClusterGenerator := &v1alpha1.ClusterGenerator{ Selector: metav1.LabelSelector{ MatchLabels: map[string]string{"environment": "{{path.basename}}"}, MatchExpressions: nil, @@ -562,14 +561,14 @@ func TestInterpolatedMatrixGenerate(t *testing.T) { } testCases := []struct { name string - baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator + baseGenerators []v1alpha1.ApplicationSetNestedGenerator expectedErr error expected []map[string]any clientError bool }{ { name: "happy flow - generate interpolated params", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: interpolatedGitGenerator, }, @@ -637,7 +636,7 @@ func TestInterpolatedMatrixGenerate(t *testing.T) { t.Run(testCaseCopy.name, func(t *testing.T) { genMock := &generatorMock{} - appSet := &argoprojiov1alpha1.ApplicationSet{} + appSet := &v1alpha1.ApplicationSet{} appClientset := kubefake.NewSimpleClientset(runtimeClusters...) fakeClient := fake.NewClientBuilder().WithObjects(clusters...).Build() @@ -648,7 +647,7 @@ func TestInterpolatedMatrixGenerate(t *testing.T) { clusterGenerator := NewClusterGenerator(cl, context.Background(), appClientset, "namespace") for _, g := range testCaseCopy.baseGenerators { - gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{ + gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{ Git: g.Git, Clusters: g.Clusters, } @@ -665,7 +664,7 @@ func TestInterpolatedMatrixGenerate(t *testing.T) { }, }, nil) genMock.On("GetTemplate", &gitGeneratorSpec). - Return(&argoprojiov1alpha1.ApplicationSetTemplate{}) + Return(&v1alpha1.ApplicationSetTemplate{}) } matrixGenerator := NewMatrixGenerator( map[string]Generator{ @@ -674,10 +673,10 @@ func TestInterpolatedMatrixGenerate(t *testing.T) { }, ) - got, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{ - Matrix: &argoprojiov1alpha1.MatrixGenerator{ + got, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{ + Matrix: &v1alpha1.MatrixGenerator{ Generators: testCaseCopy.baseGenerators, - Template: argoprojiov1alpha1.ApplicationSetTemplate{}, + Template: v1alpha1.ApplicationSetTemplate{}, }, }, appSet, nil) @@ -692,16 +691,16 @@ func TestInterpolatedMatrixGenerate(t *testing.T) { } func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { - interpolatedGitGenerator := &argoprojiov1alpha1.GitGenerator{ + interpolatedGitGenerator := &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", - Files: []argoprojiov1alpha1.GitFileGeneratorItem{ + Files: []v1alpha1.GitFileGeneratorItem{ {Path: "examples/git-generator-files-discovery/cluster-config/dev/config.json"}, {Path: "examples/git-generator-files-discovery/cluster-config/prod/config.json"}, }, } - interpolatedClusterGenerator := &argoprojiov1alpha1.ClusterGenerator{ + interpolatedClusterGenerator := &v1alpha1.ClusterGenerator{ Selector: metav1.LabelSelector{ MatchLabels: map[string]string{"environment": "{{.path.basename}}"}, MatchExpressions: nil, @@ -709,14 +708,14 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { } testCases := []struct { name string - baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator + baseGenerators []v1alpha1.ApplicationSetNestedGenerator expectedErr error expected []map[string]any clientError bool }{ { name: "happy flow - generate interpolated params", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: interpolatedGitGenerator, }, @@ -816,8 +815,8 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { t.Run(testCaseCopy.name, func(t *testing.T) { genMock := &generatorMock{} - appSet := &argoprojiov1alpha1.ApplicationSet{ - Spec: argoprojiov1alpha1.ApplicationSetSpec{ + appSet := &v1alpha1.ApplicationSet{ + Spec: v1alpha1.ApplicationSetSpec{ GoTemplate: true, }, } @@ -831,7 +830,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { clusterGenerator := NewClusterGenerator(cl, context.Background(), appClientset, "namespace") for _, g := range testCaseCopy.baseGenerators { - gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{ + gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{ Git: g.Git, Clusters: g.Clusters, } @@ -852,7 +851,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { }, }, nil) genMock.On("GetTemplate", &gitGeneratorSpec). - Return(&argoprojiov1alpha1.ApplicationSetTemplate{}) + Return(&v1alpha1.ApplicationSetTemplate{}) } matrixGenerator := NewMatrixGenerator( map[string]Generator{ @@ -861,10 +860,10 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { }, ) - got, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{ - Matrix: &argoprojiov1alpha1.MatrixGenerator{ + got, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{ + Matrix: &v1alpha1.MatrixGenerator{ Generators: testCaseCopy.baseGenerators, - Template: argoprojiov1alpha1.ApplicationSetTemplate{}, + Template: v1alpha1.ApplicationSetTemplate{}, }, }, appSet, nil) @@ -879,28 +878,28 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { } func TestMatrixGenerateListElementsYaml(t *testing.T) { - gitGenerator := &argoprojiov1alpha1.GitGenerator{ + gitGenerator := &v1alpha1.GitGenerator{ RepoURL: "RepoURL", Revision: "Revision", - Files: []argoprojiov1alpha1.GitFileGeneratorItem{ + Files: []v1alpha1.GitFileGeneratorItem{ {Path: "config.yaml"}, }, } - listGenerator := &argoprojiov1alpha1.ListGenerator{ + listGenerator := &v1alpha1.ListGenerator{ Elements: []apiextensionsv1.JSON{}, ElementsYaml: "{{ .foo.bar | toJson }}", } testCases := []struct { name string - baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator + baseGenerators []v1alpha1.ApplicationSetNestedGenerator expectedErr error expected []map[string]any }{ { name: "happy flow - generate params", - baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{ { Git: gitGenerator, }, @@ -972,17 +971,17 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) { t.Run(testCaseCopy.name, func(t *testing.T) { genMock := &generatorMock{} - appSet := &argoprojiov1alpha1.ApplicationSet{ + appSet := &v1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ Name: "set", }, - Spec: argoprojiov1alpha1.ApplicationSetSpec{ + Spec: v1alpha1.ApplicationSetSpec{ GoTemplate: true, }, } for _, g := range testCaseCopy.baseGenerators { - gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{ + gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{ Git: g.Git, List: g.List, } @@ -1012,7 +1011,7 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) { }, }}, nil) genMock.On("GetTemplate", &gitGeneratorSpec). - Return(&argoprojiov1alpha1.ApplicationSetTemplate{}) + Return(&v1alpha1.ApplicationSetTemplate{}) } matrixGenerator := NewMatrixGenerator( @@ -1022,10 +1021,10 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) { }, ) - got, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{ - Matrix: &argoprojiov1alpha1.MatrixGenerator{ + got, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{ + Matrix: &v1alpha1.MatrixGenerator{ Generators: testCaseCopy.baseGenerators, - Template: argoprojiov1alpha1.ApplicationSetTemplate{}, + Template: v1alpha1.ApplicationSetTemplate{}, }, }, appSet, nil) @@ -1043,19 +1042,19 @@ type generatorMock struct { mock.Mock } -func (g *generatorMock) GetTemplate(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) *argoprojiov1alpha1.ApplicationSetTemplate { +func (g *generatorMock) GetTemplate(appSetGenerator *v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate { args := g.Called(appSetGenerator) - return args.Get(0).(*argoprojiov1alpha1.ApplicationSetTemplate) + return args.Get(0).(*v1alpha1.ApplicationSetTemplate) } -func (g *generatorMock) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) { +func (g *generatorMock) GenerateParams(appSetGenerator *v1alpha1.ApplicationSetGenerator, appSet *v1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) { args := g.Called(appSetGenerator, appSet) return args.Get(0).([]map[string]any), args.Error(1) } -func (g *generatorMock) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) time.Duration { +func (g *generatorMock) GetRequeueAfter(appSetGenerator *v1alpha1.ApplicationSetGenerator) time.Duration { args := g.Called(appSetGenerator) return args.Get(0).(time.Duration) @@ -1078,11 +1077,11 @@ func TestGitGenerator_GenerateParams_list_x_git_matrix_generator(t *testing.T) { 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{}) + listGeneratorMock.On("GetTemplate", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator")).Return(&v1alpha1.ApplicationSetTemplate{}) - gitGeneratorSpec := &argoprojiov1alpha1.GitGenerator{ + gitGeneratorSpec := &v1alpha1.GitGenerator{ RepoURL: "https://git.example.com", - Files: []argoprojiov1alpha1.GitFileGeneratorItem{ + Files: []v1alpha1.GitFileGeneratorItem{ {Path: "some/path.json"}, }, } @@ -1098,10 +1097,10 @@ func TestGitGenerator_GenerateParams_list_x_git_matrix_generator(t *testing.T) { "Git": gitGenerator, }) - matrixGeneratorSpec := &argoprojiov1alpha1.MatrixGenerator{ - Generators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{ + matrixGeneratorSpec := &v1alpha1.MatrixGenerator{ + Generators: []v1alpha1.ApplicationSetNestedGenerator{ { - List: &argoprojiov1alpha1.ListGenerator{ + List: &v1alpha1.ListGenerator{ Elements: []apiextensionsv1.JSON{ { Raw: []byte(`{"some": "value"}`), @@ -1118,13 +1117,13 @@ func TestGitGenerator_GenerateParams_list_x_git_matrix_generator(t *testing.T) { scheme := runtime.NewScheme() err := v1alpha1.AddToScheme(scheme) require.NoError(t, err) - appProject := argoprojiov1alpha1.AppProject{} + appProject := v1alpha1.AppProject{} client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build() - params, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{ + params, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{ Matrix: matrixGeneratorSpec, - }, &argoprojiov1alpha1.ApplicationSet{}, client) + }, &v1alpha1.ApplicationSet{}, client) require.NoError(t, err) assert.Equal(t, []map[string]any{{ "path": "some", diff --git a/cmd/argocd/commands/app_test.go b/cmd/argocd/commands/app_test.go index 3dcbaa5d7a9db..c3536bc3c5406 100644 --- a/cmd/argocd/commands/app_test.go +++ b/cmd/argocd/commands/app_test.go @@ -27,7 +27,6 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/watch" - k8swatch "k8s.io/apimachinery/pkg/watch" "sigs.k8s.io/yaml" argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient" @@ -2290,10 +2289,10 @@ func (c *fakeAcdClient) WatchApplicationWithRetry(ctx context.Context, appName s go func() { modifiedEvent := new(v1alpha1.ApplicationWatchEvent) - modifiedEvent.Type = k8swatch.Modified + modifiedEvent.Type = watch.Modified appEventsCh <- modifiedEvent deletedEvent := new(v1alpha1.ApplicationWatchEvent) - deletedEvent.Type = k8swatch.Deleted + deletedEvent.Type = watch.Deleted appEventsCh <- deletedEvent }() return appEventsCh diff --git a/controller/state_test.go b/controller/state_test.go index af66e54cf169d..6c5f74c18d54d 100644 --- a/controller/state_test.go +++ b/controller/state_test.go @@ -26,7 +26,6 @@ import ( "github.com/argoproj/argo-cd/v2/common" "github.com/argoproj/argo-cd/v2/controller/testdata" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/reposerver/apiclient" "github.com/argoproj/argo-cd/v2/test" "github.com/argoproj/argo-cd/v2/util/argo" @@ -45,7 +44,7 @@ func TestCompareAppStateEmpty(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -53,7 +52,7 @@ func TestCompareAppStateEmpty(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Empty(t, app.Status.Conditions) @@ -63,7 +62,7 @@ func TestCompareAppStateEmpty(t *testing.T) { func TestCompareAppStateRepoError(t *testing.T) { app := newFakeApp() ctrl := newFakeController(&fakeData{manifestResponses: make([]*apiclient.ManifestResponse, 3)}, errors.New("test repo error")) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -81,13 +80,13 @@ func TestCompareAppStateRepoError(t *testing.T) { compRes, err = ctrl.appStateManager.CompareAppState(app, &defaultProj, revisions, sources, false, false, nil, false, false) assert.NotNil(t, compRes) require.NoError(t, err) - assert.Equal(t, argoappv1.SyncStatusCodeUnknown, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeUnknown, compRes.syncStatus.Status) } // TestCompareAppStateNamespaceMetadataDiffers tests comparison when managed namespace metadata differs func TestCompareAppStateNamespaceMetadataDiffers(t *testing.T) { app := newFakeApp() - app.Spec.SyncPolicy.ManagedNamespaceMetadata = &argoappv1.ManagedNamespaceMetadata{ + app.Spec.SyncPolicy.ManagedNamespaceMetadata = &v1alpha1.ManagedNamespaceMetadata{ Labels: map[string]string{ "foo": "bar", }, @@ -95,8 +94,8 @@ func TestCompareAppStateNamespaceMetadataDiffers(t *testing.T) { "foo": "bar", }, } - app.Status.OperationState = &argoappv1.OperationState{ - SyncResult: &argoappv1.SyncOperationResult{}, + app.Status.OperationState = &v1alpha1.OperationState{ + SyncResult: &v1alpha1.SyncOperationResult{}, } data := fakeData{ @@ -109,7 +108,7 @@ func TestCompareAppStateNamespaceMetadataDiffers(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -117,7 +116,7 @@ func TestCompareAppStateNamespaceMetadataDiffers(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Empty(t, app.Status.Conditions) @@ -131,7 +130,7 @@ func TestCompareAppStateNamespaceMetadataDiffersToManifest(t *testing.T) { ns.SetAnnotations(map[string]string{"bar": "bat"}) app := newFakeApp() - app.Spec.SyncPolicy.ManagedNamespaceMetadata = &argoappv1.ManagedNamespaceMetadata{ + app.Spec.SyncPolicy.ManagedNamespaceMetadata = &v1alpha1.ManagedNamespaceMetadata{ Labels: map[string]string{ "foo": "bar", }, @@ -139,8 +138,8 @@ func TestCompareAppStateNamespaceMetadataDiffersToManifest(t *testing.T) { "foo": "bar", }, } - app.Status.OperationState = &argoappv1.OperationState{ - SyncResult: &argoappv1.SyncOperationResult{}, + app.Status.OperationState = &v1alpha1.OperationState{ + SyncResult: &v1alpha1.SyncOperationResult{}, } liveNs := ns.DeepCopy() @@ -158,7 +157,7 @@ func TestCompareAppStateNamespaceMetadataDiffersToManifest(t *testing.T) { }, } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -166,7 +165,7 @@ func TestCompareAppStateNamespaceMetadataDiffersToManifest(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status) assert.Len(t, compRes.resources, 1) assert.Len(t, compRes.managedResources, 1) assert.NotNil(t, compRes.diffResultList) @@ -192,7 +191,7 @@ func TestCompareAppStateNamespaceMetadata(t *testing.T) { ns.SetAnnotations(map[string]string{"bar": "bat"}) app := newFakeApp() - app.Spec.SyncPolicy.ManagedNamespaceMetadata = &argoappv1.ManagedNamespaceMetadata{ + app.Spec.SyncPolicy.ManagedNamespaceMetadata = &v1alpha1.ManagedNamespaceMetadata{ Labels: map[string]string{ "foo": "bar", }, @@ -200,8 +199,8 @@ func TestCompareAppStateNamespaceMetadata(t *testing.T) { "foo": "bar", }, } - app.Status.OperationState = &argoappv1.OperationState{ - SyncResult: &argoappv1.SyncOperationResult{}, + app.Status.OperationState = &v1alpha1.OperationState{ + SyncResult: &v1alpha1.SyncOperationResult{}, } data := fakeData{ @@ -216,7 +215,7 @@ func TestCompareAppStateNamespaceMetadata(t *testing.T) { }, } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -224,7 +223,7 @@ func TestCompareAppStateNamespaceMetadata(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status) assert.Len(t, compRes.resources, 1) assert.Len(t, compRes.managedResources, 1) assert.NotNil(t, compRes.diffResultList) @@ -244,7 +243,7 @@ func TestCompareAppStateNamespaceMetadata(t *testing.T) { // TestCompareAppStateNamespaceMetadataIsTheSame tests comparison when managed namespace metadata is the same func TestCompareAppStateNamespaceMetadataIsTheSame(t *testing.T) { app := newFakeApp() - app.Spec.SyncPolicy.ManagedNamespaceMetadata = &argoappv1.ManagedNamespaceMetadata{ + app.Spec.SyncPolicy.ManagedNamespaceMetadata = &v1alpha1.ManagedNamespaceMetadata{ Labels: map[string]string{ "foo": "bar", }, @@ -252,9 +251,9 @@ func TestCompareAppStateNamespaceMetadataIsTheSame(t *testing.T) { "foo": "bar", }, } - app.Status.OperationState = &argoappv1.OperationState{ - SyncResult: &argoappv1.SyncOperationResult{ - ManagedNamespaceMetadata: &argoappv1.ManagedNamespaceMetadata{ + app.Status.OperationState = &v1alpha1.OperationState{ + SyncResult: &v1alpha1.SyncOperationResult{ + ManagedNamespaceMetadata: &v1alpha1.ManagedNamespaceMetadata{ Labels: map[string]string{ "foo": "bar", }, @@ -275,7 +274,7 @@ func TestCompareAppStateNamespaceMetadataIsTheSame(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -283,7 +282,7 @@ func TestCompareAppStateNamespaceMetadataIsTheSame(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Empty(t, app.Status.Conditions) @@ -303,7 +302,7 @@ func TestCompareAppStateMissing(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -311,7 +310,7 @@ func TestCompareAppStateMissing(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status) assert.Len(t, compRes.resources, 1) assert.Len(t, compRes.managedResources, 1) assert.Empty(t, app.Status.Conditions) @@ -335,14 +334,14 @@ func TestCompareAppStateExtra(t *testing.T) { }, } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") compRes, err := ctrl.appStateManager.CompareAppState(app, &defaultProj, revisions, sources, false, false, nil, false, false) require.NoError(t, err) assert.NotNil(t, compRes) - assert.Equal(t, argoappv1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status) assert.Len(t, compRes.resources, 1) assert.Len(t, compRes.managedResources, 1) assert.Empty(t, app.Status.Conditions) @@ -366,14 +365,14 @@ func TestCompareAppStateHook(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") compRes, err := ctrl.appStateManager.CompareAppState(app, &defaultProj, revisions, sources, false, false, nil, false, false) require.NoError(t, err) assert.NotNil(t, compRes) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Len(t, compRes.reconciliationResult.Hooks, 1) @@ -398,14 +397,14 @@ func TestCompareAppStateSkipHook(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") compRes, err := ctrl.appStateManager.CompareAppState(app, &defaultProj, revisions, sources, false, false, nil, false, false) require.NoError(t, err) assert.NotNil(t, compRes) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Len(t, compRes.resources, 1) assert.Len(t, compRes.managedResources, 1) assert.Empty(t, compRes.reconciliationResult.Hooks) @@ -429,7 +428,7 @@ func TestCompareAppStateCompareOptionIgnoreExtraneous(t *testing.T) { } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -437,7 +436,7 @@ func TestCompareAppStateCompareOptionIgnoreExtraneous(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Empty(t, app.Status.Conditions) @@ -462,7 +461,7 @@ func TestCompareAppStateExtraHook(t *testing.T) { }, } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -470,7 +469,7 @@ func TestCompareAppStateExtraHook(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Len(t, compRes.resources, 1) assert.Len(t, compRes.managedResources, 1) assert.Empty(t, compRes.reconciliationResult.Hooks) @@ -580,7 +579,7 @@ func TestCompareAppStateDuplicatedNamespacedResources(t *testing.T) { }, } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -590,15 +589,15 @@ func TestCompareAppStateDuplicatedNamespacedResources(t *testing.T) { assert.NotNil(t, compRes) assert.Len(t, app.Status.Conditions, 1) assert.NotNil(t, app.Status.Conditions[0].LastTransitionTime) - assert.Equal(t, argoappv1.ApplicationConditionRepeatedResourceWarning, app.Status.Conditions[0].Type) + assert.Equal(t, v1alpha1.ApplicationConditionRepeatedResourceWarning, app.Status.Conditions[0].Type) assert.Equal(t, "Resource /Pod/fake-dest-ns/my-pod appeared 2 times among application resources.", app.Status.Conditions[0].Message) assert.Len(t, compRes.resources, 4) } func TestCompareAppStateManagedNamespaceMetadataWithLiveNsDoesNotGetPruned(t *testing.T) { app := newFakeApp() - app.Spec.SyncPolicy = &argoappv1.SyncPolicy{ - ManagedNamespaceMetadata: &argoappv1.ManagedNamespaceMetadata{ + app.Spec.SyncPolicy = &v1alpha1.SyncPolicy{ + ManagedNamespaceMetadata: &v1alpha1.ManagedNamespaceMetadata{ Labels: nil, Annotations: nil, }, @@ -637,14 +636,14 @@ func TestCompareAppStateManagedNamespaceMetadataWithLiveNsDoesNotGetPruned(t *te assert.Len(t, compRes.managedResources, 1) } -var defaultProj = argoappv1.AppProject{ +var defaultProj = v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{ Name: "default", Namespace: test.FakeArgoCDNamespace, }, - Spec: argoappv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []argoappv1.ApplicationDestination{ + Destinations: []v1alpha1.ApplicationDestination{ { Server: "*", Namespace: "*", @@ -656,10 +655,10 @@ var defaultProj = argoappv1.AppProject{ // TestCompareAppStateWithManifestGeneratePath tests that it compares revisions when the manifest-generate-path annotation is set. func TestCompareAppStateWithManifestGeneratePath(t *testing.T) { app := newFakeApp() - app.SetAnnotations(map[string]string{argoappv1.AnnotationKeyManifestGeneratePaths: "."}) - app.Status.Sync = argoappv1.SyncStatus{ + app.SetAnnotations(map[string]string{v1alpha1.AnnotationKeyManifestGeneratePaths: "."}) + app.Status.Sync = v1alpha1.SyncStatus{ Revision: "abc123", - Status: argoappv1.SyncStatusCodeSynced, + Status: v1alpha1.SyncStatusCodeSynced, } data := fakeData{ @@ -678,7 +677,7 @@ func TestCompareAppStateWithManifestGeneratePath(t *testing.T) { compRes, err := ctrl.appStateManager.CompareAppState(app, &defaultProj, revisions, app.Spec.GetSources(), false, false, nil, false, false) require.NoError(t, err) assert.NotNil(t, compRes) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Equal(t, "abc123", compRes.syncStatus.Revision) } @@ -707,7 +706,7 @@ func TestSetHealth(t *testing.T) { }, }, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -744,7 +743,7 @@ func TestPreserveStatusTimestamp(t *testing.T) { }, }, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -782,7 +781,7 @@ func TestSetHealthSelfReferencedApp(t *testing.T) { }, }, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -795,15 +794,15 @@ func TestSetHealthSelfReferencedApp(t *testing.T) { func TestSetManagedResourcesWithOrphanedResources(t *testing.T) { proj := defaultProj.DeepCopy() - proj.Spec.OrphanedResources = &argoappv1.OrphanedResourcesMonitorSettings{} + proj.Spec.OrphanedResources = &v1alpha1.OrphanedResourcesMonitorSettings{} app := newFakeApp() ctrl := newFakeController(&fakeData{ apps: []runtime.Object{app, proj}, namespacedResources: map[kube.ResourceKey]namespacedResource{ kube.NewResourceKey("apps", kube.DeploymentKind, app.Namespace, "guestbook"): { - ResourceNode: argoappv1.ResourceNode{ - ResourceRef: argoappv1.ResourceRef{Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app.Namespace}, + ResourceNode: v1alpha1.ResourceNode{ + ResourceRef: v1alpha1.ResourceRef{Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app.Namespace}, }, AppName: "", }, @@ -820,7 +819,7 @@ func TestSetManagedResourcesWithOrphanedResources(t *testing.T) { func TestSetManagedResourcesWithResourcesOfAnotherApp(t *testing.T) { proj := defaultProj.DeepCopy() - proj.Spec.OrphanedResources = &argoappv1.OrphanedResourcesMonitorSettings{} + proj.Spec.OrphanedResources = &v1alpha1.OrphanedResourcesMonitorSettings{} app1 := newFakeApp() app1.Name = "app1" @@ -831,8 +830,8 @@ func TestSetManagedResourcesWithResourcesOfAnotherApp(t *testing.T) { apps: []runtime.Object{app1, app2, proj}, namespacedResources: map[kube.ResourceKey]namespacedResource{ kube.NewResourceKey("apps", kube.DeploymentKind, app2.Namespace, "guestbook"): { - ResourceNode: argoappv1.ResourceNode{ - ResourceRef: argoappv1.ResourceRef{Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app2.Namespace}, + ResourceNode: v1alpha1.ResourceNode{ + ResourceRef: v1alpha1.ResourceRef{Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app2.Namespace}, }, AppName: "app2", }, @@ -847,7 +846,7 @@ func TestSetManagedResourcesWithResourcesOfAnotherApp(t *testing.T) { func TestReturnUnknownComparisonStateOnSettingLoadError(t *testing.T) { proj := defaultProj.DeepCopy() - proj.Spec.OrphanedResources = &argoappv1.OrphanedResourcesMonitorSettings{} + proj.Spec.OrphanedResources = &v1alpha1.OrphanedResourcesMonitorSettings{} app := newFakeApp() @@ -858,7 +857,7 @@ func TestReturnUnknownComparisonStateOnSettingLoadError(t *testing.T) { }, }, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -867,12 +866,12 @@ func TestReturnUnknownComparisonStateOnSettingLoadError(t *testing.T) { assert.Equal(t, health.HealthStatusUnknown, compRes.healthStatus.Status) assert.False(t, compRes.healthStatus.LastTransitionTime.IsZero()) - assert.Equal(t, argoappv1.SyncStatusCodeUnknown, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeUnknown, compRes.syncStatus.Status) } func TestSetManagedResourcesKnownOrphanedResourceExceptions(t *testing.T) { proj := defaultProj.DeepCopy() - proj.Spec.OrphanedResources = &argoappv1.OrphanedResourcesMonitorSettings{} + proj.Spec.OrphanedResources = &v1alpha1.OrphanedResourcesMonitorSettings{} proj.Spec.SourceNamespaces = []string{"default"} app := newFakeApp() @@ -882,13 +881,13 @@ func TestSetManagedResourcesKnownOrphanedResourceExceptions(t *testing.T) { apps: []runtime.Object{app, proj}, namespacedResources: map[kube.ResourceKey]namespacedResource{ kube.NewResourceKey("apps", kube.DeploymentKind, app.Namespace, "guestbook"): { - ResourceNode: argoappv1.ResourceNode{ResourceRef: argoappv1.ResourceRef{Group: "apps", Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app.Namespace}}, + ResourceNode: v1alpha1.ResourceNode{ResourceRef: v1alpha1.ResourceRef{Group: "apps", Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app.Namespace}}, }, kube.NewResourceKey("", kube.ServiceAccountKind, app.Namespace, "default"): { - ResourceNode: argoappv1.ResourceNode{ResourceRef: argoappv1.ResourceRef{Kind: kube.ServiceAccountKind, Name: "default", Namespace: app.Namespace}}, + ResourceNode: v1alpha1.ResourceNode{ResourceRef: v1alpha1.ResourceRef{Kind: kube.ServiceAccountKind, Name: "default", Namespace: app.Namespace}}, }, kube.NewResourceKey("", kube.ServiceKind, app.Namespace, "kubernetes"): { - ResourceNode: argoappv1.ResourceNode{ResourceRef: argoappv1.ResourceRef{Kind: kube.ServiceAccountKind, Name: "kubernetes", Namespace: app.Namespace}}, + ResourceNode: v1alpha1.ResourceNode{ResourceRef: v1alpha1.ResourceRef{Kind: kube.ServiceAccountKind, Name: "kubernetes", Namespace: app.Namespace}}, }, }, }, nil) @@ -911,7 +910,7 @@ func Test_appStateManager_persistRevisionHistory(t *testing.T) { app.Spec.RevisionHistoryLimit = &i } addHistory := func() { - err := manager.persistRevisionHistory(app, "my-revision", argoappv1.ApplicationSource{}, []string{}, []argoappv1.ApplicationSource{}, false, metav1.Time{}, v1alpha1.OperationInitiator{}) + err := manager.persistRevisionHistory(app, "my-revision", v1alpha1.ApplicationSource{}, []string{}, []v1alpha1.ApplicationSource{}, false, metav1.Time{}, v1alpha1.OperationInitiator{}) require.NoError(t, err) } addHistory() @@ -947,7 +946,7 @@ func Test_appStateManager_persistRevisionHistory(t *testing.T) { assert.Len(t, app.Status.History, 9) metav1NowTime := metav1.NewTime(time.Now()) - err := manager.persistRevisionHistory(app, "my-revision", argoappv1.ApplicationSource{}, []string{}, []argoappv1.ApplicationSource{}, false, metav1NowTime, v1alpha1.OperationInitiator{}) + err := manager.persistRevisionHistory(app, "my-revision", v1alpha1.ApplicationSource{}, []string{}, []v1alpha1.ApplicationSource{}, false, metav1NowTime, v1alpha1.OperationInitiator{}) require.NoError(t, err) assert.Equal(t, app.Status.History.LastRevisionHistory().DeployStartedAt, &metav1NowTime) } @@ -962,20 +961,20 @@ func mustReadFile(path string) string { return string(b) } -var signedProj = argoappv1.AppProject{ +var signedProj = v1alpha1.AppProject{ ObjectMeta: metav1.ObjectMeta{ Name: "default", Namespace: test.FakeArgoCDNamespace, }, - Spec: argoappv1.AppProjectSpec{ + Spec: v1alpha1.AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []argoappv1.ApplicationDestination{ + Destinations: []v1alpha1.ApplicationDestination{ { Server: "*", Namespace: "*", }, }, - SignatureKeys: []argoappv1.SignatureKey{ + SignatureKeys: []v1alpha1.SignatureKey{ { KeyID: "4AEE18F83AFDEB23", }, @@ -1000,7 +999,7 @@ func TestSignedResponseNoSignatureRequired(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -1008,7 +1007,7 @@ func TestSignedResponseNoSignatureRequired(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Empty(t, app.Status.Conditions) @@ -1027,7 +1026,7 @@ func TestSignedResponseNoSignatureRequired(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -1035,7 +1034,7 @@ func TestSignedResponseNoSignatureRequired(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Empty(t, app.Status.Conditions) @@ -1059,7 +1058,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -1067,7 +1066,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Empty(t, app.Status.Conditions) @@ -1086,7 +1085,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "abc123") @@ -1094,7 +1093,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Len(t, app.Status.Conditions, 1) @@ -1113,7 +1112,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "abc123") @@ -1121,7 +1120,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Len(t, app.Status.Conditions, 1) @@ -1140,7 +1139,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "abc123") @@ -1148,7 +1147,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Len(t, app.Status.Conditions, 1) @@ -1170,7 +1169,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { ctrl := newFakeController(&data, nil) testProj := signedProj testProj.Spec.SignatureKeys[0].KeyID = "4AEE18F83AFDEB24" - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "abc123") @@ -1178,7 +1177,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Len(t, app.Status.Conditions, 1) @@ -1200,7 +1199,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { // it doesn't matter for our test whether local manifests are valid localManifests := []string{"foobar"} ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "abc123") @@ -1208,7 +1207,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeUnknown, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeUnknown, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Len(t, app.Status.Conditions, 1) @@ -1230,7 +1229,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "abc123") @@ -1238,7 +1237,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Empty(t, app.Status.Conditions) @@ -1260,7 +1259,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { // it doesn't matter for our test whether local manifests are valid localManifests := []string{""} ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "abc123") @@ -1268,7 +1267,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { require.NoError(t, err) assert.NotNil(t, compRes) assert.NotNil(t, compRes.syncStatus) - assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status) + assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status) assert.Empty(t, compRes.resources) assert.Empty(t, compRes.managedResources) assert.Empty(t, app.Status.Conditions) @@ -1276,7 +1275,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) { } func TestComparisonResult_GetHealthStatus(t *testing.T) { - status := &argoappv1.HealthStatus{Status: health.HealthStatusMissing} + status := &v1alpha1.HealthStatus{Status: health.HealthStatusMissing} res := comparisonResult{ healthStatus: status, } @@ -1285,7 +1284,7 @@ func TestComparisonResult_GetHealthStatus(t *testing.T) { } func TestComparisonResult_GetSyncStatus(t *testing.T) { - status := &argoappv1.SyncStatus{Status: argoappv1.SyncStatusCodeOutOfSync} + status := &v1alpha1.SyncStatus{Status: v1alpha1.SyncStatusCodeOutOfSync} res := comparisonResult{ syncStatus: status, } @@ -1477,8 +1476,8 @@ func TestUseDiffCache(t *testing.T) { testName string noCache bool manifestInfos []*apiclient.ManifestResponse - sources []argoappv1.ApplicationSource - app *argoappv1.Application + sources []v1alpha1.ApplicationSource + app *v1alpha1.Application manifestRevisions []string statusRefreshTimeout time.Duration expectedUseCache bool @@ -1500,8 +1499,8 @@ func TestUseDiffCache(t *testing.T) { }, } } - sources := func() []argoappv1.ApplicationSource { - return []argoappv1.ApplicationSource{ + sources := func() []v1alpha1.ApplicationSource { + return []v1alpha1.ApplicationSource{ { RepoURL: "https://some-repo.com", Path: "argocd/httpbin", @@ -1510,41 +1509,41 @@ func TestUseDiffCache(t *testing.T) { } } - app := func(namespace string, revision string, refresh bool, a *argoappv1.Application) *argoappv1.Application { - app := &argoappv1.Application{ + app := func(namespace string, revision string, refresh bool, a *v1alpha1.Application) *v1alpha1.Application { + app := &v1alpha1.Application{ ObjectMeta: metav1.ObjectMeta{ Name: "httpbin", Namespace: namespace, }, - Spec: argoappv1.ApplicationSpec{ - Source: &argoappv1.ApplicationSource{ + Spec: v1alpha1.ApplicationSpec{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://some-repo.com", Path: "argocd/httpbin", TargetRevision: "HEAD", }, - Destination: argoappv1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "httpbin", }, Project: "default", - SyncPolicy: &argoappv1.SyncPolicy{ + SyncPolicy: &v1alpha1.SyncPolicy{ SyncOptions: []string{ "CreateNamespace=true", "ServerSideApply=true", }, }, }, - Status: argoappv1.ApplicationStatus{ - Resources: []argoappv1.ResourceStatus{}, - Sync: argoappv1.SyncStatus{ - Status: argoappv1.SyncStatusCodeSynced, - ComparedTo: argoappv1.ComparedTo{ - Source: argoappv1.ApplicationSource{ + Status: v1alpha1.ApplicationStatus{ + Resources: []v1alpha1.ResourceStatus{}, + Sync: v1alpha1.SyncStatus{ + Status: v1alpha1.SyncStatusCodeSynced, + ComparedTo: v1alpha1.ComparedTo{ + Source: v1alpha1.ApplicationSource{ RepoURL: "https://some-repo.com", Path: "argocd/httpbin", TargetRevision: "HEAD", }, - Destination: argoappv1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "httpbin", }, @@ -1559,7 +1558,7 @@ func TestUseDiffCache(t *testing.T) { } if refresh { annotations := make(map[string]string) - annotations[argoappv1.AnnotationKeyRefresh] = string(argoappv1.RefreshTypeNormal) + annotations[v1alpha1.AnnotationKeyRefresh] = string(v1alpha1.RefreshTypeNormal) app.SetAnnotations(annotations) } if a != nil { @@ -1601,10 +1600,10 @@ func TestUseDiffCache(t *testing.T) { noCache: false, manifestInfos: manifestInfos("rev1"), sources: sources(), - app: app("httpbin", "", false, &argoappv1.Application{ - Spec: argoappv1.ApplicationSpec{ + app: app("httpbin", "", false, &v1alpha1.Application{ + Spec: v1alpha1.ApplicationSpec{ Source: nil, - Sources: argoappv1.ApplicationSources{ + Sources: v1alpha1.ApplicationSources{ { RepoURL: "multisource repo1", }, @@ -1613,13 +1612,13 @@ func TestUseDiffCache(t *testing.T) { }, }, }, - Status: argoappv1.ApplicationStatus{ - Resources: []argoappv1.ResourceStatus{}, - Sync: argoappv1.SyncStatus{ - Status: argoappv1.SyncStatusCodeSynced, - ComparedTo: argoappv1.ComparedTo{ - Source: argoappv1.ApplicationSource{}, - Sources: argoappv1.ApplicationSources{ + Status: v1alpha1.ApplicationStatus{ + Resources: []v1alpha1.ResourceStatus{}, + Sync: v1alpha1.SyncStatus{ + Status: v1alpha1.SyncStatusCodeSynced, + ComparedTo: v1alpha1.ComparedTo{ + Source: v1alpha1.ApplicationSource{}, + Sources: v1alpha1.ApplicationSources{ { RepoURL: "multisource repo1", }, @@ -1700,9 +1699,9 @@ func TestUseDiffCache(t *testing.T) { noCache: false, manifestInfos: manifestInfos("rev1"), sources: sources(), - app: app("httpbin", "rev1", false, &argoappv1.Application{ - Spec: argoappv1.ApplicationSpec{ - Source: &argoappv1.ApplicationSource{ + app: app("httpbin", "rev1", false, &v1alpha1.Application{ + Spec: v1alpha1.ApplicationSpec{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "new-repo", }, }, @@ -1717,9 +1716,9 @@ func TestUseDiffCache(t *testing.T) { noCache: false, manifestInfos: manifestInfos("rev1"), sources: sources(), - app: app("httpbin", "rev1", false, &argoappv1.Application{ - Spec: argoappv1.ApplicationSpec{ - IgnoreDifferences: []argoappv1.ResourceIgnoreDifferences{ + app: app("httpbin", "rev1", false, &v1alpha1.Application{ + Spec: v1alpha1.ApplicationSpec{ + IgnoreDifferences: []v1alpha1.ResourceIgnoreDifferences{ { Group: "app/v1", Kind: "application", @@ -1743,20 +1742,20 @@ func TestUseDiffCache(t *testing.T) { noCache: false, manifestInfos: manifestInfos("rev1"), sources: sources(), - app: app("httpbin", "rev1", false, &argoappv1.Application{ - Spec: argoappv1.ApplicationSpec{ - Destination: argoappv1.ApplicationDestination{ + app: app("httpbin", "rev1", false, &v1alpha1.Application{ + Spec: v1alpha1.ApplicationSpec{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Name: "httpbin", Namespace: "httpbin", }, }, - Status: argoappv1.ApplicationStatus{ - Resources: []argoappv1.ResourceStatus{}, - Sync: argoappv1.SyncStatus{ - Status: argoappv1.SyncStatusCodeSynced, - ComparedTo: argoappv1.ComparedTo{ - Destination: argoappv1.ApplicationDestination{ + Status: v1alpha1.ApplicationStatus{ + Resources: []v1alpha1.ResourceStatus{}, + Sync: v1alpha1.SyncStatus{ + Status: v1alpha1.SyncStatusCodeSynced, + ComparedTo: v1alpha1.ComparedTo{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "httpbin", }, @@ -1804,7 +1803,7 @@ func TestCompareAppStateDefaultRevisionUpdated(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") @@ -1827,7 +1826,7 @@ func TestCompareAppStateRevisionUpdatedWithHelmSource(t *testing.T) { managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured), } ctrl := newFakeController(&data, nil) - sources := make([]argoappv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) sources = append(sources, app.Spec.GetSource()) revisions := make([]string, 0) revisions = append(revisions, "") diff --git a/reposerver/cache/cache_test.go b/reposerver/cache/cache_test.go index 46039fa840746..18ead8aa9e52b 100644 --- a/reposerver/cache/cache_test.go +++ b/reposerver/cache/cache_test.go @@ -12,8 +12,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" - . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" + "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/reposerver/apiclient" "github.com/argoproj/argo-cd/v2/reposerver/cache/mocks" cacheutil "github.com/argoproj/argo-cd/v2/util/cache" @@ -46,7 +45,7 @@ func TestCache_GetRevisionMetadata(t *testing.T) { require.ErrorIs(t, err, ErrCacheMiss) mockCache.RedisClient.AssertCalled(t, "Get", mock.Anything, mock.Anything) // populate cache - err = cache.SetRevisionMetadata("my-repo-url", "my-revision", &RevisionMetadata{Message: "my-message"}) + err = cache.SetRevisionMetadata("my-repo-url", "my-revision", &v1alpha1.RevisionMetadata{Message: "my-message"}) require.NoError(t, err) // cache miss _, err = cache.GetRevisionMetadata("other-repo-url", "my-revision") @@ -57,7 +56,7 @@ func TestCache_GetRevisionMetadata(t *testing.T) { // cache hit value, err := cache.GetRevisionMetadata("my-repo-url", "my-revision") require.NoError(t, err) - assert.Equal(t, &RevisionMetadata{Message: "my-message"}, value) + assert.Equal(t, &v1alpha1.RevisionMetadata{Message: "my-message"}, value) mockCache.AssertCacheCalledTimes(t, &mocks.CacheCallCounts{ExternalSets: 1, ExternalGets: 4}) } @@ -93,43 +92,43 @@ func TestCache_GetManifests(t *testing.T) { // cache miss q := &apiclient.ManifestRequest{} value := &CachedManifestResponse{} - err := cache.GetManifests("my-revision", &ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", value, nil, "") + err := cache.GetManifests("my-revision", &v1alpha1.ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", value, nil, "") require.ErrorIs(t, err, ErrCacheMiss) // populate cache res := &CachedManifestResponse{ManifestResponse: &apiclient.ManifestResponse{SourceType: "my-source-type"}} - err = cache.SetManifests("my-revision", &ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", res, nil, "") + err = cache.SetManifests("my-revision", &v1alpha1.ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", res, nil, "") require.NoError(t, err) t.Run("expect cache miss because of changed revision", func(t *testing.T) { - err = cache.GetManifests("other-revision", &ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", value, nil, "") + err = cache.GetManifests("other-revision", &v1alpha1.ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", value, nil, "") require.ErrorIs(t, err, ErrCacheMiss) }) t.Run("expect cache miss because of changed path", func(t *testing.T) { - err = cache.GetManifests("my-revision", &ApplicationSource{Path: "other-path"}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", value, nil, "") + err = cache.GetManifests("my-revision", &v1alpha1.ApplicationSource{Path: "other-path"}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", value, nil, "") require.ErrorIs(t, err, ErrCacheMiss) }) t.Run("expect cache miss because of changed namespace", func(t *testing.T) { - err = cache.GetManifests("my-revision", &ApplicationSource{}, q.RefSources, q, "other-namespace", "", "my-app-label-key", "my-app-label-value", value, nil, "") + err = cache.GetManifests("my-revision", &v1alpha1.ApplicationSource{}, q.RefSources, q, "other-namespace", "", "my-app-label-key", "my-app-label-value", value, nil, "") require.ErrorIs(t, err, ErrCacheMiss) }) t.Run("expect cache miss because of changed app label key", func(t *testing.T) { - err = cache.GetManifests("my-revision", &ApplicationSource{}, q.RefSources, q, "my-namespace", "", "other-app-label-key", "my-app-label-value", value, nil, "") + err = cache.GetManifests("my-revision", &v1alpha1.ApplicationSource{}, q.RefSources, q, "my-namespace", "", "other-app-label-key", "my-app-label-value", value, nil, "") require.ErrorIs(t, err, ErrCacheMiss) }) t.Run("expect cache miss because of changed app label value", func(t *testing.T) { - err = cache.GetManifests("my-revision", &ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "other-app-label-value", value, nil, "") + err = cache.GetManifests("my-revision", &v1alpha1.ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "other-app-label-value", value, nil, "") require.ErrorIs(t, err, ErrCacheMiss) }) t.Run("expect cache miss because of changed referenced source", func(t *testing.T) { - err = cache.GetManifests("my-revision", &ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "other-app-label-value", value, map[string]string{"my-referenced-source": "my-referenced-revision"}, "") + err = cache.GetManifests("my-revision", &v1alpha1.ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "other-app-label-value", value, map[string]string{"my-referenced-source": "my-referenced-revision"}, "") require.ErrorIs(t, err, ErrCacheMiss) }) t.Run("expect cache hit", func(t *testing.T) { err = cache.SetManifests( - "my-revision1", &ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", + "my-revision1", &v1alpha1.ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", &CachedManifestResponse{ManifestResponse: &apiclient.ManifestResponse{SourceType: "my-source-type", Revision: "my-revision2"}}, nil, "") require.NoError(t, err) - err = cache.GetManifests("my-revision1", &ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", value, nil, "") + err = cache.GetManifests("my-revision1", &v1alpha1.ApplicationSource{}, q.RefSources, q, "my-namespace", "", "my-app-label-key", "my-app-label-value", value, nil, "") require.NoError(t, err) assert.Equal(t, "my-source-type", value.ManifestResponse.SourceType) @@ -145,20 +144,20 @@ func TestCache_GetAppDetails(t *testing.T) { mockCache := fixtures.mockCache // cache miss value := &apiclient.RepoAppDetailsResponse{} - emptyRefSources := map[string]*RefTarget{} - err := cache.GetAppDetails("my-revision", &ApplicationSource{}, emptyRefSources, value, "", nil) + emptyRefSources := map[string]*v1alpha1.RefTarget{} + err := cache.GetAppDetails("my-revision", &v1alpha1.ApplicationSource{}, emptyRefSources, value, "", nil) require.ErrorIs(t, err, ErrCacheMiss) res := &apiclient.RepoAppDetailsResponse{Type: "my-type"} - err = cache.SetAppDetails("my-revision", &ApplicationSource{}, emptyRefSources, res, "", nil) + err = cache.SetAppDetails("my-revision", &v1alpha1.ApplicationSource{}, emptyRefSources, res, "", nil) require.NoError(t, err) // cache miss - err = cache.GetAppDetails("other-revision", &ApplicationSource{}, emptyRefSources, value, "", nil) + err = cache.GetAppDetails("other-revision", &v1alpha1.ApplicationSource{}, emptyRefSources, value, "", nil) require.ErrorIs(t, err, ErrCacheMiss) // cache miss - err = cache.GetAppDetails("my-revision", &ApplicationSource{Path: "other-path"}, emptyRefSources, value, "", nil) + err = cache.GetAppDetails("my-revision", &v1alpha1.ApplicationSource{Path: "other-path"}, emptyRefSources, value, "", nil) require.ErrorIs(t, err, ErrCacheMiss) // cache hit - err = cache.GetAppDetails("my-revision", &ApplicationSource{}, emptyRefSources, value, "", nil) + err = cache.GetAppDetails("my-revision", &v1alpha1.ApplicationSource{}, emptyRefSources, value, "", nil) require.NoError(t, err) assert.Equal(t, &apiclient.RepoAppDetailsResponse{Type: "my-type"}, value) mockCache.AssertCacheCalledTimes(t, &mocks.CacheCallCounts{ExternalSets: 1, ExternalGets: 4}) @@ -185,7 +184,7 @@ func TestCachedManifestResponse_HashBehavior(t *testing.T) { Revision: "revision", Manifests: []string{"sample-text"}, } - appSrc := &ApplicationSource{} + appSrc := &v1alpha1.ApplicationSource{} appKey := "key" appValue := "value" @@ -600,14 +599,14 @@ func TestRevisionChartDetails(t *testing.T) { t.Cleanup(fixtures.mockCache.StopRedisCallback) details, err := fixtures.cache.GetRevisionChartDetails("test-repo", "test-revision", "v1.0.0") require.ErrorIs(t, err, ErrCacheMiss) - assert.Equal(t, &appv1.ChartDetails{}, details) + assert.Equal(t, &v1alpha1.ChartDetails{}, details) fixtures.mockCache.AssertCacheCalledTimes(t, &mocks.CacheCallCounts{ExternalGets: 1}) }) t.Run("GetRevisionChartDetails cache miss local", func(t *testing.T) { fixtures := newFixtures() t.Cleanup(fixtures.mockCache.StopRedisCallback) cache := fixtures.cache - expectedItem := &appv1.ChartDetails{ + expectedItem := &v1alpha1.ChartDetails{ Description: "test-chart", Home: "v1.0.0", Maintainers: []string{"test-maintainer"}, @@ -627,7 +626,7 @@ func TestRevisionChartDetails(t *testing.T) { fixtures := newFixtures() t.Cleanup(fixtures.mockCache.StopRedisCallback) cache := fixtures.cache - expectedItem := &appv1.ChartDetails{ + expectedItem := &v1alpha1.ChartDetails{ Description: "test-chart", Home: "v1.0.0", Maintainers: []string{"test-maintainer"}, @@ -646,7 +645,7 @@ func TestRevisionChartDetails(t *testing.T) { t.Run("SetRevisionChartDetails", func(t *testing.T) { fixtures := newFixtures() t.Cleanup(fixtures.mockCache.StopRedisCallback) - expectedItem := &appv1.ChartDetails{ + expectedItem := &v1alpha1.ChartDetails{ Description: "test-chart", Home: "v1.0.0", Maintainers: []string{"test-maintainer"}, diff --git a/reposerver/repository/repository.go b/reposerver/repository/repository.go index 18c5cf3fa49ba..2c408151bfa6c 100644 --- a/reposerver/repository/repository.go +++ b/reposerver/repository/repository.go @@ -48,7 +48,6 @@ import ( "github.com/argoproj/argo-cd/v2/reposerver/metrics" "github.com/argoproj/argo-cd/v2/util/app/discovery" apppathutil "github.com/argoproj/argo-cd/v2/util/app/path" - argopath "github.com/argoproj/argo-cd/v2/util/app/path" "github.com/argoproj/argo-cd/v2/util/argo" "github.com/argoproj/argo-cd/v2/util/cmp" "github.com/argoproj/argo-cd/v2/util/env" @@ -360,9 +359,9 @@ func (s *Service) runRepoOperation( } defer io.Close(closer) if !s.initConstants.AllowOutOfBoundsSymlinks { - err := argopath.CheckOutOfBoundsSymlinks(chartPath) + err := apppathutil.CheckOutOfBoundsSymlinks(chartPath) if err != nil { - oobError := &argopath.OutOfBoundsSymlinkError{} + oobError := &apppathutil.OutOfBoundsSymlinkError{} if errors.As(err, &oobError) { log.WithFields(log.Fields{ common.SecurityField: common.SecurityHigh, @@ -390,9 +389,9 @@ func (s *Service) runRepoOperation( defer io.Close(closer) if !s.initConstants.AllowOutOfBoundsSymlinks { - err := argopath.CheckOutOfBoundsSymlinks(gitClient.Root()) + err := apppathutil.CheckOutOfBoundsSymlinks(gitClient.Root()) if err != nil { - oobError := &argopath.OutOfBoundsSymlinkError{} + oobError := &apppathutil.OutOfBoundsSymlinkError{} if errors.As(err, &oobError) { log.WithFields(log.Fields{ common.SecurityField: common.SecurityHigh, @@ -444,7 +443,7 @@ func (s *Service) runRepoOperation( return nil, err } } - appPath, err := argopath.Path(gitClient.Root(), source.Path) + appPath, err := apppathutil.Path(gitClient.Root(), source.Path) if err != nil { return nil, err } @@ -604,9 +603,9 @@ func (s *Service) GenerateManifestWithFiles(stream apiclient.RepoServerService_G } if !s.initConstants.AllowOutOfBoundsSymlinks { - err := argopath.CheckOutOfBoundsSymlinks(workDir) + err := apppathutil.CheckOutOfBoundsSymlinks(workDir) if err != nil { - oobError := &argopath.OutOfBoundsSymlinkError{} + oobError := &apppathutil.OutOfBoundsSymlinkError{} if errors.As(err, &oobError) { log.WithFields(log.Fields{ common.SecurityField: common.SecurityHigh, @@ -620,7 +619,7 @@ func (s *Service) GenerateManifestWithFiles(stream apiclient.RepoServerService_G } promise := s.runManifestGen(stream.Context(), workDir, "streamed", metadata.Checksum, func() (*operationContext, error) { - appPath, err := argopath.Path(workDir, req.ApplicationSource.Path) + appPath, err := apppathutil.Path(workDir, req.ApplicationSource.Path) if err != nil { return nil, fmt.Errorf("failed to get app path: %w", err) } @@ -782,9 +781,9 @@ func (s *Service) runManifestGenAsync(ctx context.Context, repoRoot, commitSHA, // Symlink check must happen after acquiring lock. if !s.initConstants.AllowOutOfBoundsSymlinks { - err := argopath.CheckOutOfBoundsSymlinks(gitClient.Root()) + err := apppathutil.CheckOutOfBoundsSymlinks(gitClient.Root()) if err != nil { - oobError := &argopath.OutOfBoundsSymlinkError{} + oobError := &apppathutil.OutOfBoundsSymlinkError{} if errors.As(err, &oobError) { log.WithFields(log.Fields{ common.SecurityField: common.SecurityHigh, diff --git a/reposerver/repository/repository_test.go b/reposerver/repository/repository_test.go index 7ccadd6af84f7..38196a1fdb33a 100644 --- a/reposerver/repository/repository_test.go +++ b/reposerver/repository/repository_test.go @@ -36,7 +36,6 @@ import ( "github.com/argoproj/argo-cd/v2/common" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/reposerver/apiclient" "github.com/argoproj/argo-cd/v2/reposerver/cache" repositorymocks "github.com/argoproj/argo-cd/v2/reposerver/cache/mocks" @@ -206,9 +205,9 @@ func newServiceWithCommitSHA(t *testing.T, root, revision string) *Service { func TestGenerateYamlManifestInDir(t *testing.T) { service := newService(t, "../../manifests/base") - src := argoappv1.ApplicationSource{Path: "."} + src := v1alpha1.ApplicationSource{Path: "."} q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, ApplicationSource: &src, ProjectName: "something", ProjectSourceRepos: []string{"*"}, @@ -279,7 +278,7 @@ func Test_GenerateManifests_NoOutOfBoundsAccess(t *testing.T) { } q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: &argoappv1.ApplicationSource{}, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: &v1alpha1.ApplicationSource{}, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } res, err := GenerateManifests(context.Background(), repoDir, "", "", &q, false, &git.NoopCredsStore{}, resource.MustParse("0"), nil) @@ -297,7 +296,7 @@ func TestGenerateManifests_MissingSymlinkDestination(t *testing.T) { require.NoError(t, err) q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: &argoappv1.ApplicationSource{}, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: &v1alpha1.ApplicationSource{}, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } _, err = GenerateManifests(context.Background(), repoDir, "", "", &q, false, &git.NoopCredsStore{}, resource.MustParse("0"), nil) @@ -307,10 +306,10 @@ func TestGenerateManifests_MissingSymlinkDestination(t *testing.T) { func TestGenerateManifests_K8SAPIResetCache(t *testing.T) { service := newService(t, "../../manifests/base") - src := argoappv1.ApplicationSource{Path: "."} + src := v1alpha1.ApplicationSource{Path: "."} q := apiclient.ManifestRequest{ KubeVersion: "v1.16.0", - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, ApplicationSource: &src, ProjectName: "something", ProjectSourceRepos: []string{"*"}, @@ -335,9 +334,9 @@ func TestGenerateManifests_K8SAPIResetCache(t *testing.T) { func TestGenerateManifests_EmptyCache(t *testing.T) { service, gitMocks, mockCache := newServiceWithMocks(t, "../../manifests/base", false) - src := argoappv1.ApplicationSource{Path: "."} + src := v1alpha1.ApplicationSource{Path: "."} q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, ApplicationSource: &src, ProjectName: "something", ProjectSourceRepos: []string{"*"}, @@ -391,8 +390,8 @@ func TestGenerateManifest_RefOnlyShortCircuit(t *testing.T) { remote: repoRemote, addEmptyCommit: true, }) - src := argoappv1.ApplicationSource{RepoURL: repoRemote, TargetRevision: "HEAD", Ref: "test-ref"} - repo := &argoappv1.Repository{ + src := v1alpha1.ApplicationSource{RepoURL: repoRemote, TargetRevision: "HEAD", Ref: "test-ref"} + repo := &v1alpha1.Repository{ Repo: repoRemote, } q := apiclient.ManifestRequest{ @@ -457,10 +456,10 @@ func TestGenerateManifestsHelmWithRefs_CachedNoLsRemote(t *testing.T) { valuesFiles: map[string]map[string]string{"test.yaml": {"testval": "test"}}, }, }) - src := argoappv1.ApplicationSource{RepoURL: repoRemote, Path: ".", TargetRevision: "HEAD", Helm: &argoappv1.ApplicationSourceHelm{ + src := v1alpha1.ApplicationSource{RepoURL: repoRemote, Path: ".", TargetRevision: "HEAD", Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"$ref/test.yaml"}, }} - repo := &argoappv1.Repository{ + repo := &v1alpha1.Repository{ Repo: repoRemote, } q := apiclient.ManifestRequest{ @@ -470,7 +469,7 @@ func TestGenerateManifestsHelmWithRefs_CachedNoLsRemote(t *testing.T) { ApplicationSource: &src, ProjectName: "default", ProjectSourceRepos: []string{"*"}, - RefSources: map[string]*argoappv1.RefTarget{"$ref": {TargetRevision: "HEAD", Repo: *repo}}, + RefSources: map[string]*v1alpha1.RefTarget{"$ref": {TargetRevision: "HEAD", Repo: *repo}}, } err = cacheMocks.cacheutilCache.SetItem("git-refs|"+repoRemote, [][2]string{{"HEAD", revision}}, nil) require.NoError(t, err) @@ -486,9 +485,9 @@ func TestGenerateManifestsHelmWithRefs_CachedNoLsRemote(t *testing.T) { func TestHelmManifestFromChartRepo(t *testing.T) { root := t.TempDir() service, gitMocks, mockCache := newServiceWithMocks(t, root, false) - source := &argoappv1.ApplicationSource{Chart: "my-chart", TargetRevision: ">= 1.0.0"} + source := &v1alpha1.ApplicationSource{Chart: "my-chart", TargetRevision: ">= 1.0.0"} request := &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: source, NoCache: true, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: source, NoCache: true, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } response, err := service.GenerateManifest(context.Background(), request) @@ -511,22 +510,22 @@ func TestHelmManifestFromChartRepo(t *testing.T) { func TestHelmChartReferencingExternalValues(t *testing.T) { service := newService(t, ".") - spec := argoappv1.ApplicationSpec{ - Sources: []argoappv1.ApplicationSource{ - {RepoURL: "https://helm.example.com", Chart: "my-chart", TargetRevision: ">= 1.0.0", Helm: &argoappv1.ApplicationSourceHelm{ + spec := v1alpha1.ApplicationSpec{ + Sources: []v1alpha1.ApplicationSource{ + {RepoURL: "https://helm.example.com", Chart: "my-chart", TargetRevision: ">= 1.0.0", Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"$ref/testdata/my-chart/my-chart-values.yaml"}, }}, {Ref: "ref", RepoURL: "https://git.example.com/test/repo"}, }, } - refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { - return &argoappv1.Repository{ + refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(ctx context.Context, url string, project string) (*v1alpha1.Repository, error) { + return &v1alpha1.Repository{ Repo: "https://git.example.com/test/repo", }, nil }, []string{}, false) require.NoError(t, err) request := &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: &spec.Sources[0], NoCache: true, RefSources: refSources, HasMultipleSources: true, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: &spec.Sources[0], NoCache: true, RefSources: refSources, HasMultipleSources: true, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } response, err := service.GenerateManifest(context.Background(), request) @@ -543,9 +542,9 @@ func TestHelmChartReferencingExternalValues(t *testing.T) { } func TestHelmChartReferencingExternalValues_InvalidRefs(t *testing.T) { - spec := argoappv1.ApplicationSpec{ - Sources: []argoappv1.ApplicationSource{ - {RepoURL: "https://helm.example.com", Chart: "my-chart", TargetRevision: ">= 1.0.0", Helm: &argoappv1.ApplicationSourceHelm{ + spec := v1alpha1.ApplicationSpec{ + Sources: []v1alpha1.ApplicationSource{ + {RepoURL: "https://helm.example.com", Chart: "my-chart", TargetRevision: ">= 1.0.0", Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"$ref/testdata/my-chart/my-chart-values.yaml"}, }}, {RepoURL: "https://git.example.com/test/repo"}, @@ -555,8 +554,8 @@ func TestHelmChartReferencingExternalValues_InvalidRefs(t *testing.T) { // Empty refsource service := newService(t, ".") - getRepository := func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { - return &argoappv1.Repository{ + getRepository := func(ctx context.Context, url string, project string) (*v1alpha1.Repository, error) { + return &v1alpha1.Repository{ Repo: "https://git.example.com/test/repo", }, nil } @@ -565,7 +564,7 @@ func TestHelmChartReferencingExternalValues_InvalidRefs(t *testing.T) { require.NoError(t, err) request := &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: &spec.Sources[0], NoCache: true, RefSources: refSources, HasMultipleSources: true, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: &spec.Sources[0], NoCache: true, RefSources: refSources, HasMultipleSources: true, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } response, err := service.GenerateManifest(context.Background(), request) @@ -580,7 +579,7 @@ func TestHelmChartReferencingExternalValues_InvalidRefs(t *testing.T) { require.NoError(t, err) request = &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: &spec.Sources[0], NoCache: true, RefSources: refSources, HasMultipleSources: true, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: &spec.Sources[0], NoCache: true, RefSources: refSources, HasMultipleSources: true, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } response, err = service.GenerateManifest(context.Background(), request) @@ -596,7 +595,7 @@ func TestHelmChartReferencingExternalValues_InvalidRefs(t *testing.T) { require.NoError(t, err) request = &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: &spec.Sources[0], NoCache: true, RefSources: refSources, HasMultipleSources: true, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: &spec.Sources[0], NoCache: true, RefSources: refSources, HasMultipleSources: true, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } response, err = service.GenerateManifest(context.Background(), request) @@ -617,10 +616,10 @@ func TestHelmChartReferencingExternalValues_OutOfBounds_Symlink(t *testing.T) { // Create a regular file to reference from another source err = os.WriteFile("./testdata/oob-symlink/values.yaml", []byte("foo: bar"), 0o644) require.NoError(t, err) - spec := argoappv1.ApplicationSpec{ + spec := v1alpha1.ApplicationSpec{ Project: "default", - Sources: []argoappv1.ApplicationSource{ - {RepoURL: "https://helm.example.com", Chart: "my-chart", TargetRevision: ">= 1.0.0", Helm: &argoappv1.ApplicationSourceHelm{ + Sources: []v1alpha1.ApplicationSource{ + {RepoURL: "https://helm.example.com", Chart: "my-chart", TargetRevision: ">= 1.0.0", Helm: &v1alpha1.ApplicationSourceHelm{ // Reference `ref` but do not use the oob symlink. The mere existence of the link should be enough to // cause an error. ValueFiles: []string{"$ref/testdata/oob-symlink/values.yaml"}, @@ -628,13 +627,13 @@ func TestHelmChartReferencingExternalValues_OutOfBounds_Symlink(t *testing.T) { {Ref: "ref", RepoURL: "https://git.example.com/test/repo"}, }, } - refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { - return &argoappv1.Repository{ + refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(ctx context.Context, url string, project string) (*v1alpha1.Repository, error) { + return &v1alpha1.Repository{ Repo: "https://git.example.com/test/repo", }, nil }, []string{}, false) require.NoError(t, err) - request := &apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &spec.Sources[0], NoCache: true, RefSources: refSources, HasMultipleSources: true} + request := &apiclient.ManifestRequest{Repo: &v1alpha1.Repository{}, ApplicationSource: &spec.Sources[0], NoCache: true, RefSources: refSources, HasMultipleSources: true} _, err = service.GenerateManifest(context.Background(), request) require.Error(t, err) } @@ -642,10 +641,10 @@ func TestHelmChartReferencingExternalValues_OutOfBounds_Symlink(t *testing.T) { func TestGenerateManifestsUseExactRevision(t *testing.T) { service, gitClient, _ := newServiceWithMocks(t, ".", false) - src := argoappv1.ApplicationSource{Path: "./testdata/recurse", Directory: &argoappv1.ApplicationSourceDirectory{Recurse: true}} + src := v1alpha1.ApplicationSource{Path: "./testdata/recurse", Directory: &v1alpha1.ApplicationSourceDirectory{Recurse: true}} q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: &src, Revision: "abc", ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: &src, Revision: "abc", ProjectName: "something", ProjectSourceRepos: []string{"*"}, } @@ -658,10 +657,10 @@ func TestGenerateManifestsUseExactRevision(t *testing.T) { func TestRecurseManifestsInDir(t *testing.T) { service := newService(t, ".") - src := argoappv1.ApplicationSource{Path: "./testdata/recurse", Directory: &argoappv1.ApplicationSourceDirectory{Recurse: true}} + src := v1alpha1.ApplicationSource{Path: "./testdata/recurse", Directory: &v1alpha1.ApplicationSourceDirectory{Recurse: true}} q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: &src, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: &src, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } @@ -673,9 +672,9 @@ func TestRecurseManifestsInDir(t *testing.T) { func TestInvalidManifestsInDir(t *testing.T) { service := newService(t, ".") - src := argoappv1.ApplicationSource{Path: "./testdata/invalid-manifests", Directory: &argoappv1.ApplicationSourceDirectory{Recurse: true}} + src := v1alpha1.ApplicationSource{Path: "./testdata/invalid-manifests", Directory: &v1alpha1.ApplicationSourceDirectory{Recurse: true}} - q := apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &src} + q := apiclient.ManifestRequest{Repo: &v1alpha1.Repository{}, ApplicationSource: &src} _, err := service.GenerateManifest(context.Background(), &q) require.Error(t, err) @@ -684,8 +683,8 @@ func TestInvalidManifestsInDir(t *testing.T) { func TestInvalidMetadata(t *testing.T) { service := newService(t, ".") - src := argoappv1.ApplicationSource{Path: "./testdata/invalid-metadata", Directory: &argoappv1.ApplicationSourceDirectory{Recurse: true}} - q := apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &src, AppLabelKey: "test", AppName: "invalid-metadata", TrackingMethod: "annotation+label"} + src := v1alpha1.ApplicationSource{Path: "./testdata/invalid-metadata", Directory: &v1alpha1.ApplicationSourceDirectory{Recurse: true}} + q := apiclient.ManifestRequest{Repo: &v1alpha1.Repository{}, ApplicationSource: &src, AppLabelKey: "test", AppName: "invalid-metadata", TrackingMethod: "annotation+label"} _, err := service.GenerateManifest(context.Background(), &q) assert.ErrorContains(t, err, "contains non-string value in the map under key \"invalid\"") } @@ -694,8 +693,8 @@ func TestNilMetadataAccessors(t *testing.T) { service := newService(t, ".") expected := "{\"apiVersion\":\"v1\",\"kind\":\"ConfigMap\",\"metadata\":{\"annotations\":{\"argocd.argoproj.io/tracking-id\":\"nil-metadata-accessors:/ConfigMap:/my-map\"},\"labels\":{\"test\":\"nil-metadata-accessors\"},\"name\":\"my-map\"},\"stringData\":{\"foo\":\"bar\"}}" - src := argoappv1.ApplicationSource{Path: "./testdata/nil-metadata-accessors", Directory: &argoappv1.ApplicationSourceDirectory{Recurse: true}} - q := apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &src, AppLabelKey: "test", AppName: "nil-metadata-accessors", TrackingMethod: "annotation+label"} + src := v1alpha1.ApplicationSource{Path: "./testdata/nil-metadata-accessors", Directory: &v1alpha1.ApplicationSourceDirectory{Recurse: true}} + q := apiclient.ManifestRequest{Repo: &v1alpha1.Repository{}, ApplicationSource: &src, AppLabelKey: "test", AppName: "nil-metadata-accessors", TrackingMethod: "annotation+label"} res, err := service.GenerateManifest(context.Background(), &q) require.NoError(t, err) assert.Len(t, res.Manifests, 1) @@ -706,13 +705,13 @@ func TestGenerateJsonnetManifestInDir(t *testing.T) { service := newService(t, ".") q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./testdata/jsonnet", - Directory: &argoappv1.ApplicationSourceDirectory{ - Jsonnet: argoappv1.ApplicationSourceJsonnet{ - ExtVars: []argoappv1.JsonnetVar{{Name: "extVarString", Value: "extVarString"}, {Name: "extVarCode", Value: "\"extVarCode\"", Code: true}}, - TLAs: []argoappv1.JsonnetVar{{Name: "tlaString", Value: "tlaString"}, {Name: "tlaCode", Value: "\"tlaCode\"", Code: true}}, + Directory: &v1alpha1.ApplicationSourceDirectory{ + Jsonnet: v1alpha1.ApplicationSourceJsonnet{ + ExtVars: []v1alpha1.JsonnetVar{{Name: "extVarString", Value: "extVarString"}, {Name: "extVarCode", Value: "\"extVarCode\"", Code: true}}, + TLAs: []v1alpha1.JsonnetVar{{Name: "tlaString", Value: "tlaString"}, {Name: "tlaCode", Value: "\"tlaCode\"", Code: true}}, Libs: []string{"testdata/jsonnet/vendor"}, }, }, @@ -729,13 +728,13 @@ func TestGenerateJsonnetManifestInRootDir(t *testing.T) { service := newService(t, "testdata/jsonnet-1") q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", - Directory: &argoappv1.ApplicationSourceDirectory{ - Jsonnet: argoappv1.ApplicationSourceJsonnet{ - ExtVars: []argoappv1.JsonnetVar{{Name: "extVarString", Value: "extVarString"}, {Name: "extVarCode", Value: "\"extVarCode\"", Code: true}}, - TLAs: []argoappv1.JsonnetVar{{Name: "tlaString", Value: "tlaString"}, {Name: "tlaCode", Value: "\"tlaCode\"", Code: true}}, + Directory: &v1alpha1.ApplicationSourceDirectory{ + Jsonnet: v1alpha1.ApplicationSourceJsonnet{ + ExtVars: []v1alpha1.JsonnetVar{{Name: "extVarString", Value: "extVarString"}, {Name: "extVarCode", Value: "\"extVarCode\"", Code: true}}, + TLAs: []v1alpha1.JsonnetVar{{Name: "tlaString", Value: "tlaString"}, {Name: "tlaCode", Value: "\"tlaCode\"", Code: true}}, Libs: []string{"."}, }, }, @@ -752,11 +751,11 @@ func TestGenerateJsonnetLibOutside(t *testing.T) { service := newService(t, ".") q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./testdata/jsonnet", - Directory: &argoappv1.ApplicationSourceDirectory{ - Jsonnet: argoappv1.ApplicationSourceJsonnet{ + Directory: &v1alpha1.ApplicationSourceDirectory{ + Jsonnet: v1alpha1.ApplicationSourceJsonnet{ Libs: []string{"../../../testdata/jsonnet/vendor"}, }, }, @@ -835,9 +834,9 @@ func TestManifestGenErrorCacheByNumRequests(t *testing.T) { fmt.Printf("%d )-------------------------------------------\n", invocationCount) manifestRequest := &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./testdata/invalid-helm", }, } @@ -926,9 +925,9 @@ func TestManifestGenErrorCacheFileContentsChange(t *testing.T) { } res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", }, ProjectName: "something", @@ -984,9 +983,9 @@ func TestManifestGenErrorCacheByMinutesElapsed(t *testing.T) { // 1) Put the cache into the failure state for x := 0; x < 2; x++ { res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./testdata/invalid-helm", }, }) @@ -1002,9 +1001,9 @@ func TestManifestGenErrorCacheByMinutesElapsed(t *testing.T) { // 2) Jump forward X-1 minutes in time, where X is the expiration boundary currentTime = currentTime.Add(time.Duration(tt.PauseGenerationOnFailureForMinutes-1) * time.Minute) res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./testdata/invalid-helm", }, }) @@ -1017,9 +1016,9 @@ func TestManifestGenErrorCacheByMinutesElapsed(t *testing.T) { currentTime = currentTime.Add(2 * time.Minute) res, err = service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./testdata/invalid-helm", }, }) @@ -1044,9 +1043,9 @@ func TestManifestGenErrorCacheRespectsNoCache(t *testing.T) { // 1) Put the cache into the failure state for x := 0; x < 2; x++ { res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./testdata/invalid-helm", }, }) @@ -1061,9 +1060,9 @@ func TestManifestGenErrorCacheRespectsNoCache(t *testing.T) { // 2) Call generateManifest with NoCache enabled res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./testdata/invalid-helm", }, NoCache: true, @@ -1075,9 +1074,9 @@ func TestManifestGenErrorCacheRespectsNoCache(t *testing.T) { // 4) Call generateManifest res, err = service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./testdata/invalid-helm", }, }) @@ -1091,11 +1090,11 @@ func TestGenerateHelmWithValues(t *testing.T) { service := newService(t, "../../util/helm/testdata/redis") res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"values-production.yaml"}, ValuesObject: &runtime.RawExtension{Raw: []byte(`cluster: {slaveCount: 2}`)}, }, @@ -1128,11 +1127,11 @@ func TestHelmWithMissingValueFiles(t *testing.T) { missingValuesFile := "values-prod-overrides.yaml" req := &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"values-production.yaml", missingValuesFile}, }, }, @@ -1154,11 +1153,11 @@ func TestGenerateHelmWithEnvVars(t *testing.T) { service := newService(t, "../../util/helm/testdata/redis") res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "production", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"values-$ARGOCD_APP_NAME.yaml"}, }, }, @@ -1190,11 +1189,11 @@ func TestGenerateHelmWithEnvVars(t *testing.T) { func TestGenerateHelmWithValuesDirectoryTraversal(t *testing.T) { service := newService(t, "../../util/helm/testdata") _, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./redis", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"../minio/values.yaml"}, ValuesObject: &runtime.RawExtension{Raw: []byte(`cluster: {slaveCount: 2}`)}, }, @@ -1207,9 +1206,9 @@ func TestGenerateHelmWithValuesDirectoryTraversal(t *testing.T) { // Test the case where the path is "." service = newService(t, "./testdata") _, err = service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./my-chart", }, ProjectName: "something", @@ -1220,8 +1219,8 @@ func TestGenerateHelmWithValuesDirectoryTraversal(t *testing.T) { func TestChartRepoWithOutOfBoundsSymlink(t *testing.T) { service := newService(t, ".") - source := &argoappv1.ApplicationSource{Chart: "out-of-bounds-chart", TargetRevision: ">= 1.0.0"} - request := &apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: source, NoCache: true} + source := &v1alpha1.ApplicationSource{Chart: "out-of-bounds-chart", TargetRevision: ">= 1.0.0"} + request := &apiclient.ManifestRequest{Repo: &v1alpha1.Repository{}, ApplicationSource: source, NoCache: true} _, err := service.GenerateManifest(context.Background(), request) assert.ErrorContains(t, err, "chart contains out-of-bounds symlinks") } @@ -1230,15 +1229,15 @@ func TestChartRepoWithOutOfBoundsSymlink(t *testing.T) { // (`~/go/src/github.com/argoproj/argo-cd/reposerver/repository`), so it is allowed func TestHelmManifestFromChartRepoWithValueFile(t *testing.T) { service := newService(t, ".") - source := &argoappv1.ApplicationSource{ + source := &v1alpha1.ApplicationSource{ Chart: "my-chart", TargetRevision: ">= 1.0.0", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"./my-chart-values.yaml"}, }, } request := &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, ApplicationSource: source, NoCache: true, ProjectName: "something", @@ -1261,14 +1260,14 @@ func TestHelmManifestFromChartRepoWithValueFile(t *testing.T) { // (`~/go/src/github.com/argoproj/argo-cd/reposerver/repository`), so it is not allowed func TestHelmManifestFromChartRepoWithValueFileOutsideRepo(t *testing.T) { service := newService(t, ".") - source := &argoappv1.ApplicationSource{ + source := &v1alpha1.ApplicationSource{ Chart: "my-chart", TargetRevision: ">= 1.0.0", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"../my-chart-2/my-chart-2-values.yaml"}, }, } - request := &apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: source, NoCache: true} + request := &apiclient.ManifestRequest{Repo: &v1alpha1.Repository{}, ApplicationSource: source, NoCache: true} _, err := service.GenerateManifest(context.Background(), request) require.Error(t, err) } @@ -1276,15 +1275,15 @@ func TestHelmManifestFromChartRepoWithValueFileOutsideRepo(t *testing.T) { func TestHelmManifestFromChartRepoWithValueFileLinks(t *testing.T) { t.Run("Valid symlink", func(t *testing.T) { service := newService(t, ".") - source := &argoappv1.ApplicationSource{ + source := &v1alpha1.ApplicationSource{ Chart: "my-chart", TargetRevision: ">= 1.0.0", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"my-chart-link.yaml"}, }, } request := &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: source, NoCache: true, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: source, NoCache: true, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } _, err := service.GenerateManifest(context.Background(), request) @@ -1296,18 +1295,18 @@ func TestGenerateHelmWithURL(t *testing.T) { service := newService(t, "../../util/helm/testdata/redis") _, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"https://raw.githubusercontent.com/argoproj/argocd-example-apps/master/helm-guestbook/values.yaml"}, ValuesObject: &runtime.RawExtension{Raw: []byte(`cluster: {slaveCount: 2}`)}, }, }, ProjectName: "something", ProjectSourceRepos: []string{"*"}, - HelmOptions: &argoappv1.HelmOptions{ValuesFileSchemes: []string{"https"}}, + HelmOptions: &v1alpha1.HelmOptions{ValuesFileSchemes: []string{"https"}}, }) require.NoError(t, err) } @@ -1318,11 +1317,11 @@ func TestGenerateHelmWithValuesDirectoryTraversalOutsideRepo(t *testing.T) { t.Run("Values file with relative path pointing outside repo root", func(t *testing.T) { service := newService(t, "../../util/helm/testdata/redis") _, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"../minio/values.yaml"}, ValuesObject: &runtime.RawExtension{Raw: []byte(`cluster: {slaveCount: 2}`)}, }, @@ -1336,11 +1335,11 @@ func TestGenerateHelmWithValuesDirectoryTraversalOutsideRepo(t *testing.T) { t.Run("Values file with relative path pointing inside repo root", func(t *testing.T) { service := newService(t, "./testdata") _, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./my-chart", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"../my-chart/my-chart-values.yaml"}, ValuesObject: &runtime.RawExtension{Raw: []byte(`cluster: {slaveCount: 2}`)}, }, @@ -1354,11 +1353,11 @@ func TestGenerateHelmWithValuesDirectoryTraversalOutsideRepo(t *testing.T) { t.Run("Values file with absolute path stays within repo root", func(t *testing.T) { service := newService(t, "./testdata") _, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./my-chart", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"/my-chart/my-chart-values.yaml"}, ValuesObject: &runtime.RawExtension{Raw: []byte(`cluster: {slaveCount: 2}`)}, }, @@ -1372,11 +1371,11 @@ func TestGenerateHelmWithValuesDirectoryTraversalOutsideRepo(t *testing.T) { t.Run("Values file with absolute path using back-references outside repo root", func(t *testing.T) { service := newService(t, "./testdata") _, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./my-chart", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"/../../../my-chart-values.yaml"}, ValuesObject: &runtime.RawExtension{Raw: []byte(`cluster: {slaveCount: 2}`)}, }, @@ -1390,11 +1389,11 @@ func TestGenerateHelmWithValuesDirectoryTraversalOutsideRepo(t *testing.T) { t.Run("Remote values file from forbidden protocol", func(t *testing.T) { service := newService(t, "./testdata") _, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./my-chart", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"file://../../../../my-chart-values.yaml"}, ValuesObject: &runtime.RawExtension{Raw: []byte(`cluster: {slaveCount: 2}`)}, }, @@ -1408,15 +1407,15 @@ func TestGenerateHelmWithValuesDirectoryTraversalOutsideRepo(t *testing.T) { t.Run("Remote values file from custom allowed protocol", func(t *testing.T) { service := newService(t, "./testdata") _, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./my-chart", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"s3://my-bucket/my-chart-values.yaml"}, }, }, - HelmOptions: &argoappv1.HelmOptions{ValuesFileSchemes: []string{"s3"}}, + HelmOptions: &v1alpha1.HelmOptions{ValuesFileSchemes: []string{"s3"}}, ProjectName: "something", ProjectSourceRepos: []string{"*"}, }) @@ -1443,14 +1442,14 @@ func TestGenerateHelmWithAbsoluteFileParameter(t *testing.T) { }() _, err = service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./util/helm/testdata/redis", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"values-production.yaml"}, ValuesObject: &runtime.RawExtension{Raw: []byte(`cluster: {slaveCount: 2}`)}, - FileParameters: []argoappv1.HelmFileParameter{{ + FileParameters: []v1alpha1.HelmFileParameter{{ Name: "passwordContent", Path: externalSecretPath, }}, @@ -1470,15 +1469,15 @@ func TestGenerateHelmWithFileParameter(t *testing.T) { service := newService(t, "../../util/helm/testdata") res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, AppName: "test", - ApplicationSource: &argoappv1.ApplicationSource{ + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "./redis", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"values-production.yaml"}, Values: `cluster: {slaveCount: 10}`, ValuesObject: &runtime.RawExtension{Raw: []byte(`cluster: {slaveCount: 2}`)}, - FileParameters: []argoappv1.HelmFileParameter{{ + FileParameters: []v1alpha1.HelmFileParameter{{ Name: "passwordContent", Path: "../external/external-secret.txt", }}, @@ -1496,8 +1495,8 @@ func TestGenerateNullList(t *testing.T) { t.Run("null list", func(t *testing.T) { res1, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{Path: "./testdata/null-list"}, + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{Path: "./testdata/null-list"}, NoCache: true, ProjectName: "something", ProjectSourceRepos: []string{"*"}, @@ -1509,8 +1508,8 @@ func TestGenerateNullList(t *testing.T) { t.Run("empty list", func(t *testing.T) { res1, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{Path: "./testdata/empty-list"}, + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{Path: "./testdata/empty-list"}, NoCache: true, ProjectName: "something", ProjectSourceRepos: []string{"*"}, @@ -1522,8 +1521,8 @@ func TestGenerateNullList(t *testing.T) { t.Run("weird list", func(t *testing.T) { res1, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{Path: "./testdata/weird-list"}, + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{Path: "./testdata/weird-list"}, NoCache: true, ProjectName: "something", ProjectSourceRepos: []string{"*"}, @@ -1534,23 +1533,23 @@ func TestGenerateNullList(t *testing.T) { } func TestIdentifyAppSourceTypeByAppDirWithKustomizations(t *testing.T) { - sourceType, err := GetAppSourceType(context.Background(), &argoappv1.ApplicationSource{}, "./testdata/kustomization_yaml", "./testdata", "testapp", map[string]bool{}, []string{}, []string{}) + sourceType, err := GetAppSourceType(context.Background(), &v1alpha1.ApplicationSource{}, "./testdata/kustomization_yaml", "./testdata", "testapp", map[string]bool{}, []string{}, []string{}) require.NoError(t, err) - assert.Equal(t, argoappv1.ApplicationSourceTypeKustomize, sourceType) + assert.Equal(t, v1alpha1.ApplicationSourceTypeKustomize, sourceType) - sourceType, err = GetAppSourceType(context.Background(), &argoappv1.ApplicationSource{}, "./testdata/kustomization_yml", "./testdata", "testapp", map[string]bool{}, []string{}, []string{}) + sourceType, err = GetAppSourceType(context.Background(), &v1alpha1.ApplicationSource{}, "./testdata/kustomization_yml", "./testdata", "testapp", map[string]bool{}, []string{}, []string{}) require.NoError(t, err) - assert.Equal(t, argoappv1.ApplicationSourceTypeKustomize, sourceType) + assert.Equal(t, v1alpha1.ApplicationSourceTypeKustomize, sourceType) - sourceType, err = GetAppSourceType(context.Background(), &argoappv1.ApplicationSource{}, "./testdata/Kustomization", "./testdata", "testapp", map[string]bool{}, []string{}, []string{}) + sourceType, err = GetAppSourceType(context.Background(), &v1alpha1.ApplicationSource{}, "./testdata/Kustomization", "./testdata", "testapp", map[string]bool{}, []string{}, []string{}) require.NoError(t, err) - assert.Equal(t, argoappv1.ApplicationSourceTypeKustomize, sourceType) + assert.Equal(t, v1alpha1.ApplicationSourceTypeKustomize, sourceType) } func TestGenerateFromUTF16(t *testing.T) { q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{}, + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{}, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } @@ -1562,7 +1561,7 @@ func TestGenerateFromUTF16(t *testing.T) { func TestListApps(t *testing.T) { service := newService(t, "./testdata") - res, err := service.ListApps(context.Background(), &apiclient.ListAppsRequest{Repo: &argoappv1.Repository{}}) + res, err := service.ListApps(context.Background(), &apiclient.ListAppsRequest{Repo: &v1alpha1.Repository{}}) require.NoError(t, err) expectedApps := map[string]string{ @@ -1594,8 +1593,8 @@ func TestGetAppDetailsHelm(t *testing.T) { service := newService(t, "../../util/helm/testdata/dependency") res, err := service.GetAppDetails(context.Background(), &apiclient.RepoServerAppDetailsQuery{ - Repo: &argoappv1.Repository{}, - Source: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + Source: &v1alpha1.ApplicationSource{ Path: ".", }, }) @@ -1611,8 +1610,8 @@ func TestGetAppDetailsHelmUsesCache(t *testing.T) { service := newService(t, "../../util/helm/testdata/dependency") res, err := service.GetAppDetails(context.Background(), &apiclient.RepoServerAppDetailsQuery{ - Repo: &argoappv1.Repository{}, - Source: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + Source: &v1alpha1.ApplicationSource{ Path: ".", }, }) @@ -1628,8 +1627,8 @@ func TestGetAppDetailsHelm_WithNoValuesFile(t *testing.T) { service := newService(t, "../../util/helm/testdata/api-versions") res, err := service.GetAppDetails(context.Background(), &apiclient.RepoServerAppDetailsQuery{ - Repo: &argoappv1.Repository{}, - Source: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + Source: &v1alpha1.ApplicationSource{ Path: ".", }, }) @@ -1646,8 +1645,8 @@ func TestGetAppDetailsKustomize(t *testing.T) { service := newService(t, "../../util/kustomize/testdata/kustomization_yaml") res, err := service.GetAppDetails(context.Background(), &apiclient.RepoServerAppDetailsQuery{ - Repo: &argoappv1.Repository{}, - Source: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + Source: &v1alpha1.ApplicationSource{ Path: ".", }, }) @@ -1661,7 +1660,7 @@ func TestGetAppDetailsKustomize(t *testing.T) { func TestGetHelmCharts(t *testing.T) { service := newService(t, "../..") - res, err := service.GetHelmCharts(context.Background(), &apiclient.HelmChartsRequest{Repo: &argoappv1.Repository{}}) + res, err := service.GetHelmCharts(context.Background(), &apiclient.HelmChartsRequest{Repo: &v1alpha1.Repository{}}) // fix flakiness sort.Slice(res.Items, func(i, j int) bool { @@ -1692,7 +1691,7 @@ func TestGetRevisionMetadata(t *testing.T) { }, nil) res, err := service.GetRevisionMetadata(context.Background(), &apiclient.RepoServerRevisionMetadataRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, Revision: "c0b400fc458875d925171398f9ba9eabd5529923", CheckSignature: true, }) @@ -1706,7 +1705,7 @@ func TestGetRevisionMetadata(t *testing.T) { // Check for truncated revision value res, err = service.GetRevisionMetadata(context.Background(), &apiclient.RepoServerRevisionMetadataRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, Revision: "c0b400f", CheckSignature: true, }) @@ -1720,7 +1719,7 @@ func TestGetRevisionMetadata(t *testing.T) { // Cache hit - signature info should not be in result res, err = service.GetRevisionMetadata(context.Background(), &apiclient.RepoServerRevisionMetadataRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, Revision: "c0b400fc458875d925171398f9ba9eabd5529923", CheckSignature: false, }) @@ -1729,7 +1728,7 @@ func TestGetRevisionMetadata(t *testing.T) { // Enforce cache miss - signature info should not be in result res, err = service.GetRevisionMetadata(context.Background(), &apiclient.RepoServerRevisionMetadataRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, Revision: "da52afd3b2df1ec49470603d8bbb46954dab1091", CheckSignature: false, }) @@ -1738,7 +1737,7 @@ func TestGetRevisionMetadata(t *testing.T) { // Cache hit on previous entry that did not have signature info res, err = service.GetRevisionMetadata(context.Background(), &apiclient.RepoServerRevisionMetadataRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, Revision: "da52afd3b2df1ec49470603d8bbb46954dab1091", CheckSignature: true, }) @@ -1751,9 +1750,9 @@ func TestGetSignatureVerificationResult(t *testing.T) { { service := newServiceWithSignature(t, "../../manifests/base") - src := argoappv1.ApplicationSource{Path: "."} + src := v1alpha1.ApplicationSource{Path: "."} q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, ApplicationSource: &src, VerifySignature: true, ProjectName: "something", @@ -1768,9 +1767,9 @@ func TestGetSignatureVerificationResult(t *testing.T) { { service := newServiceWithSignature(t, "../../manifests/base") - src := argoappv1.ApplicationSource{Path: "."} + src := v1alpha1.ApplicationSource{Path: "."} q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: &src, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: &src, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } @@ -1782,9 +1781,9 @@ func TestGetSignatureVerificationResult(t *testing.T) { { service := newService(t, "../../manifests/base") - src := argoappv1.ApplicationSource{Path: "."} + src := v1alpha1.ApplicationSource{Path: "."} q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: &src, VerifySignature: true, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: &src, VerifySignature: true, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } @@ -1796,9 +1795,9 @@ func TestGetSignatureVerificationResult(t *testing.T) { { service := newService(t, "../../manifests/base") - src := argoappv1.ApplicationSource{Path: "."} + src := v1alpha1.ApplicationSource{Path: "."} q := apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, ApplicationSource: &src, VerifySignature: true, ProjectName: "something", + Repo: &v1alpha1.Repository{}, ApplicationSource: &src, VerifySignature: true, ProjectName: "something", ProjectSourceRepos: []string{"*"}, } @@ -1809,20 +1808,20 @@ func TestGetSignatureVerificationResult(t *testing.T) { } func Test_newEnv(t *testing.T) { - assert.Equal(t, &argoappv1.Env{ - &argoappv1.EnvEntry{Name: "ARGOCD_APP_NAME", Value: "my-app-name"}, - &argoappv1.EnvEntry{Name: "ARGOCD_APP_NAMESPACE", Value: "my-namespace"}, - &argoappv1.EnvEntry{Name: "ARGOCD_APP_REVISION", Value: "my-revision"}, - &argoappv1.EnvEntry{Name: "ARGOCD_APP_REVISION_SHORT", Value: "my-revi"}, - &argoappv1.EnvEntry{Name: "ARGOCD_APP_REVISION_SHORT_8", Value: "my-revis"}, - &argoappv1.EnvEntry{Name: "ARGOCD_APP_SOURCE_REPO_URL", Value: "https://github.com/my-org/my-repo"}, - &argoappv1.EnvEntry{Name: "ARGOCD_APP_SOURCE_PATH", Value: "my-path"}, - &argoappv1.EnvEntry{Name: "ARGOCD_APP_SOURCE_TARGET_REVISION", Value: "my-target-revision"}, + assert.Equal(t, &v1alpha1.Env{ + &v1alpha1.EnvEntry{Name: "ARGOCD_APP_NAME", Value: "my-app-name"}, + &v1alpha1.EnvEntry{Name: "ARGOCD_APP_NAMESPACE", Value: "my-namespace"}, + &v1alpha1.EnvEntry{Name: "ARGOCD_APP_REVISION", Value: "my-revision"}, + &v1alpha1.EnvEntry{Name: "ARGOCD_APP_REVISION_SHORT", Value: "my-revi"}, + &v1alpha1.EnvEntry{Name: "ARGOCD_APP_REVISION_SHORT_8", Value: "my-revis"}, + &v1alpha1.EnvEntry{Name: "ARGOCD_APP_SOURCE_REPO_URL", Value: "https://github.com/my-org/my-repo"}, + &v1alpha1.EnvEntry{Name: "ARGOCD_APP_SOURCE_PATH", Value: "my-path"}, + &v1alpha1.EnvEntry{Name: "ARGOCD_APP_SOURCE_TARGET_REVISION", Value: "my-target-revision"}, }, newEnv(&apiclient.ManifestRequest{ AppName: "my-app-name", Namespace: "my-namespace", - Repo: &argoappv1.Repository{Repo: "https://github.com/my-org/my-repo"}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{Repo: "https://github.com/my-org/my-repo"}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "my-path", TargetRevision: "my-target-revision", }, @@ -1833,11 +1832,11 @@ func TestService_newHelmClientResolveRevision(t *testing.T) { service := newService(t, ".") t.Run("EmptyRevision", func(t *testing.T) { - _, _, err := service.newHelmClientResolveRevision(&argoappv1.Repository{}, "", "", true) + _, _, err := service.newHelmClientResolveRevision(&v1alpha1.Repository{}, "", "", true) assert.EqualError(t, err, "invalid revision '': improper constraint: ") }) t.Run("InvalidRevision", func(t *testing.T) { - _, _, err := service.newHelmClientResolveRevision(&argoappv1.Repository{}, "???", "", true) + _, _, err := service.newHelmClientResolveRevision(&v1alpha1.Repository{}, "???", "", true) assert.EqualError(t, err, "invalid revision '???': improper constraint: ???", true) }) } @@ -1848,8 +1847,8 @@ func TestGetAppDetailsWithAppParameterFile(t *testing.T) { runWithTempTestdata(t, "multi", func(t *testing.T, path string) { t.Helper() details, err := service.GetAppDetails(context.Background(), &apiclient.RepoServerAppDetailsQuery{ - Repo: &argoappv1.Repository{}, - Source: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + Source: &v1alpha1.ApplicationSource{ Path: path, }, }) @@ -1862,8 +1861,8 @@ func TestGetAppDetailsWithAppParameterFile(t *testing.T) { runWithTempTestdata(t, "single-global", func(t *testing.T, path string) { t.Helper() details, err := service.GetAppDetails(context.Background(), &apiclient.RepoServerAppDetailsQuery{ - Repo: &argoappv1.Repository{}, - Source: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + Source: &v1alpha1.ApplicationSource{ Path: path, }, AppName: "testapp", @@ -1877,8 +1876,8 @@ func TestGetAppDetailsWithAppParameterFile(t *testing.T) { runWithTempTestdata(t, "single-app-only", func(t *testing.T, path string) { t.Helper() details, err := service.GetAppDetails(context.Background(), &apiclient.RepoServerAppDetailsQuery{ - Repo: &argoappv1.Repository{}, - Source: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + Source: &v1alpha1.ApplicationSource{ Path: path, }, AppName: "testapp", @@ -1892,8 +1891,8 @@ func TestGetAppDetailsWithAppParameterFile(t *testing.T) { runWithTempTestdata(t, "multi", func(t *testing.T, path string) { t.Helper() details, err := service.GetAppDetails(context.Background(), &apiclient.RepoServerAppDetailsQuery{ - Repo: &argoappv1.Repository{}, - Source: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + Source: &v1alpha1.ApplicationSource{ Path: path, }, AppName: "testapp", @@ -1907,8 +1906,8 @@ func TestGetAppDetailsWithAppParameterFile(t *testing.T) { runWithTempTestdata(t, "multi", func(t *testing.T, path string) { t.Helper() details, err := service.GetAppDetails(context.Background(), &apiclient.RepoServerAppDetailsQuery{ - Repo: &argoappv1.Repository{}, - Source: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + Source: &v1alpha1.ApplicationSource{ Path: path, }, AppName: "unmergeable", @@ -1922,8 +1921,8 @@ func TestGetAppDetailsWithAppParameterFile(t *testing.T) { runWithTempTestdata(t, "multi", func(t *testing.T, path string) { t.Helper() _, err := service.GetAppDetails(context.Background(), &apiclient.RepoServerAppDetailsQuery{ - Repo: &argoappv1.Repository{}, - Source: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + Source: &v1alpha1.ApplicationSource{ Path: path, }, AppName: "broken", @@ -1965,8 +1964,8 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { t.Helper() service := newService(t, ".") manifests, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: path, }, ProjectName: "something", @@ -1995,8 +1994,8 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { t.Helper() service := newService(t, ".") manifests, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: path, }, ProjectName: "something", @@ -2025,8 +2024,8 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { runWithTempTestdata(t, "single-app-only", func(t *testing.T, path string) { t.Helper() manifests, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: path, }, AppName: "testapp", @@ -2056,8 +2055,8 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { runWithTempTestdata(t, "single-app-only", func(t *testing.T, path string) { t.Helper() manifests, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: "", Chart: "", Ref: "test", @@ -2078,8 +2077,8 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { runWithTempTestdata(t, "single-app-only", func(t *testing.T, path string) { t.Helper() manifests, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: path, }, AppName: "testapp2", @@ -2108,12 +2107,12 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { service := newService(t, ".") runWithTempTestdata(t, "single-global", func(t *testing.T, path string) { t.Helper() - source := &argoappv1.ApplicationSource{ + source := &v1alpha1.ApplicationSource{ Path: path, } sourceCopy := source.DeepCopy() // make a copy in case GenerateManifest mutates it. _, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, + Repo: &v1alpha1.Repository{}, ApplicationSource: sourceCopy, AppName: "test", ProjectName: "something", @@ -2124,7 +2123,7 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { // Try to pull from the cache with a `source` that does not include any overrides. Overrides should not be // part of the cache key, because you can't get the overrides without a repo operation. And avoiding repo // operations is the point of the cache. - err = service.cache.GetManifests(mock.Anything, source, argoappv1.RefTargetRevisionMapping{}, &argoappv1.ClusterInfo{}, "", "", "", "test", res, nil, "") + err = service.cache.GetManifests(mock.Anything, source, v1alpha1.RefTargetRevisionMapping{}, &v1alpha1.ClusterInfo{}, "", "", "", "test", res, nil, "") require.NoError(t, err) }) }) @@ -2147,8 +2146,8 @@ func TestGenerateManifestWithAnnotatedAndRegularGitTagHashes(t *testing.T) { name: "Case: Git tag hash matches latest commit SHA (regular tag)", ctx: context.Background(), manifestRequest: &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ TargetRevision: regularGitTagHash, }, NoCache: true, @@ -2163,8 +2162,8 @@ func TestGenerateManifestWithAnnotatedAndRegularGitTagHashes(t *testing.T) { name: "Case: Git tag hash does not match latest commit SHA (annotated tag)", ctx: context.Background(), manifestRequest: &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ TargetRevision: annotatedGitTaghash, }, NoCache: true, @@ -2179,8 +2178,8 @@ func TestGenerateManifestWithAnnotatedAndRegularGitTagHashes(t *testing.T) { name: "Case: Git tag hash is invalid", ctx: context.Background(), manifestRequest: &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ TargetRevision: invalidGitTaghash, }, NoCache: true, @@ -2209,21 +2208,21 @@ func TestGenerateManifestWithAnnotatedTagsAndMultiSourceApp(t *testing.T) { service := newServiceWithCommitSHA(t, ".", annotatedGitTaghash) - refSources := map[string]*argoappv1.RefTarget{} + refSources := map[string]*v1alpha1.RefTarget{} - refSources["$global"] = &argoappv1.RefTarget{ + refSources["$global"] = &v1alpha1.RefTarget{ TargetRevision: annotatedGitTaghash, } - refSources["$default"] = &argoappv1.RefTarget{ + refSources["$default"] = &v1alpha1.RefTarget{ TargetRevision: annotatedGitTaghash, } manifestRequest := &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ TargetRevision: annotatedGitTaghash, - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"$global/values.yaml", "$default/secrets.yaml"}, }, }, @@ -2245,12 +2244,12 @@ func TestGenerateMultiSourceHelmWithFileParameter(t *testing.T) { testCases := []struct { name string - refSources map[string]*argoappv1.RefTarget + refSources map[string]*v1alpha1.RefTarget expectedContent string expectedErr bool }{{ name: "Successfully resolve multi-source ref for helm set-file", - refSources: map[string]*argoappv1.RefTarget{ + refSources: map[string]*v1alpha1.RefTarget{ "$global": { TargetRevision: "HEAD", }, @@ -2259,7 +2258,7 @@ func TestGenerateMultiSourceHelmWithFileParameter(t *testing.T) { expectedErr: false, }, { name: "Failed to resolve multi-source ref for helm set-file", - refSources: map[string]*argoappv1.RefTarget{}, + refSources: map[string]*v1alpha1.RefTarget{}, expectedContent: "DOES-NOT-EXIST", expectedErr: true, }} @@ -2268,14 +2267,14 @@ func TestGenerateMultiSourceHelmWithFileParameter(t *testing.T) { tc := testCases[i] t.Run(tc.name, func(t *testing.T) { manifestRequest := &apiclient.ManifestRequest{ - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Ref: "$global", Path: "./redis", TargetRevision: "HEAD", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValueFiles: []string{"$global/redis/values-production.yaml"}, - FileParameters: []argoappv1.HelmFileParameter{{ + FileParameters: []v1alpha1.HelmFileParameter{{ Name: "passwordContent", Path: "$global/external/external-secret.txt", }}, @@ -2337,7 +2336,7 @@ func TestFindResources(t *testing.T) { for i := range testCases { tc := testCases[i] t.Run(tc.name, func(t *testing.T) { - objs, err := findManifests(&log.Entry{}, "testdata/app-include-exclude", ".", nil, argoappv1.ApplicationSourceDirectory{ + objs, err := findManifests(&log.Entry{}, "testdata/app-include-exclude", ".", nil, v1alpha1.ApplicationSourceDirectory{ Recurse: true, Include: tc.include, Exclude: tc.exclude, @@ -2353,7 +2352,7 @@ func TestFindResources(t *testing.T) { } func TestFindManifests_Exclude(t *testing.T) { - objs, err := findManifests(&log.Entry{}, "testdata/app-include-exclude", ".", nil, argoappv1.ApplicationSourceDirectory{ + objs, err := findManifests(&log.Entry{}, "testdata/app-include-exclude", ".", nil, v1alpha1.ApplicationSourceDirectory{ Recurse: true, Exclude: "subdir/deploymentSub.yaml", }, map[string]bool{}, resource.MustParse("0")) @@ -2365,7 +2364,7 @@ func TestFindManifests_Exclude(t *testing.T) { } func TestFindManifests_Exclude_NothingMatches(t *testing.T) { - objs, err := findManifests(&log.Entry{}, "testdata/app-include-exclude", ".", nil, argoappv1.ApplicationSourceDirectory{ + objs, err := findManifests(&log.Entry{}, "testdata/app-include-exclude", ".", nil, v1alpha1.ApplicationSourceDirectory{ Recurse: true, Exclude: "nothing.yaml", }, map[string]bool{}, resource.MustParse("0")) @@ -2695,7 +2694,7 @@ func Test_getPotentiallyValidManifests(t *testing.T) { func Test_findManifests(t *testing.T) { logCtx := log.WithField("test", "test") - noRecurse := argoappv1.ApplicationSourceDirectory{Recurse: false} + noRecurse := v1alpha1.ApplicationSourceDirectory{Recurse: false} t.Run("unreadable file throws error", func(t *testing.T) { appDir := t.TempDir() @@ -2723,7 +2722,7 @@ func Test_findManifests(t *testing.T) { }) t.Run("recursion when recursion is enabled", func(t *testing.T) { - recurse := argoappv1.ApplicationSourceDirectory{Recurse: true} + recurse := v1alpha1.ApplicationSourceDirectory{Recurse: true} manifests, err := findManifests(logCtx, "./testdata/recurse", "./testdata/recurse", nil, recurse, nil, resource.MustParse("0")) assert.Len(t, manifests, 4) require.NoError(t, err) @@ -2853,7 +2852,7 @@ func Test_findManifests(t *testing.T) { func TestTestRepoOCI(t *testing.T) { service := newService(t, ".") _, err := service.TestRepository(context.Background(), &apiclient.TestRepositoryRequest{ - Repo: &argoappv1.Repository{ + Repo: &v1alpha1.Repository{ Repo: "https://demo.goharbor.io", Type: "helm", EnableOCI: true, @@ -2875,8 +2874,8 @@ func Test_getHelmDependencyRepos(t *testing.T) { func TestResolveRevision(t *testing.T) { service := newService(t, ".") - repo := &argoappv1.Repository{Repo: "https://github.com/argoproj/argo-cd"} - app := &argoappv1.Application{Spec: argoappv1.ApplicationSpec{Source: &argoappv1.ApplicationSource{}}} + repo := &v1alpha1.Repository{Repo: "https://github.com/argoproj/argo-cd"} + app := &v1alpha1.Application{Spec: v1alpha1.ApplicationSpec{Source: &v1alpha1.ApplicationSource{}}} resolveRevisionResponse, err := service.ResolveRevision(context.Background(), &apiclient.ResolveRevisionRequest{ Repo: repo, App: app, @@ -2895,8 +2894,8 @@ func TestResolveRevision(t *testing.T) { func TestResolveRevisionNegativeScenarios(t *testing.T) { service := newService(t, ".") - repo := &argoappv1.Repository{Repo: "https://github.com/argoproj/argo-cd"} - app := &argoappv1.Application{Spec: argoappv1.ApplicationSpec{Source: &argoappv1.ApplicationSource{}}} + repo := &v1alpha1.Repository{Repo: "https://github.com/argoproj/argo-cd"} + app := &v1alpha1.Application{Spec: v1alpha1.ApplicationSpec{Source: &v1alpha1.ApplicationSource{}}} resolveRevisionResponse, err := service.ResolveRevision(context.Background(), &apiclient.ResolveRevisionRequest{ Repo: repo, App: app, @@ -3118,9 +3117,9 @@ func Test_populateHelmAppDetails(t *testing.T) { emptyTempPaths := io.NewRandomizedTempPaths(t.TempDir()) res := apiclient.RepoAppDetailsResponse{} q := apiclient.RepoServerAppDetailsQuery{ - Repo: &argoappv1.Repository{}, - Source: &argoappv1.ApplicationSource{ - Helm: &argoappv1.ApplicationSourceHelm{ValueFiles: []string{"exclude.yaml", "has-the-word-values.yaml"}}, + Repo: &v1alpha1.Repository{}, + Source: &v1alpha1.ApplicationSource{ + Helm: &v1alpha1.ApplicationSourceHelm{ValueFiles: []string{"exclude.yaml", "has-the-word-values.yaml"}}, }, } appPath, err := filepath.Abs("./testdata/values-files/") @@ -3135,7 +3134,7 @@ func Test_populateHelmAppDetails_values_symlinks(t *testing.T) { emptyTempPaths := io.NewRandomizedTempPaths(t.TempDir()) t.Run("inbound", func(t *testing.T) { res := apiclient.RepoAppDetailsResponse{} - q := apiclient.RepoServerAppDetailsQuery{Repo: &argoappv1.Repository{}, Source: &argoappv1.ApplicationSource{}} + q := apiclient.RepoServerAppDetailsQuery{Repo: &v1alpha1.Repository{}, Source: &v1alpha1.ApplicationSource{}} err := populateHelmAppDetails(&res, "./testdata/in-bounds-values-file-link/", "./testdata/in-bounds-values-file-link/", &q, emptyTempPaths) require.NoError(t, err) assert.NotEmpty(t, res.Helm.Values) @@ -3144,7 +3143,7 @@ func Test_populateHelmAppDetails_values_symlinks(t *testing.T) { t.Run("out of bounds", func(t *testing.T) { res := apiclient.RepoAppDetailsResponse{} - q := apiclient.RepoServerAppDetailsQuery{Repo: &argoappv1.Repository{}, Source: &argoappv1.ApplicationSource{}} + q := apiclient.RepoServerAppDetailsQuery{Repo: &v1alpha1.Repository{}, Source: &v1alpha1.ApplicationSource{}} err := populateHelmAppDetails(&res, "./testdata/out-of-bounds-values-file-link/", "./testdata/out-of-bounds-values-file-link/", &q, emptyTempPaths) require.NoError(t, err) assert.Empty(t, res.Helm.Values) @@ -3153,8 +3152,8 @@ func Test_populateHelmAppDetails_values_symlinks(t *testing.T) { } func TestGetHelmRepos_OCIDependenciesWithHelmRepo(t *testing.T) { - src := argoappv1.ApplicationSource{Path: "."} - q := apiclient.ManifestRequest{Repos: []*argoappv1.Repository{}, ApplicationSource: &src, HelmRepoCreds: []*argoappv1.RepoCreds{ + src := v1alpha1.ApplicationSource{Path: "."} + q := apiclient.ManifestRequest{Repos: []*v1alpha1.Repository{}, ApplicationSource: &src, HelmRepoCreds: []*v1alpha1.RepoCreds{ {URL: "example.com", Username: "test", Password: "test", EnableOCI: true}, }} @@ -3168,8 +3167,8 @@ func TestGetHelmRepos_OCIDependenciesWithHelmRepo(t *testing.T) { } func TestGetHelmRepos_OCIDependenciesWithRepo(t *testing.T) { - src := argoappv1.ApplicationSource{Path: "."} - q := apiclient.ManifestRequest{Repos: []*argoappv1.Repository{{Repo: "example.com", Username: "test", Password: "test", EnableOCI: true}}, ApplicationSource: &src, HelmRepoCreds: []*argoappv1.RepoCreds{}} + src := v1alpha1.ApplicationSource{Path: "."} + q := apiclient.ManifestRequest{Repos: []*v1alpha1.Repository{{Repo: "example.com", Username: "test", Password: "test", EnableOCI: true}}, ApplicationSource: &src, HelmRepoCreds: []*v1alpha1.RepoCreds{}} helmRepos, err := getHelmRepos("./testdata/oci-dependencies", q.Repos, q.HelmRepoCreds) require.NoError(t, err) @@ -3181,8 +3180,8 @@ func TestGetHelmRepos_OCIDependenciesWithRepo(t *testing.T) { } func TestGetHelmRepo_NamedRepos(t *testing.T) { - src := argoappv1.ApplicationSource{Path: "."} - q := apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &src, Repos: []*argoappv1.Repository{{ + src := v1alpha1.ApplicationSource{Path: "."} + q := apiclient.ManifestRequest{Repo: &v1alpha1.Repository{}, ApplicationSource: &src, Repos: []*v1alpha1.Repository{{ Name: "custom-repo", Repo: "https://example.com", Username: "test", @@ -3197,8 +3196,8 @@ func TestGetHelmRepo_NamedRepos(t *testing.T) { } func TestGetHelmRepo_NamedReposAlias(t *testing.T) { - src := argoappv1.ApplicationSource{Path: "."} - q := apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &src, Repos: []*argoappv1.Repository{{ + src := v1alpha1.ApplicationSource{Path: "."} + q := apiclient.ManifestRequest{Repo: &v1alpha1.Repository{}, ApplicationSource: &src, Repos: []*v1alpha1.Repository{{ Name: "custom-repo-alias", Repo: "https://example.com", Username: "test-alias", @@ -3222,25 +3221,25 @@ func Test_getResolvedValueFiles(t *testing.T) { testCases := []struct { name string rawPath string - env *argoappv1.Env - refSources map[string]*argoappv1.RefTarget + env *v1alpha1.Env + refSources map[string]*v1alpha1.RefTarget expectedPath string expectedErr bool }{ { name: "simple path", rawPath: "values.yaml", - env: &argoappv1.Env{}, - refSources: map[string]*argoappv1.RefTarget{}, + env: &v1alpha1.Env{}, + refSources: map[string]*v1alpha1.RefTarget{}, expectedPath: path.Join(tempDir, "main-repo", "values.yaml"), }, { name: "simple ref", rawPath: "$ref/values.yaml", - env: &argoappv1.Env{}, - refSources: map[string]*argoappv1.RefTarget{ + env: &v1alpha1.Env{}, + refSources: map[string]*v1alpha1.RefTarget{ "$ref": { - Repo: argoappv1.Repository{ + Repo: v1alpha1.Repository{ Repo: "https://github.com/org/repo1", }, }, @@ -3250,10 +3249,10 @@ func Test_getResolvedValueFiles(t *testing.T) { { name: "only ref", rawPath: "$ref", - env: &argoappv1.Env{}, - refSources: map[string]*argoappv1.RefTarget{ + env: &v1alpha1.Env{}, + refSources: map[string]*v1alpha1.RefTarget{ "$ref": { - Repo: argoappv1.Repository{ + Repo: v1alpha1.Repository{ Repo: "https://github.com/org/repo1", }, }, @@ -3263,10 +3262,10 @@ func Test_getResolvedValueFiles(t *testing.T) { { name: "attempted traversal", rawPath: "$ref/../values.yaml", - env: &argoappv1.Env{}, - refSources: map[string]*argoappv1.RefTarget{ + env: &v1alpha1.Env{}, + refSources: map[string]*v1alpha1.RefTarget{ "$ref": { - Repo: argoappv1.Repository{ + Repo: v1alpha1.Repository{ Repo: "https://github.com/org/repo1", }, }, @@ -3279,17 +3278,17 @@ func Test_getResolvedValueFiles(t *testing.T) { // ref targets were introduced. name: "ref doesn't exist", rawPath: "$ref/values.yaml", - env: &argoappv1.Env{}, - refSources: map[string]*argoappv1.RefTarget{}, + env: &v1alpha1.Env{}, + refSources: map[string]*v1alpha1.RefTarget{}, expectedPath: path.Join(tempDir, "main-repo", "values.yaml"), }, { name: "repo doesn't exist", rawPath: "$ref/values.yaml", - env: &argoappv1.Env{}, - refSources: map[string]*argoappv1.RefTarget{ + env: &v1alpha1.Env{}, + refSources: map[string]*v1alpha1.RefTarget{ "$ref": { - Repo: argoappv1.Repository{ + Repo: v1alpha1.Repository{ Repo: "https://github.com/org/repo2", }, }, @@ -3299,15 +3298,15 @@ func Test_getResolvedValueFiles(t *testing.T) { { name: "env var is resolved", rawPath: "$ref/$APP_PATH/values.yaml", - env: &argoappv1.Env{ - &argoappv1.EnvEntry{ + env: &v1alpha1.Env{ + &v1alpha1.EnvEntry{ Name: "APP_PATH", Value: "app-path", }, }, - refSources: map[string]*argoappv1.RefTarget{ + refSources: map[string]*v1alpha1.RefTarget{ "$ref": { - Repo: argoappv1.Repository{ + Repo: v1alpha1.Repository{ Repo: "https://github.com/org/repo1", }, }, @@ -3317,15 +3316,15 @@ func Test_getResolvedValueFiles(t *testing.T) { { name: "traversal in env var is blocked", rawPath: "$ref/$APP_PATH/values.yaml", - env: &argoappv1.Env{ - &argoappv1.EnvEntry{ + env: &v1alpha1.Env{ + &v1alpha1.EnvEntry{ Name: "APP_PATH", Value: "..", }, }, - refSources: map[string]*argoappv1.RefTarget{ + refSources: map[string]*v1alpha1.RefTarget{ "$ref": { - Repo: argoappv1.Repository{ + Repo: v1alpha1.Repository{ Repo: "https://github.com/org/repo1", }, }, @@ -3335,20 +3334,20 @@ func Test_getResolvedValueFiles(t *testing.T) { { name: "env var prefix", rawPath: "$APP_PATH/values.yaml", - env: &argoappv1.Env{ - &argoappv1.EnvEntry{ + env: &v1alpha1.Env{ + &v1alpha1.EnvEntry{ Name: "APP_PATH", Value: "app-path", }, }, - refSources: map[string]*argoappv1.RefTarget{}, + refSources: map[string]*v1alpha1.RefTarget{}, expectedPath: path.Join(tempDir, "main-repo", "app-path", "values.yaml"), }, { name: "unresolved env var", rawPath: "$APP_PATH/values.yaml", - env: &argoappv1.Env{}, - refSources: map[string]*argoappv1.RefTarget{}, + env: &v1alpha1.Env{}, + refSources: map[string]*v1alpha1.RefTarget{}, expectedPath: path.Join(tempDir, "main-repo", "values.yaml"), }, } @@ -3408,7 +3407,7 @@ func TestErrorGetGitDirectories(t *testing.T) { }()}, args: args{ ctx: context.TODO(), request: &apiclient.GitDirectoriesRequest{ - Repo: &argoappv1.Repository{Repo: "not-a-valid-url"}, + Repo: &v1alpha1.Repository{Repo: "not-a-valid-url"}, SubmoduleEnabled: false, Revision: "sadfsadf", }, @@ -3426,7 +3425,7 @@ func TestErrorGetGitDirectories(t *testing.T) { }()}, args: args{ ctx: context.TODO(), request: &apiclient.GitDirectoriesRequest{ - Repo: &argoappv1.Repository{Repo: "not-a-valid-url"}, + Repo: &v1alpha1.Repository{Repo: "not-a-valid-url"}, SubmoduleEnabled: false, Revision: "sadfsadf", VerifyCommit: true, @@ -3459,7 +3458,7 @@ func TestGetGitDirectories(t *testing.T) { paths.On("GetPathIfExists", mock.Anything).Return(root, nil) }, root) dirRequest := &apiclient.GitDirectoriesRequest{ - Repo: &argoappv1.Repository{Repo: "a-url.com"}, + Repo: &v1alpha1.Repository{Repo: "a-url.com"}, SubmoduleEnabled: false, Revision: "HEAD", } @@ -3493,7 +3492,7 @@ func TestGetGitDirectoriesWithHiddenDirSupported(t *testing.T) { }, root) s.initConstants.IncludeHiddenDirectories = true dirRequest := &apiclient.GitDirectoriesRequest{ - Repo: &argoappv1.Repository{Repo: "a-url.com"}, + Repo: &v1alpha1.Repository{Repo: "a-url.com"}, SubmoduleEnabled: false, Revision: "HEAD", } @@ -3550,7 +3549,7 @@ func TestErrorGetGitFiles(t *testing.T) { }()}, args: args{ ctx: context.TODO(), request: &apiclient.GitFilesRequest{ - Repo: &argoappv1.Repository{Repo: "not-a-valid-url"}, + Repo: &v1alpha1.Repository{Repo: "not-a-valid-url"}, SubmoduleEnabled: false, Revision: "sadfsadf", }, @@ -3587,7 +3586,7 @@ func TestGetGitFiles(t *testing.T) { paths.On("GetPathIfExists", mock.Anything).Return(root, nil) }, root) filesRequest := &apiclient.GitFilesRequest{ - Repo: &argoappv1.Repository{Repo: "a-url.com"}, + Repo: &v1alpha1.Repository{Repo: "a-url.com"}, SubmoduleEnabled: false, Revision: "HEAD", } @@ -3653,7 +3652,7 @@ func TestErrorUpdateRevisionForPaths(t *testing.T) { }()}, args: args{ ctx: context.TODO(), request: &apiclient.UpdateRevisionForPathsRequest{ - Repo: &argoappv1.Repository{Repo: "not-a-valid-url"}, + Repo: &v1alpha1.Repository{Repo: "not-a-valid-url"}, Revision: "sadfsadf", SyncedRevision: "HEAD", Paths: []string{"."}, @@ -3672,7 +3671,7 @@ func TestErrorUpdateRevisionForPaths(t *testing.T) { }()}, args: args{ ctx: context.TODO(), request: &apiclient.UpdateRevisionForPathsRequest{ - Repo: &argoappv1.Repository{Repo: "not-a-valid-url"}, + Repo: &v1alpha1.Repository{Repo: "not-a-valid-url"}, Revision: "HEAD", SyncedRevision: "sadfsadf", Paths: []string{"."}, @@ -3723,7 +3722,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { }(), args: args{ ctx: context.TODO(), request: &apiclient.UpdateRevisionForPathsRequest{ - Repo: &argoappv1.Repository{Repo: "a-url.com"}, + Repo: &v1alpha1.Repository{Repo: "a-url.com"}, Paths: []string{}, }, }, want: &apiclient.UpdateRevisionForPathsResponse{}, wantErr: assert.NoError}, @@ -3742,7 +3741,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { }(), args: args{ ctx: context.TODO(), request: &apiclient.UpdateRevisionForPathsRequest{ - Repo: &argoappv1.Repository{Repo: "a-url.com"}, + Repo: &v1alpha1.Repository{Repo: "a-url.com"}, Revision: "HEAD", SyncedRevision: "SYNCEDHEAD", Paths: []string{"."}, @@ -3770,7 +3769,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { }(), args: args{ ctx: context.TODO(), request: &apiclient.UpdateRevisionForPathsRequest{ - Repo: &argoappv1.Repository{Repo: "a-url.com"}, + Repo: &v1alpha1.Repository{Repo: "a-url.com"}, Revision: "HEAD", SyncedRevision: "SYNCEDHEAD", Paths: []string{"."}, @@ -3799,7 +3798,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { }(), args: args{ ctx: context.TODO(), request: &apiclient.UpdateRevisionForPathsRequest{ - Repo: &argoappv1.Repository{Repo: "a-url.com"}, + Repo: &v1alpha1.Repository{Repo: "a-url.com"}, Revision: "HEAD", SyncedRevision: "SYNCEDHEAD", Paths: []string{"."}, @@ -3808,7 +3807,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { AppName: "no-change-update-cache", Namespace: "default", TrackingMethod: "annotation+label", - ApplicationSource: &argoappv1.ApplicationSource{Path: "."}, + ApplicationSource: &v1alpha1.ApplicationSource{Path: "."}, KubeVersion: "v1.16.0", }, }, want: &apiclient.UpdateRevisionForPathsResponse{ @@ -3837,7 +3836,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { }(), args: args{ ctx: context.TODO(), request: &apiclient.UpdateRevisionForPathsRequest{ - Repo: &argoappv1.Repository{Repo: "a-url.com"}, + Repo: &v1alpha1.Repository{Repo: "a-url.com"}, Revision: "HEAD", SyncedRevision: "SYNCEDHEAD", Paths: []string{"."}, @@ -3846,7 +3845,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { AppName: "no-change-update-cache", Namespace: "default", TrackingMethod: "annotation+label", - ApplicationSource: &argoappv1.ApplicationSource{Path: ".", Helm: &argoappv1.ApplicationSourceHelm{ReleaseName: "test"}}, + ApplicationSource: &v1alpha1.ApplicationSource{Path: ".", Helm: &v1alpha1.ApplicationSourceHelm{ReleaseName: "test"}}, KubeVersion: "v1.16.0", HasMultipleSources: true, @@ -4056,7 +4055,7 @@ func TestGetRevisionChartDetails(t *testing.T) { root := t.TempDir() service := newService(t, root) repoUrl := "file://" + root - err := service.cache.SetRevisionChartDetails(repoUrl, "my-chart", "1.1.0", &argoappv1.ChartDetails{ + err := service.cache.SetRevisionChartDetails(repoUrl, "my-chart", "1.1.0", &v1alpha1.ChartDetails{ Description: "test-description", Home: "test-home", Maintainers: []string{"test-maintainer"}, @@ -4137,17 +4136,17 @@ func Test_GenerateManifests_Commands(t *testing.T) { Namespace: "test-namespace", KubeVersion: "1.2.3", ApiVersions: []string{"v1/Test", "v2/Test"}, - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", - Helm: &argoappv1.ApplicationSourceHelm{ - FileParameters: []argoappv1.HelmFileParameter{ + Helm: &v1alpha1.ApplicationSourceHelm{ + FileParameters: []v1alpha1.HelmFileParameter{ { Name: "test-file-param-name", Path: "test-file-param.yaml", }, }, - Parameters: []argoappv1.HelmParameter{ + Parameters: []v1alpha1.HelmParameter{ { Name: "test-param-name", // Use build env var to test substitution. @@ -4208,8 +4207,8 @@ func Test_GenerateManifests_Commands(t *testing.T) { q := apiclient.ManifestRequest{ AppName: "test-app", Namespace: "test-namespace", - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", }, ProjectName: "something", @@ -4256,10 +4255,10 @@ images: Namespace: "test-namespace", KubeVersion: "1.2.3", ApiVersions: []string{"v1/Test", "v2/Test"}, - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", - Kustomize: &argoappv1.ApplicationSourceKustomize{ + Kustomize: &v1alpha1.ApplicationSourceKustomize{ APIVersions: []string{"v1", "v2"}, CommonAnnotations: map[string]string{ // Use build env var to test substitution. @@ -4272,7 +4271,7 @@ images: Components: []string{"component"}, ForceCommonAnnotations: true, ForceCommonLabels: true, - Images: argoappv1.KustomizeImages{ + Images: v1alpha1.KustomizeImages{ "image=override", }, KubeVersion: "5.6.7", @@ -4280,7 +4279,7 @@ images: NamePrefix: "test-prefix", NameSuffix: "test-suffix", Namespace: "override-namespace", - Replicas: argoappv1.KustomizeReplicas{ + Replicas: v1alpha1.KustomizeReplicas{ { Name: "guestbook-ui", Count: intstr.Parse("1337"), @@ -4315,10 +4314,10 @@ func Test_SkipSchemaValidation(t *testing.T) { q := apiclient.ManifestRequest{ AppName: "test-app", - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ SkipSchemaValidation: true, }, }, @@ -4334,10 +4333,10 @@ func Test_SkipSchemaValidation(t *testing.T) { q := apiclient.ManifestRequest{ AppName: "test-app", - Repo: &argoappv1.Repository{}, - ApplicationSource: &argoappv1.ApplicationSource{ + Repo: &v1alpha1.Repository{}, + ApplicationSource: &v1alpha1.ApplicationSource{ Path: ".", - Helm: &argoappv1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ SkipSchemaValidation: false, }, }, diff --git a/server/application/application.go b/server/application/application.go index 9a12da04f1be2..b260c4ca1f6b2 100644 --- a/server/application/application.go +++ b/server/application/application.go @@ -39,7 +39,6 @@ import ( argocommon "github.com/argoproj/argo-cd/v2/common" "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" appclientset "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned" applisters "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1" "github.com/argoproj/argo-cd/v2/reposerver/apiclient" @@ -47,7 +46,6 @@ import ( "github.com/argoproj/argo-cd/v2/server/deeplinks" "github.com/argoproj/argo-cd/v2/server/rbacpolicy" "github.com/argoproj/argo-cd/v2/util/argo" - argoutil "github.com/argoproj/argo-cd/v2/util/argo" "github.com/argoproj/argo-cd/v2/util/collections" "github.com/argoproj/argo-cd/v2/util/db" "github.com/argoproj/argo-cd/v2/util/env" @@ -63,7 +61,7 @@ import ( applicationType "github.com/argoproj/argo-cd/v2/pkg/apis/application" ) -type AppResourceTreeFn func(ctx context.Context, app *appv1.Application) (*appv1.ApplicationTree, error) +type AppResourceTreeFn func(ctx context.Context, app *v1alpha1.Application) (*v1alpha1.ApplicationTree, error) const ( backgroundPropagationPolicy string = "background" @@ -149,7 +147,7 @@ func NewServer( // // If the user does provide a "project," we can respond more specifically. If the user does not have access to the given // app name in the given project, we return "permission denied." If the app exists, but the project is different from -func (s *Server) getAppEnforceRBAC(ctx context.Context, action, project, namespace, name string, getApp func() (*appv1.Application, error)) (*appv1.Application, *appv1.AppProject, error) { +func (s *Server) getAppEnforceRBAC(ctx context.Context, action, project, namespace, name string, getApp func() (*v1alpha1.Application, error)) (*v1alpha1.Application, *v1alpha1.AppProject, error) { user := session.Username(ctx) if user == "" { user = "Unknown user" @@ -231,9 +229,9 @@ func (s *Server) getAppEnforceRBAC(ctx context.Context, action, project, namespa // getApplicationEnforceRBACInformer uses an informer to get an Application. If the app does not exist, permission is // denied, or any other error occurs when getting the app, we return a permission denied error to obscure any sensitive // information. -func (s *Server) getApplicationEnforceRBACInformer(ctx context.Context, action, project, namespace, name string) (*appv1.Application, *appv1.AppProject, error) { +func (s *Server) getApplicationEnforceRBACInformer(ctx context.Context, action, project, namespace, name string) (*v1alpha1.Application, *v1alpha1.AppProject, error) { namespaceOrDefault := s.appNamespaceOrDefault(namespace) - return s.getAppEnforceRBAC(ctx, action, project, namespaceOrDefault, name, func() (*appv1.Application, error) { + return s.getAppEnforceRBAC(ctx, action, project, namespaceOrDefault, name, func() (*v1alpha1.Application, error) { return s.appLister.Applications(namespaceOrDefault).Get(name) }) } @@ -241,9 +239,9 @@ func (s *Server) getApplicationEnforceRBACInformer(ctx context.Context, action, // getApplicationEnforceRBACClient uses a client to get an Application. If the app does not exist, permission is denied, // or any other error occurs when getting the app, we return a permission denied error to obscure any sensitive // information. -func (s *Server) getApplicationEnforceRBACClient(ctx context.Context, action, project, namespace, name, resourceVersion string) (*appv1.Application, *appv1.AppProject, error) { +func (s *Server) getApplicationEnforceRBACClient(ctx context.Context, action, project, namespace, name, resourceVersion string) (*v1alpha1.Application, *v1alpha1.AppProject, error) { namespaceOrDefault := s.appNamespaceOrDefault(namespace) - return s.getAppEnforceRBAC(ctx, action, project, namespaceOrDefault, name, func() (*appv1.Application, error) { + return s.getAppEnforceRBAC(ctx, action, project, namespaceOrDefault, name, func() (*v1alpha1.Application, error) { if !s.isNamespaceEnabled(namespaceOrDefault) { return nil, security.NamespaceNotPermittedError(namespaceOrDefault) } @@ -254,12 +252,12 @@ func (s *Server) getApplicationEnforceRBACClient(ctx context.Context, action, pr } // List returns list of applications -func (s *Server) List(ctx context.Context, q *application.ApplicationQuery) (*appv1.ApplicationList, error) { +func (s *Server) List(ctx context.Context, q *application.ApplicationQuery) (*v1alpha1.ApplicationList, error) { selector, err := labels.Parse(q.GetSelector()) if err != nil { return nil, fmt.Errorf("error parsing the selector: %w", err) } - var apps []*appv1.Application + var apps []*v1alpha1.Application if q.GetAppNamespace() == "" { apps, err = s.appLister.List(selector) } else { @@ -272,16 +270,16 @@ func (s *Server) List(ctx context.Context, q *application.ApplicationQuery) (*ap filteredApps := apps // Filter applications by name if q.Name != nil { - filteredApps = argoutil.FilterByNameP(filteredApps, *q.Name) + filteredApps = argo.FilterByNameP(filteredApps, *q.Name) } // Filter applications by projects - filteredApps = argoutil.FilterByProjectsP(filteredApps, getProjectsFromApplicationQuery(*q)) + filteredApps = argo.FilterByProjectsP(filteredApps, getProjectsFromApplicationQuery(*q)) // Filter applications by source repo URL - filteredApps = argoutil.FilterByRepoP(filteredApps, q.GetRepo()) + filteredApps = argo.FilterByRepoP(filteredApps, q.GetRepo()) - newItems := make([]appv1.Application, 0) + newItems := make([]v1alpha1.Application, 0) for _, a := range filteredApps { // Skip any application that is neither in the control plane's namespace // nor in the list of enabled namespaces. @@ -298,7 +296,7 @@ func (s *Server) List(ctx context.Context, q *application.ApplicationQuery) (*ap return newItems[i].Name < newItems[j].Name }) - appList := appv1.ApplicationList{ + appList := v1alpha1.ApplicationList{ ListMeta: metav1.ListMeta{ ResourceVersion: s.appInformer.LastSyncResourceVersion(), }, @@ -308,7 +306,7 @@ func (s *Server) List(ctx context.Context, q *application.ApplicationQuery) (*ap } // Create creates an application -func (s *Server) Create(ctx context.Context, q *application.ApplicationCreateRequest) (*appv1.Application, error) { +func (s *Server) Create(ctx context.Context, q *application.ApplicationCreateRequest) (*v1alpha1.Application, error) { if q.GetApplication() == nil { return nil, errors.New("error creating application: application is nil in request") } @@ -393,11 +391,11 @@ func (s *Server) Create(ctx context.Context, q *application.ApplicationCreateReq return updated, nil } -func (s *Server) queryRepoServer(ctx context.Context, proj *appv1.AppProject, action func( +func (s *Server) queryRepoServer(ctx context.Context, proj *v1alpha1.AppProject, action func( client apiclient.RepoServerServiceClient, - helmRepos []*appv1.Repository, - helmCreds []*appv1.RepoCreds, - helmOptions *appv1.HelmOptions, + helmRepos []*v1alpha1.Repository, + helmCreds []*v1alpha1.RepoCreds, + helmOptions *v1alpha1.HelmOptions, enabledSourceTypes map[string]bool, ) error, ) error { @@ -451,7 +449,7 @@ func (s *Server) GetManifests(ctx context.Context, q *application.ApplicationMan manifestInfos := make([]*apiclient.ManifestResponse, 0) err = s.queryRepoServer(ctx, proj, func( - client apiclient.RepoServerServiceClient, helmRepos []*appv1.Repository, helmCreds []*appv1.RepoCreds, helmOptions *appv1.HelmOptions, enableGenerateManifests map[string]bool, + client apiclient.RepoServerServiceClient, helmRepos []*v1alpha1.Repository, helmCreds []*v1alpha1.RepoCreds, helmOptions *v1alpha1.HelmOptions, enableGenerateManifests map[string]bool, ) error { appInstanceLabelKey, err := s.settingsMgr.GetAppInstanceLabelKey() if err != nil { @@ -473,7 +471,7 @@ func (s *Server) GetManifests(ctx context.Context, q *application.ApplicationMan return fmt.Errorf("error getting API resources: %w", err) } - sources := make([]appv1.ApplicationSource, 0) + sources := make([]v1alpha1.ApplicationSource, 0) appSpec := a.Spec.DeepCopy() if a.Spec.HasMultipleSources() { numOfSources := int64(len(a.Spec.GetSources())) @@ -531,7 +529,7 @@ func (s *Server) GetManifests(ctx context.Context, q *application.ApplicationMan ApiVersions: argo.APIResourcesToStrings(apiResources, true), HelmRepoCreds: helmCreds, HelmOptions: helmOptions, - TrackingMethod: string(argoutil.GetTrackingMethod(s.settingsMgr)), + TrackingMethod: string(argo.GetTrackingMethod(s.settingsMgr)), EnabledSourceTypes: enableGenerateManifests, ProjectName: proj.Name, ProjectSourceRepos: proj.Spec.SourceRepos, @@ -595,7 +593,7 @@ func (s *Server) GetManifestsWithFiles(stream application.ApplicationService_Get var manifestInfo *apiclient.ManifestResponse err = s.queryRepoServer(ctx, proj, func( - client apiclient.RepoServerServiceClient, helmRepos []*appv1.Repository, helmCreds []*appv1.RepoCreds, helmOptions *appv1.HelmOptions, enableGenerateManifests map[string]bool, + client apiclient.RepoServerServiceClient, helmRepos []*v1alpha1.Repository, helmCreds []*v1alpha1.RepoCreds, helmOptions *v1alpha1.HelmOptions, enableGenerateManifests map[string]bool, ) error { appInstanceLabelKey, err := s.settingsMgr.GetAppInstanceLabelKey() if err != nil { @@ -651,7 +649,7 @@ func (s *Server) GetManifestsWithFiles(stream application.ApplicationService_Get ApiVersions: argo.APIResourcesToStrings(apiResources, true), HelmRepoCreds: helmCreds, HelmOptions: helmOptions, - TrackingMethod: string(argoutil.GetTrackingMethod(s.settingsMgr)), + TrackingMethod: string(argo.GetTrackingMethod(s.settingsMgr)), EnabledSourceTypes: enableGenerateManifests, ProjectName: proj.Name, ProjectSourceRepos: proj.Spec.SourceRepos, @@ -704,7 +702,7 @@ func (s *Server) GetManifestsWithFiles(stream application.ApplicationService_Get } // Get returns an application by name -func (s *Server) Get(ctx context.Context, q *application.ApplicationQuery) (*appv1.Application, error) { +func (s *Server) Get(ctx context.Context, q *application.ApplicationQuery) (*v1alpha1.Application, error) { appName := q.GetName() appNs := s.appNamespaceOrDefault(q.GetAppNamespace()) @@ -730,31 +728,31 @@ func (s *Server) Get(ctx context.Context, q *application.ApplicationQuery) (*app return a, nil } - refreshType := appv1.RefreshTypeNormal - if *q.Refresh == string(appv1.RefreshTypeHard) { - refreshType = appv1.RefreshTypeHard + refreshType := v1alpha1.RefreshTypeNormal + if *q.Refresh == string(v1alpha1.RefreshTypeHard) { + refreshType = v1alpha1.RefreshTypeHard } appIf := s.appclientset.ArgoprojV1alpha1().Applications(appNs) // subscribe early with buffered channel to ensure we don't miss events - events := make(chan *appv1.ApplicationWatchEvent, watchAPIBufferSize) - unsubscribe := s.appBroadcaster.Subscribe(events, func(event *appv1.ApplicationWatchEvent) bool { + events := make(chan *v1alpha1.ApplicationWatchEvent, watchAPIBufferSize) + unsubscribe := s.appBroadcaster.Subscribe(events, func(event *v1alpha1.ApplicationWatchEvent) bool { return event.Application.Name == appName && event.Application.Namespace == appNs }) defer unsubscribe() - app, err := argoutil.RefreshApp(appIf, appName, refreshType) + app, err := argo.RefreshApp(appIf, appName, refreshType) if err != nil { return nil, fmt.Errorf("error refreshing the app: %w", err) } - if refreshType == appv1.RefreshTypeHard { + if refreshType == v1alpha1.RefreshTypeHard { // force refresh cached application details if err := s.queryRepoServer(ctx, proj, func( client apiclient.RepoServerServiceClient, - helmRepos []*appv1.Repository, - _ []*appv1.RepoCreds, - helmOptions *appv1.HelmOptions, + helmRepos []*v1alpha1.Repository, + _ []*v1alpha1.RepoCreds, + helmOptions *v1alpha1.HelmOptions, enabledSourceTypes map[string]bool, ) error { source := app.Spec.GetSource() @@ -777,7 +775,7 @@ func (s *Server) Get(ctx context.Context, q *application.ApplicationQuery) (*app KustomizeOptions: kustomizeOptions, Repos: helmRepos, NoCache: true, - TrackingMethod: string(argoutil.GetTrackingMethod(s.settingsMgr)), + TrackingMethod: string(argo.GetTrackingMethod(s.settingsMgr)), EnabledSourceTypes: enabledSourceTypes, HelmOptions: helmOptions, }) @@ -802,7 +800,7 @@ func (s *Server) Get(ctx context.Context, q *application.ApplicationQuery) (*app if annotations == nil { annotations = make(map[string]string) } - if _, ok := annotations[appv1.AnnotationKeyRefresh]; !ok { + if _, ok := annotations[v1alpha1.AnnotationKeyRefresh]; !ok { return &event.Application, nil } } @@ -876,7 +874,7 @@ func (s *Server) ListResourceEvents(ctx context.Context, q *application.Applicat // validateAndUpdateApp validates and updates the application. currentProject is the name of the project the app // currently is under. If not specified, we assume that the app is under the project specified in the app spec. -func (s *Server) validateAndUpdateApp(ctx context.Context, newApp *appv1.Application, merge bool, validate bool, action string, currentProject string) (*appv1.Application, error) { +func (s *Server) validateAndUpdateApp(ctx context.Context, newApp *v1alpha1.Application, merge bool, validate bool, action string, currentProject string) (*v1alpha1.Application, error) { s.projectLock.RLock(newApp.Spec.GetProject()) defer s.projectLock.RUnlock(newApp.Spec.GetProject()) @@ -906,7 +904,7 @@ var informerSyncTimeout = 2 * time.Second // eventually consistent, it is possible that it doesn't reflect an application change immediately // after a mutating API call (create/update). This function should be called after a creates & // update to give a probable (but not guaranteed) chance of being up-to-date after the create/update. -func (s *Server) waitSync(app *appv1.Application) { +func (s *Server) waitSync(app *v1alpha1.Application) { logCtx := log.WithField("application", app.Name) deadline := time.Now().Add(informerSyncTimeout) minVersion, err := strconv.Atoi(app.ResourceVersion) @@ -930,7 +928,7 @@ func (s *Server) waitSync(app *appv1.Application) { logCtx.Warnf("waitSync failed: timed out") } -func (s *Server) updateApp(app *appv1.Application, newApp *appv1.Application, ctx context.Context, merge bool) (*appv1.Application, error) { +func (s *Server) updateApp(app *v1alpha1.Application, newApp *v1alpha1.Application, ctx context.Context, merge bool) (*v1alpha1.Application, error) { for i := 0; i < 10; i++ { app.Spec = newApp.Spec if merge { @@ -963,7 +961,7 @@ func (s *Server) updateApp(app *appv1.Application, newApp *appv1.Application, ct } // Update updates an application -func (s *Server) Update(ctx context.Context, q *application.ApplicationUpdateRequest) (*appv1.Application, error) { +func (s *Server) Update(ctx context.Context, q *application.ApplicationUpdateRequest) (*v1alpha1.Application, error) { if q.GetApplication() == nil { return nil, errors.New("error updating application: application is nil in request") } @@ -980,7 +978,7 @@ func (s *Server) Update(ctx context.Context, q *application.ApplicationUpdateReq } // UpdateSpec updates an application spec and filters out any invalid parameter overrides -func (s *Server) UpdateSpec(ctx context.Context, q *application.ApplicationUpdateSpecRequest) (*appv1.ApplicationSpec, error) { +func (s *Server) UpdateSpec(ctx context.Context, q *application.ApplicationUpdateSpecRequest) (*v1alpha1.ApplicationSpec, error) { if q.GetSpec() == nil { return nil, errors.New("error updating application spec: spec is nil in request") } @@ -1002,7 +1000,7 @@ func (s *Server) UpdateSpec(ctx context.Context, q *application.ApplicationUpdat } // Patch patches an application -func (s *Server) Patch(ctx context.Context, q *application.ApplicationPatchRequest) (*appv1.Application, error) { +func (s *Server) Patch(ctx context.Context, q *application.ApplicationPatchRequest) (*v1alpha1.Application, error) { app, _, err := s.getApplicationEnforceRBACClient(ctx, rbacpolicy.ActionGet, q.GetProject(), q.GetAppNamespace(), q.GetName(), "") if err != nil { return nil, err @@ -1038,7 +1036,7 @@ func (s *Server) Patch(ctx context.Context, q *application.ApplicationPatchReque return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("Patch type '%s' is not supported", q.GetPatchType())) } - newApp := &appv1.Application{} + newApp := &v1alpha1.Application{} err = json.Unmarshal(patchApp, newApp) if err != nil { return nil, fmt.Errorf("error unmarshaling patched app: %w", err) @@ -1046,7 +1044,7 @@ func (s *Server) Patch(ctx context.Context, q *application.ApplicationPatchReque return s.validateAndUpdateApp(ctx, newApp, false, true, rbacpolicy.ActionUpdate, q.GetProject()) } -func (s *Server) getAppProject(ctx context.Context, a *appv1.Application, logCtx *log.Entry) (*appv1.AppProject, error) { +func (s *Server) getAppProject(ctx context.Context, a *v1alpha1.Application, logCtx *log.Entry) (*v1alpha1.AppProject, error) { proj, err := argo.GetAppProject(a, applisters.NewAppProjectLister(s.projInformer.GetIndexer()), s.ns, s.settingsMgr, s.db, ctx) if err == nil { return proj, nil @@ -1059,7 +1057,7 @@ func (s *Server) getAppProject(ctx context.Context, a *appv1.Application, logCtx return nil, vagueError } - var applicationNotAllowedToUseProjectErr *appv1.ErrApplicationNotAllowedToUseProject + var applicationNotAllowedToUseProjectErr *v1alpha1.ErrApplicationNotAllowedToUseProject if errors.As(err, &applicationNotAllowedToUseProjectErr) { logCtx.WithFields(map[string]any{ "project": a.Spec.Project, @@ -1133,7 +1131,7 @@ func (s *Server) Delete(ctx context.Context, q *application.ApplicationDeleteReq return &application.ApplicationResponse{}, nil } -func (s *Server) isApplicationPermitted(selector labels.Selector, minVersion int, claims any, appName, appNs string, projects map[string]bool, a appv1.Application) bool { +func (s *Server) isApplicationPermitted(selector labels.Selector, minVersion int, claims any, appName, appNs string, projects map[string]bool, a v1alpha1.Application) bool { if len(projects) > 0 && !projects[a.Spec.GetProject()] { return false } @@ -1183,13 +1181,13 @@ func (s *Server) Watch(q *application.ApplicationQuery, ws application.Applicati // sendIfPermitted is a helper to send the application to the client's streaming channel if the // caller has RBAC privileges permissions to view it - sendIfPermitted := func(a appv1.Application, eventType watch.EventType) { + sendIfPermitted := func(a v1alpha1.Application, eventType watch.EventType) { permitted := s.isApplicationPermitted(selector, minVersion, claims, appName, appNs, projects, a) if !permitted { return } s.inferResourcesStatusHealth(&a) - err := ws.Send(&appv1.ApplicationWatchEvent{ + err := ws.Send(&v1alpha1.ApplicationWatchEvent{ Type: eventType, Application: a, }) @@ -1199,7 +1197,7 @@ func (s *Server) Watch(q *application.ApplicationQuery, ws application.Applicati } } - events := make(chan *appv1.ApplicationWatchEvent, watchAPIBufferSize) + events := make(chan *v1alpha1.ApplicationWatchEvent, watchAPIBufferSize) // Mimic watch API behavior: send ADDED events if no resource version provided // If watch API is executed for one application when emit event even if resource version is provided // This is required since single app watch API is used for during operations like app syncing and it is @@ -1228,7 +1226,7 @@ func (s *Server) Watch(q *application.ApplicationQuery, ws application.Applicati } } -func (s *Server) validateAndNormalizeApp(ctx context.Context, app *appv1.Application, proj *appv1.AppProject, validate bool) error { +func (s *Server) validateAndNormalizeApp(ctx context.Context, app *v1alpha1.Application, proj *v1alpha1.AppProject, validate bool) error { if app.GetName() == "" { return errors.New("resource name may not be empty") } @@ -1270,10 +1268,10 @@ func (s *Server) validateAndNormalizeApp(ctx context.Context, app *appv1.Applica return status.Errorf(codes.InvalidArgument, "application destination spec for %s is invalid: %s", app.Name, err.Error()) } - var conditions []appv1.ApplicationCondition + var conditions []v1alpha1.ApplicationCondition if validate { - conditions := make([]appv1.ApplicationCondition, 0) + conditions := make([]v1alpha1.ApplicationCondition, 0) condition, err := argo.ValidateRepo(ctx, app, s.repoClientset, s.db, s.kubectl, proj, s.settingsMgr) if err != nil { return fmt.Errorf("error validating the repo: %w", err) @@ -1296,7 +1294,7 @@ func (s *Server) validateAndNormalizeApp(ctx context.Context, app *appv1.Applica return nil } -func (s *Server) getApplicationClusterConfig(ctx context.Context, a *appv1.Application) (*rest.Config, error) { +func (s *Server) getApplicationClusterConfig(ctx context.Context, a *v1alpha1.Application) (*rest.Config, error) { if err := argo.ValidateDestination(ctx, &a.Spec.Destination, s.db); err != nil { return nil, fmt.Errorf("error validating destination: %w", err) } @@ -1313,20 +1311,20 @@ func (s *Server) getApplicationClusterConfig(ctx context.Context, a *appv1.Appli } // getCachedAppState loads the cached state and trigger app refresh if cache is missing -func (s *Server) getCachedAppState(ctx context.Context, a *appv1.Application, getFromCache func() error) error { +func (s *Server) getCachedAppState(ctx context.Context, a *v1alpha1.Application, getFromCache func() error) error { err := getFromCache() if err != nil && errors.Is(err, servercache.ErrCacheMiss) { - conditions := a.Status.GetConditions(map[appv1.ApplicationConditionType]bool{ - appv1.ApplicationConditionComparisonError: true, - appv1.ApplicationConditionInvalidSpecError: true, + conditions := a.Status.GetConditions(map[v1alpha1.ApplicationConditionType]bool{ + v1alpha1.ApplicationConditionComparisonError: true, + v1alpha1.ApplicationConditionInvalidSpecError: true, }) if len(conditions) > 0 { - return errors.New(argoutil.FormatAppConditions(conditions)) + return errors.New(argo.FormatAppConditions(conditions)) } _, err = s.Get(ctx, &application.ApplicationQuery{ Name: ptr.To(a.GetName()), AppNamespace: ptr.To(a.GetNamespace()), - Refresh: ptr.To(string(appv1.RefreshTypeNormal)), + Refresh: ptr.To(string(v1alpha1.RefreshTypeNormal)), }) if err != nil { return fmt.Errorf("error getting application by query: %w", err) @@ -1336,8 +1334,8 @@ func (s *Server) getCachedAppState(ctx context.Context, a *appv1.Application, ge return err } -func (s *Server) getAppResources(ctx context.Context, a *appv1.Application) (*appv1.ApplicationTree, error) { - var tree appv1.ApplicationTree +func (s *Server) getAppResources(ctx context.Context, a *v1alpha1.Application) (*v1alpha1.ApplicationTree, error) { + var tree v1alpha1.ApplicationTree err := s.getCachedAppState(ctx, a, func() error { return s.cache.GetAppResourcesTree(a.InstanceName(s.ns), &tree) }) @@ -1347,7 +1345,7 @@ func (s *Server) getAppResources(ctx context.Context, a *appv1.Application) (*ap return &tree, nil } -func (s *Server) getAppLiveResource(ctx context.Context, action string, q *application.ApplicationResourceRequest) (*appv1.ResourceNode, *rest.Config, *appv1.Application, error) { +func (s *Server) getAppLiveResource(ctx context.Context, action string, q *application.ApplicationResourceRequest) (*v1alpha1.ResourceNode, *rest.Config, *v1alpha1.Application, error) { a, _, err := s.getApplicationEnforceRBACInformer(ctx, action, q.GetProject(), q.GetAppNamespace(), q.GetName()) if err != nil && errors.Is(err, argocommon.PermissionDeniedAPIError) && (action == rbacpolicy.ActionDelete || action == rbacpolicy.ActionUpdate) { // If users dont have permission on the whole applications, maybe they have fine-grained access to the specific resources @@ -1490,7 +1488,7 @@ func (s *Server) DeleteResource(ctx context.Context, q *application.ApplicationR return &application.ApplicationResponse{}, nil } -func (s *Server) ResourceTree(ctx context.Context, q *application.ResourcesQuery) (*appv1.ApplicationTree, error) { +func (s *Server) ResourceTree(ctx context.Context, q *application.ResourcesQuery) (*v1alpha1.ApplicationTree, error) { a, _, err := s.getApplicationEnforceRBACInformer(ctx, rbacpolicy.ActionGet, q.GetProject(), q.GetAppNamespace(), q.GetApplicationName()) if err != nil { return nil, err @@ -1507,7 +1505,7 @@ func (s *Server) WatchResourceTree(q *application.ResourcesQuery, ws application cacheKey := argo.AppInstanceName(q.GetApplicationName(), q.GetAppNamespace(), s.ns) return s.cache.OnAppResourcesTreeChanged(ws.Context(), cacheKey, func() error { - var tree appv1.ApplicationTree + var tree v1alpha1.ApplicationTree err := s.cache.GetAppResourcesTree(cacheKey, &tree) if err != nil { return fmt.Errorf("error getting app resource tree: %w", err) @@ -1516,7 +1514,7 @@ func (s *Server) WatchResourceTree(q *application.ResourcesQuery, ws application }) } -func (s *Server) RevisionMetadata(ctx context.Context, q *application.RevisionMetadataQuery) (*appv1.RevisionMetadata, error) { +func (s *Server) RevisionMetadata(ctx context.Context, q *application.RevisionMetadataQuery) (*v1alpha1.RevisionMetadata, error) { a, proj, err := s.getApplicationEnforceRBACInformer(ctx, rbacpolicy.ActionGet, q.GetProject(), q.GetAppNamespace(), q.GetName()) if err != nil { return nil, err @@ -1544,7 +1542,7 @@ func (s *Server) RevisionMetadata(ctx context.Context, q *application.RevisionMe } // RevisionChartDetails returns the helm chart metadata, as fetched from the reposerver -func (s *Server) RevisionChartDetails(ctx context.Context, q *application.RevisionMetadataQuery) (*appv1.ChartDetails, error) { +func (s *Server) RevisionChartDetails(ctx context.Context, q *application.RevisionMetadataQuery) (*v1alpha1.ChartDetails, error) { a, _, err := s.getApplicationEnforceRBACInformer(ctx, rbacpolicy.ActionGet, q.GetProject(), q.GetAppNamespace(), q.GetName()) if err != nil { return nil, err @@ -1579,7 +1577,7 @@ func (s *Server) RevisionChartDetails(ctx context.Context, q *application.Revisi // we use the source(s) currently configured for the app. If the version ID is specified, we find the source for that // version ID. If the version ID is not found, we return an error. If the source index is out of bounds for whichever // source we choose (configured sources or sources for a specific version), we return an error. -func getAppSourceBySourceIndexAndVersionId(a *appv1.Application, sourceIndexMaybe *int32, versionIdMaybe *int32) (appv1.ApplicationSource, error) { +func getAppSourceBySourceIndexAndVersionId(a *v1alpha1.Application, sourceIndexMaybe *int32, versionIdMaybe *int32) (v1alpha1.ApplicationSource, error) { // Start with all the app's configured sources. sources := a.Spec.GetSources() @@ -1589,7 +1587,7 @@ func getAppSourceBySourceIndexAndVersionId(a *appv1.Application, sourceIndexMayb var err error sources, err = getSourcesByVersionId(a, versionId) if err != nil { - return appv1.ApplicationSource{}, fmt.Errorf("error getting source by version ID: %w", err) + return v1alpha1.ApplicationSource{}, fmt.Errorf("error getting source by version ID: %w", err) } } @@ -1601,9 +1599,9 @@ func getAppSourceBySourceIndexAndVersionId(a *appv1.Application, sourceIndexMayb sourceIndex = int(*sourceIndexMaybe) if sourceIndex >= len(sources) { if len(sources) == 1 { - return appv1.ApplicationSource{}, fmt.Errorf("source index %d not found because there is only 1 source", sourceIndex) + return v1alpha1.ApplicationSource{}, fmt.Errorf("source index %d not found because there is only 1 source", sourceIndex) } - return appv1.ApplicationSource{}, fmt.Errorf("source index %d not found because there are only %d sources", sourceIndex, len(sources)) + return v1alpha1.ApplicationSource{}, fmt.Errorf("source index %d not found because there are only %d sources", sourceIndex, len(sources)) } } @@ -1614,20 +1612,20 @@ func getAppSourceBySourceIndexAndVersionId(a *appv1.Application, sourceIndexMayb // getRevisionHistoryByVersionId returns the revision history for a specific version ID. // If the version ID is not found, it returns an empty revision history and false. -func getRevisionHistoryByVersionId(histories v1alpha1.RevisionHistories, versionId int64) (appv1.RevisionHistory, bool) { +func getRevisionHistoryByVersionId(histories v1alpha1.RevisionHistories, versionId int64) (v1alpha1.RevisionHistory, bool) { for _, h := range histories { if h.ID == versionId { return h, true } } - return appv1.RevisionHistory{}, false + return v1alpha1.RevisionHistory{}, false } // getSourcesByVersionId returns the sources for a specific version ID. If there is no history, it returns an error. // If the version ID is not found, it returns an error. If the version ID is found, and there are multiple sources, // it returns the sources for that version ID. If the version ID is found, and there is only one source, it returns // a slice with just the single source. -func getSourcesByVersionId(a *appv1.Application, versionId int64) ([]appv1.ApplicationSource, error) { +func getSourcesByVersionId(a *v1alpha1.Application, versionId int64) ([]v1alpha1.ApplicationSource, error) { if len(a.Status.History) == 0 { return nil, fmt.Errorf("version ID %d not found because the app has no history", versionId) } @@ -1657,7 +1655,7 @@ func (s *Server) ManagedResources(ctx context.Context, q *application.ResourcesQ return nil, err } - items := make([]*appv1.ResourceDiff, 0) + items := make([]*v1alpha1.ResourceDiff, 0) err = s.getCachedAppState(ctx, a, func() error { return s.cache.GetAppManagedResources(a.InstanceName(s.ns), &items) }) @@ -1851,8 +1849,8 @@ func (s *Server) PodLogs(q *application.ApplicationPodLogsQuery, ws application. } // from all of the treeNodes, get the pod who meets the criteria or whose parents meets the criteria -func getSelectedPods(treeNodes []appv1.ResourceNode, q *application.ApplicationPodLogsQuery) []appv1.ResourceNode { - var pods []appv1.ResourceNode +func getSelectedPods(treeNodes []v1alpha1.ResourceNode, q *application.ApplicationPodLogsQuery) []v1alpha1.ResourceNode { + var pods []v1alpha1.ResourceNode isTheOneMap := make(map[string]bool) for _, treeNode := range treeNodes { if treeNode.Kind == kube.PodKind && treeNode.Group == "" && treeNode.UID != "" { @@ -1865,7 +1863,7 @@ func getSelectedPods(treeNodes []appv1.ResourceNode, q *application.ApplicationP } // check is currentNode is matching with group, kind, and name, or if any of its parents matches -func isTheSelectedOne(currentNode *appv1.ResourceNode, q *application.ApplicationPodLogsQuery, resourceNodes []appv1.ResourceNode, isTheOneMap map[string]bool) bool { +func isTheSelectedOne(currentNode *v1alpha1.ResourceNode, q *application.ApplicationPodLogsQuery, resourceNodes []v1alpha1.ResourceNode, isTheOneMap map[string]bool) bool { exist, value := isTheOneMap[currentNode.UID] if exist { return value @@ -1905,7 +1903,7 @@ func isTheSelectedOne(currentNode *appv1.ResourceNode, q *application.Applicatio } // Sync syncs an application to its target state -func (s *Server) Sync(ctx context.Context, syncReq *application.ApplicationSyncRequest) (*appv1.Application, error) { +func (s *Server) Sync(ctx context.Context, syncReq *application.ApplicationSyncRequest) (*v1alpha1.Application, error) { a, proj, err := s.getApplicationEnforceRBACClient(ctx, rbacpolicy.ActionGet, syncReq.GetProject(), syncReq.GetAppNamespace(), syncReq.GetName(), "") if err != nil { return nil, err @@ -1942,8 +1940,8 @@ func (s *Server) Sync(ctx context.Context, syncReq *application.ApplicationSyncR return nil, err } - var retry *appv1.RetryStrategy - var syncOptions appv1.SyncOptions + var retry *v1alpha1.RetryStrategy + var syncOptions v1alpha1.SyncOptions if a.Spec.SyncPolicy != nil { syncOptions = a.Spec.SyncPolicy.SyncOptions retry = a.Spec.SyncPolicy.Retry @@ -1960,7 +1958,7 @@ func (s *Server) Sync(ctx context.Context, syncReq *application.ApplicationSyncR return nil, status.Errorf(codes.FailedPrecondition, "Cannot use local sync when signature keys are required.") } - resources := []appv1.SyncOperationResource{} + resources := []v1alpha1.SyncOperationResource{} if syncReq.GetResources() != nil { for _, r := range syncReq.GetResources() { if r != nil { @@ -1968,8 +1966,8 @@ func (s *Server) Sync(ctx context.Context, syncReq *application.ApplicationSyncR } } } - op := appv1.Operation{ - Sync: &appv1.SyncOperation{ + op := v1alpha1.Operation{ + Sync: &v1alpha1.SyncOperation{ Revision: revision, Prune: syncReq.GetPrune(), DryRun: syncReq.GetDryRun(), @@ -1980,7 +1978,7 @@ func (s *Server) Sync(ctx context.Context, syncReq *application.ApplicationSyncR Sources: a.Spec.Sources, Revisions: sourceRevisions, }, - InitiatedBy: appv1.OperationInitiator{Username: session.Username(ctx)}, + InitiatedBy: v1alpha1.OperationInitiator{Username: session.Username(ctx)}, Info: syncReq.Infos, } if retry != nil { @@ -2011,7 +2009,7 @@ func (s *Server) Sync(ctx context.Context, syncReq *application.ApplicationSyncR return a, nil } -func (s *Server) resolveSourceRevisions(ctx context.Context, a *appv1.Application, syncReq *application.ApplicationSyncRequest) (string, string, []string, []string, error) { +func (s *Server) resolveSourceRevisions(ctx context.Context, a *v1alpha1.Application, syncReq *application.ApplicationSyncRequest) (string, string, []string, []string, error) { if a.Spec.HasMultipleSources() { numOfSources := int64(len(a.Spec.GetSources())) sourceRevisions := make([]string, numOfSources) @@ -2053,7 +2051,7 @@ func (s *Server) resolveSourceRevisions(ctx context.Context, a *appv1.Applicatio } } -func (s *Server) Rollback(ctx context.Context, rollbackReq *application.ApplicationRollbackRequest) (*appv1.Application, error) { +func (s *Server) Rollback(ctx context.Context, rollbackReq *application.ApplicationRollbackRequest) (*v1alpha1.Application, error) { a, _, err := s.getApplicationEnforceRBACClient(ctx, rbacpolicy.ActionSync, rollbackReq.GetProject(), rollbackReq.GetAppNamespace(), rollbackReq.GetName(), "") if err != nil { return nil, err @@ -2068,7 +2066,7 @@ func (s *Server) Rollback(ctx context.Context, rollbackReq *application.Applicat return nil, status.Errorf(codes.FailedPrecondition, "rollback cannot be initiated when auto-sync is enabled") } - var deploymentInfo *appv1.RevisionHistory + var deploymentInfo *v1alpha1.RevisionHistory for _, info := range a.Status.History { if info.ID == rollbackReq.GetId() { deploymentInfo = &info @@ -2085,24 +2083,24 @@ func (s *Server) Rollback(ctx context.Context, rollbackReq *application.Applicat return nil, status.Errorf(codes.FailedPrecondition, "cannot rollback to revision deployed with Argo CD v0.11 or lower. sync to revision instead.") } - var syncOptions appv1.SyncOptions + var syncOptions v1alpha1.SyncOptions if a.Spec.SyncPolicy != nil { syncOptions = a.Spec.SyncPolicy.SyncOptions } // Rollback is just a convenience around Sync - op := appv1.Operation{ - Sync: &appv1.SyncOperation{ + op := v1alpha1.Operation{ + Sync: &v1alpha1.SyncOperation{ Revision: deploymentInfo.Revision, Revisions: deploymentInfo.Revisions, DryRun: rollbackReq.GetDryRun(), Prune: rollbackReq.GetPrune(), SyncOptions: syncOptions, - SyncStrategy: &appv1.SyncStrategy{Apply: &appv1.SyncStrategyApply{}}, + SyncStrategy: &v1alpha1.SyncStrategy{Apply: &v1alpha1.SyncStrategyApply{}}, Source: &deploymentInfo.Source, Sources: deploymentInfo.Sources, }, - InitiatedBy: appv1.OperationInitiator{Username: session.Username(ctx)}, + InitiatedBy: v1alpha1.OperationInitiator{Username: session.Username(ctx)}, } appName := rollbackReq.GetName() appNs := s.appNamespaceOrDefault(rollbackReq.GetAppNamespace()) @@ -2146,16 +2144,16 @@ func (s *Server) ListLinks(ctx context.Context, req *application.ListAppLinksReq return finalList, nil } -func (s *Server) getObjectsForDeepLinks(ctx context.Context, app *appv1.Application, proj *appv1.AppProject) (cluster *unstructured.Unstructured, project *unstructured.Unstructured, err error) { +func (s *Server) getObjectsForDeepLinks(ctx context.Context, app *v1alpha1.Application, proj *v1alpha1.AppProject) (cluster *unstructured.Unstructured, project *unstructured.Unstructured, err error) { // sanitize project jwt tokens - proj.Status = appv1.AppProjectStatus{} + proj.Status = v1alpha1.AppProjectStatus{} project, err = kube.ToUnstructured(proj) if err != nil { return nil, nil, err } - getProjectClusters := func(project string) ([]*appv1.Cluster, error) { + getProjectClusters := func(project string) ([]*v1alpha1.Cluster, error) { return s.db.GetProjectClusters(ctx, project) } @@ -2228,7 +2226,7 @@ func (s *Server) ListResourceLinks(ctx context.Context, req *application.Applica return finalList, nil } -func getAmbiguousRevision(app *appv1.Application, syncReq *application.ApplicationSyncRequest, sourceIndex int) string { +func getAmbiguousRevision(app *v1alpha1.Application, syncReq *application.ApplicationSyncRequest, sourceIndex int) string { ambiguousRevision := "" if app.Spec.HasMultipleSources() { for i, pos := range syncReq.SourcePositions { @@ -2250,7 +2248,7 @@ func getAmbiguousRevision(app *appv1.Application, syncReq *application.Applicati // resolveRevision resolves the revision specified either in the sync request, or the // application source, into a concrete revision that will be used for a sync operation. -func (s *Server) resolveRevision(ctx context.Context, app *appv1.Application, syncReq *application.ApplicationSyncRequest, sourceIndex int) (string, string, error) { +func (s *Server) resolveRevision(ctx context.Context, app *v1alpha1.Application, syncReq *application.ApplicationSyncRequest, sourceIndex int) (string, string, error) { if syncReq.Manifests != nil { return "", "", nil } @@ -2324,7 +2322,7 @@ func (s *Server) TerminateOperation(ctx context.Context, termOpReq *application. return nil, status.Errorf(codes.Internal, "Failed to terminate app. Too many conflicts") } -func (s *Server) logAppEvent(a *appv1.Application, ctx context.Context, reason string, action string) { +func (s *Server) logAppEvent(a *v1alpha1.Application, ctx context.Context, reason string, action string) { eventInfo := argo.EventInfo{Type: corev1.EventTypeNormal, Reason: reason} user := session.Username(ctx) if user == "" { @@ -2335,7 +2333,7 @@ func (s *Server) logAppEvent(a *appv1.Application, ctx context.Context, reason s s.auditLogger.LogAppEvent(a, eventInfo, message, user, eventLabels) } -func (s *Server) logResourceEvent(res *appv1.ResourceNode, ctx context.Context, reason string, action string) { +func (s *Server) logResourceEvent(res *v1alpha1.ResourceNode, ctx context.Context, reason string, action string) { eventInfo := argo.EventInfo{Type: corev1.EventTypeNormal, Reason: reason} user := session.Username(ctx) if user == "" { @@ -2359,7 +2357,7 @@ func (s *Server) ListResourceActions(ctx context.Context, q *application.Applica if err != nil { return nil, fmt.Errorf("error getting available actions: %w", err) } - actionsPtr := []*appv1.ResourceAction{} + actionsPtr := []*v1alpha1.ResourceAction{} for i := range availableActions { actionsPtr = append(actionsPtr, &availableActions[i]) } @@ -2367,7 +2365,7 @@ func (s *Server) ListResourceActions(ctx context.Context, q *application.Applica return &application.ResourceActionsListResponse{Actions: actionsPtr}, nil } -func (s *Server) getUnstructuredLiveResourceOrApp(ctx context.Context, rbacRequest string, q *application.ApplicationResourceRequest) (obj *unstructured.Unstructured, res *appv1.ResourceNode, app *appv1.Application, config *rest.Config, err error) { +func (s *Server) getUnstructuredLiveResourceOrApp(ctx context.Context, rbacRequest string, q *application.ApplicationResourceRequest) (obj *unstructured.Unstructured, res *v1alpha1.ResourceNode, app *v1alpha1.Application, config *rest.Config, err error) { if q.GetKind() == applicationType.ApplicationKind && q.GetGroup() == applicationType.Group && q.GetName() == q.GetResourceName() { app, _, err = s.getApplicationEnforceRBACInformer(ctx, rbacRequest, q.GetProject(), q.GetAppNamespace(), q.GetName()) if err != nil { @@ -2394,7 +2392,7 @@ func (s *Server) getUnstructuredLiveResourceOrApp(ctx context.Context, rbacReque return } -func (s *Server) getAvailableActions(resourceOverrides map[string]appv1.ResourceOverride, obj *unstructured.Unstructured) ([]appv1.ResourceAction, error) { +func (s *Server) getAvailableActions(resourceOverrides map[string]v1alpha1.ResourceOverride, obj *unstructured.Unstructured) ([]v1alpha1.ResourceAction, error) { luaVM := lua.VM{ ResourceOverrides: resourceOverrides, } @@ -2404,7 +2402,7 @@ func (s *Server) getAvailableActions(resourceOverrides map[string]appv1.Resource return nil, fmt.Errorf("error getting Lua discovery script: %w", err) } if len(discoveryScripts) == 0 { - return []appv1.ResourceAction{}, nil + return []v1alpha1.ResourceAction{}, nil } availableActions, err := luaVM.ExecuteResourceActionDiscovery(obj, discoveryScripts) if err != nil { @@ -2453,7 +2451,7 @@ func (s *Server) RunResourceAction(ctx context.Context, q *application.ResourceA return nil, fmt.Errorf("error executing Lua resource action: %w", err) } - var app *appv1.Application + var app *v1alpha1.Application // Only bother getting the app if we know we're going to need it for a resource permission check. if len(newObjects) > 0 { // No need for an RBAC check, we checked above that the user is allowed to run this action. @@ -2568,8 +2566,8 @@ func (s *Server) patchResource(ctx context.Context, config *rest.Config, liveObj return &application.ApplicationResponse{}, nil } -func (s *Server) verifyResourcePermitted(app *appv1.Application, proj *appv1.AppProject, obj *unstructured.Unstructured) error { - permitted, err := proj.IsResourcePermitted(schema.GroupKind{Group: obj.GroupVersionKind().Group, Kind: obj.GroupVersionKind().Kind}, obj.GetNamespace(), app.Spec.Destination, func(project string) ([]*appv1.Cluster, error) { +func (s *Server) verifyResourcePermitted(app *v1alpha1.Application, proj *v1alpha1.AppProject, obj *unstructured.Unstructured) error { + permitted, err := proj.IsResourcePermitted(schema.GroupKind{Group: obj.GroupVersionKind().Group, Kind: obj.GroupVersionKind().Kind}, obj.GetNamespace(), app.Spec.Destination, func(project string) ([]*v1alpha1.Cluster, error) { clusters, err := s.db.GetProjectClusters(context.TODO(), project) if err != nil { return nil, fmt.Errorf("failed to get project clusters: %w", err) @@ -2652,11 +2650,11 @@ func (s *Server) GetApplicationSyncWindows(ctx context.Context, q *application.A return res, nil } -func (s *Server) inferResourcesStatusHealth(app *appv1.Application) { - if app.Status.ResourceHealthSource == appv1.ResourceHealthLocationAppTree { - tree := &appv1.ApplicationTree{} +func (s *Server) inferResourcesStatusHealth(app *v1alpha1.Application) { + if app.Status.ResourceHealthSource == v1alpha1.ResourceHealthLocationAppTree { + tree := &v1alpha1.ApplicationTree{} if err := s.cache.GetAppResourcesTree(app.Name, tree); err == nil { - healthByKey := map[kube.ResourceKey]*appv1.HealthStatus{} + healthByKey := map[kube.ResourceKey]*v1alpha1.HealthStatus{} for _, node := range tree.Nodes { healthByKey[kube.NewResourceKey(node.Group, node.Kind, node.Namespace, node.Name)] = node.Health } @@ -2668,7 +2666,7 @@ func (s *Server) inferResourcesStatusHealth(app *appv1.Application) { } } -func convertSyncWindows(w *appv1.SyncWindows) []*application.ApplicationSyncWindow { +func convertSyncWindows(w *v1alpha1.SyncWindows) []*application.ApplicationSyncWindow { if w != nil { var windows []*application.ApplicationSyncWindow for _, w := range *w { @@ -2690,11 +2688,11 @@ func convertSyncWindows(w *appv1.SyncWindows) []*application.ApplicationSyncWind func getPropagationPolicyFinalizer(policy string) string { switch strings.ToLower(policy) { case backgroundPropagationPolicy: - return appv1.BackgroundPropagationPolicyFinalizer + return v1alpha1.BackgroundPropagationPolicyFinalizer case foregroundPropagationPolicy: - return appv1.ForegroundPropagationPolicyFinalizer + return v1alpha1.ForegroundPropagationPolicyFinalizer case "": - return appv1.ResourcesFinalizerName + return v1alpha1.ResourcesFinalizerName default: return "" } diff --git a/server/application/application_test.go b/server/application/application_test.go index a3e26d52a6028..51074a86cec65 100644 --- a/server/application/application_test.go +++ b/server/application/application_test.go @@ -52,7 +52,6 @@ import ( "github.com/argoproj/argo-cd/v2/util/argo" "github.com/argoproj/argo-cd/v2/util/assets" "github.com/argoproj/argo-cd/v2/util/cache" - cacheutil "github.com/argoproj/argo-cd/v2/util/cache" "github.com/argoproj/argo-cd/v2/util/cache/appstate" "github.com/argoproj/argo-cd/v2/util/db" "github.com/argoproj/argo-cd/v2/util/errors" @@ -2357,7 +2356,7 @@ func TestGetAppRefresh_HardRefresh(t *testing.T) { } func TestInferResourcesStatusHealth(t *testing.T) { - cacheClient := cacheutil.NewCache(cacheutil.NewInMemoryCache(1 * time.Hour)) + cacheClient := cache.NewCache(cache.NewInMemoryCache(1 * time.Hour)) testApp := newTestApp() testApp.Status.ResourceHealthSource = v1alpha1.ResourceHealthLocationAppTree @@ -2397,7 +2396,7 @@ func TestInferResourcesStatusHealth(t *testing.T) { } func TestRunNewStyleResourceAction(t *testing.T) { - cacheClient := cacheutil.NewCache(cacheutil.NewInMemoryCache(1 * time.Hour)) + cacheClient := cache.NewCache(cache.NewInMemoryCache(1 * time.Hour)) group := "batch" kind := "CronJob" @@ -2526,7 +2525,7 @@ func TestRunNewStyleResourceAction(t *testing.T) { } func TestRunOldStyleResourceAction(t *testing.T) { - cacheClient := cacheutil.NewCache(cacheutil.NewInMemoryCache(1 * time.Hour)) + cacheClient := cache.NewCache(cache.NewInMemoryCache(1 * time.Hour)) group := "apps" kind := "Deployment" diff --git a/server/application/terminal.go b/server/application/terminal.go index ecfc20f85c090..bc493f74a0a56 100644 --- a/server/application/terminal.go +++ b/server/application/terminal.go @@ -16,8 +16,6 @@ import ( "k8s.io/client-go/rest" "k8s.io/client-go/tools/remotecommand" - util_session "github.com/argoproj/argo-cd/v2/util/session" - appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" applisters "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1" servercache "github.com/argoproj/argo-cd/v2/server/cache" @@ -26,7 +24,7 @@ import ( "github.com/argoproj/argo-cd/v2/util/db" "github.com/argoproj/argo-cd/v2/util/rbac" "github.com/argoproj/argo-cd/v2/util/security" - sessionmgr "github.com/argoproj/argo-cd/v2/util/session" + util_session "github.com/argoproj/argo-cd/v2/util/session" "github.com/argoproj/argo-cd/v2/util/settings" ) @@ -48,7 +46,7 @@ type TerminalOptions struct { } // NewHandler returns a new terminal handler. -func NewHandler(appLister applisters.ApplicationLister, namespace string, enabledNamespaces []string, db db.ArgoDB, cache *servercache.Cache, appResourceTree AppResourceTreeFn, allowedShells []string, sessionManager *sessionmgr.SessionManager, terminalOptions *TerminalOptions) *terminalHandler { +func NewHandler(appLister applisters.ApplicationLister, namespace string, enabledNamespaces []string, db db.ArgoDB, cache *servercache.Cache, appResourceTree AppResourceTreeFn, allowedShells []string, sessionManager *util_session.SessionManager, terminalOptions *TerminalOptions) *terminalHandler { return &terminalHandler{ appLister: appLister, db: db, @@ -164,7 +162,7 @@ func (s *terminalHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } fieldLog := log.WithFields(log.Fields{ - "application": app, "userName": sessionmgr.Username(ctx), "container": container, + "application": app, "userName": util_session.Username(ctx), "container": container, "podName": podName, "namespace": namespace, "project": project, "appNamespace": appNamespace, }) diff --git a/server/cluster/cluster_test.go b/server/cluster/cluster_test.go index 9f9290b36bbac..33aad37bc4f37 100644 --- a/server/cluster/cluster_test.go +++ b/server/cluster/cluster_test.go @@ -25,9 +25,7 @@ import ( "github.com/argoproj/argo-cd/v2/common" "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" - clusterapi "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" servercache "github.com/argoproj/argo-cd/v2/server/cache" "github.com/argoproj/argo-cd/v2/test" cacheutil "github.com/argoproj/argo-cd/v2/util/cache" @@ -137,23 +135,23 @@ func newEnforcer() *rbac.Enforcer { func TestUpdateCluster_RejectInvalidParams(t *testing.T) { testCases := []struct { name string - request clusterapi.ClusterUpdateRequest + request cluster.ClusterUpdateRequest }{ { name: "allowed cluster URL in body, disallowed cluster URL in query", - request: clusterapi.ClusterUpdateRequest{Cluster: &v1alpha1.Cluster{Name: "", Server: "https://127.0.0.1", Project: "", ClusterResources: true}, Id: &clusterapi.ClusterID{Type: "", Value: "https://127.0.0.2"}, UpdatedFields: []string{"clusterResources", "project"}}, + request: cluster.ClusterUpdateRequest{Cluster: &v1alpha1.Cluster{Name: "", Server: "https://127.0.0.1", Project: "", ClusterResources: true}, Id: &cluster.ClusterID{Type: "", Value: "https://127.0.0.2"}, UpdatedFields: []string{"clusterResources", "project"}}, }, { name: "allowed cluster URL in body, disallowed cluster name in query", - request: clusterapi.ClusterUpdateRequest{Cluster: &v1alpha1.Cluster{Name: "", Server: "https://127.0.0.1", Project: "", ClusterResources: true}, Id: &clusterapi.ClusterID{Type: "name", Value: "disallowed-unscoped"}, UpdatedFields: []string{"clusterResources", "project"}}, + request: cluster.ClusterUpdateRequest{Cluster: &v1alpha1.Cluster{Name: "", Server: "https://127.0.0.1", Project: "", ClusterResources: true}, Id: &cluster.ClusterID{Type: "name", Value: "disallowed-unscoped"}, UpdatedFields: []string{"clusterResources", "project"}}, }, { name: "allowed cluster URL in body, disallowed cluster name in query, changing unscoped to scoped", - request: clusterapi.ClusterUpdateRequest{Cluster: &v1alpha1.Cluster{Name: "", Server: "https://127.0.0.1", Project: "allowed-project", ClusterResources: true}, Id: &clusterapi.ClusterID{Type: "", Value: "https://127.0.0.2"}, UpdatedFields: []string{"clusterResources", "project"}}, + request: cluster.ClusterUpdateRequest{Cluster: &v1alpha1.Cluster{Name: "", Server: "https://127.0.0.1", Project: "allowed-project", ClusterResources: true}, Id: &cluster.ClusterID{Type: "", Value: "https://127.0.0.2"}, UpdatedFields: []string{"clusterResources", "project"}}, }, { name: "allowed cluster URL in body, disallowed cluster URL in query, changing unscoped to scoped", - request: clusterapi.ClusterUpdateRequest{Cluster: &v1alpha1.Cluster{Name: "", Server: "https://127.0.0.1", Project: "allowed-project", ClusterResources: true}, Id: &clusterapi.ClusterID{Type: "name", Value: "disallowed-unscoped"}, UpdatedFields: []string{"clusterResources", "project"}}, + request: cluster.ClusterUpdateRequest{Cluster: &v1alpha1.Cluster{Name: "", Server: "https://127.0.0.1", Project: "allowed-project", ClusterResources: true}, Id: &cluster.ClusterID{Type: "name", Value: "disallowed-unscoped"}, UpdatedFields: []string{"clusterResources", "project"}}, }, } @@ -264,15 +262,15 @@ func TestGetCluster_UrlEncodedName(t *testing.T) { server := NewServer(db, newNoopEnforcer(), newServerInMemoryCache(), &kubetest.MockKubectlCmd{}) - cluster, err := server.Get(context.Background(), &clusterapi.ClusterQuery{ - Id: &clusterapi.ClusterID{ + localCluster, err := server.Get(context.Background(), &cluster.ClusterQuery{ + Id: &cluster.ClusterID{ Type: "name_escaped", Value: "test%2fing", }, }) require.NoError(t, err) - assert.Equal(t, "test/ing", cluster.Name) + assert.Equal(t, "test/ing", localCluster.Name) } func TestGetCluster_NameWithUrlEncodingButShouldNotBeUnescaped(t *testing.T) { @@ -294,20 +292,20 @@ func TestGetCluster_NameWithUrlEncodingButShouldNotBeUnescaped(t *testing.T) { server := NewServer(db, newNoopEnforcer(), newServerInMemoryCache(), &kubetest.MockKubectlCmd{}) - cluster, err := server.Get(context.Background(), &clusterapi.ClusterQuery{ - Id: &clusterapi.ClusterID{ + localCluster, err := server.Get(context.Background(), &cluster.ClusterQuery{ + Id: &cluster.ClusterID{ Type: "name", Value: "test%2fing", }, }) require.NoError(t, err) - assert.Equal(t, "test%2fing", cluster.Name) + assert.Equal(t, "test%2fing", localCluster.Name) } func TestGetCluster_CannotSetCADataAndInsecureTrue(t *testing.T) { testNamespace := "default" - cluster := &v1alpha1.Cluster{ + localCluster := &v1alpha1.Cluster{ Name: "my-cluster-name", Server: "https://my-cluster-server", Namespaces: []string{testNamespace}, @@ -325,17 +323,17 @@ func TestGetCluster_CannotSetCADataAndInsecureTrue(t *testing.T) { server := NewServer(db, newNoopEnforcer(), newServerInMemoryCache(), &kubetest.MockKubectlCmd{}) t.Run("Create Fails When CAData is Set and Insecure is True", func(t *testing.T) { - _, err := server.Create(context.Background(), &clusterapi.ClusterCreateRequest{ - Cluster: cluster, + _, err := server.Create(context.Background(), &cluster.ClusterCreateRequest{ + Cluster: localCluster, }) assert.EqualError(t, err, `error getting REST config: Unable to apply K8s REST config defaults: specifying a root certificates file with the insecure flag is not allowed`) }) - cluster.Config.TLSClientConfig.CAData = nil + localCluster.Config.TLSClientConfig.CAData = nil t.Run("Create Succeeds When CAData is nil and Insecure is True", func(t *testing.T) { - _, err := server.Create(context.Background(), &clusterapi.ClusterCreateRequest{ - Cluster: cluster, + _, err := server.Create(context.Background(), &cluster.ClusterCreateRequest{ + Cluster: localCluster, }) require.NoError(t, err) }) @@ -366,7 +364,7 @@ func TestUpdateCluster_NoFieldsPaths(t *testing.T) { server := NewServer(db, newNoopEnforcer(), newServerInMemoryCache(), &kubetest.MockKubectlCmd{}) - _, err := server.Update(context.Background(), &clusterapi.ClusterUpdateRequest{ + _, err := server.Update(context.Background(), &cluster.ClusterUpdateRequest{ Cluster: &v1alpha1.Cluster{ Name: "minikube", Namespaces: []string{"default", "kube-system"}, @@ -394,7 +392,7 @@ func TestUpdateCluster_FieldsPathSet(t *testing.T) { server := NewServer(db, newNoopEnforcer(), newServerInMemoryCache(), &kubetest.MockKubectlCmd{}) - _, err := server.Update(context.Background(), &clusterapi.ClusterUpdateRequest{ + _, err := server.Update(context.Background(), &cluster.ClusterUpdateRequest{ Cluster: &v1alpha1.Cluster{ Server: "https://127.0.0.1", Shard: ptr.To(int64(1)), @@ -411,7 +409,7 @@ func TestUpdateCluster_FieldsPathSet(t *testing.T) { labelEnv := map[string]string{ "env": "qa", } - _, err = server.Update(context.Background(), &clusterapi.ClusterUpdateRequest{ + _, err = server.Update(context.Background(), &cluster.ClusterUpdateRequest{ Cluster: &v1alpha1.Cluster{ Server: "https://127.0.0.1", Labels: labelEnv, @@ -428,7 +426,7 @@ func TestUpdateCluster_FieldsPathSet(t *testing.T) { annotationEnv := map[string]string{ "env": "qa", } - _, err = server.Update(context.Background(), &clusterapi.ClusterUpdateRequest{ + _, err = server.Update(context.Background(), &cluster.ClusterUpdateRequest{ Cluster: &v1alpha1.Cluster{ Server: "https://127.0.0.1", Annotations: annotationEnv, @@ -442,7 +440,7 @@ func TestUpdateCluster_FieldsPathSet(t *testing.T) { assert.Equal(t, []string{"default", "kube-system"}, updated.Namespaces) assert.Equal(t, updated.Annotations, annotationEnv) - _, err = server.Update(context.Background(), &clusterapi.ClusterUpdateRequest{ + _, err = server.Update(context.Background(), &cluster.ClusterUpdateRequest{ Cluster: &v1alpha1.Cluster{ Server: "https://127.0.0.1", Project: "new-project", @@ -480,7 +478,7 @@ func TestDeleteClusterByName(t *testing.T) { server := NewServer(db, newNoopEnforcer(), newServerInMemoryCache(), &kubetest.MockKubectlCmd{}) t.Run("Delete Fails When Deleting by Unknown Name", func(t *testing.T) { - _, err := server.Delete(context.Background(), &clusterapi.ClusterQuery{ + _, err := server.Delete(context.Background(), &cluster.ClusterQuery{ Name: "foo", }) @@ -488,7 +486,7 @@ func TestDeleteClusterByName(t *testing.T) { }) t.Run("Delete Succeeds When Deleting by Name", func(t *testing.T) { - _, err := server.Delete(context.Background(), &clusterapi.ClusterQuery{ + _, err := server.Delete(context.Background(), &cluster.ClusterQuery{ Name: "my-cluster-name", }) require.NoError(t, err) @@ -557,7 +555,7 @@ func TestRotateAuth(t *testing.T) { server := NewServer(db, newNoopEnforcer(), newServerInMemoryCache(), &kubetest.MockKubectlCmd{}) t.Run("RotateAuth by Unknown Name", func(t *testing.T) { - _, err := server.RotateAuth(context.Background(), &clusterapi.ClusterQuery{ + _, err := server.RotateAuth(context.Background(), &cluster.ClusterQuery{ Name: "foo", }) @@ -568,7 +566,7 @@ func TestRotateAuth(t *testing.T) { // demonstrate the proper mapping of cluster names/server to server info (i.e. my-cluster-name // results in https://my-cluster-name info being used and https://my-cluster-name results in https://my-cluster-name). t.Run("RotateAuth by Name - Error from no such host", func(t *testing.T) { - _, err := server.RotateAuth(context.Background(), &clusterapi.ClusterQuery{ + _, err := server.RotateAuth(context.Background(), &cluster.ClusterQuery{ Name: "my-cluster-name", }) @@ -576,7 +574,7 @@ func TestRotateAuth(t *testing.T) { }) t.Run("RotateAuth by Server - Error from no such host", func(t *testing.T) { - _, err := server.RotateAuth(context.Background(), &clusterapi.ClusterQuery{ + _, err := server.RotateAuth(context.Background(), &cluster.ClusterQuery{ Server: "https://my-cluster-name", }) @@ -639,12 +637,12 @@ func TestListCluster(t *testing.T) { tests := []struct { name string q *cluster.ClusterQuery - want *appv1.ClusterList + want *v1alpha1.ClusterList wantErr bool }{ { name: "filter by name", - q: &clusterapi.ClusterQuery{ + q: &cluster.ClusterQuery{ Name: fooCluster.Name, }, want: &v1alpha1.ClusterList{ @@ -654,7 +652,7 @@ func TestListCluster(t *testing.T) { }, { name: "filter by server", - q: &clusterapi.ClusterQuery{ + q: &cluster.ClusterQuery{ Server: barCluster.Server, }, want: &v1alpha1.ClusterList{ @@ -664,8 +662,8 @@ func TestListCluster(t *testing.T) { }, { name: "filter by id - name", - q: &clusterapi.ClusterQuery{ - Id: &clusterapi.ClusterID{ + q: &cluster.ClusterQuery{ + Id: &cluster.ClusterID{ Type: "name", Value: fooCluster.Name, }, @@ -677,8 +675,8 @@ func TestListCluster(t *testing.T) { }, { name: "filter by id - name_escaped", - q: &clusterapi.ClusterQuery{ - Id: &clusterapi.ClusterID{ + q: &cluster.ClusterQuery{ + Id: &cluster.ClusterID{ Type: "name_escaped", Value: "test%2fing", }, @@ -690,8 +688,8 @@ func TestListCluster(t *testing.T) { }, { name: "filter by id - server", - q: &clusterapi.ClusterQuery{ - Id: &clusterapi.ClusterID{ + q: &cluster.ClusterQuery{ + Id: &cluster.ClusterID{ Type: "server", Value: barCluster.Server, }, @@ -737,11 +735,11 @@ func TestGetClusterAndVerifyAccess(t *testing.T) { db.On("ListClusters", mock.Anything).Return(&mockClusterList, nil) server := NewServer(db, newNoopEnforcer(), newServerInMemoryCache(), &kubetest.MockKubectlCmd{}) - cluster, err := server.getClusterAndVerifyAccess(context.Background(), &clusterapi.ClusterQuery{ + localCluster, err := server.getClusterAndVerifyAccess(context.Background(), &cluster.ClusterQuery{ Name: "test/not-exists", }, rbacpolicy.ActionGet) - assert.Nil(t, cluster) + assert.Nil(t, localCluster) assert.ErrorIs(t, err, common.PermissionDeniedAPIError) }) @@ -763,11 +761,11 @@ func TestGetClusterAndVerifyAccess(t *testing.T) { db.On("ListClusters", mock.Anything).Return(&mockClusterList, nil) server := NewServer(db, newEnforcer(), newServerInMemoryCache(), &kubetest.MockKubectlCmd{}) - cluster, err := server.getClusterAndVerifyAccess(context.Background(), &clusterapi.ClusterQuery{ + localCluster, err := server.getClusterAndVerifyAccess(context.Background(), &cluster.ClusterQuery{ Name: "test/ing", }, rbacpolicy.ActionGet) - assert.Nil(t, cluster) + assert.Nil(t, localCluster) assert.ErrorIs(t, err, common.PermissionDeniedAPIError) }) } @@ -793,26 +791,26 @@ func TestNoClusterEnumeration(t *testing.T) { server := NewServer(db, newEnforcer(), newServerInMemoryCache(), &kubetest.MockKubectlCmd{}) t.Run("Get", func(t *testing.T) { - _, err := server.Get(context.Background(), &clusterapi.ClusterQuery{ + _, err := server.Get(context.Background(), &cluster.ClusterQuery{ Name: "cluster-not-exists", }) require.ErrorIs(t, err, common.PermissionDeniedAPIError, "error message must be _only_ the permission error, to avoid leaking information about cluster existence") - _, err = server.Get(context.Background(), &clusterapi.ClusterQuery{ + _, err = server.Get(context.Background(), &cluster.ClusterQuery{ Name: "test/ing", }) assert.ErrorIs(t, err, common.PermissionDeniedAPIError, "error message must be _only_ the permission error, to avoid leaking information about cluster existence") }) t.Run("Update", func(t *testing.T) { - _, err := server.Update(context.Background(), &clusterapi.ClusterUpdateRequest{ + _, err := server.Update(context.Background(), &cluster.ClusterUpdateRequest{ Cluster: &v1alpha1.Cluster{ Name: "cluster-not-exists", }, }) require.ErrorIs(t, err, common.PermissionDeniedAPIError, "error message must be _only_ the permission error, to avoid leaking information about cluster existence") - _, err = server.Update(context.Background(), &clusterapi.ClusterUpdateRequest{ + _, err = server.Update(context.Background(), &cluster.ClusterUpdateRequest{ Cluster: &v1alpha1.Cluster{ Name: "test/ing", }, @@ -821,36 +819,36 @@ func TestNoClusterEnumeration(t *testing.T) { }) t.Run("Delete", func(t *testing.T) { - _, err := server.Delete(context.Background(), &clusterapi.ClusterQuery{ + _, err := server.Delete(context.Background(), &cluster.ClusterQuery{ Server: "https://127.0.0.2", }) require.ErrorIs(t, err, common.PermissionDeniedAPIError, "error message must be _only_ the permission error, to avoid leaking information about cluster existence") - _, err = server.Delete(context.Background(), &clusterapi.ClusterQuery{ + _, err = server.Delete(context.Background(), &cluster.ClusterQuery{ Server: "https://127.0.0.1", }) assert.ErrorIs(t, err, common.PermissionDeniedAPIError, "error message must be _only_ the permission error, to avoid leaking information about cluster existence") }) t.Run("RotateAuth", func(t *testing.T) { - _, err := server.RotateAuth(context.Background(), &clusterapi.ClusterQuery{ + _, err := server.RotateAuth(context.Background(), &cluster.ClusterQuery{ Server: "https://127.0.0.2", }) require.ErrorIs(t, err, common.PermissionDeniedAPIError, "error message must be _only_ the permission error, to avoid leaking information about cluster existence") - _, err = server.RotateAuth(context.Background(), &clusterapi.ClusterQuery{ + _, err = server.RotateAuth(context.Background(), &cluster.ClusterQuery{ Server: "https://127.0.0.1", }) assert.ErrorIs(t, err, common.PermissionDeniedAPIError, "error message must be _only_ the permission error, to avoid leaking information about cluster existence") }) t.Run("InvalidateCache", func(t *testing.T) { - _, err := server.InvalidateCache(context.Background(), &clusterapi.ClusterQuery{ + _, err := server.InvalidateCache(context.Background(), &cluster.ClusterQuery{ Server: "https://127.0.0.2", }) require.ErrorIs(t, err, common.PermissionDeniedAPIError, "error message must be _only_ the permission error, to avoid leaking information about cluster existence") - _, err = server.InvalidateCache(context.Background(), &clusterapi.ClusterQuery{ + _, err = server.InvalidateCache(context.Background(), &cluster.ClusterQuery{ Server: "https://127.0.0.1", }) assert.ErrorIs(t, err, common.PermissionDeniedAPIError, "error message must be _only_ the permission error, to avoid leaking information about cluster existence") diff --git a/server/repository/repository.go b/server/repository/repository.go index 0e91811e929b4..b2bee86f19fdd 100644 --- a/server/repository/repository.go +++ b/server/repository/repository.go @@ -19,7 +19,6 @@ import ( "github.com/argoproj/argo-cd/v2/common" repositorypkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/repository" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - appsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" applisters "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1" "github.com/argoproj/argo-cd/v2/reposerver/apiclient" servercache "github.com/argoproj/argo-cd/v2/server/cache" @@ -71,7 +70,7 @@ func NewServer( } } -func (s *Server) getRepo(ctx context.Context, url, project string) (*appsv1.Repository, error) { +func (s *Server) getRepo(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { repo, err := s.db.GetRepository(ctx, url, project) if err != nil { return nil, common.PermissionDeniedAPIError @@ -79,7 +78,7 @@ func (s *Server) getRepo(ctx context.Context, url, project string) (*appsv1.Repo return repo, nil } -func (s *Server) getWriteRepo(ctx context.Context, url, project string) (*appsv1.Repository, error) { +func (s *Server) getWriteRepo(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { repo, err := s.db.GetWriteRepository(ctx, url, project) if err != nil { return nil, common.PermissionDeniedAPIError @@ -97,15 +96,15 @@ func createRBACObject(project string, repo string) string { // Get the connection state for a given repository URL by connecting to the // repo and evaluate the results. Unless forceRefresh is set to true, the // result may be retrieved out of the cache. -func (s *Server) getConnectionState(ctx context.Context, url string, project string, forceRefresh bool) appsv1.ConnectionState { +func (s *Server) getConnectionState(ctx context.Context, url string, project string, forceRefresh bool) v1alpha1.ConnectionState { if !forceRefresh { if connectionState, err := s.cache.GetRepoConnectionState(url, project); err == nil { return connectionState } } now := metav1.Now() - connectionState := appsv1.ConnectionState{ - Status: appsv1.ConnectionStatusSuccessful, + connectionState := v1alpha1.ConnectionState{ + Status: v1alpha1.ConnectionStatusSuccessful, ModifiedAt: &now, } var err error @@ -114,7 +113,7 @@ func (s *Server) getConnectionState(ctx context.Context, url string, project str err = s.testRepo(ctx, repo) } if err != nil { - connectionState.Status = appsv1.ConnectionStatusFailed + connectionState.Status = v1alpha1.ConnectionStatusFailed if errors.IsCredentialsConfigurationError(err) { connectionState.Message = "Configuration error - please check the server logs" log.Warnf("could not retrieve repo: %s", err.Error()) @@ -131,12 +130,12 @@ func (s *Server) getConnectionState(ctx context.Context, url string, project str // List returns list of repositories // Deprecated: Use ListRepositories instead -func (s *Server) List(ctx context.Context, q *repositorypkg.RepoQuery) (*appsv1.RepositoryList, error) { +func (s *Server) List(ctx context.Context, q *repositorypkg.RepoQuery) (*v1alpha1.RepositoryList, error) { return s.ListRepositories(ctx, q) } // Get return the requested configured repository by URL and the state of its connections. -func (s *Server) Get(ctx context.Context, q *repositorypkg.RepoQuery) (*appsv1.Repository, error) { +func (s *Server) Get(ctx context.Context, q *repositorypkg.RepoQuery) (*v1alpha1.Repository, error) { // ListRepositories normalizes the repo, sanitizes it, and augments it with connection details. repo, err := getRepository(ctx, s.ListRepositories, q) if err != nil { @@ -158,7 +157,7 @@ func (s *Server) Get(ctx context.Context, q *repositorypkg.RepoQuery) (*appsv1.R return repo, nil } -func (s *Server) GetWrite(ctx context.Context, q *repositorypkg.RepoQuery) (*appsv1.Repository, error) { +func (s *Server) GetWrite(ctx context.Context, q *repositorypkg.RepoQuery) (*v1alpha1.Repository, error) { if !s.hydratorEnabled { return nil, status.Error(codes.Unimplemented, "hydrator is disabled") } @@ -184,7 +183,7 @@ func (s *Server) GetWrite(ctx context.Context, q *repositorypkg.RepoQuery) (*app } // ListRepositories returns a list of all configured repositories and the state of their connections -func (s *Server) ListRepositories(ctx context.Context, q *repositorypkg.RepoQuery) (*appsv1.RepositoryList, error) { +func (s *Server) ListRepositories(ctx context.Context, q *repositorypkg.RepoQuery) (*v1alpha1.RepositoryList, error) { repos, err := s.db.ListRepositories(ctx) if err != nil { return nil, err @@ -193,12 +192,12 @@ func (s *Server) ListRepositories(ctx context.Context, q *repositorypkg.RepoQuer if err != nil { return nil, err } - return &appsv1.RepositoryList{Items: items}, nil + return &v1alpha1.RepositoryList{Items: items}, nil } // ListWriteRepositories returns a list of all configured repositories where the user has write access and the state of // their connections -func (s *Server) ListWriteRepositories(ctx context.Context, q *repositorypkg.RepoQuery) (*appsv1.RepositoryList, error) { +func (s *Server) ListWriteRepositories(ctx context.Context, q *repositorypkg.RepoQuery) (*v1alpha1.RepositoryList, error) { if !s.hydratorEnabled { return nil, status.Error(codes.Unimplemented, "hydrator is disabled") } @@ -211,18 +210,18 @@ func (s *Server) ListWriteRepositories(ctx context.Context, q *repositorypkg.Rep if err != nil { return nil, err } - return &appsv1.RepositoryList{Items: items}, nil + return &v1alpha1.RepositoryList{Items: items}, nil } // ListRepositoriesByAppProject returns a list of all configured repositories and the state of their connections. It // normalizes, sanitizes, and filters out repositories that the user does not have access to in the specified project. // It also sorts the repositories by project and repo name. -func (s *Server) prepareRepoList(ctx context.Context, resourceType string, repos []*appsv1.Repository, forceRefresh bool) (appsv1.Repositories, error) { - items := appsv1.Repositories{} +func (s *Server) prepareRepoList(ctx context.Context, resourceType string, repos []*v1alpha1.Repository, forceRefresh bool) (v1alpha1.Repositories, error) { + items := v1alpha1.Repositories{} for _, repo := range repos { items = append(items, repo.Normalize().Sanitized()) } - items = items.Filter(func(r *appsv1.Repository) bool { + items = items.Filter(func(r *v1alpha1.Repository) bool { return s.enf.Enforce(ctx.Value("claims"), resourceType, rbacpolicy.ActionGet, createRBACObject(r.Project, r.Repo)) }) err := kube.RunAllAsync(len(items), func(i int) error { @@ -373,7 +372,7 @@ func (s *Server) GetAppDetails(ctx context.Context, q *repositorypkg.RepoAppDeta return nil, err } - refSources := make(appsv1.RefTargetRevisionMapping) + refSources := make(v1alpha1.RefTargetRevisionMapping) if app != nil && app.Spec.HasMultipleSources() { // Store the map of all sources having ref field into a map for applications with sources field refSources, err = argo.GetRefSources(ctx, app.Spec.Sources, q.AppProject, s.db.GetRepository, []string{}, false) @@ -412,12 +411,12 @@ func (s *Server) GetHelmCharts(ctx context.Context, q *repositorypkg.RepoQuery) // Create creates a repository or repository credential set // Deprecated: Use CreateRepository() instead -func (s *Server) Create(ctx context.Context, q *repositorypkg.RepoCreateRequest) (*appsv1.Repository, error) { +func (s *Server) Create(ctx context.Context, q *repositorypkg.RepoCreateRequest) (*v1alpha1.Repository, error) { return s.CreateRepository(ctx, q) } // CreateRepository creates a repository configuration -func (s *Server) CreateRepository(ctx context.Context, q *repositorypkg.RepoCreateRequest) (*appsv1.Repository, error) { +func (s *Server) CreateRepository(ctx context.Context, q *repositorypkg.RepoCreateRequest) (*v1alpha1.Repository, error) { if q.Repo == nil { return nil, status.Errorf(codes.InvalidArgument, "missing payload in request") } @@ -426,7 +425,7 @@ func (s *Server) CreateRepository(ctx context.Context, q *repositorypkg.RepoCrea return nil, err } - var repo *appsv1.Repository + var repo *v1alpha1.Repository var err error // check we can connect to the repo, copying any existing creds (not supported for project scoped repositories) @@ -447,7 +446,7 @@ func (s *Server) CreateRepository(ctx context.Context, q *repositorypkg.RepoCrea } r := q.Repo - r.ConnectionState = appsv1.ConnectionState{Status: appsv1.ConnectionStatusSuccessful} + r.ConnectionState = v1alpha1.ConnectionState{Status: v1alpha1.ConnectionStatusSuccessful} repo, err = s.db.CreateRepository(ctx, r) if status.Convert(err).Code() == codes.AlreadyExists { // act idempotent if existing spec matches new spec @@ -471,11 +470,11 @@ func (s *Server) CreateRepository(ctx context.Context, q *repositorypkg.RepoCrea if err != nil { return nil, err } - return &appsv1.Repository{Repo: repo.Repo, Type: repo.Type, Name: repo.Name}, nil + return &v1alpha1.Repository{Repo: repo.Repo, Type: repo.Type, Name: repo.Name}, nil } // CreateWriteRepository creates a repository configuration with write credentials -func (s *Server) CreateWriteRepository(ctx context.Context, q *repositorypkg.RepoCreateRequest) (*appsv1.Repository, error) { +func (s *Server) CreateWriteRepository(ctx context.Context, q *repositorypkg.RepoCreateRequest) (*v1alpha1.Repository, error) { if !s.hydratorEnabled { return nil, status.Error(codes.Unimplemented, "hydrator is disabled") } @@ -515,17 +514,17 @@ func (s *Server) CreateWriteRepository(ctx context.Context, q *repositorypkg.Rep if err != nil { return nil, err } - return &appsv1.Repository{Repo: repo.Repo, Type: repo.Type, Name: repo.Name}, nil + return &v1alpha1.Repository{Repo: repo.Repo, Type: repo.Type, Name: repo.Name}, nil } // Update updates a repository or credential set // Deprecated: Use UpdateRepository() instead -func (s *Server) Update(ctx context.Context, q *repositorypkg.RepoUpdateRequest) (*appsv1.Repository, error) { +func (s *Server) Update(ctx context.Context, q *repositorypkg.RepoUpdateRequest) (*v1alpha1.Repository, error) { return s.UpdateRepository(ctx, q) } // UpdateRepository updates a repository configuration -func (s *Server) UpdateRepository(ctx context.Context, q *repositorypkg.RepoUpdateRequest) (*appsv1.Repository, error) { +func (s *Server) UpdateRepository(ctx context.Context, q *repositorypkg.RepoUpdateRequest) (*v1alpha1.Repository, error) { if q.Repo == nil { return nil, status.Errorf(codes.InvalidArgument, "missing payload in request") } @@ -544,11 +543,11 @@ func (s *Server) UpdateRepository(ctx context.Context, q *repositorypkg.RepoUpda return nil, err } _, err = s.db.UpdateRepository(ctx, q.Repo) - return &appsv1.Repository{Repo: q.Repo.Repo, Type: q.Repo.Type, Name: q.Repo.Name}, err + return &v1alpha1.Repository{Repo: q.Repo.Repo, Type: q.Repo.Type, Name: q.Repo.Name}, err } // UpdateWriteRepository updates a repository configuration with write credentials -func (s *Server) UpdateWriteRepository(ctx context.Context, q *repositorypkg.RepoUpdateRequest) (*appsv1.Repository, error) { +func (s *Server) UpdateWriteRepository(ctx context.Context, q *repositorypkg.RepoUpdateRequest) (*v1alpha1.Repository, error) { if !s.hydratorEnabled { return nil, status.Error(codes.Unimplemented, "hydrator is disabled") } @@ -571,7 +570,7 @@ func (s *Server) UpdateWriteRepository(ctx context.Context, q *repositorypkg.Rep return nil, err } _, err = s.db.UpdateWriteRepository(ctx, q.Repo) - return &appsv1.Repository{Repo: q.Repo.Repo, Type: q.Repo.Type, Name: q.Repo.Name}, err + return &v1alpha1.Repository{Repo: q.Repo.Repo, Type: q.Repo.Type, Name: q.Repo.Name}, err } // Delete removes a repository from the configuration @@ -622,7 +621,7 @@ func (s *Server) DeleteWriteRepository(ctx context.Context, q *repositorypkg.Rep // getRepository fetches a single repository which the user has access to. If only one repository can be found which // matches the same URL, that will be returned (this is for backward compatibility reasons). If multiple repositories // are matched, a repository is only returned if it matches the app project of the incoming request. -func getRepository(ctx context.Context, listRepositories func(context.Context, *repositorypkg.RepoQuery) (*v1alpha1.RepositoryList, error), q *repositorypkg.RepoQuery) (*appsv1.Repository, error) { +func getRepository(ctx context.Context, listRepositories func(context.Context, *repositorypkg.RepoQuery) (*v1alpha1.RepositoryList, error), q *repositorypkg.RepoQuery) (*v1alpha1.Repository, error) { repositories, err := listRepositories(ctx, q) if err != nil { return nil, err @@ -665,7 +664,7 @@ func (s *Server) ValidateAccess(ctx context.Context, q *repositorypkg.RepoAccess return nil, err } - repo := &appsv1.Repository{ + repo := &v1alpha1.Repository{ Repo: q.Repo, Type: q.Type, Name: q.Name, @@ -713,7 +712,7 @@ func (s *Server) ValidateWriteAccess(ctx context.Context, q *repositorypkg.RepoA return nil, err } - repo := &appsv1.Repository{ + repo := &v1alpha1.Repository{ Repo: q.Repo, Type: q.Type, Name: q.Name, @@ -739,7 +738,7 @@ func (s *Server) ValidateWriteAccess(ctx context.Context, q *repositorypkg.RepoA return &repositorypkg.RepoResponse{}, nil } -func (s *Server) testRepo(ctx context.Context, repo *appsv1.Repository) error { +func (s *Server) testRepo(ctx context.Context, repo *v1alpha1.Repository) error { conn, repoClient, err := s.repoClientset.NewRepoServerClient() if err != nil { return fmt.Errorf("failed to connect to repo-server: %w", err) @@ -757,7 +756,7 @@ func (s *Server) isRepoPermittedInProject(ctx context.Context, repo string, proj if err != nil { return err } - if !proj.IsSourcePermitted(appsv1.ApplicationSource{RepoURL: repo}) { + if !proj.IsSourcePermitted(v1alpha1.ApplicationSource{RepoURL: repo}) { return status.Errorf(codes.PermissionDenied, "repository '%s' not permitted in project '%s'", repo, projName) } return nil diff --git a/server/repository/repository_test.go b/server/repository/repository_test.go index 60522b7497aed..fd3b56040921f 100644 --- a/server/repository/repository_test.go +++ b/server/repository/repository_test.go @@ -20,7 +20,6 @@ import ( "github.com/argoproj/argo-cd/v2/common" "github.com/argoproj/argo-cd/v2/pkg/apiclient/repository" - repositorypkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/repository" appsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" fakeapps "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned/fake" appinformer "github.com/argoproj/argo-cd/v2/pkg/client/informers/externalversions" @@ -1153,7 +1152,7 @@ func TestDeleteRepository(t *testing.T) { s := NewServer(&repoServerClientset, db, enforcer, newFixtures().Cache, appLister, projLister, testNamespace, settingsMgr, false) resp, err := s.DeleteRepository(context.TODO(), &repository.RepoQuery{Repo: repo, AppProject: "default"}) require.NoError(t, err) - assert.Equal(t, repositorypkg.RepoResponse{}, *resp) + assert.Equal(t, repository.RepoResponse{}, *resp) }) } } diff --git a/server/server_test.go b/server/server_test.go index f3e9fe5313168..45426b2c6efcc 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -39,7 +39,6 @@ import ( "github.com/argoproj/argo-cd/v2/test" "github.com/argoproj/argo-cd/v2/util/assets" "github.com/argoproj/argo-cd/v2/util/cache" - cacheutil "github.com/argoproj/argo-cd/v2/util/cache" appstatecache "github.com/argoproj/argo-cd/v2/util/cache/appstate" "github.com/argoproj/argo-cd/v2/util/oidc" "github.com/argoproj/argo-cd/v2/util/rbac" @@ -80,7 +79,7 @@ func fakeServer(t *testing.T) (*FakeArgoCDServer, func()) { ContentSecurityPolicy: "frame-ancestors 'self';", Cache: servercache.NewCache( appstatecache.NewCache( - cacheutil.NewCache(cacheutil.NewInMemoryCache(1*time.Hour)), + cache.NewCache(cache.NewInMemoryCache(1*time.Hour)), 1*time.Minute, ), 1*time.Minute, diff --git a/test/e2e/app_management_ns_test.go b/test/e2e/app_management_ns_test.go index f1cb7117dd98c..2423ba5462413 100644 --- a/test/e2e/app_management_ns_test.go +++ b/test/e2e/app_management_ns_test.go @@ -29,7 +29,6 @@ import ( applicationpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/test/e2e/fixture" - . "github.com/argoproj/argo-cd/v2/test/e2e/fixture" accountFixture "github.com/argoproj/argo-cd/v2/test/e2e/fixture/account" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/app" projectFixture "github.com/argoproj/argo-cd/v2/test/e2e/fixture/project" @@ -48,7 +47,7 @@ func TestNamespacedGetLogsAllowNoSwitch(t *testing.T) { } func TestNamespacedGetLogsDenySwitchOn(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") accountFixture.Given(t). Name("test"). @@ -79,7 +78,7 @@ func TestNamespacedGetLogsDenySwitchOn(t *testing.T) { }, "app-creator") ctx := GivenWithSameState(t) - ctx.SetAppNamespace(ArgoCDAppNamespace) + ctx.SetAppNamespace(fixture.ArgoCDAppNamespace) ctx. Path("guestbook-logs"). SetTrackingMethod("annotation"). @@ -90,13 +89,13 @@ func TestNamespacedGetLogsDenySwitchOn(t *testing.T) { Then(). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - _, err := RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") + _, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") assert.ErrorContains(t, err, "permission denied") }) } func TestNamespacedGetLogsAllowSwitchOnNS(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") accountFixture.Given(t). Name("test"). @@ -132,7 +131,7 @@ func TestNamespacedGetLogsAllowSwitchOnNS(t *testing.T) { }, "app-creator") ctx := GivenWithSameState(t) - ctx.SetAppNamespace(AppNamespace()) + ctx.SetAppNamespace(fixture.AppNamespace()) ctx. Path("guestbook-logs"). SetTrackingMethod("annotation"). @@ -143,24 +142,24 @@ func TestNamespacedGetLogsAllowSwitchOnNS(t *testing.T) { Then(). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - out, err := RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") + out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Pod") + out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Pod") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Service") + out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Service") require.NoError(t, err) assert.NotContains(t, out, "Hi") }) } func TestNamespacedGetLogsAllowSwitchOff(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") accountFixture.Given(t). Name("test"). @@ -190,7 +189,7 @@ func TestNamespacedGetLogsAllowSwitchOff(t *testing.T) { }, }, "app-creator") ctx := GivenWithSameState(t) - ctx.SetAppNamespace(AppNamespace()) + ctx.SetAppNamespace(fixture.AppNamespace()) ctx. Path("guestbook-logs"). SetTrackingMethod("annotation"). @@ -201,25 +200,25 @@ func TestNamespacedGetLogsAllowSwitchOff(t *testing.T) { Then(). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - out, err := RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") + out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Pod") + out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Pod") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Service") + out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Service") require.NoError(t, err) assert.NotContains(t, out, "Hi") }) } func TestNamespacedSyncToUnsignedCommit(t *testing.T) { - SkipOnEnv(t, "GPG") - GivenWithNamespace(t, AppNamespace()). + fixture.SkipOnEnv(t, "GPG") + GivenWithNamespace(t, fixture.AppNamespace()). SetTrackingMethod("annotation"). Project("gpg"). Path(guestbookPath). @@ -234,9 +233,9 @@ func TestNamespacedSyncToUnsignedCommit(t *testing.T) { } func TestNamespacedSyncToSignedCommitWKK(t *testing.T) { - SkipOnEnv(t, "GPG") + fixture.SkipOnEnv(t, "GPG") Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Project("gpg"). Path(guestbookPath). @@ -252,9 +251,9 @@ func TestNamespacedSyncToSignedCommitWKK(t *testing.T) { } func TestNamespacedSyncToSignedCommitKWKK(t *testing.T) { - SkipOnEnv(t, "GPG") + fixture.SkipOnEnv(t, "GPG") Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Project("gpg"). Path(guestbookPath). @@ -276,23 +275,23 @@ func TestNamespacedAppCreation(t *testing.T) { ctx. Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Then(). Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). And(func(app *Application) { - assert.Equal(t, Name(), app.Name) - assert.Equal(t, AppNamespace(), app.Namespace) - assert.Equal(t, RepoURL(RepoURLTypeFile), app.Spec.GetSource().RepoURL) + assert.Equal(t, fixture.Name(), app.Name) + assert.Equal(t, fixture.AppNamespace(), app.Namespace) + assert.Equal(t, fixture.RepoURL(fixture.RepoURLTypeFile), app.Spec.GetSource().RepoURL) assert.Equal(t, guestbookPath, app.Spec.GetSource().Path) - assert.Equal(t, DeploymentNamespace(), app.Spec.Destination.Namespace) + assert.Equal(t, fixture.DeploymentNamespace(), app.Spec.Destination.Namespace) assert.Equal(t, KubernetesInternalAPIServerAddr, app.Spec.Destination.Server) }). - Expect(NamespacedEvent(AppNamespace(), EventReasonResourceCreated, "create")). + Expect(NamespacedEvent(fixture.AppNamespace(), EventReasonResourceCreated, "create")). And(func(app *Application) { // app should be listed - output, err := RunCli("app", "list") + output, err := fixture.RunCli("app", "list") require.NoError(t, err) assert.Contains(t, output, ctx.AppQualifiedName()) }). @@ -305,7 +304,7 @@ func TestNamespacedAppCreation(t *testing.T) { When(). // ensure that update replaces spec and merge labels and annotations And(func() { - FailOnErr(AppClientset.ArgoprojV1alpha1().Applications(AppNamespace()).Patch(context.Background(), + FailOnErr(fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.AppNamespace()).Patch(context.Background(), ctx.GetName(), types.MergePatchType, []byte(`{"metadata": {"labels": { "test": "label" }, "annotations": { "test": "annotation" }}}`), metav1.PatchOptions{})) }). CreateApp("--upsert"). @@ -323,7 +322,7 @@ func TestNamespacedAppCreationWithoutForceUpdate(t *testing.T) { ctx. Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). DestName("in-cluster"). When(). CreateApp(). @@ -331,16 +330,16 @@ func TestNamespacedAppCreationWithoutForceUpdate(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). And(func(app *Application) { assert.Equal(t, ctx.AppName(), app.Name) - assert.Equal(t, AppNamespace(), app.Namespace) - assert.Equal(t, RepoURL(RepoURLTypeFile), app.Spec.GetSource().RepoURL) + assert.Equal(t, fixture.AppNamespace(), app.Namespace) + assert.Equal(t, fixture.RepoURL(fixture.RepoURLTypeFile), app.Spec.GetSource().RepoURL) assert.Equal(t, guestbookPath, app.Spec.GetSource().Path) - assert.Equal(t, DeploymentNamespace(), app.Spec.Destination.Namespace) + assert.Equal(t, fixture.DeploymentNamespace(), app.Spec.Destination.Namespace) assert.Equal(t, "in-cluster", app.Spec.Destination.Name) }). - Expect(NamespacedEvent(AppNamespace(), EventReasonResourceCreated, "create")). + Expect(NamespacedEvent(fixture.AppNamespace(), EventReasonResourceCreated, "create")). And(func(_ *Application) { // app should be listed - output, err := RunCli("app", "list") + output, err := fixture.RunCli("app", "list") require.NoError(t, err) assert.Contains(t, output, ctx.AppQualifiedName()) }). @@ -357,7 +356,7 @@ func TestNamespacedDeleteAppResource(t *testing.T) { ctx. Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Sync(). @@ -365,7 +364,7 @@ func TestNamespacedDeleteAppResource(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(_ *Application) { // app should be listed - if _, err := RunCli("app", "delete-resource", ctx.AppQualifiedName(), "--kind", "Service", "--resource-name", "guestbook-ui"); err != nil { + if _, err := fixture.RunCli("app", "delete-resource", ctx.AppQualifiedName(), "--kind", "Service", "--resource-name", "guestbook-ui"); err != nil { require.NoError(t, err) } }). @@ -375,11 +374,11 @@ func TestNamespacedDeleteAppResource(t *testing.T) { // demonstrate that we cannot use a standard sync when an immutable field is changed, we must use "force" func TestNamespacedImmutableChange(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") Given(t). Path("secrets"). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). PatchFile("secrets.yaml", `[{"op": "add", "path": "/data/new-field", "value": "dGVzdA=="}, {"op": "add", "path": "/immutable", "value": true}]`). @@ -400,7 +399,7 @@ func TestNamespacedImmutableChange(t *testing.T) { Expect(ResourceResultMatches(ResourceResult{ Kind: "Secret", Version: "v1", - Namespace: DeploymentNamespace(), + Namespace: fixture.DeploymentNamespace(), Name: "test-secret", SyncPhase: "Sync", Status: "SyncFailed", @@ -422,7 +421,7 @@ func TestNamespacedInvalidAppProject(t *testing.T) { Given(t). SetTrackingMethod("annotation"). Path(guestbookPath). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). Project("does-not-exist"). When(). IgnoreErrors(). @@ -438,7 +437,7 @@ func TestNamespacedAppDeletion(t *testing.T) { ctx. Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Then(). @@ -447,9 +446,9 @@ func TestNamespacedAppDeletion(t *testing.T) { Delete(true). Then(). Expect(DoesNotExist()). - Expect(NamespacedEvent(AppNamespace(), EventReasonResourceDeleted, "delete")) + Expect(NamespacedEvent(fixture.AppNamespace(), EventReasonResourceDeleted, "delete")) - output, err := RunCli("app", "list") + output, err := fixture.RunCli("app", "list") require.NoError(t, err) assert.NotContains(t, output, ctx.AppQualifiedName()) } @@ -459,14 +458,14 @@ func TestNamespacedAppLabels(t *testing.T) { ctx. Path("config-map"). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp("-l", "foo=bar"). Then(). And(func(app *Application) { - assert.Contains(t, FailOnErr(RunCli("app", "list")), ctx.AppQualifiedName()) - assert.Contains(t, FailOnErr(RunCli("app", "list", "-l", "foo=bar")), ctx.AppQualifiedName()) - assert.NotContains(t, FailOnErr(RunCli("app", "list", "-l", "foo=rubbish")), ctx.AppQualifiedName()) + assert.Contains(t, FailOnErr(fixture.RunCli("app", "list")), ctx.AppQualifiedName()) + assert.Contains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=bar")), ctx.AppQualifiedName()) + assert.NotContains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=rubbish")), ctx.AppQualifiedName()) }). Given(). // remove both name and replace labels means nothing will sync @@ -487,7 +486,7 @@ func TestNamespacedTrackAppStateAndSyncApp(t *testing.T) { Given(t). Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Sync(). @@ -495,9 +494,9 @@ func TestNamespacedTrackAppStateAndSyncApp(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - Expect(Success(fmt.Sprintf("Service %s guestbook-ui Synced ", DeploymentNamespace()))). - Expect(Success(fmt.Sprintf("apps Deployment %s guestbook-ui Synced", DeploymentNamespace()))). - Expect(NamespacedEvent(AppNamespace(), EventReasonResourceUpdated, "sync")). + Expect(Success(fmt.Sprintf("Service %s guestbook-ui Synced ", fixture.DeploymentNamespace()))). + Expect(Success(fmt.Sprintf("apps Deployment %s guestbook-ui Synced", fixture.DeploymentNamespace()))). + Expect(NamespacedEvent(fixture.AppNamespace(), EventReasonResourceUpdated, "sync")). And(func(app *Application) { assert.NotNil(t, app.Status.OperationState.SyncResult) }) @@ -508,7 +507,7 @@ func TestNamespacedAppRollbackSuccessful(t *testing.T) { ctx. Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Sync(). @@ -532,14 +531,14 @@ func TestNamespacedAppRollbackSuccessful(t *testing.T) { }} patch, _, err := diff.CreateTwoWayMergePatch(app, appWithHistory, &Application{}) require.NoError(t, err) - app, err = AppClientset.ArgoprojV1alpha1().Applications(AppNamespace()).Patch(context.Background(), app.Name, types.MergePatchType, patch, metav1.PatchOptions{}) + app, err = fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.AppNamespace()).Patch(context.Background(), app.Name, types.MergePatchType, patch, metav1.PatchOptions{}) require.NoError(t, err) // sync app and make sure it reaches InSync state - _, err = RunCli("app", "rollback", app.QualifiedName(), "1") + _, err = fixture.RunCli("app", "rollback", app.QualifiedName(), "1") require.NoError(t, err) }). - Expect(NamespacedEvent(AppNamespace(), EventReasonOperationStarted, "rollback")). + Expect(NamespacedEvent(fixture.AppNamespace(), EventReasonOperationStarted, "rollback")). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { assert.Equal(t, SyncStatusCodeSynced, app.Status.Sync.Status) @@ -554,7 +553,7 @@ func TestNamespacedComparisonFailsIfClusterNotAdded(t *testing.T) { Given(t). Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). DestServer("https://not-registered-cluster/api"). When(). IgnoreErrors(). @@ -567,7 +566,7 @@ func TestNamespacedCannotSetInvalidPath(t *testing.T) { Given(t). Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). IgnoreErrors(). @@ -581,14 +580,14 @@ func TestNamespacedManipulateApplicationResources(t *testing.T) { ctx. Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - manifests, err := RunCli("app", "manifests", ctx.AppQualifiedName(), "--source", "live") + manifests, err := fixture.RunCli("app", "manifests", ctx.AppQualifiedName(), "--source", "live") require.NoError(t, err) resources, err := kube.SplitYAML([]byte(manifests)) require.NoError(t, err) @@ -604,13 +603,13 @@ func TestNamespacedManipulateApplicationResources(t *testing.T) { deployment := resources[index] - closer, client, err := ArgoCDClientset.NewApplicationClient() + closer, client, err := fixture.ArgoCDClientset.NewApplicationClient() require.NoError(t, err) defer io.Close(closer) _, err = client.DeleteResource(context.Background(), &applicationpkg.ApplicationResourceDeleteRequest{ Name: &app.Name, - AppNamespace: ptr.To(AppNamespace()), + AppNamespace: ptr.To(fixture.AppNamespace()), Group: ptr.To(deployment.GroupVersionKind().Group), Kind: ptr.To(deployment.GroupVersionKind().Kind), Version: ptr.To(deployment.GroupVersionKind().Version), @@ -623,14 +622,14 @@ func TestNamespacedManipulateApplicationResources(t *testing.T) { } func TestNamespacedAppWithSecrets(t *testing.T) { - closer, client, err := ArgoCDClientset.NewApplicationClient() + closer, client, err := fixture.ArgoCDClientset.NewApplicationClient() require.NoError(t, err) defer io.Close(closer) ctx := Given(t) ctx. Path("secrets"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). When(). CreateApp(). @@ -640,7 +639,7 @@ func TestNamespacedAppWithSecrets(t *testing.T) { And(func(app *Application) { res := FailOnErr(client.GetResource(context.Background(), &applicationpkg.ApplicationResourceRequest{ Namespace: &app.Spec.Destination.Namespace, - AppNamespace: ptr.To(AppNamespace()), + AppNamespace: ptr.To(fixture.AppNamespace()), Kind: ptr.To(kube.SecretKind), Group: ptr.To(""), Name: &app.Name, @@ -651,7 +650,7 @@ func TestNamespacedAppWithSecrets(t *testing.T) { manifests, err := client.GetManifests(context.Background(), &applicationpkg.ApplicationManifestQuery{ Name: &app.Name, - AppNamespace: ptr.To(AppNamespace()), + AppNamespace: ptr.To(fixture.AppNamespace()), }) errors.CheckError(err) @@ -659,19 +658,19 @@ func TestNamespacedAppWithSecrets(t *testing.T) { assetSecretDataHidden(t, manifest) } - diffOutput := FailOnErr(RunCli("app", "diff", ctx.AppQualifiedName())).(string) + diffOutput := FailOnErr(fixture.RunCli("app", "diff", ctx.AppQualifiedName())).(string) assert.Empty(t, diffOutput) // make sure resource update error does not print secret details - _, err = RunCli("app", "patch-resource", ctx.AppQualifiedName(), "--resource-name", "test-secret", + _, err = fixture.RunCli("app", "patch-resource", ctx.AppQualifiedName(), "--resource-name", "test-secret", "--kind", "Secret", "--patch", `{"op": "add", "path": "/data", "value": "hello"}'`, "--patch-type", "application/json-patch+json") - require.ErrorContains(t, err, fmt.Sprintf("failed to patch Secret %s/test-secret", DeploymentNamespace())) + require.ErrorContains(t, err, fmt.Sprintf("failed to patch Secret %s/test-secret", fixture.DeploymentNamespace())) assert.NotContains(t, err.Error(), "username") assert.NotContains(t, err.Error(), "password") // patch secret and make sure app is out of sync and diff detects the change - FailOnErr(KubeClientset.CoreV1().Secrets(DeploymentNamespace()).Patch(context.Background(), + FailOnErr(fixture.KubeClientset.CoreV1().Secrets(fixture.DeploymentNamespace()).Patch(context.Background(), "test-secret", types.JSONPatchType, []byte(`[ {"op": "remove", "path": "/data/username"}, {"op": "add", "path": "/stringData", "value": {"password": "foo"}} @@ -682,20 +681,20 @@ func TestNamespacedAppWithSecrets(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). And(func(app *Application) { - diffOutput, err := RunCli("app", "diff", ctx.AppQualifiedName()) + diffOutput, err := fixture.RunCli("app", "diff", ctx.AppQualifiedName()) require.Error(t, err) assert.Contains(t, diffOutput, "username: ++++++++") assert.Contains(t, diffOutput, "password: ++++++++++++") // local diff should ignore secrets - diffOutput = FailOnErr(RunCli("app", "diff", ctx.AppQualifiedName(), "--local", "testdata/secrets")).(string) + diffOutput = FailOnErr(fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local", "testdata/secrets")).(string) assert.Empty(t, diffOutput) // ignore missing field and make sure diff shows no difference app.Spec.IgnoreDifferences = []ResourceIgnoreDifferences{{ Kind: kube.SecretKind, JSONPointers: []string{"/data"}, }} - FailOnErr(client.UpdateSpec(context.Background(), &applicationpkg.ApplicationUpdateSpecRequest{Name: &app.Name, AppNamespace: ptr.To(AppNamespace()), Spec: &app.Spec})) + FailOnErr(client.UpdateSpec(context.Background(), &applicationpkg.ApplicationUpdateSpecRequest{Name: &app.Name, AppNamespace: ptr.To(fixture.AppNamespace()), Spec: &app.Spec})) }). When(). Refresh(RefreshTypeNormal). @@ -703,7 +702,7 @@ func TestNamespacedAppWithSecrets(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - diffOutput := FailOnErr(RunCli("app", "diff", ctx.AppQualifiedName())).(string) + diffOutput := FailOnErr(fixture.RunCli("app", "diff", ctx.AppQualifiedName())).(string) assert.Empty(t, diffOutput) }). // verify not committed secret also ignore during diffing @@ -717,7 +716,7 @@ stringData: username: test-username`). Then(). And(func(app *Application) { - diffOutput := FailOnErr(RunCli("app", "diff", ctx.AppQualifiedName(), "--local", "testdata/secrets")).(string) + diffOutput := FailOnErr(fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local", "testdata/secrets")).(string) assert.Empty(t, diffOutput) }) } @@ -727,7 +726,7 @@ func TestNamespacedResourceDiffing(t *testing.T) { ctx. Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Sync(). @@ -735,7 +734,7 @@ func TestNamespacedResourceDiffing(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { // Patch deployment - _, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Patch(context.Background(), + _, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Patch(context.Background(), "guestbook-ui", types.JSONPatchType, []byte(`[{ "op": "replace", "path": "/spec/template/spec/containers/0/image", "value": "test" }]`), metav1.PatchOptions{}) require.NoError(t, err) }). @@ -744,9 +743,9 @@ func TestNamespacedResourceDiffing(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). And(func(app *Application) { - diffOutput, err := RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", "testdata/guestbook") + diffOutput, err := fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", "testdata/guestbook") require.Error(t, err) - assert.Contains(t, diffOutput, fmt.Sprintf("===== apps/Deployment %s/guestbook-ui ======", DeploymentNamespace())) + assert.Contains(t, diffOutput, fmt.Sprintf("===== apps/Deployment %s/guestbook-ui ======", fixture.DeploymentNamespace())) }). Given(). ResourceOverrides(map[string]ResourceOverride{"apps/Deployment": { @@ -757,7 +756,7 @@ func TestNamespacedResourceDiffing(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - diffOutput, err := RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", "testdata/guestbook") + diffOutput, err := fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", "testdata/guestbook") require.NoError(t, err) assert.Empty(t, diffOutput) }). @@ -775,7 +774,7 @@ func TestNamespacedResourceDiffing(t *testing.T) { }]`). Sync(). And(func() { - output, err := RunWithStdin(testdata.SSARevisionHistoryDeployment, "", "kubectl", "apply", "-n", DeploymentNamespace(), "--server-side=true", "--field-manager=revision-history-manager", "--validate=false", "--force-conflicts", "-f", "-") + output, err := fixture.RunWithStdin(testdata.SSARevisionHistoryDeployment, "", "kubectl", "apply", "-n", fixture.DeploymentNamespace(), "--server-side=true", "--field-manager=revision-history-manager", "--validate=false", "--force-conflicts", "-f", "-") require.NoError(t, err) assert.Contains(t, output, "serverside-applied") }). @@ -802,12 +801,12 @@ func TestNamespacedResourceDiffing(t *testing.T) { "value": { "syncOptions": ["RespectIgnoreDifferences=true"] } }]`). And(func() { - deployment, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(3), *deployment.Spec.RevisionHistoryLimit) }). And(func() { - output, err := RunWithStdin(testdata.SSARevisionHistoryDeployment, "", "kubectl", "apply", "-n", DeploymentNamespace(), "--server-side=true", "--field-manager=revision-history-manager", "--validate=false", "--force-conflicts", "-f", "-") + output, err := fixture.RunWithStdin(testdata.SSARevisionHistoryDeployment, "", "kubectl", "apply", "-n", fixture.DeploymentNamespace(), "--server-side=true", "--field-manager=revision-history-manager", "--validate=false", "--force-conflicts", "-f", "-") require.NoError(t, err) assert.Contains(t, output, "serverside-applied") }). @@ -816,13 +815,13 @@ func TestNamespacedResourceDiffing(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - deployment, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) }). When().Sync().Then().Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - deployment, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) }) @@ -839,12 +838,12 @@ func TestNamespacedKnownTypesInCRDDiffing(t *testing.T) { ctx. Path("crd-creation"). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When().CreateApp().Sync().Then(). Expect(OperationPhaseIs(OperationSucceeded)).Expect(SyncStatusIs(SyncStatusCodeSynced)). When(). And(func() { - dummyResIf := DynamicClientset.Resource(dummiesGVR).Namespace(DeploymentNamespace()) + dummyResIf := fixture.DynamicClientset.Resource(dummiesGVR).Namespace(fixture.DeploymentNamespace()) patchData := []byte(`{"spec":{"cpu": "2"}}`) FailOnErr(dummyResIf.Patch(context.Background(), "dummy-crd-instance", types.MergePatchType, patchData, metav1.PatchOptions{})) }).Refresh(RefreshTypeNormal). @@ -852,7 +851,7 @@ func TestNamespacedKnownTypesInCRDDiffing(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). When(). And(func() { - CheckError(SetResourceOverrides(map[string]ResourceOverride{ + CheckError(fixture.SetResourceOverrides(map[string]ResourceOverride{ "argoproj.io/Dummy": { KnownTypeFields: []KnownTypeField{{ Field: "spec", @@ -881,7 +880,7 @@ func testNSEdgeCasesApplicationResources(t *testing.T, appPath string, statusCod expect := ctx. Path(appPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Sync(). @@ -894,7 +893,7 @@ func testNSEdgeCasesApplicationResources(t *testing.T, appPath string, statusCod expect. Expect(HealthIs(statusCode)). And(func(app *Application) { - diffOutput, err := RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", path.Join("testdata", appPath)) + diffOutput, err := fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", path.Join("testdata", appPath)) assert.Empty(t, diffOutput) require.NoError(t, err) }) @@ -914,24 +913,24 @@ func TestNamespacedResourceAction(t *testing.T) { ctx. Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). ResourceOverrides(map[string]ResourceOverride{"apps/Deployment": {Actions: actionsConfig}}). When(). CreateApp(). Sync(). Then(). And(func(app *Application) { - closer, client, err := ArgoCDClientset.NewApplicationClient() + closer, client, err := fixture.ArgoCDClientset.NewApplicationClient() require.NoError(t, err) defer io.Close(closer) actions, err := client.ListResourceActions(context.Background(), &applicationpkg.ApplicationResourceRequest{ Name: &app.Name, - AppNamespace: ptr.To(AppNamespace()), + AppNamespace: ptr.To(fixture.AppNamespace()), Group: ptr.To("apps"), Kind: ptr.To("Deployment"), Version: ptr.To("v1"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), ResourceName: ptr.To("guestbook-ui"), }) require.NoError(t, err) @@ -942,14 +941,14 @@ func TestNamespacedResourceAction(t *testing.T) { Group: ptr.To("apps"), Kind: ptr.To("Deployment"), Version: ptr.To("v1"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), ResourceName: ptr.To("guestbook-ui"), Action: ptr.To("sample"), - AppNamespace: ptr.To(AppNamespace()), + AppNamespace: ptr.To(fixture.AppNamespace()), }) require.NoError(t, err) - deployment, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, "test", deployment.Labels["sample"]) @@ -961,17 +960,17 @@ func TestNamespacedSyncResourceByLabel(t *testing.T) { ctx. Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Sync(). Then(). And(func(app *Application) { - _, _ = RunCli("app", "sync", ctx.AppQualifiedName(), "--label", "app.kubernetes.io/instance="+app.Name) + _, _ = fixture.RunCli("app", "sync", ctx.AppQualifiedName(), "--label", "app.kubernetes.io/instance="+app.Name) }). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - _, err := RunCli("app", "sync", ctx.AppQualifiedName(), "--label", "this-label=does-not-exist") + _, err := fixture.RunCli("app", "sync", ctx.AppQualifiedName(), "--label", "this-label=does-not-exist") assert.ErrorContains(t, err, "level=fatal") }) } @@ -981,13 +980,13 @@ func TestNamespacedLocalManifestSync(t *testing.T) { ctx. Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Sync(). Then(). And(func(app *Application) { - res, _ := RunCli("app", "manifests", ctx.AppQualifiedName()) + res, _ := fixture.RunCli("app", "manifests", ctx.AppQualifiedName()) assert.Contains(t, res, "containerPort: 80") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.2") }). @@ -998,7 +997,7 @@ func TestNamespacedLocalManifestSync(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - res, _ := RunCli("app", "manifests", ctx.AppQualifiedName()) + res, _ := fixture.RunCli("app", "manifests", ctx.AppQualifiedName()) assert.Contains(t, res, "containerPort: 81") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.3") }). @@ -1009,7 +1008,7 @@ func TestNamespacedLocalManifestSync(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - res, _ := RunCli("app", "manifests", ctx.AppQualifiedName()) + res, _ := fixture.RunCli("app", "manifests", ctx.AppQualifiedName()) assert.Contains(t, res, "containerPort: 80") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.2") }) @@ -1020,12 +1019,12 @@ func TestNamespacedLocalSync(t *testing.T) { // we've got to use Helm as this uses kubeVersion Path("helm"). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Then(). And(func(app *Application) { - FailOnErr(RunCli("app", "sync", app.QualifiedName(), "--local", "testdata/helm")) + FailOnErr(fixture.RunCli("app", "sync", app.QualifiedName(), "--local", "testdata/helm")) }) } @@ -1033,16 +1032,16 @@ func TestNamespacedNoLocalSyncWithAutosyncEnabled(t *testing.T) { Given(t). Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Sync(). Then(). And(func(app *Application) { - _, err := RunCli("app", "set", app.QualifiedName(), "--sync-policy", "automated") + _, err := fixture.RunCli("app", "set", app.QualifiedName(), "--sync-policy", "automated") require.NoError(t, err) - _, err = RunCli("app", "sync", app.QualifiedName(), "--local", guestbookPathLocal) + _, err = fixture.RunCli("app", "sync", app.QualifiedName(), "--local", guestbookPathLocal) assert.ErrorContains(t, err, "Cannot use local sync") }) } @@ -1051,17 +1050,17 @@ func TestNamespacedLocalSyncDryRunWithASEnabled(t *testing.T) { Given(t). Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Sync(). Then(). And(func(app *Application) { - _, err := RunCli("app", "set", app.QualifiedName(), "--sync-policy", "automated") + _, err := fixture.RunCli("app", "set", app.QualifiedName(), "--sync-policy", "automated") require.NoError(t, err) appBefore := app.DeepCopy() - _, err = RunCli("app", "sync", app.QualifiedName(), "--dry-run", "--local-repo-root", ".", "--local", guestbookPathLocal) + _, err = fixture.RunCli("app", "sync", app.QualifiedName(), "--dry-run", "--local-repo-root", ".", "--local", guestbookPathLocal) require.NoError(t, err) appAfter := app.DeepCopy() @@ -1073,7 +1072,7 @@ func TestNamespacedSyncAsync(t *testing.T) { Given(t). Path(guestbookPath). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). Async(true). When(). CreateApp(). @@ -1095,18 +1094,18 @@ func assertNSResourceActions(t *testing.T, appName string, successful bool) { } } - closer, cdClient := ArgoCDClientset.NewApplicationClientOrDie() + closer, cdClient := fixture.ArgoCDClientset.NewApplicationClientOrDie() defer io.Close(closer) - deploymentResource, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + deploymentResource, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) logs, err := cdClient.PodLogs(context.Background(), &applicationpkg.ApplicationPodLogsQuery{ Group: ptr.To("apps"), Kind: ptr.To("Deployment"), Name: &appName, - AppNamespace: ptr.To(AppNamespace()), - Namespace: ptr.To(DeploymentNamespace()), + AppNamespace: ptr.To(fixture.AppNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), Container: ptr.To(""), SinceSeconds: ptr.To(int64(0)), TailLines: ptr.To(int64(0)), @@ -1120,18 +1119,18 @@ func assertNSResourceActions(t *testing.T, appName string, successful bool) { _, err = cdClient.ListResourceEvents(context.Background(), &applicationpkg.ApplicationResourceEventsQuery{ Name: &appName, - AppNamespace: ptr.To(AppNamespace()), + AppNamespace: ptr.To(fixture.AppNamespace()), ResourceName: ptr.To("guestbook-ui"), - ResourceNamespace: ptr.To(DeploymentNamespace()), + ResourceNamespace: ptr.To(fixture.DeploymentNamespace()), ResourceUID: ptr.To(string(deploymentResource.UID)), }) assertError(err, fmt.Sprintf("%s not found as part of application %s", "guestbook-ui", appName)) _, err = cdClient.GetResource(context.Background(), &applicationpkg.ApplicationResourceRequest{ Name: &appName, - AppNamespace: ptr.To(AppNamespace()), + AppNamespace: ptr.To(fixture.AppNamespace()), ResourceName: ptr.To("guestbook-ui"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), Version: ptr.To("v1"), Group: ptr.To("apps"), Kind: ptr.To("Deployment"), @@ -1140,9 +1139,9 @@ func assertNSResourceActions(t *testing.T, appName string, successful bool) { _, err = cdClient.RunResourceAction(context.Background(), &applicationpkg.ResourceActionRunRequest{ Name: &appName, - AppNamespace: ptr.To(AppNamespace()), + AppNamespace: ptr.To(fixture.AppNamespace()), ResourceName: ptr.To("guestbook-ui"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), Version: ptr.To("v1"), Group: ptr.To("apps"), Kind: ptr.To("Deployment"), @@ -1152,9 +1151,9 @@ func assertNSResourceActions(t *testing.T, appName string, successful bool) { _, err = cdClient.DeleteResource(context.Background(), &applicationpkg.ApplicationResourceDeleteRequest{ Name: &appName, - AppNamespace: ptr.To(AppNamespace()), + AppNamespace: ptr.To(fixture.AppNamespace()), ResourceName: ptr.To("guestbook-ui"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), Version: ptr.To("v1"), Group: ptr.To("apps"), Kind: ptr.To("Deployment"), @@ -1168,17 +1167,17 @@ func TestNamespacedPermissions(t *testing.T) { projActions := projectFixture. Given(t). Name(projName). - SourceNamespaces([]string{AppNamespace()}). + SourceNamespaces([]string{fixture.AppNamespace()}). When(). Create() - sourceError := fmt.Sprintf("application repo %s is not permitted in project 'argo-project'", RepoURL(RepoURLTypeFile)) - destinationError := fmt.Sprintf("application destination server '%s' and namespace '%s' do not match any of the allowed destinations in project 'argo-project'", KubernetesInternalAPIServerAddr, DeploymentNamespace()) + sourceError := fmt.Sprintf("application repo %s is not permitted in project 'argo-project'", fixture.RepoURL(fixture.RepoURLTypeFile)) + destinationError := fmt.Sprintf("application destination server '%s' and namespace '%s' do not match any of the allowed destinations in project 'argo-project'", KubernetesInternalAPIServerAddr, fixture.DeploymentNamespace()) appCtx. Path("guestbook-logs"). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). Project(projName). When(). IgnoreErrors(). @@ -1215,7 +1214,7 @@ func TestNamespacedPermissions(t *testing.T) { Expect(Condition(ApplicationConditionInvalidSpecError, destinationError)). Expect(Condition(ApplicationConditionInvalidSpecError, sourceError)). And(func(app *Application) { - closer, cdClient := ArgoCDClientset.NewApplicationClientOrDie() + closer, cdClient := fixture.ArgoCDClientset.NewApplicationClientOrDie() defer io.Close(closer) tree, err := cdClient.ResourceTree(context.Background(), &applicationpkg.ResourcesQuery{ApplicationName: &app.Name, AppNamespace: &app.Namespace}) require.NoError(t, err) @@ -1246,23 +1245,23 @@ func TestNamespacedPermissionWithScopedRepo(t *testing.T) { projectFixture. Given(t). Name(projName). - SourceNamespaces([]string{AppNamespace()}). + SourceNamespaces([]string{fixture.AppNamespace()}). Destination("*,*"). When(). Create() repoFixture.GivenWithSameState(t). When(). - Path(RepoURL(RepoURLTypeFile)). + Path(fixture.RepoURL(fixture.RepoURLTypeFile)). Project(projName). Create() GivenWithSameState(t). Project(projName). - RepoURLType(RepoURLTypeFile). + RepoURLType(fixture.RepoURLTypeFile). Path("two-nice-pods"). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). PatchFile("pod-1.yaml", `[{"op": "add", "path": "/metadata/annotations", "value": {"argocd.argoproj.io/sync-options": "Prune=false"}}]`). CreateApp(). @@ -1287,20 +1286,20 @@ func TestNamespacedPermissionDeniedWithScopedRepo(t *testing.T) { Given(t). Name(projName). Destination("*,*"). - SourceNamespaces([]string{AppNamespace()}). + SourceNamespaces([]string{fixture.AppNamespace()}). When(). Create() repoFixture.GivenWithSameState(t). When(). - Path(RepoURL(RepoURLTypeFile)). + Path(fixture.RepoURL(fixture.RepoURLTypeFile)). Create() GivenWithSameState(t). Project(projName). - RepoURLType(RepoURLTypeFile). + RepoURLType(fixture.RepoURLTypeFile). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). Path("two-nice-pods"). When(). PatchFile("pod-1.yaml", `[{"op": "add", "path": "/metadata/annotations", "value": {"argocd.argoproj.io/sync-options": "Prune=false"}}]`). @@ -1315,7 +1314,7 @@ func TestNamespacedSyncOptionPruneFalse(t *testing.T) { Given(t). Path("two-nice-pods"). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). PatchFile("pod-1.yaml", `[{"op": "add", "path": "/metadata/annotations", "value": {"argocd.argoproj.io/sync-options": "Prune=false"}}]`). CreateApp(). @@ -1339,7 +1338,7 @@ func TestNamespacedSyncOptionValidateFalse(t *testing.T) { Given(t). Path("crd-validation"). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Then(). @@ -1363,7 +1362,7 @@ func TestNamespacedCompareOptionIgnoreExtraneous(t *testing.T) { Given(t). Prune(false). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). Path("two-nice-pods"). When(). PatchFile("pod-1.yaml", `[{"op": "add", "path": "/metadata/annotations", "value": {"argocd.argoproj.io/compare-options": "IgnoreExtraneous"}}]`). @@ -1397,9 +1396,9 @@ func TestNamespacedSelfManagedApps(t *testing.T) { Given(t). Path("self-managed-app"). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). - PatchFile("resources.yaml", fmt.Sprintf(`[{"op": "replace", "path": "/spec/source/repoURL", "value": "%s"}]`, RepoURL(RepoURLTypeFile))). + PatchFile("resources.yaml", fmt.Sprintf(`[{"op": "replace", "path": "/spec/source/repoURL", "value": "%s"}]`, fixture.RepoURL(fixture.RepoURLTypeFile))). CreateApp(). Sync(). Then(). @@ -1411,7 +1410,7 @@ func TestNamespacedSelfManagedApps(t *testing.T) { reconciledCount := 0 var lastReconciledAt *metav1.Time - for event := range ArgoCDClientset.WatchApplicationWithRetry(ctx, a.QualifiedName(), a.ResourceVersion) { + for event := range fixture.ArgoCDClientset.WatchApplicationWithRetry(ctx, a.QualifiedName(), a.ResourceVersion) { reconciledAt := event.Application.Status.ReconciledAt if reconciledAt == nil { reconciledAt = &metav1.Time{} @@ -1430,7 +1429,7 @@ func TestNamespacedExcludedResource(t *testing.T) { Given(t). ResourceOverrides(map[string]ResourceOverride{"apps/Deployment": {Actions: actionsConfig}}). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). Path(guestbookPath). ResourceFilter(settings.ResourcesFilter{ ResourceExclusions: []settings.FilteredResource{{Kinds: []string{kube.DeploymentKind}}}, @@ -1447,7 +1446,7 @@ func TestNamespacedRevisionHistoryLimit(t *testing.T) { Given(t). Path("config-map"). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). When(). CreateApp(). Sync(). @@ -1469,16 +1468,16 @@ func TestNamespacedRevisionHistoryLimit(t *testing.T) { } func TestNamespacedOrphanedResource(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") Given(t). ProjectSpec(AppProjectSpec{ SourceRepos: []string{"*"}, Destinations: []ApplicationDestination{{Namespace: "*", Server: "*"}}, OrphanedResources: &OrphanedResourcesMonitorSettings{Warn: ptr.To(true)}, - SourceNamespaces: []string{AppNamespace()}, + SourceNamespaces: []string{fixture.AppNamespace()}, }). SetTrackingMethod("annotation"). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). Path(guestbookPath). When(). CreateApp(). @@ -1488,7 +1487,7 @@ func TestNamespacedOrphanedResource(t *testing.T) { Expect(NoConditions()). When(). And(func() { - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "orphaned-configmap", }, @@ -1498,7 +1497,7 @@ func TestNamespacedOrphanedResource(t *testing.T) { Then(). Expect(Condition(ApplicationConditionOrphanedResourceWarning, "Application has 1 orphaned resources")). And(func(app *Application) { - output, err := RunCli("app", "resources", app.QualifiedName()) + output, err := fixture.RunCli("app", "resources", app.QualifiedName()) require.NoError(t, err) assert.Contains(t, output, "orphaned-configmap") }). @@ -1507,14 +1506,14 @@ func TestNamespacedOrphanedResource(t *testing.T) { SourceRepos: []string{"*"}, Destinations: []ApplicationDestination{{Namespace: "*", Server: "*"}}, OrphanedResources: &OrphanedResourcesMonitorSettings{Warn: ptr.To(true), Ignore: []OrphanedResourceKey{{Group: "Test", Kind: "ConfigMap"}}}, - SourceNamespaces: []string{AppNamespace()}, + SourceNamespaces: []string{fixture.AppNamespace()}, }). When(). Refresh(RefreshTypeNormal). Then(). Expect(Condition(ApplicationConditionOrphanedResourceWarning, "Application has 1 orphaned resources")). And(func(app *Application) { - output, err := RunCli("app", "resources", app.QualifiedName()) + output, err := fixture.RunCli("app", "resources", app.QualifiedName()) require.NoError(t, err) assert.Contains(t, output, "orphaned-configmap") }). @@ -1523,7 +1522,7 @@ func TestNamespacedOrphanedResource(t *testing.T) { SourceRepos: []string{"*"}, Destinations: []ApplicationDestination{{Namespace: "*", Server: "*"}}, OrphanedResources: &OrphanedResourcesMonitorSettings{Warn: ptr.To(true), Ignore: []OrphanedResourceKey{{Kind: "ConfigMap"}}}, - SourceNamespaces: []string{AppNamespace()}, + SourceNamespaces: []string{fixture.AppNamespace()}, }). When(). Refresh(RefreshTypeNormal). @@ -1531,7 +1530,7 @@ func TestNamespacedOrphanedResource(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(NoConditions()). And(func(app *Application) { - output, err := RunCli("app", "resources", app.QualifiedName()) + output, err := fixture.RunCli("app", "resources", app.QualifiedName()) require.NoError(t, err) assert.NotContains(t, output, "orphaned-configmap") }). @@ -1540,7 +1539,7 @@ func TestNamespacedOrphanedResource(t *testing.T) { SourceRepos: []string{"*"}, Destinations: []ApplicationDestination{{Namespace: "*", Server: "*"}}, OrphanedResources: &OrphanedResourcesMonitorSettings{Warn: ptr.To(true), Ignore: []OrphanedResourceKey{{Kind: "ConfigMap", Name: "orphaned-configmap"}}}, - SourceNamespaces: []string{AppNamespace()}, + SourceNamespaces: []string{fixture.AppNamespace()}, }). When(). Refresh(RefreshTypeNormal). @@ -1548,7 +1547,7 @@ func TestNamespacedOrphanedResource(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(NoConditions()). And(func(app *Application) { - output, err := RunCli("app", "resources", app.QualifiedName()) + output, err := fixture.RunCli("app", "resources", app.QualifiedName()) require.NoError(t, err) assert.NotContains(t, output, "orphaned-configmap") }). @@ -1557,7 +1556,7 @@ func TestNamespacedOrphanedResource(t *testing.T) { SourceRepos: []string{"*"}, Destinations: []ApplicationDestination{{Namespace: "*", Server: "*"}}, OrphanedResources: nil, - SourceNamespaces: []string{AppNamespace()}, + SourceNamespaces: []string{fixture.AppNamespace()}, }). When(). Refresh(RefreshTypeNormal). @@ -1568,13 +1567,13 @@ func TestNamespacedOrphanedResource(t *testing.T) { func TestNamespacedNotPermittedResources(t *testing.T) { ctx := Given(t) - ctx.SetAppNamespace(AppNamespace()) + ctx.SetAppNamespace(fixture.AppNamespace()) pathType := networkingv1.PathTypePrefix ingress := &networkingv1.Ingress{ ObjectMeta: metav1.ObjectMeta{ Name: "sample-ingress", Annotations: map[string]string{ - common.AnnotationKeyAppInstance: fmt.Sprintf("%s_%s:networking/Ingress:%s/sample-ingress", AppNamespace(), ctx.AppName(), DeploymentNamespace()), + common.AnnotationKeyAppInstance: fmt.Sprintf("%s_%s:networking/Ingress:%s/sample-ingress", fixture.AppNamespace(), ctx.AppName(), fixture.DeploymentNamespace()), }, }, Spec: networkingv1.IngressSpec{ @@ -1597,15 +1596,15 @@ func TestNamespacedNotPermittedResources(t *testing.T) { }, } defer func() { - log.Infof("Ingress 'sample-ingress' deleted from %s", TestNamespace()) - CheckError(KubeClientset.NetworkingV1().Ingresses(TestNamespace()).Delete(context.Background(), "sample-ingress", metav1.DeleteOptions{})) + log.Infof("Ingress 'sample-ingress' deleted from %s", fixture.TestNamespace()) + CheckError(fixture.KubeClientset.NetworkingV1().Ingresses(fixture.TestNamespace()).Delete(context.Background(), "sample-ingress", metav1.DeleteOptions{})) }() svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "guestbook-ui", Annotations: map[string]string{ - common.AnnotationKeyAppInstance: fmt.Sprintf("%s_%s:Service:%s/guesbook-ui", TestNamespace(), ctx.AppQualifiedName(), DeploymentNamespace()), + common.AnnotationKeyAppInstance: fmt.Sprintf("%s_%s:Service:%s/guesbook-ui", fixture.TestNamespace(), ctx.AppQualifiedName(), fixture.DeploymentNamespace()), }, }, Spec: corev1.ServiceSpec{ @@ -1621,15 +1620,15 @@ func TestNamespacedNotPermittedResources(t *testing.T) { ctx.ProjectSpec(AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []ApplicationDestination{{Namespace: DeploymentNamespace(), Server: "*"}}, - SourceNamespaces: []string{AppNamespace()}, + Destinations: []ApplicationDestination{{Namespace: fixture.DeploymentNamespace(), Server: "*"}}, + SourceNamespaces: []string{fixture.AppNamespace()}, NamespaceResourceBlacklist: []metav1.GroupKind{ {Group: "", Kind: "Service"}, }, }). And(func() { - FailOnErr(KubeClientset.NetworkingV1().Ingresses(TestNamespace()).Create(context.Background(), ingress, metav1.CreateOptions{})) - FailOnErr(KubeClientset.CoreV1().Services(DeploymentNamespace()).Create(context.Background(), svc, metav1.CreateOptions{})) + FailOnErr(fixture.KubeClientset.NetworkingV1().Ingresses(fixture.TestNamespace()).Create(context.Background(), ingress, metav1.CreateOptions{})) + FailOnErr(fixture.KubeClientset.CoreV1().Services(fixture.DeploymentNamespace()).Create(context.Background(), svc, metav1.CreateOptions{})) }). Path(guestbookPath). When(). @@ -1654,8 +1653,8 @@ func TestNamespacedNotPermittedResources(t *testing.T) { Expect(DoesNotExist()) // Make sure prohibited resources are not deleted during application deletion - FailOnErr(KubeClientset.NetworkingV1().Ingresses(TestNamespace()).Get(context.Background(), "sample-ingress", metav1.GetOptions{})) - FailOnErr(KubeClientset.CoreV1().Services(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{})) + FailOnErr(fixture.KubeClientset.NetworkingV1().Ingresses(fixture.TestNamespace()).Get(context.Background(), "sample-ingress", metav1.GetOptions{})) + FailOnErr(fixture.KubeClientset.CoreV1().Services(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{})) } func TestNamespacedSyncWithInfos(t *testing.T) { @@ -1664,14 +1663,14 @@ func TestNamespacedSyncWithInfos(t *testing.T) { expectedInfo[1] = &Info{Name: "name2", Value: "val2"} Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path(guestbookPath). When(). CreateApp(). Then(). And(func(app *Application) { - _, err := RunCli("app", "sync", app.QualifiedName(), + _, err := fixture.RunCli("app", "sync", app.QualifiedName(), "--info", fmt.Sprintf("%s=%s", expectedInfo[0].Name, expectedInfo[0].Value), "--info", fmt.Sprintf("%s=%s", expectedInfo[1].Name, expectedInfo[1].Value)) require.NoError(t, err) @@ -1689,14 +1688,14 @@ func TestNamespacedSyncWithInfos(t *testing.T) { // Expect: no app.Status.Conditions func TestNamespacedCreateAppWithNoNameSpaceForGlobalResource(t *testing.T) { Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path(globalWithNoNameSpace). When(). CreateWithNoNameSpace(). Then(). And(func(app *Application) { - app, err := AppClientset.ArgoprojV1alpha1().Applications(AppNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) + app, err := fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.AppNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) require.NoError(t, err) assert.Empty(t, app.Status.Conditions) }) @@ -1710,7 +1709,7 @@ func TestNamespacedCreateAppWithNoNameSpaceForGlobalResource(t *testing.T) { // Expect: app.Status.Conditions for deployment ans service which does not have namespace in manifest func TestNamespacedCreateAppWithNoNameSpaceWhenRequired(t *testing.T) { Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path(guestbookPath). When(). @@ -1718,7 +1717,7 @@ func TestNamespacedCreateAppWithNoNameSpaceWhenRequired(t *testing.T) { Refresh(RefreshTypeNormal). Then(). And(func(app *Application) { - updatedApp, err := AppClientset.ArgoprojV1alpha1().Applications(AppNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) + updatedApp, err := fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.AppNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) require.NoError(t, err) assert.Len(t, updatedApp.Status.Conditions, 2) @@ -1736,7 +1735,7 @@ func TestNamespacedCreateAppWithNoNameSpaceWhenRequired(t *testing.T) { // Expect: app.Status.Conditions for deployment and service which does not have namespace in manifest func TestNamespacedCreateAppWithNoNameSpaceWhenRequired2(t *testing.T) { Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path(guestbookWithNamespace). When(). @@ -1744,7 +1743,7 @@ func TestNamespacedCreateAppWithNoNameSpaceWhenRequired2(t *testing.T) { Refresh(RefreshTypeNormal). Then(). And(func(app *Application) { - updatedApp, err := AppClientset.ArgoprojV1alpha1().Applications(AppNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) + updatedApp, err := fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.AppNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) require.NoError(t, err) assert.Len(t, updatedApp.Status.Conditions, 2) @@ -1754,15 +1753,15 @@ func TestNamespacedCreateAppWithNoNameSpaceWhenRequired2(t *testing.T) { } func TestNamespacedListResource(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). ProjectSpec(AppProjectSpec{ SourceRepos: []string{"*"}, Destinations: []ApplicationDestination{{Namespace: "*", Server: "*"}}, OrphanedResources: &OrphanedResourcesMonitorSettings{Warn: ptr.To(true)}, - SourceNamespaces: []string{AppNamespace()}, + SourceNamespaces: []string{fixture.AppNamespace()}, }). Path(guestbookPath). When(). @@ -1773,7 +1772,7 @@ func TestNamespacedListResource(t *testing.T) { Expect(NoConditions()). When(). And(func() { - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "orphaned-configmap", }, @@ -1783,19 +1782,19 @@ func TestNamespacedListResource(t *testing.T) { Then(). Expect(Condition(ApplicationConditionOrphanedResourceWarning, "Application has 1 orphaned resources")). And(func(app *Application) { - output, err := RunCli("app", "resources", app.QualifiedName()) + output, err := fixture.RunCli("app", "resources", app.QualifiedName()) require.NoError(t, err) assert.Contains(t, output, "orphaned-configmap") assert.Contains(t, output, "guestbook-ui") }). And(func(app *Application) { - output, err := RunCli("app", "resources", app.QualifiedName(), "--orphaned=true") + output, err := fixture.RunCli("app", "resources", app.QualifiedName(), "--orphaned=true") require.NoError(t, err) assert.Contains(t, output, "orphaned-configmap") assert.NotContains(t, output, "guestbook-ui") }). And(func(app *Application) { - output, err := RunCli("app", "resources", app.QualifiedName(), "--orphaned=false") + output, err := fixture.RunCli("app", "resources", app.QualifiedName(), "--orphaned=false") require.NoError(t, err) assert.NotContains(t, output, "orphaned-configmap") assert.Contains(t, output, "guestbook-ui") @@ -1805,7 +1804,7 @@ func TestNamespacedListResource(t *testing.T) { SourceRepos: []string{"*"}, Destinations: []ApplicationDestination{{Namespace: "*", Server: "*"}}, OrphanedResources: nil, - SourceNamespaces: []string{AppNamespace()}, + SourceNamespaces: []string{fixture.AppNamespace()}, }). When(). Refresh(RefreshTypeNormal). @@ -1823,16 +1822,16 @@ func TestNamespacedListResource(t *testing.T) { // application sync successful // when application is deleted, --dest-namespace is not deleted func TestNamespacedNamespaceAutoCreation(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") updatedNamespace := getNewNamespace(t) defer func() { if !t.Skipped() { - _, err := Run("", "kubectl", "delete", "namespace", updatedNamespace) + _, err := fixture.Run("", "kubectl", "delete", "namespace", updatedNamespace) require.NoError(t, err) } }() Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Timeout(30). Path("guestbook"). @@ -1855,7 +1854,7 @@ func TestNamespacedNamespaceAutoCreation(t *testing.T) { Expect(Success("")). And(func(app *Application) { // Verify delete app does not delete the namespace auto created - output, err := Run("", "kubectl", "get", "namespace", updatedNamespace) + output, err := fixture.Run("", "kubectl", "get", "namespace", updatedNamespace) require.NoError(t, err) assert.Contains(t, output, updatedNamespace) }) @@ -1867,17 +1866,17 @@ func TestNamespacedNamespaceAutoCreation(t *testing.T) { // // Verify application --dest-namespace is created with managedNamespaceMetadata func TestNamespacedNamespaceAutoCreationWithMetadata(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") updatedNamespace := getNewNamespace(t) defer func() { if !t.Skipped() { - _, err := Run("", "kubectl", "delete", "namespace", updatedNamespace) + _, err := fixture.Run("", "kubectl", "delete", "namespace", updatedNamespace) require.NoError(t, err) } }() ctx := Given(t) ctx. - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Timeout(30). Path("guestbook"). @@ -1916,7 +1915,7 @@ func TestNamespacedNamespaceAutoCreationWithMetadata(t *testing.T) { Expect(ResourceSyncStatusWithNamespaceIs("Deployment", "guestbook-ui", updatedNamespace, SyncStatusCodeSynced)). When(). And(func() { - FailOnErr(AppClientset.ArgoprojV1alpha1().Applications(AppNamespace()).Patch(context.Background(), + FailOnErr(fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.AppNamespace()).Patch(context.Background(), ctx.GetName(), types.JSONPatchType, []byte(`[{ "op": "replace", "path": "/spec/syncPolicy/managedNamespaceMetadata/labels", "value": {"new":"label"} }]`), metav1.PatchOptions{})) }). Sync(). @@ -1935,7 +1934,7 @@ func TestNamespacedNamespaceAutoCreationWithMetadata(t *testing.T) { })). When(). And(func() { - FailOnErr(AppClientset.ArgoprojV1alpha1().Applications(AppNamespace()).Patch(context.Background(), + FailOnErr(fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.AppNamespace()).Patch(context.Background(), ctx.GetName(), types.JSONPatchType, []byte(`[{ "op": "replace", "path": "/spec/syncPolicy/managedNamespaceMetadata/annotations", "value": {"new":"custom-annotation"} }]`), metav1.PatchOptions{})) }). Sync(). @@ -1960,18 +1959,18 @@ func TestNamespacedNamespaceAutoCreationWithMetadata(t *testing.T) { // // Verify application namespace manifest takes precedence over managedNamespaceMetadata func TestNamespacedNamespaceAutoCreationWithMetadataAndNsManifest(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") namespace := "guestbook-ui-with-namespace-manifest" defer func() { if !t.Skipped() { - _, err := Run("", "kubectl", "delete", "namespace", namespace) + _, err := fixture.Run("", "kubectl", "delete", "namespace", namespace) require.NoError(t, err) } }() ctx := Given(t) ctx. - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Timeout(30). Path("guestbook-with-namespace-manifest"). @@ -2014,11 +2013,11 @@ func TestNamespacedNamespaceAutoCreationWithMetadataAndNsManifest(t *testing.T) // // Verify application --dest-namespace is updated with managedNamespaceMetadata labels and annotations func TestNamespacedNamespaceAutoCreationWithPreexistingNs(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") updatedNamespace := getNewNamespace(t) defer func() { if !t.Skipped() { - _, err := Run("", "kubectl", "delete", "namespace", updatedNamespace) + _, err := fixture.Run("", "kubectl", "delete", "namespace", updatedNamespace) require.NoError(t, err) } }() @@ -2040,12 +2039,12 @@ metadata: _, err = tmpFile.Write([]byte(s)) errors.CheckError(err) - _, err = Run("", "kubectl", "apply", "-f", tmpFile.Name()) + _, err = fixture.Run("", "kubectl", "apply", "-f", tmpFile.Name()) require.NoError(t, err) ctx := Given(t) ctx. - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Timeout(30). Path("guestbook"). @@ -2087,7 +2086,7 @@ metadata: })). When(). And(func() { - FailOnErr(AppClientset.ArgoprojV1alpha1().Applications(AppNamespace()).Patch(context.Background(), + FailOnErr(fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.AppNamespace()).Patch(context.Background(), ctx.GetName(), types.JSONPatchType, []byte(`[{ "op": "add", "path": "/spec/syncPolicy/managedNamespaceMetadata/annotations/something", "value": "hmm" }]`), metav1.PatchOptions{})) }). Sync(). @@ -2107,7 +2106,7 @@ metadata: })). When(). And(func() { - FailOnErr(AppClientset.ArgoprojV1alpha1().Applications(AppNamespace()).Patch(context.Background(), + FailOnErr(fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.AppNamespace()).Patch(context.Background(), ctx.GetName(), types.JSONPatchType, []byte(`[{ "op": "remove", "path": "/spec/syncPolicy/managedNamespaceMetadata/annotations/something" }]`), metav1.PatchOptions{})) }). Sync(). @@ -2132,7 +2131,7 @@ metadata: func TestNamespacedFailedSyncWithRetry(t *testing.T) { Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path("hook"). When(). @@ -2149,15 +2148,15 @@ func TestNamespacedFailedSyncWithRetry(t *testing.T) { func TestNamespacedCreateDisableValidation(t *testing.T) { Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path("baddir"). When(). CreateApp("--validate=false"). Then(). And(func(app *Application) { - _, err := RunCli("app", "create", app.QualifiedName(), "--upsert", "--validate=false", "--repo", RepoURL(RepoURLTypeFile), - "--path", "baddir2", "--project", app.Spec.Project, "--dest-server", KubernetesInternalAPIServerAddr, "--dest-namespace", DeploymentNamespace()) + _, err := fixture.RunCli("app", "create", app.QualifiedName(), "--upsert", "--validate=false", "--repo", fixture.RepoURL(fixture.RepoURLTypeFile), + "--path", "baddir2", "--project", app.Spec.Project, "--dest-server", KubernetesInternalAPIServerAddr, "--dest-namespace", fixture.DeploymentNamespace()) require.NoError(t, err) }). When(). @@ -2181,7 +2180,7 @@ spec: path := "helm-values" Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). When(). // app should be auto-synced once created @@ -2228,11 +2227,11 @@ definitions: return obj ` Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path("crd-subresource"). And(func() { - CheckError(SetResourceOverrides(map[string]ResourceOverride{ + CheckError(fixture.SetResourceOverrides(map[string]ResourceOverride{ "argoproj.io/StatusSubResource": { Actions: actions, }, @@ -2248,49 +2247,49 @@ definitions: Then(). // tests resource actions on a CRD using status subresource And(func(app *Application) { - _, err := RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "StatusSubResource", "update-both") + _, err := fixture.RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "StatusSubResource", "update-both") require.NoError(t, err) - text := FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.spec.foo}")).(string) + text := FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.spec.foo}")).(string) assert.Equal(t, "update-both", text) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.status.bar}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.status.bar}")).(string) assert.Equal(t, "update-both", text) - _, err = RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "StatusSubResource", "update-spec") + _, err = fixture.RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "StatusSubResource", "update-spec") require.NoError(t, err) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.spec.foo}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.spec.foo}")).(string) assert.Equal(t, "update-spec", text) - _, err = RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "StatusSubResource", "update-status") + _, err = fixture.RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "StatusSubResource", "update-status") require.NoError(t, err) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.status.bar}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.status.bar}")).(string) assert.Equal(t, "update-status", text) }). // tests resource actions on a CRD *not* using status subresource And(func(app *Application) { - _, err := RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "NonStatusSubResource", "update-both") + _, err := fixture.RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "NonStatusSubResource", "update-both") require.NoError(t, err) - text := FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.spec.foo}")).(string) + text := FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.spec.foo}")).(string) assert.Equal(t, "update-both", text) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.status.bar}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.status.bar}")).(string) assert.Equal(t, "update-both", text) - _, err = RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "NonStatusSubResource", "update-spec") + _, err = fixture.RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "NonStatusSubResource", "update-spec") require.NoError(t, err) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.spec.foo}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.spec.foo}")).(string) assert.Equal(t, "update-spec", text) - _, err = RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "NonStatusSubResource", "update-status") + _, err = fixture.RunCli("app", "actions", "run", app.QualifiedName(), "--kind", "NonStatusSubResource", "update-status") require.NoError(t, err) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.status.bar}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.status.bar}")).(string) assert.Equal(t, "update-status", text) }) } func TestNamespacedAppLogs(t *testing.T) { t.SkipNow() // Too flaky. https://github.com/argoproj/argo-cd/issues/13834 - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path("guestbook-logs"). When(). @@ -2299,17 +2298,17 @@ func TestNamespacedAppLogs(t *testing.T) { Then(). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - out, err := RunCliWithRetry(5, "app", "logs", app.QualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") + out, err := fixture.RunCliWithRetry(5, "app", "logs", app.QualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(5, "app", "logs", app.QualifiedName(), "--kind", "Pod") + out, err := fixture.RunCliWithRetry(5, "app", "logs", app.QualifiedName(), "--kind", "Pod") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(5, "app", "logs", app.QualifiedName(), "--kind", "Service") + out, err := fixture.RunCliWithRetry(5, "app", "logs", app.QualifiedName(), "--kind", "Service") require.NoError(t, err) assert.NotContains(t, out, "Hi") }) @@ -2317,10 +2316,10 @@ func TestNamespacedAppLogs(t *testing.T) { func TestNamespacedAppWaitOperationInProgress(t *testing.T) { Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). And(func() { - CheckError(SetResourceOverrides(map[string]ResourceOverride{ + CheckError(fixture.SetResourceOverrides(map[string]ResourceOverride{ "batch/Job": { HealthLua: `return { status = 'Running' }`, }, @@ -2340,14 +2339,14 @@ func TestNamespacedAppWaitOperationInProgress(t *testing.T) { When(). Then(). And(func(app *Application) { - _, err := RunCli("app", "wait", app.QualifiedName(), "--suspended") + _, err := fixture.RunCli("app", "wait", app.QualifiedName(), "--suspended") errors.CheckError(err) }) } func TestNamespacedSyncOptionReplace(t *testing.T) { Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path("config-map"). When(). @@ -2370,7 +2369,7 @@ func TestNamespacedSyncOptionReplace(t *testing.T) { func TestNamespacedSyncOptionReplaceFromCLI(t *testing.T) { Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path("config-map"). Replace(). @@ -2394,7 +2393,7 @@ func TestNamespacedSyncOptionReplaceFromCLI(t *testing.T) { func TestNamespacedDiscoverNewCommit(t *testing.T) { var sha string Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path("config-map"). When(). @@ -2426,7 +2425,7 @@ func TestNamespacedDiscoverNewCommit(t *testing.T) { func TestNamespacedDisableManifestGeneration(t *testing.T) { Given(t). - SetAppNamespace(AppNamespace()). + SetAppNamespace(fixture.AppNamespace()). SetTrackingMethod("annotation"). Path("guestbook"). When(). @@ -2438,7 +2437,7 @@ func TestNamespacedDisableManifestGeneration(t *testing.T) { }). When(). And(func() { - CheckError(SetEnableManifestGeneration(map[ApplicationSourceType]bool{ + CheckError(fixture.SetEnableManifestGeneration(map[ApplicationSourceType]bool{ ApplicationSourceTypeKustomize: false, })) }). diff --git a/test/e2e/app_management_test.go b/test/e2e/app_management_test.go index 31137af8d54a1..65d725fa0d97b 100644 --- a/test/e2e/app_management_test.go +++ b/test/e2e/app_management_test.go @@ -30,14 +30,12 @@ import ( applicationpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/test/e2e/fixture" - . "github.com/argoproj/argo-cd/v2/test/e2e/fixture" accountFixture "github.com/argoproj/argo-cd/v2/test/e2e/fixture/account" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/app" projectFixture "github.com/argoproj/argo-cd/v2/test/e2e/fixture/project" repoFixture "github.com/argoproj/argo-cd/v2/test/e2e/fixture/repos" "github.com/argoproj/argo-cd/v2/test/e2e/testdata" "github.com/argoproj/argo-cd/v2/util/argo" - . "github.com/argoproj/argo-cd/v2/util/argo" . "github.com/argoproj/argo-cd/v2/util/errors" "github.com/argoproj/argo-cd/v2/util/io" "github.com/argoproj/argo-cd/v2/util/settings" @@ -59,7 +57,7 @@ func TestGetLogsAllowNoSwitch(t *testing.T) { } func TestGetLogsDenySwitchOn(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") accountFixture.Given(t). Name("test"). @@ -98,13 +96,13 @@ func TestGetLogsDenySwitchOn(t *testing.T) { Then(). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - _, err := RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") + _, err := fixture.RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") assert.ErrorContains(t, err, "permission denied") }) } func TestGetLogsAllowSwitchOn(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") accountFixture.Given(t). Name("test"). @@ -148,24 +146,24 @@ func TestGetLogsAllowSwitchOn(t *testing.T) { Then(). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - out, err := RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") + out, err := fixture.RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Pod") + out, err := fixture.RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Pod") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Service") + out, err := fixture.RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Service") require.NoError(t, err) assert.NotContains(t, out, "Hi") }) } func TestGetLogsAllowSwitchOff(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") accountFixture.Given(t). Name("test"). @@ -204,24 +202,24 @@ func TestGetLogsAllowSwitchOff(t *testing.T) { Then(). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - out, err := RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") + out, err := fixture.RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Pod") + out, err := fixture.RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Pod") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Service") + out, err := fixture.RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Service") require.NoError(t, err) assert.NotContains(t, out, "Hi") }) } func TestSyncToUnsignedCommit(t *testing.T) { - SkipOnEnv(t, "GPG") + fixture.SkipOnEnv(t, "GPG") Given(t). Project("gpg"). Path(guestbookPath). @@ -236,7 +234,7 @@ func TestSyncToUnsignedCommit(t *testing.T) { } func TestSyncToSignedCommitWithoutKnownKey(t *testing.T) { - SkipOnEnv(t, "GPG") + fixture.SkipOnEnv(t, "GPG") Given(t). Project("gpg"). Path(guestbookPath). @@ -252,7 +250,7 @@ func TestSyncToSignedCommitWithoutKnownKey(t *testing.T) { } func TestSyncToSignedCommitWithKnownKey(t *testing.T) { - SkipOnEnv(t, "GPG") + fixture.SkipOnEnv(t, "GPG") Given(t). Project("gpg"). Path(guestbookPath). @@ -270,7 +268,7 @@ func TestSyncToSignedCommitWithKnownKey(t *testing.T) { } func TestSyncToSignedBranchWithKnownKey(t *testing.T) { - SkipOnEnv(t, "GPG") + fixture.SkipOnEnv(t, "GPG") Given(t). Project("gpg"). Path(guestbookPath). @@ -289,7 +287,7 @@ func TestSyncToSignedBranchWithKnownKey(t *testing.T) { } func TestSyncToSignedBranchWithUnknownKey(t *testing.T) { - SkipOnEnv(t, "GPG") + fixture.SkipOnEnv(t, "GPG") Given(t). Project("gpg"). Path(guestbookPath). @@ -307,7 +305,7 @@ func TestSyncToSignedBranchWithUnknownKey(t *testing.T) { } func TestSyncToUnsignedBranch(t *testing.T) { - SkipOnEnv(t, "GPG") + fixture.SkipOnEnv(t, "GPG") Given(t). Project("gpg"). Revision("master"). @@ -325,7 +323,7 @@ func TestSyncToUnsignedBranch(t *testing.T) { } func TestSyncToSignedTagWithKnownKey(t *testing.T) { - SkipOnEnv(t, "GPG") + fixture.SkipOnEnv(t, "GPG") Given(t). Project("gpg"). Revision("signed-tag"). @@ -344,7 +342,7 @@ func TestSyncToSignedTagWithKnownKey(t *testing.T) { } func TestSyncToSignedTagWithUnknownKey(t *testing.T) { - SkipOnEnv(t, "GPG") + fixture.SkipOnEnv(t, "GPG") Given(t). Project("gpg"). Revision("signed-tag"). @@ -362,7 +360,7 @@ func TestSyncToSignedTagWithUnknownKey(t *testing.T) { } func TestSyncToUnsignedTag(t *testing.T) { - SkipOnEnv(t, "GPG") + fixture.SkipOnEnv(t, "GPG") Given(t). Project("gpg"). Revision("unsigned-tag"). @@ -389,18 +387,18 @@ func TestAppCreation(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). And(func(app *Application) { - assert.Equal(t, Name(), app.Name) - assert.Equal(t, RepoURL(RepoURLTypeFile), app.Spec.GetSource().RepoURL) + assert.Equal(t, fixture.Name(), app.Name) + assert.Equal(t, fixture.RepoURL(fixture.RepoURLTypeFile), app.Spec.GetSource().RepoURL) assert.Equal(t, guestbookPath, app.Spec.GetSource().Path) - assert.Equal(t, DeploymentNamespace(), app.Spec.Destination.Namespace) + assert.Equal(t, fixture.DeploymentNamespace(), app.Spec.Destination.Namespace) assert.Equal(t, KubernetesInternalAPIServerAddr, app.Spec.Destination.Server) }). - Expect(Event(EventReasonResourceCreated, "create")). + Expect(Event(argo.EventReasonResourceCreated, "create")). And(func(_ *Application) { // app should be listed - output, err := RunCli("app", "list") + output, err := fixture.RunCli("app", "list") require.NoError(t, err) - assert.Contains(t, output, Name()) + assert.Contains(t, output, fixture.Name()) }). When(). // ensure that create is idempotent @@ -411,7 +409,7 @@ func TestAppCreation(t *testing.T) { When(). // ensure that update replaces spec and merge labels and annotations And(func() { - FailOnErr(AppClientset.ArgoprojV1alpha1().Applications(TestNamespace()).Patch(context.Background(), + FailOnErr(fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.TestNamespace()).Patch(context.Background(), ctx.GetName(), types.MergePatchType, []byte(`{"metadata": {"labels": { "test": "label" }, "annotations": { "test": "annotation" }}}`), metav1.PatchOptions{})) }). CreateApp("--upsert"). @@ -435,17 +433,17 @@ func TestAppCreationWithoutForceUpdate(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). And(func(app *Application) { assert.Equal(t, ctx.AppName(), app.Name) - assert.Equal(t, RepoURL(RepoURLTypeFile), app.Spec.GetSource().RepoURL) + assert.Equal(t, fixture.RepoURL(fixture.RepoURLTypeFile), app.Spec.GetSource().RepoURL) assert.Equal(t, guestbookPath, app.Spec.GetSource().Path) - assert.Equal(t, DeploymentNamespace(), app.Spec.Destination.Namespace) + assert.Equal(t, fixture.DeploymentNamespace(), app.Spec.Destination.Namespace) assert.Equal(t, "in-cluster", app.Spec.Destination.Name) }). - Expect(Event(EventReasonResourceCreated, "create")). + Expect(Event(argo.EventReasonResourceCreated, "create")). And(func(_ *Application) { // app should be listed - output, err := RunCli("app", "list") + output, err := fixture.RunCli("app", "list") require.NoError(t, err) - assert.Contains(t, output, Name()) + assert.Contains(t, output, fixture.Name()) }). When(). IgnoreErrors(). @@ -505,7 +503,7 @@ func TestDeleteAppResource(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(_ *Application) { // app should be listed - if _, err := RunCli("app", "delete-resource", Name(), "--kind", "Service", "--resource-name", "guestbook-ui"); err != nil { + if _, err := fixture.RunCli("app", "delete-resource", fixture.Name(), "--kind", "Service", "--resource-name", "guestbook-ui"); err != nil { require.NoError(t, err) } }). @@ -532,7 +530,7 @@ func TestPatchHttp(t *testing.T) { // demonstrate that we cannot use a standard sync when an immutable field is changed, we must use "force" func TestImmutableChange(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") Given(t). Path("secrets"). When(). @@ -555,7 +553,7 @@ func TestImmutableChange(t *testing.T) { Expect(ResourceResultMatches(ResourceResult{ Kind: "Secret", Version: "v1", - Namespace: DeploymentNamespace(), + Namespace: fixture.DeploymentNamespace(), Name: "test-secret", SyncPhase: "Sync", Status: "SyncFailed", @@ -597,11 +595,11 @@ func TestAppDeletion(t *testing.T) { Delete(true). Then(). Expect(DoesNotExist()). - Expect(Event(EventReasonResourceDeleted, "delete")) + Expect(Event(argo.EventReasonResourceDeleted, "delete")) - output, err := RunCli("app", "list") + output, err := fixture.RunCli("app", "list") require.NoError(t, err) - assert.NotContains(t, output, Name()) + assert.NotContains(t, output, fixture.Name()) } func TestAppLabels(t *testing.T) { @@ -611,9 +609,9 @@ func TestAppLabels(t *testing.T) { CreateApp("-l", "foo=bar"). Then(). And(func(app *Application) { - assert.Contains(t, FailOnErr(RunCli("app", "list")), Name()) - assert.Contains(t, FailOnErr(RunCli("app", "list", "-l", "foo=bar")), Name()) - assert.NotContains(t, FailOnErr(RunCli("app", "list", "-l", "foo=rubbish")), Name()) + assert.Contains(t, FailOnErr(fixture.RunCli("app", "list")), fixture.Name()) + assert.Contains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=bar")), fixture.Name()) + assert.NotContains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=rubbish")), fixture.Name()) }). Given(). // remove both name and replace labels means nothing will sync @@ -640,9 +638,9 @@ func TestTrackAppStateAndSyncApp(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - Expect(Success(fmt.Sprintf("Service %s guestbook-ui Synced ", DeploymentNamespace()))). - Expect(Success(fmt.Sprintf("apps Deployment %s guestbook-ui Synced", DeploymentNamespace()))). - Expect(Event(EventReasonResourceUpdated, "sync")). + Expect(Success(fmt.Sprintf("Service %s guestbook-ui Synced ", fixture.DeploymentNamespace()))). + Expect(Success(fmt.Sprintf("apps Deployment %s guestbook-ui Synced", fixture.DeploymentNamespace()))). + Expect(Event(argo.EventReasonResourceUpdated, "sync")). And(func(app *Application) { assert.NotNil(t, app.Status.OperationState.SyncResult) }) @@ -674,14 +672,14 @@ func TestAppRollbackSuccessful(t *testing.T) { }} patch, _, err := diff.CreateTwoWayMergePatch(app, appWithHistory, &Application{}) require.NoError(t, err) - app, err = AppClientset.ArgoprojV1alpha1().Applications(TestNamespace()).Patch(context.Background(), app.Name, types.MergePatchType, patch, metav1.PatchOptions{}) + app, err = fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.TestNamespace()).Patch(context.Background(), app.Name, types.MergePatchType, patch, metav1.PatchOptions{}) require.NoError(t, err) // sync app and make sure it reaches InSync state - _, err = RunCli("app", "rollback", app.Name, "1") + _, err = fixture.RunCli("app", "rollback", app.Name, "1") require.NoError(t, err) }). - Expect(Event(EventReasonOperationStarted, "rollback")). + Expect(Event(argo.EventReasonOperationStarted, "rollback")). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { assert.Equal(t, SyncStatusCodeSynced, app.Status.Sync.Status) @@ -723,7 +721,7 @@ func TestManipulateApplicationResources(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - manifests, err := RunCli("app", "manifests", app.Name, "--source", "live") + manifests, err := fixture.RunCli("app", "manifests", app.Name, "--source", "live") require.NoError(t, err) resources, err := kube.SplitYAML([]byte(manifests)) require.NoError(t, err) @@ -739,7 +737,7 @@ func TestManipulateApplicationResources(t *testing.T) { deployment := resources[index] - closer, client, err := ArgoCDClientset.NewApplicationClient() + closer, client, err := fixture.ArgoCDClientset.NewApplicationClient() require.NoError(t, err) defer io.Close(closer) @@ -782,7 +780,7 @@ func assetSecretDataHidden(t *testing.T, manifest string) { } func TestAppWithSecrets(t *testing.T) { - closer, client, err := ArgoCDClientset.NewApplicationClient() + closer, client, err := fixture.ArgoCDClientset.NewApplicationClient() require.NoError(t, err) defer io.Close(closer) @@ -811,19 +809,19 @@ func TestAppWithSecrets(t *testing.T) { assetSecretDataHidden(t, manifest) } - diffOutput := FailOnErr(RunCli("app", "diff", app.Name)).(string) + diffOutput := FailOnErr(fixture.RunCli("app", "diff", app.Name)).(string) assert.Empty(t, diffOutput) // make sure resource update error does not print secret details - _, err = RunCli("app", "patch-resource", "test-app-with-secrets", "--resource-name", "test-secret", + _, err = fixture.RunCli("app", "patch-resource", "test-app-with-secrets", "--resource-name", "test-secret", "--kind", "Secret", "--patch", `{"op": "add", "path": "/data", "value": "hello"}'`, "--patch-type", "application/json-patch+json") - require.ErrorContains(t, err, fmt.Sprintf("failed to patch Secret %s/test-secret", DeploymentNamespace())) + require.ErrorContains(t, err, fmt.Sprintf("failed to patch Secret %s/test-secret", fixture.DeploymentNamespace())) assert.NotContains(t, err.Error(), "username") assert.NotContains(t, err.Error(), "password") // patch secret and make sure app is out of sync and diff detects the change - FailOnErr(KubeClientset.CoreV1().Secrets(DeploymentNamespace()).Patch(context.Background(), + FailOnErr(fixture.KubeClientset.CoreV1().Secrets(fixture.DeploymentNamespace()).Patch(context.Background(), "test-secret", types.JSONPatchType, []byte(`[ {"op": "remove", "path": "/data/username"}, {"op": "add", "path": "/stringData", "value": {"password": "foo"}} @@ -834,13 +832,13 @@ func TestAppWithSecrets(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). And(func(app *Application) { - diffOutput, err := RunCli("app", "diff", app.Name) + diffOutput, err := fixture.RunCli("app", "diff", app.Name) require.Error(t, err) assert.Contains(t, diffOutput, "username: ++++++++") assert.Contains(t, diffOutput, "password: ++++++++++++") // local diff should ignore secrets - diffOutput = FailOnErr(RunCli("app", "diff", app.Name, "--local", "testdata", "--server-side-generate")).(string) + diffOutput = FailOnErr(fixture.RunCli("app", "diff", app.Name, "--local", "testdata", "--server-side-generate")).(string) assert.Empty(t, diffOutput) // ignore missing field and make sure diff shows no difference @@ -855,7 +853,7 @@ func TestAppWithSecrets(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - diffOutput := FailOnErr(RunCli("app", "diff", app.Name)).(string) + diffOutput := FailOnErr(fixture.RunCli("app", "diff", app.Name)).(string) assert.Empty(t, diffOutput) }). // verify not committed secret also ignore during diffing @@ -869,7 +867,7 @@ stringData: username: test-username`). Then(). And(func(app *Application) { - diffOutput := FailOnErr(RunCli("app", "diff", app.Name, "--local", "testdata", "--server-side-generate")).(string) + diffOutput := FailOnErr(fixture.RunCli("app", "diff", app.Name, "--local", "testdata", "--server-side-generate")).(string) assert.Empty(t, diffOutput) }) } @@ -884,7 +882,7 @@ func TestResourceDiffing(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { // Patch deployment - _, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Patch(context.Background(), + _, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Patch(context.Background(), "guestbook-ui", types.JSONPatchType, []byte(`[{ "op": "replace", "path": "/spec/template/spec/containers/0/image", "value": "test" }]`), metav1.PatchOptions{}) require.NoError(t, err) }). @@ -893,9 +891,9 @@ func TestResourceDiffing(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). And(func(app *Application) { - diffOutput, err := RunCli("app", "diff", app.Name, "--local", "testdata", "--server-side-generate") + diffOutput, err := fixture.RunCli("app", "diff", app.Name, "--local", "testdata", "--server-side-generate") require.Error(t, err) - assert.Contains(t, diffOutput, fmt.Sprintf("===== apps/Deployment %s/guestbook-ui ======", DeploymentNamespace())) + assert.Contains(t, diffOutput, fmt.Sprintf("===== apps/Deployment %s/guestbook-ui ======", fixture.DeploymentNamespace())) }). Given(). ResourceOverrides(map[string]ResourceOverride{"apps/Deployment": { @@ -906,7 +904,7 @@ func TestResourceDiffing(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - diffOutput, err := RunCli("app", "diff", app.Name, "--local", "testdata", "--server-side-generate") + diffOutput, err := fixture.RunCli("app", "diff", app.Name, "--local", "testdata", "--server-side-generate") require.NoError(t, err) assert.Empty(t, diffOutput) }). @@ -924,7 +922,7 @@ func TestResourceDiffing(t *testing.T) { }]`). Sync(). And(func() { - output, err := RunWithStdin(testdata.SSARevisionHistoryDeployment, "", "kubectl", "apply", "-n", DeploymentNamespace(), "--server-side=true", "--field-manager=revision-history-manager", "--validate=false", "--force-conflicts", "-f", "-") + output, err := fixture.RunWithStdin(testdata.SSARevisionHistoryDeployment, "", "kubectl", "apply", "-n", fixture.DeploymentNamespace(), "--server-side=true", "--field-manager=revision-history-manager", "--validate=false", "--force-conflicts", "-f", "-") require.NoError(t, err) assert.Contains(t, output, "serverside-applied") }). @@ -951,12 +949,12 @@ func TestResourceDiffing(t *testing.T) { "value": { "syncOptions": ["RespectIgnoreDifferences=true"] } }]`). And(func() { - deployment, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(3), *deployment.Spec.RevisionHistoryLimit) }). And(func() { - output, err := RunWithStdin(testdata.SSARevisionHistoryDeployment, "", "kubectl", "apply", "-n", DeploymentNamespace(), "--server-side=true", "--field-manager=revision-history-manager", "--validate=false", "--force-conflicts", "-f", "-") + output, err := fixture.RunWithStdin(testdata.SSARevisionHistoryDeployment, "", "kubectl", "apply", "-n", fixture.DeploymentNamespace(), "--server-side=true", "--field-manager=revision-history-manager", "--validate=false", "--force-conflicts", "-f", "-") require.NoError(t, err) assert.Contains(t, output, "serverside-applied") }). @@ -965,13 +963,13 @@ func TestResourceDiffing(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - deployment, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) }). When().Sync().Then().Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - deployment, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) }) @@ -990,7 +988,7 @@ func TestKnownTypesInCRDDiffing(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)).Expect(SyncStatusIs(SyncStatusCodeSynced)). When(). And(func() { - dummyResIf := DynamicClientset.Resource(dummiesGVR).Namespace(DeploymentNamespace()) + dummyResIf := fixture.DynamicClientset.Resource(dummiesGVR).Namespace(fixture.DeploymentNamespace()) patchData := []byte(`{"spec":{"cpu": "2"}}`) FailOnErr(dummyResIf.Patch(context.Background(), "dummy-crd-instance", types.MergePatchType, patchData, metav1.PatchOptions{})) }).Refresh(RefreshTypeNormal). @@ -998,7 +996,7 @@ func TestKnownTypesInCRDDiffing(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). When(). And(func() { - CheckError(SetResourceOverrides(map[string]ResourceOverride{ + CheckError(fixture.SetResourceOverrides(map[string]ResourceOverride{ "argoproj.io/Dummy": { KnownTypeFields: []KnownTypeField{{ Field: "spec", @@ -1036,7 +1034,7 @@ func testEdgeCasesApplicationResources(t *testing.T, appPath string, statusCode expect. Expect(HealthIs(statusCode)). And(func(app *Application) { - diffOutput, err := RunCli("app", "diff", app.Name, "--local", "testdata", "--server-side-generate") + diffOutput, err := fixture.RunCli("app", "diff", app.Name, "--local", "testdata", "--server-side-generate") assert.Empty(t, diffOutput) require.NoError(t, err) }) @@ -1058,7 +1056,7 @@ func TestOldStyleResourceAction(t *testing.T) { Sync(). Then(). And(func(app *Application) { - closer, client, err := ArgoCDClientset.NewApplicationClient() + closer, client, err := fixture.ArgoCDClientset.NewApplicationClient() require.NoError(t, err) defer io.Close(closer) @@ -1067,7 +1065,7 @@ func TestOldStyleResourceAction(t *testing.T) { Group: ptr.To("apps"), Kind: ptr.To("Deployment"), Version: ptr.To("v1"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), ResourceName: ptr.To("guestbook-ui"), }) require.NoError(t, err) @@ -1078,13 +1076,13 @@ func TestOldStyleResourceAction(t *testing.T) { Group: ptr.To("apps"), Kind: ptr.To("Deployment"), Version: ptr.To("v1"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), ResourceName: ptr.To("guestbook-ui"), Action: ptr.To("sample"), }) require.NoError(t, err) - deployment, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, "test", deployment.Labels["sample"]) @@ -1164,7 +1162,7 @@ func TestNewStyleResourceActionPermitted(t *testing.T) { Sync(). Then(). And(func(app *Application) { - closer, client, err := ArgoCDClientset.NewApplicationClient() + closer, client, err := fixture.ArgoCDClientset.NewApplicationClient() require.NoError(t, err) defer io.Close(closer) @@ -1173,7 +1171,7 @@ func TestNewStyleResourceActionPermitted(t *testing.T) { Group: ptr.To("batch"), Kind: ptr.To("CronJob"), Version: ptr.To("v1"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), ResourceName: ptr.To("hello"), }) require.NoError(t, err) @@ -1184,13 +1182,13 @@ func TestNewStyleResourceActionPermitted(t *testing.T) { Group: ptr.To("batch"), Kind: ptr.To("CronJob"), Version: ptr.To("v1"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), ResourceName: ptr.To("hello"), Action: ptr.To("sample"), }) require.NoError(t, err) - _, err = KubeClientset.BatchV1().Jobs(DeploymentNamespace()).Get(context.Background(), "hello-123", metav1.GetOptions{}) + _, err = fixture.KubeClientset.BatchV1().Jobs(fixture.DeploymentNamespace()).Get(context.Background(), "hello-123", metav1.GetOptions{}) require.NoError(t, err) }) } @@ -1275,7 +1273,7 @@ func TestNewStyleResourceActionMixedOk(t *testing.T) { Sync(). Then(). And(func(app *Application) { - closer, client, err := ArgoCDClientset.NewApplicationClient() + closer, client, err := fixture.ArgoCDClientset.NewApplicationClient() require.NoError(t, err) defer io.Close(closer) @@ -1284,7 +1282,7 @@ func TestNewStyleResourceActionMixedOk(t *testing.T) { Group: ptr.To("batch"), Kind: ptr.To("CronJob"), Version: ptr.To("v1"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), ResourceName: ptr.To("hello"), }) require.NoError(t, err) @@ -1295,17 +1293,17 @@ func TestNewStyleResourceActionMixedOk(t *testing.T) { Group: ptr.To("batch"), Kind: ptr.To("CronJob"), Version: ptr.To("v1"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), ResourceName: ptr.To("hello"), Action: ptr.To("sample"), }) require.NoError(t, err) // Assert new Job was created - _, err = KubeClientset.BatchV1().Jobs(DeploymentNamespace()).Get(context.Background(), "hello-123", metav1.GetOptions{}) + _, err = fixture.KubeClientset.BatchV1().Jobs(fixture.DeploymentNamespace()).Get(context.Background(), "hello-123", metav1.GetOptions{}) require.NoError(t, err) // Assert the original CronJob was patched - cronJob, err := KubeClientset.BatchV1().CronJobs(DeploymentNamespace()).Get(context.Background(), "hello", metav1.GetOptions{}) + cronJob, err := fixture.KubeClientset.BatchV1().CronJobs(fixture.DeploymentNamespace()).Get(context.Background(), "hello", metav1.GetOptions{}) assert.Equal(t, "aValue", cronJob.Labels["aKey"]) require.NoError(t, err) }) @@ -1319,11 +1317,11 @@ func TestSyncResourceByLabel(t *testing.T) { Sync(). Then(). And(func(app *Application) { - _, _ = RunCli("app", "sync", app.Name, "--label", "app.kubernetes.io/instance="+app.Name) + _, _ = fixture.RunCli("app", "sync", app.Name, "--label", "app.kubernetes.io/instance="+app.Name) }). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - _, err := RunCli("app", "sync", app.Name, "--label", "this-label=does-not-exist") + _, err := fixture.RunCli("app", "sync", app.Name, "--label", "this-label=does-not-exist") assert.ErrorContains(t, err, "level=fatal") }) } @@ -1336,11 +1334,11 @@ func TestSyncResourceByProject(t *testing.T) { Sync(). Then(). And(func(app *Application) { - _, _ = RunCli("app", "sync", app.Name, "--project", app.Spec.Project) + _, _ = fixture.RunCli("app", "sync", app.Name, "--project", app.Spec.Project) }). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - _, err := RunCli("app", "sync", app.Name, "--project", "this-project-does-not-exist") + _, err := fixture.RunCli("app", "sync", app.Name, "--project", "this-project-does-not-exist") assert.ErrorContains(t, err, "level=fatal") }) } @@ -1353,7 +1351,7 @@ func TestLocalManifestSync(t *testing.T) { Sync(). Then(). And(func(app *Application) { - res, _ := RunCli("app", "manifests", app.Name) + res, _ := fixture.RunCli("app", "manifests", app.Name) assert.Contains(t, res, "containerPort: 80") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.2") }). @@ -1364,7 +1362,7 @@ func TestLocalManifestSync(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - res, _ := RunCli("app", "manifests", app.Name) + res, _ := fixture.RunCli("app", "manifests", app.Name) assert.Contains(t, res, "containerPort: 81") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.3") }). @@ -1375,7 +1373,7 @@ func TestLocalManifestSync(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - res, _ := RunCli("app", "manifests", app.Name) + res, _ := fixture.RunCli("app", "manifests", app.Name) assert.Contains(t, res, "containerPort: 80") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.2") }) @@ -1389,7 +1387,7 @@ func TestLocalSync(t *testing.T) { CreateApp(). Then(). And(func(app *Application) { - FailOnErr(RunCli("app", "sync", app.Name, "--local", "testdata/helm")) + FailOnErr(fixture.RunCli("app", "sync", app.Name, "--local", "testdata/helm")) }) } @@ -1401,10 +1399,10 @@ func TestNoLocalSyncWithAutosyncEnabled(t *testing.T) { Sync(). Then(). And(func(app *Application) { - _, err := RunCli("app", "set", app.Name, "--sync-policy", "automated") + _, err := fixture.RunCli("app", "set", app.Name, "--sync-policy", "automated") require.NoError(t, err) - _, err = RunCli("app", "sync", app.Name, "--local", guestbookPathLocal) + _, err = fixture.RunCli("app", "sync", app.Name, "--local", guestbookPathLocal) require.Error(t, err) }) } @@ -1417,11 +1415,11 @@ func TestLocalSyncDryRunWithAutosyncEnabled(t *testing.T) { Sync(). Then(). And(func(app *Application) { - _, err := RunCli("app", "set", app.Name, "--sync-policy", "automated") + _, err := fixture.RunCli("app", "set", app.Name, "--sync-policy", "automated") require.NoError(t, err) appBefore := app.DeepCopy() - _, err = RunCli("app", "sync", app.Name, "--dry-run", "--local-repo-root", ".", "--local", guestbookPathLocal) + _, err = fixture.RunCli("app", "sync", app.Name, "--dry-run", "--local-repo-root", ".", "--local", guestbookPathLocal) require.NoError(t, err) appAfter := app.DeepCopy() @@ -1453,17 +1451,17 @@ func assertResourceActions(t *testing.T, appName string, successful bool) { } } - closer, cdClient := ArgoCDClientset.NewApplicationClientOrDie() + closer, cdClient := fixture.ArgoCDClientset.NewApplicationClientOrDie() defer io.Close(closer) - deploymentResource, err := KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + deploymentResource, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) logs, err := cdClient.PodLogs(context.Background(), &applicationpkg.ApplicationPodLogsQuery{ Group: ptr.To("apps"), Kind: ptr.To("Deployment"), Name: &appName, - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), Container: ptr.To(""), SinceSeconds: ptr.To(int64(0)), TailLines: ptr.To(int64(0)), @@ -1478,7 +1476,7 @@ func assertResourceActions(t *testing.T, appName string, successful bool) { _, err = cdClient.ListResourceEvents(context.Background(), &applicationpkg.ApplicationResourceEventsQuery{ Name: &appName, ResourceName: ptr.To("guestbook-ui"), - ResourceNamespace: ptr.To(DeploymentNamespace()), + ResourceNamespace: ptr.To(fixture.DeploymentNamespace()), ResourceUID: ptr.To(string(deploymentResource.UID)), }) assertError(err, fmt.Sprintf("%s not found as part of application %s", "guestbook-ui", appName)) @@ -1486,7 +1484,7 @@ func assertResourceActions(t *testing.T, appName string, successful bool) { _, err = cdClient.GetResource(context.Background(), &applicationpkg.ApplicationResourceRequest{ Name: &appName, ResourceName: ptr.To("guestbook-ui"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), Version: ptr.To("v1"), Group: ptr.To("apps"), Kind: ptr.To("Deployment"), @@ -1496,7 +1494,7 @@ func assertResourceActions(t *testing.T, appName string, successful bool) { _, err = cdClient.RunResourceAction(context.Background(), &applicationpkg.ResourceActionRunRequest{ Name: &appName, ResourceName: ptr.To("guestbook-ui"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), Version: ptr.To("v1"), Group: ptr.To("apps"), Kind: ptr.To("Deployment"), @@ -1507,7 +1505,7 @@ func assertResourceActions(t *testing.T, appName string, successful bool) { _, err = cdClient.DeleteResource(context.Background(), &applicationpkg.ApplicationResourceDeleteRequest{ Name: &appName, ResourceName: ptr.To("guestbook-ui"), - Namespace: ptr.To(DeploymentNamespace()), + Namespace: ptr.To(fixture.DeploymentNamespace()), Version: ptr.To("v1"), Group: ptr.To("apps"), Kind: ptr.To("Deployment"), @@ -1524,8 +1522,8 @@ func TestPermissions(t *testing.T) { When(). Create() - sourceError := fmt.Sprintf("application repo %s is not permitted in project 'argo-project'", RepoURL(RepoURLTypeFile)) - destinationError := fmt.Sprintf("application destination server '%s' and namespace '%s' do not match any of the allowed destinations in project 'argo-project'", KubernetesInternalAPIServerAddr, DeploymentNamespace()) + sourceError := fmt.Sprintf("application repo %s is not permitted in project 'argo-project'", fixture.RepoURL(fixture.RepoURLTypeFile)) + destinationError := fmt.Sprintf("application destination server '%s' and namespace '%s' do not match any of the allowed destinations in project 'argo-project'", KubernetesInternalAPIServerAddr, fixture.DeploymentNamespace()) appCtx. Path("guestbook-logs"). @@ -1565,7 +1563,7 @@ func TestPermissions(t *testing.T) { Expect(Condition(ApplicationConditionInvalidSpecError, destinationError)). Expect(Condition(ApplicationConditionInvalidSpecError, sourceError)). And(func(app *Application) { - closer, cdClient := ArgoCDClientset.NewApplicationClientOrDie() + closer, cdClient := fixture.ArgoCDClientset.NewApplicationClientOrDie() defer io.Close(closer) appName, appNs := argo.ParseFromQualifiedName(app.Name, "") fmt.Printf("APP NAME: %s\n", appName) @@ -1605,13 +1603,13 @@ func TestPermissionWithScopedRepo(t *testing.T) { repoFixture.GivenWithSameState(t). When(). - Path(RepoURL(RepoURLTypeFile)). + Path(fixture.RepoURL(fixture.RepoURLTypeFile)). Project(projName). Create() GivenWithSameState(t). Project(projName). - RepoURLType(RepoURLTypeFile). + RepoURLType(fixture.RepoURLTypeFile). Path("two-nice-pods"). When(). PatchFile("pod-1.yaml", `[{"op": "add", "path": "/metadata/annotations", "value": {"argocd.argoproj.io/sync-options": "Prune=false"}}]`). @@ -1642,12 +1640,12 @@ func TestPermissionDeniedWithScopedRepo(t *testing.T) { repoFixture.GivenWithSameState(t). When(). - Path(RepoURL(RepoURLTypeFile)). + Path(fixture.RepoURL(fixture.RepoURLTypeFile)). Create() GivenWithSameState(t). Project(projName). - RepoURLType(RepoURLTypeFile). + RepoURLType(fixture.RepoURLTypeFile). Path("two-nice-pods"). When(). PatchFile("pod-1.yaml", `[{"op": "add", "path": "/metadata/annotations", "value": {"argocd.argoproj.io/sync-options": "Prune=false"}}]`). @@ -1668,13 +1666,13 @@ func TestPermissionDeniedWithNegatedNamespace(t *testing.T) { repoFixture.GivenWithSameState(t). When(). - Path(RepoURL(RepoURLTypeFile)). + Path(fixture.RepoURL(fixture.RepoURLTypeFile)). Project(projName). Create() GivenWithSameState(t). Project(projName). - RepoURLType(RepoURLTypeFile). + RepoURLType(fixture.RepoURLTypeFile). Path("two-nice-pods"). When(). PatchFile("pod-1.yaml", `[{"op": "add", "path": "/metadata/annotations", "value": {"argocd.argoproj.io/sync-options": "Prune=false"}}]`). @@ -1695,13 +1693,13 @@ func TestPermissionDeniedWithNegatedServer(t *testing.T) { repoFixture.GivenWithSameState(t). When(). - Path(RepoURL(RepoURLTypeFile)). + Path(fixture.RepoURL(fixture.RepoURLTypeFile)). Project(projName). Create() GivenWithSameState(t). Project(projName). - RepoURLType(RepoURLTypeFile). + RepoURLType(fixture.RepoURLTypeFile). Path("two-nice-pods"). When(). PatchFile("pod-1.yaml", `[{"op": "add", "path": "/metadata/annotations", "value": {"argocd.argoproj.io/sync-options": "Prune=false"}}]`). @@ -1793,7 +1791,7 @@ func TestSourceNamespaceCanBeMigratedToManagedNamespaceWithoutBeingPrunedOrOutOf Prune(true). Path("guestbook-with-plain-namespace-manifest"). When(). - PatchFile("guestbook-ui-namespace.yaml", fmt.Sprintf(`[{"op": "replace", "path": "/metadata/name", "value": "%s"}]`, DeploymentNamespace())). + PatchFile("guestbook-ui-namespace.yaml", fmt.Sprintf(`[{"op": "replace", "path": "/metadata/name", "value": "%s"}]`, fixture.DeploymentNamespace())). CreateApp(). Sync(). Then(). @@ -1826,7 +1824,7 @@ func TestSelfManagedApps(t *testing.T) { Given(t). Path("self-managed-app"). When(). - PatchFile("resources.yaml", fmt.Sprintf(`[{"op": "replace", "path": "/spec/source/repoURL", "value": "%s"}]`, RepoURL(RepoURLTypeFile))). + PatchFile("resources.yaml", fmt.Sprintf(`[{"op": "replace", "path": "/spec/source/repoURL", "value": "%s"}]`, fixture.RepoURL(fixture.RepoURLTypeFile))). CreateApp(). Sync(). Then(). @@ -1838,7 +1836,7 @@ func TestSelfManagedApps(t *testing.T) { reconciledCount := 0 var lastReconciledAt *metav1.Time - for event := range ArgoCDClientset.WatchApplicationWithRetry(ctx, a.Name, a.ResourceVersion) { + for event := range fixture.ArgoCDClientset.WatchApplicationWithRetry(ctx, a.Name, a.ResourceVersion) { reconciledAt := event.Application.Status.ReconciledAt if reconciledAt == nil { reconciledAt = &metav1.Time{} @@ -1892,7 +1890,7 @@ func TestRevisionHistoryLimit(t *testing.T) { } func TestOrphanedResource(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") Given(t). ProjectSpec(AppProjectSpec{ SourceRepos: []string{"*"}, @@ -1908,7 +1906,7 @@ func TestOrphanedResource(t *testing.T) { Expect(NoConditions()). When(). And(func() { - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "orphaned-configmap", }, @@ -1918,7 +1916,7 @@ func TestOrphanedResource(t *testing.T) { Then(). Expect(Condition(ApplicationConditionOrphanedResourceWarning, "Application has 1 orphaned resources")). And(func(app *Application) { - output, err := RunCli("app", "resources", app.Name) + output, err := fixture.RunCli("app", "resources", app.Name) require.NoError(t, err) assert.Contains(t, output, "orphaned-configmap") }). @@ -1933,7 +1931,7 @@ func TestOrphanedResource(t *testing.T) { Then(). Expect(Condition(ApplicationConditionOrphanedResourceWarning, "Application has 1 orphaned resources")). And(func(app *Application) { - output, err := RunCli("app", "resources", app.Name) + output, err := fixture.RunCli("app", "resources", app.Name) require.NoError(t, err) assert.Contains(t, output, "orphaned-configmap") }). @@ -1949,7 +1947,7 @@ func TestOrphanedResource(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(NoConditions()). And(func(app *Application) { - output, err := RunCli("app", "resources", app.Name) + output, err := fixture.RunCli("app", "resources", app.Name) require.NoError(t, err) assert.NotContains(t, output, "orphaned-configmap") }). @@ -1965,7 +1963,7 @@ func TestOrphanedResource(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(NoConditions()). And(func(app *Application) { - output, err := RunCli("app", "resources", app.Name) + output, err := fixture.RunCli("app", "resources", app.Name) require.NoError(t, err) assert.NotContains(t, output, "orphaned-configmap") }). @@ -2013,8 +2011,8 @@ func TestNotPermittedResources(t *testing.T) { }, } defer func() { - log.Infof("Ingress 'sample-ingress' deleted from %s", TestNamespace()) - CheckError(KubeClientset.NetworkingV1().Ingresses(TestNamespace()).Delete(context.Background(), "sample-ingress", metav1.DeleteOptions{})) + log.Infof("Ingress 'sample-ingress' deleted from %s", fixture.TestNamespace()) + CheckError(fixture.KubeClientset.NetworkingV1().Ingresses(fixture.TestNamespace()).Delete(context.Background(), "sample-ingress", metav1.DeleteOptions{})) }() svc := &corev1.Service{ @@ -2037,14 +2035,14 @@ func TestNotPermittedResources(t *testing.T) { ctx.ProjectSpec(AppProjectSpec{ SourceRepos: []string{"*"}, - Destinations: []ApplicationDestination{{Namespace: DeploymentNamespace(), Server: "*"}}, + Destinations: []ApplicationDestination{{Namespace: fixture.DeploymentNamespace(), Server: "*"}}, NamespaceResourceBlacklist: []metav1.GroupKind{ {Group: "", Kind: "Service"}, }, }). And(func() { - FailOnErr(KubeClientset.NetworkingV1().Ingresses(TestNamespace()).Create(context.Background(), ingress, metav1.CreateOptions{})) - FailOnErr(KubeClientset.CoreV1().Services(DeploymentNamespace()).Create(context.Background(), svc, metav1.CreateOptions{})) + FailOnErr(fixture.KubeClientset.NetworkingV1().Ingresses(fixture.TestNamespace()).Create(context.Background(), ingress, metav1.CreateOptions{})) + FailOnErr(fixture.KubeClientset.CoreV1().Services(fixture.DeploymentNamespace()).Create(context.Background(), svc, metav1.CreateOptions{})) }). Path(guestbookPath). When(). @@ -2069,8 +2067,8 @@ func TestNotPermittedResources(t *testing.T) { Expect(DoesNotExist()) // Make sure prohibited resources are not deleted during application deletion - FailOnErr(KubeClientset.NetworkingV1().Ingresses(TestNamespace()).Get(context.Background(), "sample-ingress", metav1.GetOptions{})) - FailOnErr(KubeClientset.CoreV1().Services(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{})) + FailOnErr(fixture.KubeClientset.NetworkingV1().Ingresses(fixture.TestNamespace()).Get(context.Background(), "sample-ingress", metav1.GetOptions{})) + FailOnErr(fixture.KubeClientset.CoreV1().Services(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{})) } func TestSyncWithInfos(t *testing.T) { @@ -2084,7 +2082,7 @@ func TestSyncWithInfos(t *testing.T) { CreateApp(). Then(). And(func(app *Application) { - _, err := RunCli("app", "sync", app.Name, + _, err := fixture.RunCli("app", "sync", app.Name, "--info", fmt.Sprintf("%s=%s", expectedInfo[0].Name, expectedInfo[0].Value), "--info", fmt.Sprintf("%s=%s", expectedInfo[1].Name, expectedInfo[1].Value)) require.NoError(t, err) @@ -2107,7 +2105,7 @@ func TestCreateAppWithNoNameSpaceForGlobalResource(t *testing.T) { CreateWithNoNameSpace(). Then(). And(func(app *Application) { - app, err := AppClientset.ArgoprojV1alpha1().Applications(TestNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) + app, err := fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.TestNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) require.NoError(t, err) assert.Empty(t, app.Status.Conditions) }) @@ -2127,7 +2125,7 @@ func TestCreateAppWithNoNameSpaceWhenRequired(t *testing.T) { Refresh(RefreshTypeNormal). Then(). And(func(app *Application) { - updatedApp, err := AppClientset.ArgoprojV1alpha1().Applications(TestNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) + updatedApp, err := fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.TestNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) require.NoError(t, err) assert.Len(t, updatedApp.Status.Conditions, 2) @@ -2151,7 +2149,7 @@ func TestCreateAppWithNoNameSpaceWhenRequired2(t *testing.T) { Refresh(RefreshTypeNormal). Then(). And(func(app *Application) { - updatedApp, err := AppClientset.ArgoprojV1alpha1().Applications(TestNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) + updatedApp, err := fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.TestNamespace()).Get(context.Background(), app.Name, metav1.GetOptions{}) require.NoError(t, err) assert.Len(t, updatedApp.Status.Conditions, 2) @@ -2161,7 +2159,7 @@ func TestCreateAppWithNoNameSpaceWhenRequired2(t *testing.T) { } func TestListResource(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") Given(t). ProjectSpec(AppProjectSpec{ SourceRepos: []string{"*"}, @@ -2177,7 +2175,7 @@ func TestListResource(t *testing.T) { Expect(NoConditions()). When(). And(func() { - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "orphaned-configmap", }, @@ -2187,19 +2185,19 @@ func TestListResource(t *testing.T) { Then(). Expect(Condition(ApplicationConditionOrphanedResourceWarning, "Application has 1 orphaned resources")). And(func(app *Application) { - output, err := RunCli("app", "resources", app.Name) + output, err := fixture.RunCli("app", "resources", app.Name) require.NoError(t, err) assert.Contains(t, output, "orphaned-configmap") assert.Contains(t, output, "guestbook-ui") }). And(func(app *Application) { - output, err := RunCli("app", "resources", app.Name, "--orphaned=true") + output, err := fixture.RunCli("app", "resources", app.Name, "--orphaned=true") require.NoError(t, err) assert.Contains(t, output, "orphaned-configmap") assert.NotContains(t, output, "guestbook-ui") }). And(func(app *Application) { - output, err := RunCli("app", "resources", app.Name, "--orphaned=false") + output, err := fixture.RunCli("app", "resources", app.Name, "--orphaned=false") require.NoError(t, err) assert.NotContains(t, output, "orphaned-configmap") assert.Contains(t, output, "guestbook-ui") @@ -2226,11 +2224,11 @@ func TestListResource(t *testing.T) { // application sync successful // when application is deleted, --dest-namespace is not deleted func TestNamespaceAutoCreation(t *testing.T) { - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") updatedNamespace := getNewNamespace(t) defer func() { if !t.Skipped() { - _, err := Run("", "kubectl", "delete", "namespace", updatedNamespace) + _, err := fixture.Run("", "kubectl", "delete", "namespace", updatedNamespace) require.NoError(t, err) } }() @@ -2242,7 +2240,7 @@ func TestNamespaceAutoCreation(t *testing.T) { Then(). And(func(app *Application) { // Make sure the namespace we are about to update to does not exist - _, err := Run("", "kubectl", "get", "namespace", updatedNamespace) + _, err := fixture.Run("", "kubectl", "get", "namespace", updatedNamespace) assert.ErrorContains(t, err, "not found") }). When(). @@ -2260,7 +2258,7 @@ func TestNamespaceAutoCreation(t *testing.T) { Expect(Success("")). And(func(app *Application) { // Verify delete app does not delete the namespace auto created - output, err := Run("", "kubectl", "get", "namespace", updatedNamespace) + output, err := fixture.Run("", "kubectl", "get", "namespace", updatedNamespace) require.NoError(t, err) assert.Contains(t, output, updatedNamespace) }) @@ -2288,8 +2286,8 @@ func TestCreateDisableValidation(t *testing.T) { CreateApp("--validate=false"). Then(). And(func(app *Application) { - _, err := RunCli("app", "create", app.Name, "--upsert", "--validate=false", "--repo", RepoURL(RepoURLTypeFile), - "--path", "baddir2", "--project", app.Spec.Project, "--dest-server", KubernetesInternalAPIServerAddr, "--dest-namespace", DeploymentNamespace()) + _, err := fixture.RunCli("app", "create", app.Name, "--upsert", "--validate=false", "--repo", fixture.RepoURL(fixture.RepoURLTypeFile), + "--path", "baddir2", "--project", app.Spec.Project, "--dest-server", KubernetesInternalAPIServerAddr, "--dest-namespace", fixture.DeploymentNamespace()) require.NoError(t, err) }). When(). @@ -2360,7 +2358,7 @@ definitions: Given(t). Path("crd-subresource"). And(func() { - CheckError(SetResourceOverrides(map[string]ResourceOverride{ + CheckError(fixture.SetResourceOverrides(map[string]ResourceOverride{ "argoproj.io/StatusSubResource": { Actions: actions, }, @@ -2376,47 +2374,47 @@ definitions: Then(). // tests resource actions on a CRD using status subresource And(func(app *Application) { - _, err := RunCli("app", "actions", "run", app.Name, "--kind", "StatusSubResource", "update-both") + _, err := fixture.RunCli("app", "actions", "run", app.Name, "--kind", "StatusSubResource", "update-both") require.NoError(t, err) - text := FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.spec.foo}")).(string) + text := FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.spec.foo}")).(string) assert.Equal(t, "update-both", text) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.status.bar}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.status.bar}")).(string) assert.Equal(t, "update-both", text) - _, err = RunCli("app", "actions", "run", app.Name, "--kind", "StatusSubResource", "update-spec") + _, err = fixture.RunCli("app", "actions", "run", app.Name, "--kind", "StatusSubResource", "update-spec") require.NoError(t, err) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.spec.foo}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.spec.foo}")).(string) assert.Equal(t, "update-spec", text) - _, err = RunCli("app", "actions", "run", app.Name, "--kind", "StatusSubResource", "update-status") + _, err = fixture.RunCli("app", "actions", "run", app.Name, "--kind", "StatusSubResource", "update-status") require.NoError(t, err) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.status.bar}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "statussubresources", "status-subresource", "-o", "jsonpath={.status.bar}")).(string) assert.Equal(t, "update-status", text) }). // tests resource actions on a CRD *not* using status subresource And(func(app *Application) { - _, err := RunCli("app", "actions", "run", app.Name, "--kind", "NonStatusSubResource", "update-both") + _, err := fixture.RunCli("app", "actions", "run", app.Name, "--kind", "NonStatusSubResource", "update-both") require.NoError(t, err) - text := FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.spec.foo}")).(string) + text := FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.spec.foo}")).(string) assert.Equal(t, "update-both", text) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.status.bar}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.status.bar}")).(string) assert.Equal(t, "update-both", text) - _, err = RunCli("app", "actions", "run", app.Name, "--kind", "NonStatusSubResource", "update-spec") + _, err = fixture.RunCli("app", "actions", "run", app.Name, "--kind", "NonStatusSubResource", "update-spec") require.NoError(t, err) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.spec.foo}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.spec.foo}")).(string) assert.Equal(t, "update-spec", text) - _, err = RunCli("app", "actions", "run", app.Name, "--kind", "NonStatusSubResource", "update-status") + _, err = fixture.RunCli("app", "actions", "run", app.Name, "--kind", "NonStatusSubResource", "update-status") require.NoError(t, err) - text = FailOnErr(Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.status.bar}")).(string) + text = FailOnErr(fixture.Run(".", "kubectl", "-n", app.Spec.Destination.Namespace, "get", "nonstatussubresources", "non-status-subresource", "-o", "jsonpath={.status.bar}")).(string) assert.Equal(t, "update-status", text) }) } func TestAppLogs(t *testing.T) { t.SkipNow() // Too flaky. https://github.com/argoproj/argo-cd/issues/13834 - SkipOnEnv(t, "OPENSHIFT") + fixture.SkipOnEnv(t, "OPENSHIFT") Given(t). Path("guestbook-logs"). When(). @@ -2425,17 +2423,17 @@ func TestAppLogs(t *testing.T) { Then(). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - out, err := RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") + out, err := fixture.RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Pod") + out, err := fixture.RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Pod") require.NoError(t, err) assert.Contains(t, out, "Hi") }). And(func(app *Application) { - out, err := RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Service") + out, err := fixture.RunCliWithRetry(appLogsRetryCount, "app", "logs", app.Name, "--kind", "Service") require.NoError(t, err) assert.NotContains(t, out, "Hi") }) @@ -2445,7 +2443,7 @@ func TestAppWaitOperationInProgress(t *testing.T) { ctx := Given(t) ctx. And(func() { - CheckError(SetResourceOverrides(map[string]ResourceOverride{ + CheckError(fixture.SetResourceOverrides(map[string]ResourceOverride{ "batch/Job": { HealthLua: `return { status = 'Running' }`, }, @@ -2464,7 +2462,7 @@ func TestAppWaitOperationInProgress(t *testing.T) { Expect(OperationPhaseIs(OperationRunning)). When(). And(func() { - _, err := RunCli("app", "wait", ctx.AppName(), "--suspended") + _, err := fixture.RunCli("app", "wait", ctx.AppName(), "--suspended") errors.CheckError(err) }) } @@ -2554,7 +2552,7 @@ func TestDisableManifestGeneration(t *testing.T) { }). When(). And(func() { - CheckError(SetEnableManifestGeneration(map[ApplicationSourceType]bool{ + CheckError(fixture.SetEnableManifestGeneration(map[ApplicationSourceType]bool{ ApplicationSourceTypeKustomize: false, })) }). @@ -2587,11 +2585,11 @@ func TestSwitchTrackingMethod(t *testing.T) { And(func() { // Add resource with tracking annotation. This should put the // application OutOfSync. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Annotations: map[string]string{ - common.AnnotationKeyAppInstance: fmt.Sprintf("%s:/ConfigMap:%s/other-configmap", Name(), DeploymentNamespace()), + common.AnnotationKeyAppInstance: fmt.Sprintf("%s:/ConfigMap:%s/other-configmap", fixture.Name(), fixture.DeploymentNamespace()), }, }, }, metav1.CreateOptions{})) @@ -2603,7 +2601,7 @@ func TestSwitchTrackingMethod(t *testing.T) { When(). And(func() { // Delete resource to bring application back in sync - FailOnErr(nil, KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Delete(context.Background(), "other-configmap", metav1.DeleteOptions{})) + FailOnErr(nil, fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Delete(context.Background(), "other-configmap", metav1.DeleteOptions{})) }). Then(). Expect(OperationPhaseIs(OperationSucceeded)). @@ -2621,11 +2619,11 @@ func TestSwitchTrackingMethod(t *testing.T) { // Add a resource with a tracking annotation. This should not // affect the application, because we now use the tracking method // "label". - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Annotations: map[string]string{ - common.AnnotationKeyAppInstance: fmt.Sprintf("%s:/ConfigMap:%s/other-configmap", Name(), DeploymentNamespace()), + common.AnnotationKeyAppInstance: fmt.Sprintf("%s:/ConfigMap:%s/other-configmap", fixture.Name(), fixture.DeploymentNamespace()), }, }, }, metav1.CreateOptions{})) @@ -2638,11 +2636,11 @@ func TestSwitchTrackingMethod(t *testing.T) { And(func() { // Add a resource with the tracking label. The app should become // OutOfSync. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "extra-configmap", Labels: map[string]string{ - common.LabelKeyAppInstance: Name(), + common.LabelKeyAppInstance: fixture.Name(), }, }, }, metav1.CreateOptions{})) @@ -2654,7 +2652,7 @@ func TestSwitchTrackingMethod(t *testing.T) { When(). And(func() { // Delete resource to bring application back in sync - FailOnErr(nil, KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Delete(context.Background(), "extra-configmap", metav1.DeleteOptions{})) + FailOnErr(nil, fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Delete(context.Background(), "extra-configmap", metav1.DeleteOptions{})) }). Then(). Expect(OperationPhaseIs(OperationSucceeded)). @@ -2679,11 +2677,11 @@ func TestSwitchTrackingLabel(t *testing.T) { And(func() { // Add extra resource that carries the default tracking label // We expect the app to go out of sync. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Labels: map[string]string{ - common.LabelKeyAppInstance: Name(), + common.LabelKeyAppInstance: fixture.Name(), }, }, }, metav1.CreateOptions{})) @@ -2695,7 +2693,7 @@ func TestSwitchTrackingLabel(t *testing.T) { When(). And(func() { // Delete resource to bring application back in sync - FailOnErr(nil, KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Delete(context.Background(), "other-configmap", metav1.DeleteOptions{})) + FailOnErr(nil, fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Delete(context.Background(), "other-configmap", metav1.DeleteOptions{})) }). Then(). Expect(OperationPhaseIs(OperationSucceeded)). @@ -2713,11 +2711,11 @@ func TestSwitchTrackingLabel(t *testing.T) { And(func() { // Create resource with the new tracking label, the application // is expected to go out of sync - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Labels: map[string]string{ - "argocd.tracking": Name(), + "argocd.tracking": fixture.Name(), }, }, }, metav1.CreateOptions{})) @@ -2729,7 +2727,7 @@ func TestSwitchTrackingLabel(t *testing.T) { When(). And(func() { // Delete resource to bring application back in sync - FailOnErr(nil, KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Delete(context.Background(), "other-configmap", metav1.DeleteOptions{})) + FailOnErr(nil, fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Delete(context.Background(), "other-configmap", metav1.DeleteOptions{})) }). Then(). Expect(OperationPhaseIs(OperationSucceeded)). @@ -2740,11 +2738,11 @@ func TestSwitchTrackingLabel(t *testing.T) { // Add extra resource that carries the default tracking label // We expect the app to stay in sync, because the configured // label is different. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Labels: map[string]string{ - common.LabelKeyAppInstance: Name(), + common.LabelKeyAppInstance: fixture.Name(), }, }, }, metav1.CreateOptions{})) @@ -2758,7 +2756,7 @@ func TestSwitchTrackingLabel(t *testing.T) { func TestAnnotationTrackingExtraResources(t *testing.T) { ctx := Given(t) - CheckError(SetTrackingMethod(string(argo.TrackingMethodAnnotation))) + CheckError(fixture.SetTrackingMethod(string(argo.TrackingMethodAnnotation))) ctx. Path("deployment"). When(). @@ -2773,11 +2771,11 @@ func TestAnnotationTrackingExtraResources(t *testing.T) { And(func() { // Add a resource with an annotation that is not referencing the // resource. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "extra-configmap", Annotations: map[string]string{ - common.AnnotationKeyAppInstance: fmt.Sprintf("%s:apps/Deployment:%s/guestbook-cm", Name(), DeploymentNamespace()), + common.AnnotationKeyAppInstance: fmt.Sprintf("%s:apps/Deployment:%s/guestbook-cm", fixture.Name(), fixture.DeploymentNamespace()), }, }, }, metav1.CreateOptions{})) @@ -2791,18 +2789,18 @@ func TestAnnotationTrackingExtraResources(t *testing.T) { Sync("--prune"). And(func() { // The extra configmap must not be pruned, because it's not tracked - cm, err := KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Get(context.Background(), "extra-configmap", metav1.GetOptions{}) + cm, err := fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Get(context.Background(), "extra-configmap", metav1.GetOptions{}) require.NoError(t, err) require.Equal(t, "extra-configmap", cm.Name) }). And(func() { // Add a resource with an annotation that is self-referencing the // resource. - FailOnErr(KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ + FailOnErr(fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create(context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "other-configmap", Annotations: map[string]string{ - common.AnnotationKeyAppInstance: fmt.Sprintf("%s:/ConfigMap:%s/other-configmap", Name(), DeploymentNamespace()), + common.AnnotationKeyAppInstance: fmt.Sprintf("%s:/ConfigMap:%s/other-configmap", fixture.Name(), fixture.DeploymentNamespace()), }, }, }, metav1.CreateOptions{})) @@ -2816,7 +2814,7 @@ func TestAnnotationTrackingExtraResources(t *testing.T) { Sync("--prune"). And(func() { // The extra configmap must be pruned now, because it's tracked - cm, err := KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Get(context.Background(), "other-configmap", metav1.GetOptions{}) + cm, err := fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Get(context.Background(), "other-configmap", metav1.GetOptions{}) require.Error(t, err) require.Equal(t, "", cm.Name) }). @@ -2827,11 +2825,11 @@ func TestAnnotationTrackingExtraResources(t *testing.T) { When(). And(func() { // Add a cluster-scoped resource that is not referencing itself - FailOnErr(KubeClientset.RbacV1().ClusterRoles().Create(context.Background(), &rbacv1.ClusterRole{ + FailOnErr(fixture.KubeClientset.RbacV1().ClusterRoles().Create(context.Background(), &rbacv1.ClusterRole{ ObjectMeta: metav1.ObjectMeta{ Name: "e2e-test-clusterrole", Annotations: map[string]string{ - common.AnnotationKeyAppInstance: fmt.Sprintf("%s:rbac.authorization.k8s.io/ClusterRole:%s/e2e-other-clusterrole", Name(), DeploymentNamespace()), + common.AnnotationKeyAppInstance: fmt.Sprintf("%s:rbac.authorization.k8s.io/ClusterRole:%s/e2e-other-clusterrole", fixture.Name(), fixture.DeploymentNamespace()), }, Labels: map[string]string{ fixture.TestingLabel: "true", @@ -2847,11 +2845,11 @@ func TestAnnotationTrackingExtraResources(t *testing.T) { When(). And(func() { // Add a cluster-scoped resource that is referencing itself - FailOnErr(KubeClientset.RbacV1().ClusterRoles().Create(context.Background(), &rbacv1.ClusterRole{ + FailOnErr(fixture.KubeClientset.RbacV1().ClusterRoles().Create(context.Background(), &rbacv1.ClusterRole{ ObjectMeta: metav1.ObjectMeta{ Name: "e2e-other-clusterrole", Annotations: map[string]string{ - common.AnnotationKeyAppInstance: fmt.Sprintf("%s:rbac.authorization.k8s.io/ClusterRole:%s/e2e-other-clusterrole", Name(), DeploymentNamespace()), + common.AnnotationKeyAppInstance: fmt.Sprintf("%s:rbac.authorization.k8s.io/ClusterRole:%s/e2e-other-clusterrole", fixture.Name(), fixture.DeploymentNamespace()), }, Labels: map[string]string{ fixture.TestingLabel: "true", @@ -2868,7 +2866,7 @@ func TestAnnotationTrackingExtraResources(t *testing.T) { Sync("--prune"). And(func() { // The extra configmap must be pruned now, because it's tracked and does not exist in git - cr, err := KubeClientset.RbacV1().ClusterRoles().Get(context.Background(), "e2e-other-clusterrole", metav1.GetOptions{}) + cr, err := fixture.KubeClientset.RbacV1().ClusterRoles().Get(context.Background(), "e2e-other-clusterrole", metav1.GetOptions{}) require.Error(t, err) require.Equal(t, "", cr.Name) }). @@ -2886,7 +2884,7 @@ func TestCreateConfigMapsAndWaitForUpdate(t *testing.T) { Sync(). Then(). And(func(app *Application) { - _, err := RunCli("app", "set", app.Name, "--sync-policy", "automated") + _, err := fixture.RunCli("app", "set", app.Name, "--sync-policy", "automated") require.NoError(t, err) }). When(). @@ -2915,10 +2913,10 @@ data: Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - Expect(ResourceHealthWithNamespaceIs("ConfigMap", "other-map", DeploymentNamespace(), health.HealthStatusHealthy)). - Expect(ResourceSyncStatusWithNamespaceIs("ConfigMap", "other-map", DeploymentNamespace(), SyncStatusCodeSynced)). - Expect(ResourceHealthWithNamespaceIs("ConfigMap", "yet-another-map", DeploymentNamespace(), health.HealthStatusHealthy)). - Expect(ResourceSyncStatusWithNamespaceIs("ConfigMap", "yet-another-map", DeploymentNamespace(), SyncStatusCodeSynced)) + Expect(ResourceHealthWithNamespaceIs("ConfigMap", "other-map", fixture.DeploymentNamespace(), health.HealthStatusHealthy)). + Expect(ResourceSyncStatusWithNamespaceIs("ConfigMap", "other-map", fixture.DeploymentNamespace(), SyncStatusCodeSynced)). + Expect(ResourceHealthWithNamespaceIs("ConfigMap", "yet-another-map", fixture.DeploymentNamespace(), health.HealthStatusHealthy)). + Expect(ResourceSyncStatusWithNamespaceIs("ConfigMap", "yet-another-map", fixture.DeploymentNamespace(), SyncStatusCodeSynced)) } func TestInstallationID(t *testing.T) { @@ -2926,12 +2924,12 @@ func TestInstallationID(t *testing.T) { ctx. SetTrackingMethod(string(argo.TrackingMethodAnnotation)). And(func() { - _, err := fixture.KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create( + _, err := fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create( context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "test-configmap", Annotations: map[string]string{ - common.AnnotationKeyAppInstance: fmt.Sprintf("%s:/ConfigMap:%s/test-configmap", ctx.AppName(), DeploymentNamespace()), + common.AnnotationKeyAppInstance: fmt.Sprintf("%s:/ConfigMap:%s/test-configmap", ctx.AppName(), fixture.DeploymentNamespace()), }, }, }, metav1.CreateOptions{}) @@ -2957,11 +2955,11 @@ func TestInstallationID(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { require.Len(t, app.Status.Resources, 2) - svc, err := fixture.KubeClientset.CoreV1().Services(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + svc, err := fixture.KubeClientset.CoreV1().Services(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) require.Equal(t, "test", svc.Annotations[common.AnnotationInstallationID]) - deploy, err := fixture.KubeClientset.AppsV1().Deployments(DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) + deploy, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) require.Equal(t, "test", deploy.Annotations[common.AnnotationInstallationID]) }) @@ -2971,7 +2969,7 @@ func TestDeletionConfirmation(t *testing.T) { ctx := Given(t) ctx. And(func() { - _, err := fixture.KubeClientset.CoreV1().ConfigMaps(DeploymentNamespace()).Create( + _, err := fixture.KubeClientset.CoreV1().ConfigMaps(fixture.DeploymentNamespace()).Create( context.Background(), &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "test-configmap", diff --git a/test/e2e/applicationset_test.go b/test/e2e/applicationset_test.go index 247fc3af2d40a..74cf61f76d1b7 100644 --- a/test/e2e/applicationset_test.go +++ b/test/e2e/applicationset_test.go @@ -22,7 +22,6 @@ import ( "github.com/argoproj/argo-cd/v2/common" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/test/e2e/fixture" "github.com/stretchr/testify/assert" @@ -59,7 +58,7 @@ var ExpectedConditions = []v1alpha1.ApplicationSetCondition{ func TestSimpleListGeneratorExternalNamespace(t *testing.T) { externalNamespace := string(utils.ArgoCDExternalNamespace) - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: "Application", APIVersion: "argoproj.io/v1alpha1", @@ -69,21 +68,21 @@ func TestSimpleListGeneratorExternalNamespace(t *testing.T) { Namespace: externalNamespace, Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, }, } - var expectedAppNewNamespace *argov1alpha1.Application - var expectedAppNewMetadata *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application + var expectedAppNewMetadata *v1alpha1.Application Given(t). // Create a ListGenerator-based ApplicationSet @@ -98,14 +97,14 @@ func TestSimpleListGeneratorExternalNamespace(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.cluster}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{.url}}", Namespace: "guestbook", }, @@ -121,7 +120,7 @@ func TestSimpleListGeneratorExternalNamespace(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -131,7 +130,7 @@ func TestSimpleListGeneratorExternalNamespace(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template, and make sure it propagates to the apps When(). @@ -147,21 +146,21 @@ func TestSimpleListGeneratorExternalNamespace(t *testing.T) { appset.Spec.Template.Labels = map[string]string{ "label-key": "label-value", } - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // verify the ApplicationSet status conditions were set correctly Expect(ApplicationSetHasConditions("simple-list-generator-external", ExpectedConditions)). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewMetadata})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewMetadata})) } func TestSimpleListGeneratorExternalNamespaceNoConflict(t *testing.T) { externalNamespace := string(utils.ArgoCDExternalNamespace) externalNamespace2 := string(utils.ArgoCDExternalNamespace2) - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: "Application", APIVersion: "argoproj.io/v1alpha1", @@ -171,21 +170,21 @@ func TestSimpleListGeneratorExternalNamespaceNoConflict(t *testing.T) { Namespace: externalNamespace, Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, }, } - expectedAppExternalNamespace2 := argov1alpha1.Application{ + expectedAppExternalNamespace2 := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: "Application", APIVersion: "argoproj.io/v1alpha1", @@ -195,22 +194,22 @@ func TestSimpleListGeneratorExternalNamespaceNoConflict(t *testing.T) { Namespace: externalNamespace2, Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, }, } - var expectedAppNewNamespace *argov1alpha1.Application - var expectedAppNewMetadata *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application + var expectedAppNewMetadata *v1alpha1.Application Given(t). // Create a ListGenerator-based ApplicationSet @@ -225,14 +224,14 @@ func TestSimpleListGeneratorExternalNamespaceNoConflict(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.cluster}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{.url}}", Namespace: "guestbook", }, @@ -248,7 +247,7 @@ func TestSimpleListGeneratorExternalNamespaceNoConflict(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppExternalNamespace2})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppExternalNamespace2})). When(). SwitchToExternalNamespace(utils.ArgoCDExternalNamespace). CreateNamespace(externalNamespace).Create(v1alpha1.ApplicationSet{ @@ -260,14 +259,14 @@ func TestSimpleListGeneratorExternalNamespaceNoConflict(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.cluster}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{.url}}", Namespace: "guestbook", }, @@ -283,11 +282,11 @@ func TestSimpleListGeneratorExternalNamespaceNoConflict(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). When(). SwitchToExternalNamespace(utils.ArgoCDExternalNamespace2). Then(). - Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppExternalNamespace2})). + Expect(ApplicationsExist([]v1alpha1.Application{expectedAppExternalNamespace2})). When(). SwitchToExternalNamespace(utils.ArgoCDExternalNamespace). Then(). @@ -299,11 +298,11 @@ func TestSimpleListGeneratorExternalNamespaceNoConflict(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). When(). SwitchToExternalNamespace(utils.ArgoCDExternalNamespace2). Then(). - Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppExternalNamespace2})). + Expect(ApplicationsExist([]v1alpha1.Application{expectedAppExternalNamespace2})). When(). SwitchToExternalNamespace(utils.ArgoCDExternalNamespace). Then(). @@ -321,30 +320,30 @@ func TestSimpleListGeneratorExternalNamespaceNoConflict(t *testing.T) { appset.Spec.Template.Labels = map[string]string{ "label-key": "label-value", } - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // verify the ApplicationSet status conditions were set correctly Expect(ApplicationSetHasConditions("simple-list-generator-external", ExpectedConditions)). When(). SwitchToExternalNamespace(utils.ArgoCDExternalNamespace2). Then(). - Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppExternalNamespace2})). + Expect(ApplicationsExist([]v1alpha1.Application{expectedAppExternalNamespace2})). When(). SwitchToExternalNamespace(utils.ArgoCDExternalNamespace). Then(). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewMetadata})). When(). SwitchToExternalNamespace(utils.ArgoCDExternalNamespace2). Then(). - Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppExternalNamespace2})). + Expect(ApplicationsExist([]v1alpha1.Application{expectedAppExternalNamespace2})). When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedAppExternalNamespace2})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedAppExternalNamespace2})) } func TestSimpleListGenerator(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -354,21 +353,21 @@ func TestSimpleListGenerator(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, }, } - var expectedAppNewNamespace *argov1alpha1.Application - var expectedAppNewMetadata *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application + var expectedAppNewMetadata *v1alpha1.Application Given(t). // Create a ListGenerator-based ApplicationSet @@ -379,14 +378,14 @@ func TestSimpleListGenerator(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{cluster}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{url}}", Namespace: "guestbook", }, @@ -402,7 +401,7 @@ func TestSimpleListGenerator(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -412,7 +411,7 @@ func TestSimpleListGenerator(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template, and make sure it propagates to the apps When(). @@ -424,18 +423,18 @@ func TestSimpleListGenerator(t *testing.T) { Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Annotations = map[string]string{"annotation-key": "annotation-value"} appset.Spec.Template.Labels = map[string]string{"label-key": "label-value"} - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // verify the ApplicationSet status conditions were set correctly Expect(ApplicationSetHasConditions("simple-list-generator", ExpectedConditions)). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewMetadata})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewMetadata})) } func TestSimpleListGeneratorGoTemplate(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -445,21 +444,21 @@ func TestSimpleListGeneratorGoTemplate(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, }, } - var expectedAppNewNamespace *argov1alpha1.Application - var expectedAppNewMetadata *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application + var expectedAppNewMetadata *v1alpha1.Application Given(t). // Create a ListGenerator-based ApplicationSet @@ -471,14 +470,14 @@ func TestSimpleListGeneratorGoTemplate(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.cluster}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{.url}}", Namespace: "guestbook", }, @@ -494,7 +493,7 @@ func TestSimpleListGeneratorGoTemplate(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -504,7 +503,7 @@ func TestSimpleListGeneratorGoTemplate(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template, and make sure it propagates to the apps When(). @@ -516,18 +515,18 @@ func TestSimpleListGeneratorGoTemplate(t *testing.T) { Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Annotations = map[string]string{"annotation-key": "annotation-value"} appset.Spec.Template.Labels = map[string]string{"label-key": "label-value"} - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // verify the ApplicationSet status conditions were set correctly Expect(ApplicationSetHasConditions("simple-list-generator", ExpectedConditions)). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewMetadata})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewMetadata})) } func TestRenderHelmValuesObject(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -537,20 +536,20 @@ func TestRenderHelmValuesObject(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "helm-guestbook", - Helm: &argov1alpha1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValuesObject: &runtime.RawExtension{ // This will always be converted as yaml Raw: []byte(`{"some":{"string":"Hello world"}}`), }, }, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -567,19 +566,19 @@ func TestRenderHelmValuesObject(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.cluster}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "helm-guestbook", - Helm: &argov1alpha1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValuesObject: &runtime.RawExtension{ Raw: []byte(`{"some":{"string":"{{.test}}"}}`), }, }, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{.url}}", Namespace: "guestbook", }, @@ -595,14 +594,14 @@ func TestRenderHelmValuesObject(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedApp})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedApp})) } func TestTemplatePatch(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -615,19 +614,19 @@ func TestTemplatePatch(t *testing.T) { "annotation-some-key": "annotation-some-value", }, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, - SyncPolicy: &argov1alpha1.SyncPolicy{ - SyncOptions: argov1alpha1.SyncOptions{"CreateNamespace=true"}, + SyncPolicy: &v1alpha1.SyncPolicy{ + SyncOptions: v1alpha1.SyncOptions{"CreateNamespace=true"}, }, }, } @@ -652,8 +651,8 @@ func TestTemplatePatch(t *testing.T) { } ` - var expectedAppNewNamespace *argov1alpha1.Application - var expectedAppNewMetadata *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application + var expectedAppNewMetadata *v1alpha1.Application Given(t). // Create a ListGenerator-based ApplicationSet @@ -665,14 +664,14 @@ func TestTemplatePatch(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.cluster}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{.url}}", Namespace: "guestbook", }, @@ -696,7 +695,7 @@ func TestTemplatePatch(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -706,7 +705,7 @@ func TestTemplatePatch(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template, and make sure it propagates to the apps When(). @@ -718,18 +717,18 @@ func TestTemplatePatch(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Labels = map[string]string{"label-key": "label-value"} - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // verify the ApplicationSet status conditions were set correctly Expect(ApplicationSetHasConditions("patch-template", ExpectedConditions)). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewMetadata})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewMetadata})) } func TestUpdateHelmValuesObject(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -739,20 +738,20 @@ func TestUpdateHelmValuesObject(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "helm-guestbook", - Helm: &argov1alpha1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValuesObject: &runtime.RawExtension{ // This will always be converted as yaml Raw: []byte(`{"some":{"foo":"bar"}}`), }, }, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -769,19 +768,19 @@ func TestUpdateHelmValuesObject(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.cluster}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "helm-guestbook", - Helm: &argov1alpha1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ ValuesObject: &runtime.RawExtension{ Raw: []byte(`{"some":{"string":"{{.test}}"}}`), }, }, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{.url}}", Namespace: "guestbook", }, @@ -801,20 +800,20 @@ func TestUpdateHelmValuesObject(t *testing.T) { Expect(ApplicationSetHasConditions("test-values-object-patch", ExpectedConditions)). When(). // Update the app spec with some knew ValuesObject to force a merge - Update(func(as *argov1alpha1.ApplicationSet) { + Update(func(as *v1alpha1.ApplicationSet) { as.Spec.Template.Spec.Source.Helm.ValuesObject = &runtime.RawExtension{ Raw: []byte(`{"some":{"foo":"bar"}}`), } }). Then(). - Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). When(). // Delete the ApplicationSet, and verify it deletes the Applications - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedApp})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedApp})) } func TestSyncPolicyCreateUpdate(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: "Application", APIVersion: "argoproj.io/v1alpha1", @@ -824,21 +823,21 @@ func TestSyncPolicyCreateUpdate(t *testing.T) { Namespace: utils.ArgoCDNamespace, Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, }, } - var expectedAppNewNamespace *argov1alpha1.Application - var expectedAppNewMetadata *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application + var expectedAppNewMetadata *v1alpha1.Application Given(t). // Create a ListGenerator-based ApplicationSet @@ -853,14 +852,14 @@ func TestSyncPolicyCreateUpdate(t *testing.T) { Name: "{{.cluster}}-guestbook-sync-policy-create-update", Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{.url}}", Namespace: "guestbook", }, @@ -876,7 +875,7 @@ func TestSyncPolicyCreateUpdate(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -886,7 +885,7 @@ func TestSyncPolicyCreateUpdate(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template // Update as well the policy @@ -904,18 +903,18 @@ func TestSyncPolicyCreateUpdate(t *testing.T) { appset.Spec.Template.Labels = map[string]string{ "label-key": "label-value", } - applicationsSyncPolicy := argov1alpha1.ApplicationsSyncPolicyCreateUpdate - appset.Spec.SyncPolicy = &argov1alpha1.ApplicationSetSyncPolicy{ + applicationsSyncPolicy := v1alpha1.ApplicationsSyncPolicyCreateUpdate + appset.Spec.SyncPolicy = &v1alpha1.ApplicationSetSyncPolicy{ ApplicationsSync: &applicationsSyncPolicy, } - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // Update the list and remove element // As policy is create-update, app deletion must not be reflected When(). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Generators = []v1alpha1.ApplicationSetGenerator{} - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // verify the ApplicationSet status conditions were set correctly Expect(ApplicationSetHasConditions("sync-policy-create-update", ExpectedConditions)). @@ -924,11 +923,11 @@ func TestSyncPolicyCreateUpdate(t *testing.T) { // As policy is create-update, AppSet controller will remove all generated applications's ownerReferences on delete AppSet // So AppSet deletion will be reflected, but all the applications it generates will still exist When(). - Delete().Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})) + Delete().Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})) } func TestSyncPolicyCreateDelete(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: "Application", APIVersion: "argoproj.io/v1alpha1", @@ -938,20 +937,20 @@ func TestSyncPolicyCreateDelete(t *testing.T) { Namespace: utils.ArgoCDNamespace, Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, }, } - var expectedAppNewNamespace *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application Given(t). // Create a ListGenerator-based ApplicationSet @@ -963,14 +962,14 @@ func TestSyncPolicyCreateDelete(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.cluster}}-guestbook-sync-policy-create-delete"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{.url}}", Namespace: "guestbook", }, @@ -986,7 +985,7 @@ func TestSyncPolicyCreateDelete(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -996,7 +995,7 @@ func TestSyncPolicyCreateDelete(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template // Update as well the policy @@ -1005,29 +1004,29 @@ func TestSyncPolicyCreateDelete(t *testing.T) { Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Annotations = map[string]string{"annotation-key": "annotation-value"} appset.Spec.Template.Labels = map[string]string{"label-key": "label-value"} - applicationsSyncPolicy := argov1alpha1.ApplicationsSyncPolicyCreateDelete - appset.Spec.SyncPolicy = &argov1alpha1.ApplicationSetSyncPolicy{ + applicationsSyncPolicy := v1alpha1.ApplicationsSyncPolicyCreateDelete + appset.Spec.SyncPolicy = &v1alpha1.ApplicationSetSyncPolicy{ ApplicationsSync: &applicationsSyncPolicy, } - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the list and remove element // As policy is create-delete, app deletion must be reflected When(). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Generators = []v1alpha1.ApplicationSetGenerator{} - }).Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewNamespace})). // verify the ApplicationSet status conditions were set correctly Expect(ApplicationSetHasConditions("sync-policy-create-delete", ExpectedConditions)). // Delete the ApplicationSet When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewNamespace})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewNamespace})) } func TestSyncPolicyCreateOnly(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: "Application", APIVersion: "argoproj.io/v1alpha1", @@ -1037,20 +1036,20 @@ func TestSyncPolicyCreateOnly(t *testing.T) { Namespace: utils.ArgoCDNamespace, Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, }, } - var expectedAppNewNamespace *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application Given(t). // Create a ListGenerator-based ApplicationSet @@ -1065,14 +1064,14 @@ func TestSyncPolicyCreateOnly(t *testing.T) { Name: "{{.cluster}}-guestbook-sync-policy-create-only", Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{.url}}", Namespace: "guestbook", }, @@ -1088,7 +1087,7 @@ func TestSyncPolicyCreateOnly(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -1098,7 +1097,7 @@ func TestSyncPolicyCreateOnly(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template // Update as well the policy @@ -1107,18 +1106,18 @@ func TestSyncPolicyCreateOnly(t *testing.T) { Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Annotations = map[string]string{"annotation-key": "annotation-value"} appset.Spec.Template.Labels = map[string]string{"label-key": "label-value"} - applicationsSyncPolicy := argov1alpha1.ApplicationsSyncPolicyCreateOnly - appset.Spec.SyncPolicy = &argov1alpha1.ApplicationSetSyncPolicy{ + applicationsSyncPolicy := v1alpha1.ApplicationsSyncPolicyCreateOnly + appset.Spec.SyncPolicy = &v1alpha1.ApplicationSetSyncPolicy{ ApplicationsSync: &applicationsSyncPolicy, } - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the list and remove element // As policy is create-only, app deletion must not be reflected When(). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Generators = []v1alpha1.ApplicationSetGenerator{} - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // verify the ApplicationSet status conditions were set correctly Expect(ApplicationSetHasConditions("sync-policy-create-only", ExpectedConditions)). @@ -1127,12 +1126,12 @@ func TestSyncPolicyCreateOnly(t *testing.T) { // As policy is create-update, AppSet controller will remove all generated applications's ownerReferences on delete AppSet // So AppSet deletion will be reflected, but all the applications it generates will still exist When(). - Delete().Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})) + Delete().Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})) } func TestSimpleGitDirectoryGenerator(t *testing.T) { - generateExpectedApp := func(name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -1142,14 +1141,14 @@ func TestSimpleGitDirectoryGenerator(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: name, }, @@ -1157,14 +1156,14 @@ func TestSimpleGitDirectoryGenerator(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("kustomize-guestbook"), generateExpectedApp("helm-guestbook"), generateExpectedApp("ksonnet-guestbook"), } - var expectedAppsNewNamespace []argov1alpha1.Application - var expectedAppsNewMetadata []argov1alpha1.Application + var expectedAppsNewNamespace []v1alpha1.Application + var expectedAppsNewMetadata []v1alpha1.Application Given(t). When(). @@ -1176,14 +1175,14 @@ func TestSimpleGitDirectoryGenerator(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{path.basename}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "{{path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "{{path.basename}}", }, @@ -1241,8 +1240,8 @@ func TestSimpleGitDirectoryGenerator(t *testing.T) { } func TestSimpleGitDirectoryGeneratorGoTemplate(t *testing.T) { - generateExpectedApp := func(name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -1252,14 +1251,14 @@ func TestSimpleGitDirectoryGeneratorGoTemplate(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: name, }, @@ -1267,14 +1266,14 @@ func TestSimpleGitDirectoryGeneratorGoTemplate(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("kustomize-guestbook"), generateExpectedApp("helm-guestbook"), generateExpectedApp("ksonnet-guestbook"), } - var expectedAppsNewNamespace []argov1alpha1.Application - var expectedAppsNewMetadata []argov1alpha1.Application + var expectedAppsNewNamespace []v1alpha1.Application + var expectedAppsNewMetadata []v1alpha1.Application Given(t). When(). @@ -1287,14 +1286,14 @@ func TestSimpleGitDirectoryGeneratorGoTemplate(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.path.basename}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "{{.path.path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "{{.path.basename}}", }, @@ -1374,8 +1373,8 @@ func TestSimpleGitDirectoryGeneratorGPGEnabledUnsignedCommits(t *testing.T) { Reason: v1alpha1.ApplicationSetReasonApplicationParamsGenerationError, }, } - generateExpectedApp := func(name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -1385,14 +1384,14 @@ func TestSimpleGitDirectoryGeneratorGPGEnabledUnsignedCommits(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: name, }, @@ -1400,7 +1399,7 @@ func TestSimpleGitDirectoryGeneratorGPGEnabledUnsignedCommits(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("guestbook"), } project := "gpg" @@ -1416,14 +1415,14 @@ func TestSimpleGitDirectoryGeneratorGPGEnabledUnsignedCommits(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{path.basename}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: project, - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "{{path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "{{path.basename}}", }, @@ -1473,8 +1472,8 @@ func TestSimpleGitDirectoryGeneratorGPGEnabledWithoutKnownKeys(t *testing.T) { Reason: v1alpha1.ApplicationSetReasonApplicationParamsGenerationError, }, } - generateExpectedApp := func(name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -1484,14 +1483,14 @@ func TestSimpleGitDirectoryGeneratorGPGEnabledWithoutKnownKeys(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: name, }, @@ -1499,7 +1498,7 @@ func TestSimpleGitDirectoryGeneratorGPGEnabledWithoutKnownKeys(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("guestbook"), } @@ -1521,20 +1520,20 @@ func TestSimpleGitDirectoryGeneratorGPGEnabledWithoutKnownKeys(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{path.basename}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: project, - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "{{path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "{{path.basename}}", }, // Automatically create resources - SyncPolicy: &argov1alpha1.SyncPolicy{ - Automated: &argov1alpha1.SyncPolicyAutomated{}, + SyncPolicy: &v1alpha1.SyncPolicy{ + Automated: &v1alpha1.SyncPolicyAutomated{}, }, }, }, @@ -1560,8 +1559,8 @@ func TestSimpleGitDirectoryGeneratorGPGEnabledWithoutKnownKeys(t *testing.T) { } func TestSimpleGitFilesGenerator(t *testing.T) { - generateExpectedApp := func(name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -1571,14 +1570,14 @@ func TestSimpleGitFilesGenerator(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -1586,13 +1585,13 @@ func TestSimpleGitFilesGenerator(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("engineering-dev-guestbook"), generateExpectedApp("engineering-prod-guestbook"), } - var expectedAppsNewNamespace []argov1alpha1.Application - var expectedAppsNewMetadata []argov1alpha1.Application + var expectedAppsNewNamespace []v1alpha1.Application + var expectedAppsNewMetadata []v1alpha1.Application Given(t). When(). @@ -1604,14 +1603,14 @@ func TestSimpleGitFilesGenerator(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{cluster.name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -1692,8 +1691,8 @@ func TestSimpleGitFilesGeneratorGPGEnabledUnsignedCommits(t *testing.T) { }, } project := "gpg" - generateExpectedApp := func(name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -1703,14 +1702,14 @@ func TestSimpleGitFilesGeneratorGPGEnabledUnsignedCommits(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: project, - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -1718,7 +1717,7 @@ func TestSimpleGitFilesGeneratorGPGEnabledUnsignedCommits(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("engineering-dev-guestbook"), generateExpectedApp("engineering-prod-guestbook"), } @@ -1734,14 +1733,14 @@ func TestSimpleGitFilesGeneratorGPGEnabledUnsignedCommits(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{cluster.name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: project, - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -1791,8 +1790,8 @@ func TestSimpleGitFilesGeneratorGPGEnabledWithoutKnownKeys(t *testing.T) { }, } project := "gpg" - generateExpectedApp := func(name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -1802,14 +1801,14 @@ func TestSimpleGitFilesGeneratorGPGEnabledWithoutKnownKeys(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: project, - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -1819,7 +1818,7 @@ func TestSimpleGitFilesGeneratorGPGEnabledWithoutKnownKeys(t *testing.T) { str, _ := rand.RandString(1) - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("engineering-dev-guestbook"), generateExpectedApp("engineering-prod-guestbook"), } @@ -1838,14 +1837,14 @@ func TestSimpleGitFilesGeneratorGPGEnabledWithoutKnownKeys(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{cluster.name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: project, - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -1873,8 +1872,8 @@ func TestSimpleGitFilesGeneratorGPGEnabledWithoutKnownKeys(t *testing.T) { } func TestSimpleGitFilesGeneratorGoTemplate(t *testing.T) { - generateExpectedApp := func(name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -1884,14 +1883,14 @@ func TestSimpleGitFilesGeneratorGoTemplate(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -1899,13 +1898,13 @@ func TestSimpleGitFilesGeneratorGoTemplate(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("engineering-dev-guestbook"), generateExpectedApp("engineering-prod-guestbook"), } - var expectedAppsNewNamespace []argov1alpha1.Application - var expectedAppsNewMetadata []argov1alpha1.Application + var expectedAppsNewNamespace []v1alpha1.Application + var expectedAppsNewMetadata []v1alpha1.Application Given(t). When(). @@ -1918,14 +1917,14 @@ func TestSimpleGitFilesGeneratorGoTemplate(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.cluster.name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -1994,21 +1993,21 @@ func TestSimpleGitFilesPreserveResourcesOnDeletion(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{cluster.name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: utils.ApplicationsResourcesNamespace, }, // Automatically create resources - SyncPolicy: &argov1alpha1.SyncPolicy{ - Automated: &argov1alpha1.SyncPolicyAutomated{}, + SyncPolicy: &v1alpha1.SyncPolicy{ + Automated: &v1alpha1.SyncPolicyAutomated{}, }, }, }, @@ -2055,21 +2054,21 @@ func TestSimpleGitFilesPreserveResourcesOnDeletionGoTemplate(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.cluster.name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: utils.ApplicationsResourcesNamespace, }, // Automatically create resources - SyncPolicy: &argov1alpha1.SyncPolicy{ - Automated: &argov1alpha1.SyncPolicyAutomated{}, + SyncPolicy: &v1alpha1.SyncPolicy{ + Automated: &v1alpha1.SyncPolicyAutomated{}, }, }, }, @@ -2314,7 +2313,7 @@ func TestSimpleSCMProviderGenerator(t *testing.T) { ts.Start() defer ts.Close() - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -2324,14 +2323,14 @@ func TestSimpleSCMProviderGenerator(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "git@github.com:argoproj/argo-cd.git", TargetRevision: "master", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2350,14 +2349,14 @@ func TestSimpleSCMProviderGenerator(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{ repository }}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "{{ url }}", TargetRevision: "{{ branch }}", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2379,7 +2378,7 @@ func TestSimpleSCMProviderGenerator(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})) + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})) } func TestSimpleSCMProviderGeneratorGoTemplate(t *testing.T) { @@ -2389,7 +2388,7 @@ func TestSimpleSCMProviderGeneratorGoTemplate(t *testing.T) { ts.Start() defer ts.Close() - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -2399,14 +2398,14 @@ func TestSimpleSCMProviderGeneratorGoTemplate(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "git@github.com:argoproj/argo-cd.git", TargetRevision: "master", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2426,14 +2425,14 @@ func TestSimpleSCMProviderGeneratorGoTemplate(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{ .repository }}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "{{ .url }}", TargetRevision: "{{ .branch }}", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2455,11 +2454,11 @@ func TestSimpleSCMProviderGeneratorGoTemplate(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})) + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})) } func TestSCMProviderGeneratorSCMProviderNotAllowed(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -2469,14 +2468,14 @@ func TestSCMProviderGeneratorSCMProviderNotAllowed(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "git@github.com:argoproj/argo-cd.git", TargetRevision: "master", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2496,14 +2495,14 @@ func TestSCMProviderGeneratorSCMProviderNotAllowed(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{ .repository }}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "{{ .url }}", TargetRevision: "{{ .branch }}", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2525,7 +2524,7 @@ func TestSCMProviderGeneratorSCMProviderNotAllowed(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedApp})). And(func() { // app should be listed output, err := fixture.RunCli("appset", "get", "scm-provider-generator-scm-provider-not-allowed") @@ -2535,7 +2534,7 @@ func TestSCMProviderGeneratorSCMProviderNotAllowed(t *testing.T) { } func TestCustomApplicationFinalizers(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -2545,14 +2544,14 @@ func TestCustomApplicationFinalizers(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io/background"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2571,14 +2570,14 @@ func TestCustomApplicationFinalizers(t *testing.T) { Name: "{{cluster}}-guestbook", Finalizers: []string{"resources-finalizer.argocd.argoproj.io/background"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{url}}", Namespace: "guestbook", }, @@ -2594,15 +2593,15 @@ func TestCustomApplicationFinalizers(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedApp})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedApp})) } func TestCustomApplicationFinalizersGoTemplate(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -2612,14 +2611,14 @@ func TestCustomApplicationFinalizersGoTemplate(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io/background"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2639,14 +2638,14 @@ func TestCustomApplicationFinalizersGoTemplate(t *testing.T) { Name: "{{.cluster}}-guestbook", Finalizers: []string{"resources-finalizer.argocd.argoproj.io/background"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "{{.url}}", Namespace: "guestbook", }, @@ -2662,11 +2661,11 @@ func TestCustomApplicationFinalizersGoTemplate(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedApp})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedApp})) } func githubPullMockHandler(t *testing.T) func(http.ResponseWriter, *http.Request) { @@ -2716,7 +2715,7 @@ func TestSimpleSCMProviderGeneratorTokenRefStrictOk(t *testing.T) { ts.Start() defer ts.Close() - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -2726,14 +2725,14 @@ func TestSimpleSCMProviderGeneratorTokenRefStrictOk(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "git@github.com:argoproj/argo-cd.git", TargetRevision: "master", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2768,14 +2767,14 @@ func TestSimpleSCMProviderGeneratorTokenRefStrictOk(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{ repository }}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "{{ url }}", TargetRevision: "{{ branch }}", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2787,7 +2786,7 @@ func TestSimpleSCMProviderGeneratorTokenRefStrictOk(t *testing.T) { Github: &v1alpha1.SCMProviderGeneratorGithub{ Organization: "argoproj", API: ts.URL, - TokenRef: &argov1alpha1.SecretRef{ + TokenRef: &v1alpha1.SecretRef{ SecretName: secretName, Key: "hello", }, @@ -2801,7 +2800,7 @@ func TestSimpleSCMProviderGeneratorTokenRefStrictOk(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). When().And(func() { err := utils.GetE2EFixtureK8sClient().KubeClientset.CoreV1().Secrets(fixture.TestNamespace()).Delete(context.Background(), secretName, metav1.DeleteOptions{}) assert.NoError(t, err) @@ -2818,7 +2817,7 @@ func TestSimpleSCMProviderGeneratorTokenRefStrictKo(t *testing.T) { ts.Start() defer ts.Close() - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -2831,14 +2830,14 @@ func TestSimpleSCMProviderGeneratorTokenRefStrictKo(t *testing.T) { common.LabelKeyAppInstance: "simple-scm-provider-generator-strict-ko", }, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "git@github.com:argoproj/argo-cd.git", TargetRevision: "master", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2874,14 +2873,14 @@ func TestSimpleSCMProviderGeneratorTokenRefStrictKo(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{ repository }}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "{{ url }}", TargetRevision: "{{ branch }}", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, @@ -2893,7 +2892,7 @@ func TestSimpleSCMProviderGeneratorTokenRefStrictKo(t *testing.T) { Github: &v1alpha1.SCMProviderGeneratorGithub{ Organization: "argoproj", API: ts.URL, - TokenRef: &argov1alpha1.SecretRef{ + TokenRef: &v1alpha1.SecretRef{ SecretName: secretName, Key: "hello", }, @@ -2907,7 +2906,7 @@ func TestSimpleSCMProviderGeneratorTokenRefStrictKo(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedApp})). When(). And(func() { // app should be listed @@ -2927,7 +2926,7 @@ func TestSimplePullRequestGenerator(t *testing.T) { ts.Start() defer ts.Close() - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -2937,17 +2936,17 @@ func TestSimplePullRequestGenerator(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "git@github.com:applicationset-test-org/argocd-example-apps.git", TargetRevision: "824a5c987fdfb2b0629e9dbf5f31636c69ba4772", Path: "kustomize-guestbook", - Kustomize: &argov1alpha1.ApplicationSourceKustomize{ + Kustomize: &v1alpha1.ApplicationSourceKustomize{ NamePrefix: "guestbook-1", }, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook-pull-request", }, @@ -2963,17 +2962,17 @@ func TestSimplePullRequestGenerator(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "guestbook-{{ number }}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "git@github.com:applicationset-test-org/argocd-example-apps.git", TargetRevision: "{{ head_sha }}", Path: "kustomize-guestbook", - Kustomize: &argov1alpha1.ApplicationSourceKustomize{ + Kustomize: &v1alpha1.ApplicationSourceKustomize{ NamePrefix: "guestbook-{{ number }}", }, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook-{{ branch }}", }, @@ -2994,7 +2993,7 @@ func TestSimplePullRequestGenerator(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})) + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})) } func TestSimplePullRequestGeneratorGoTemplate(t *testing.T) { @@ -3005,7 +3004,7 @@ func TestSimplePullRequestGeneratorGoTemplate(t *testing.T) { ts.Start() defer ts.Close() - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -3016,17 +3015,17 @@ func TestSimplePullRequestGeneratorGoTemplate(t *testing.T) { Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, Labels: map[string]string{"app": "preview"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "git@github.com:applicationset-test-org/argocd-example-apps.git", TargetRevision: "824a5c987fdfb2b0629e9dbf5f31636c69ba4772", Path: "kustomize-guestbook", - Kustomize: &argov1alpha1.ApplicationSourceKustomize{ + Kustomize: &v1alpha1.ApplicationSourceKustomize{ NamePrefix: "guestbook-1", }, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook-pull-request", }, @@ -3046,17 +3045,17 @@ func TestSimplePullRequestGeneratorGoTemplate(t *testing.T) { Name: "guestbook-{{ .number }}", Labels: map[string]string{"app": "{{index .labels 0}}"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "git@github.com:applicationset-test-org/argocd-example-apps.git", TargetRevision: "{{ .head_sha }}", Path: "kustomize-guestbook", - Kustomize: &argov1alpha1.ApplicationSourceKustomize{ + Kustomize: &v1alpha1.ApplicationSourceKustomize{ NamePrefix: "guestbook-{{ .number }}", }, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook-{{ .branch }}", }, @@ -3077,11 +3076,11 @@ func TestSimplePullRequestGeneratorGoTemplate(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})) + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})) } func TestPullRequestGeneratorNotAllowedSCMProvider(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -3094,17 +3093,17 @@ func TestPullRequestGeneratorNotAllowedSCMProvider(t *testing.T) { "app": "preview", }, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "git@github.com:applicationset-test-org/argocd-example-apps.git", TargetRevision: "824a5c987fdfb2b0629e9dbf5f31636c69ba4772", Path: "kustomize-guestbook", - Kustomize: &argov1alpha1.ApplicationSourceKustomize{ + Kustomize: &v1alpha1.ApplicationSourceKustomize{ NamePrefix: "guestbook-1", }, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook-pull-request", }, @@ -3124,17 +3123,17 @@ func TestPullRequestGeneratorNotAllowedSCMProvider(t *testing.T) { Name: "guestbook-{{ .number }}", Labels: map[string]string{"app": "{{index .labels 0}}"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "git@github.com:applicationset-test-org/argocd-example-apps.git", TargetRevision: "{{ .head_sha }}", Path: "kustomize-guestbook", - Kustomize: &argov1alpha1.ApplicationSourceKustomize{ + Kustomize: &v1alpha1.ApplicationSourceKustomize{ NamePrefix: "guestbook-{{ .number }}", }, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook-{{ .branch }}", }, @@ -3155,7 +3154,7 @@ func TestPullRequestGeneratorNotAllowedSCMProvider(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedApp})). And(func() { // app should be listed output, err := fixture.RunCli("appset", "get", "pull-request-generator-not-allowed-scm") @@ -3166,8 +3165,8 @@ func TestPullRequestGeneratorNotAllowedSCMProvider(t *testing.T) { func TestGitGeneratorPrivateRepo(t *testing.T) { FailOnErr(fixture.RunCli("repo", "add", fixture.RepoURL(fixture.RepoURLTypeHTTPS), "--username", fixture.GitUsername, "--password", fixture.GitPassword, "--insecure-skip-server-verification")) - generateExpectedApp := func(name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -3177,14 +3176,14 @@ func TestGitGeneratorPrivateRepo(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: fixture.RepoURL(fixture.RepoURLTypeHTTPS), TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: name, }, @@ -3192,11 +3191,11 @@ func TestGitGeneratorPrivateRepo(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("https-kustomize-base"), } - var expectedAppsNewNamespace []argov1alpha1.Application + var expectedAppsNewNamespace []v1alpha1.Application Given(t). When(). @@ -3208,14 +3207,14 @@ func TestGitGeneratorPrivateRepo(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{path.basename}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: fixture.RepoURL(fixture.RepoURLTypeHTTPS), TargetRevision: "HEAD", Path: "{{path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "{{path.basename}}", }, @@ -3242,8 +3241,8 @@ func TestGitGeneratorPrivateRepo(t *testing.T) { func TestGitGeneratorPrivateRepoGoTemplate(t *testing.T) { FailOnErr(fixture.RunCli("repo", "add", fixture.RepoURL(fixture.RepoURLTypeHTTPS), "--username", fixture.GitUsername, "--password", fixture.GitPassword, "--insecure-skip-server-verification")) - generateExpectedApp := func(name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -3253,14 +3252,14 @@ func TestGitGeneratorPrivateRepoGoTemplate(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: fixture.RepoURL(fixture.RepoURLTypeHTTPS), TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: name, }, @@ -3268,11 +3267,11 @@ func TestGitGeneratorPrivateRepoGoTemplate(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("https-kustomize-base"), } - var expectedAppsNewNamespace []argov1alpha1.Application + var expectedAppsNewNamespace []v1alpha1.Application Given(t). When(). @@ -3285,14 +3284,14 @@ func TestGitGeneratorPrivateRepoGoTemplate(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{.path.basename}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: fixture.RepoURL(fixture.RepoURLTypeHTTPS), TargetRevision: "HEAD", Path: "{{.path.path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "{{.path.basename}}", }, diff --git a/test/e2e/cluster_generator_test.go b/test/e2e/cluster_generator_test.go index 558d5c9c84ef5..959fd67b0a966 100644 --- a/test/e2e/cluster_generator_test.go +++ b/test/e2e/cluster_generator_test.go @@ -4,22 +4,19 @@ import ( "testing" "time" - "github.com/argoproj/argo-cd/v2/test/e2e/fixture" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "github.com/argoproj/argo-cd/v2/pkg/apis/application" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" + "github.com/argoproj/argo-cd/v2/test/e2e/fixture" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/applicationsets" "github.com/argoproj/argo-cd/v2/test/e2e/fixture/applicationsets/utils" - - "github.com/argoproj/argo-cd/v2/pkg/apis/application" ) func TestSimpleClusterGeneratorExternalNamespace(t *testing.T) { externalNamespace := string(utils.ArgoCDExternalNamespace) - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: "Application", APIVersion: "argoproj.io/v1alpha1", @@ -29,22 +26,22 @@ func TestSimpleClusterGeneratorExternalNamespace(t *testing.T) { Namespace: externalNamespace, Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "cluster1", Namespace: "guestbook", }, }, } - var expectedAppNewNamespace *argov1alpha1.Application - var expectedAppNewMetadata *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application + var expectedAppNewMetadata *v1alpha1.Application Given(t). // Create a ClusterGenerator-based ApplicationSet @@ -59,14 +56,14 @@ func TestSimpleClusterGeneratorExternalNamespace(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{name}}", // Server: "{{server}}", Namespace: "guestbook", @@ -85,7 +82,7 @@ func TestSimpleClusterGeneratorExternalNamespace(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -95,7 +92,7 @@ func TestSimpleClusterGeneratorExternalNamespace(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template, and make sure it propagates to the apps When(). @@ -111,15 +108,15 @@ func TestSimpleClusterGeneratorExternalNamespace(t *testing.T) { appset.Spec.Template.Labels = map[string]string{ "label-key": "label-value", } - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewNamespace})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewNamespace})) } func TestSimpleClusterGenerator(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -129,22 +126,22 @@ func TestSimpleClusterGenerator(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "cluster1", Namespace: "guestbook", }, }, } - var expectedAppNewNamespace *argov1alpha1.Application - var expectedAppNewMetadata *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application + var expectedAppNewMetadata *v1alpha1.Application Given(t). // Create a ClusterGenerator-based ApplicationSet @@ -157,14 +154,14 @@ func TestSimpleClusterGenerator(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{name}}", // Server: "{{server}}", Namespace: "guestbook", @@ -183,7 +180,7 @@ func TestSimpleClusterGenerator(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -193,7 +190,7 @@ func TestSimpleClusterGenerator(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template, and make sure it propagates to the apps When(). @@ -205,15 +202,15 @@ func TestSimpleClusterGenerator(t *testing.T) { Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Annotations = map[string]string{"annotation-key": "annotation-value"} appset.Spec.Template.Labels = map[string]string{"label-key": "label-value"} - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewNamespace})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewNamespace})) } func TestClusterGeneratorWithLocalCluster(t *testing.T) { - expectedAppTemplate := argov1alpha1.Application{ + expectedAppTemplate := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -223,9 +220,9 @@ func TestClusterGeneratorWithLocalCluster(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", @@ -236,27 +233,27 @@ func TestClusterGeneratorWithLocalCluster(t *testing.T) { tests := []struct { name string - appsetDestination argov1alpha1.ApplicationDestination - appDestination argov1alpha1.ApplicationDestination + appsetDestination v1alpha1.ApplicationDestination + appDestination v1alpha1.ApplicationDestination }{ { name: "specify local cluster by server field", - appDestination: argov1alpha1.ApplicationDestination{ + appDestination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "guestbook", }, - appsetDestination: argov1alpha1.ApplicationDestination{ + appsetDestination: v1alpha1.ApplicationDestination{ Server: "{{server}}", Namespace: "guestbook", }, }, { name: "specify local cluster by name field", - appDestination: argov1alpha1.ApplicationDestination{ + appDestination: v1alpha1.ApplicationDestination{ Name: "in-cluster", Namespace: "guestbook", }, - appsetDestination: argov1alpha1.ApplicationDestination{ + appsetDestination: v1alpha1.ApplicationDestination{ Name: "{{name}}", Namespace: "guestbook", }, @@ -265,8 +262,8 @@ func TestClusterGeneratorWithLocalCluster(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - var expectedAppNewNamespace *argov1alpha1.Application - var expectedAppNewMetadata *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application + var expectedAppNewMetadata *v1alpha1.Application // Create the expected application from the template, and copy in the destination from the test case expectedApp := *expectedAppTemplate.DeepCopy() @@ -282,9 +279,9 @@ func TestClusterGeneratorWithLocalCluster(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", @@ -298,7 +295,7 @@ func TestClusterGeneratorWithLocalCluster(t *testing.T) { }, }, }, - }).Then().ExpectWithDuration(ApplicationsExist([]argov1alpha1.Application{expectedApp}), 8*time.Minute). + }).Then().ExpectWithDuration(ApplicationsExist([]v1alpha1.Application{expectedApp}), 8*time.Minute). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -308,7 +305,7 @@ func TestClusterGeneratorWithLocalCluster(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template, and make sure it propagates to the apps When(). @@ -320,17 +317,17 @@ func TestClusterGeneratorWithLocalCluster(t *testing.T) { Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Annotations = map[string]string{"annotation-key": "annotation-value"} appset.Spec.Template.Labels = map[string]string{"label-key": "label-value"} - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewNamespace})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewNamespace})) }) } } func TestSimpleClusterGeneratorAddingCluster(t *testing.T) { - expectedAppTemplate := argov1alpha1.Application{ + expectedAppTemplate := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -340,14 +337,14 @@ func TestSimpleClusterGeneratorAddingCluster(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{name}}", Namespace: "guestbook", }, @@ -373,14 +370,14 @@ func TestSimpleClusterGeneratorAddingCluster(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{name}}", // Server: "{{server}}", Namespace: "guestbook", @@ -399,20 +396,20 @@ func TestSimpleClusterGeneratorAddingCluster(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster1})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster1})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). CreateClusterSecret("my-secret2", "cluster2", "https://kubernetes.default.svc"). - Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster1, expectedAppCluster2})). + Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster1, expectedAppCluster2})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedAppCluster1, expectedAppCluster2})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedAppCluster1, expectedAppCluster2})) } func TestSimpleClusterGeneratorDeletingCluster(t *testing.T) { - expectedAppTemplate := argov1alpha1.Application{ + expectedAppTemplate := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -422,14 +419,14 @@ func TestSimpleClusterGeneratorDeletingCluster(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{name}}", Namespace: "guestbook", }, @@ -456,14 +453,14 @@ func TestSimpleClusterGeneratorDeletingCluster(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{name}}", // Server: "{{server}}", Namespace: "guestbook", @@ -482,21 +479,21 @@ func TestSimpleClusterGeneratorDeletingCluster(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster1, expectedAppCluster2})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster1, expectedAppCluster2})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). DeleteClusterSecret("my-secret2"). - Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster1})). - Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedAppCluster2})). + Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster1})). + Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedAppCluster2})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedAppCluster1})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedAppCluster1})) } func TestClusterGeneratorWithFlatListMode(t *testing.T) { - expectedAppTemplate := argov1alpha1.Application{ + expectedAppTemplate := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -506,32 +503,32 @@ func TestClusterGeneratorWithFlatListMode(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "helm-guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "cluster1", Namespace: fixture.TestNamespace(), }, - SyncPolicy: &argov1alpha1.SyncPolicy{ - Automated: &argov1alpha1.SyncPolicyAutomated{}, + SyncPolicy: &v1alpha1.SyncPolicy{ + Automated: &v1alpha1.SyncPolicyAutomated{}, }, }, } expectedAppCluster1 := *expectedAppTemplate.DeepCopy() - expectedAppCluster1.Spec.Source.Helm = &argov1alpha1.ApplicationSourceHelm{ + expectedAppCluster1.Spec.Source.Helm = &v1alpha1.ApplicationSourceHelm{ Values: `clusters: - name: cluster1 `, } expectedAppCluster2 := *expectedAppTemplate.DeepCopy() - expectedAppCluster2.Spec.Source.Helm = &argov1alpha1.ApplicationSourceHelm{ + expectedAppCluster2.Spec.Source.Helm = &v1alpha1.ApplicationSourceHelm{ Values: `clusters: - name: cluster1 - name: cluster2 @@ -550,13 +547,13 @@ func TestClusterGeneratorWithFlatListMode(t *testing.T) { GoTemplate: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "flat-clusters"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "helm-guestbook", - Helm: &argov1alpha1.ApplicationSourceHelm{ + Helm: &v1alpha1.ApplicationSourceHelm{ Values: `clusters: {{- range .clusters }} - name: {{ .name }} @@ -564,12 +561,12 @@ func TestClusterGeneratorWithFlatListMode(t *testing.T) { `, }, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "cluster1", Namespace: fixture.TestNamespace(), }, - SyncPolicy: &argov1alpha1.SyncPolicy{ - Automated: &argov1alpha1.SyncPolicyAutomated{}, + SyncPolicy: &v1alpha1.SyncPolicy{ + Automated: &v1alpha1.SyncPolicyAutomated{}, }, }, }, @@ -586,15 +583,15 @@ func TestClusterGeneratorWithFlatListMode(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster1})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster1})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). CreateClusterSecret("my-secret2", "cluster2", "https://kubernetes.default.svc"). Then(). - Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster2})). + Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster2})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedAppCluster2})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedAppCluster2})) } diff --git a/test/e2e/cluster_test.go b/test/e2e/cluster_test.go index c0beb74c88312..d65bd1c4649bc 100644 --- a/test/e2e/cluster_test.go +++ b/test/e2e/cluster_test.go @@ -11,7 +11,6 @@ import ( . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/test/e2e/fixture" - . "github.com/argoproj/argo-cd/v2/test/e2e/fixture" accountFixture "github.com/argoproj/argo-cd/v2/test/e2e/fixture/account" "github.com/argoproj/argo-cd/v2/test/e2e/fixture/app" clusterFixture "github.com/argoproj/argo-cd/v2/test/e2e/fixture/cluster" @@ -19,16 +18,16 @@ import ( ) func TestClusterList(t *testing.T) { - SkipIfAlreadyRun(t) - defer RecordTestRun(t) + fixture.SkipIfAlreadyRun(t) + defer fixture.RecordTestRun(t) last := "" expected := fmt.Sprintf(`SERVER NAME VERSION STATUS MESSAGE PROJECT -https://kubernetes.default.svc in-cluster %v Successful `, GetVersions().ServerVersion) +https://kubernetes.default.svc in-cluster %v Successful `, fixture.GetVersions().ServerVersion) clusterFixture. Given(t). - Project(ProjectName) + Project(fixture.ProjectName) // We need an application targeting the cluster, otherwise the test will // fail if run isolated. @@ -59,7 +58,7 @@ https://kubernetes.default.svc in-cluster %v Successful `, GetVe func TestClusterAdd(t *testing.T) { clusterFixture. Given(t). - Project(ProjectName). + Project(fixture.ProjectName). Upsert(true). Server(KubernetesInternalAPIServerAddr). When(). @@ -68,7 +67,7 @@ func TestClusterAdd(t *testing.T) { Then(). AndCLIOutput(func(output string, err error) { assert.Equal(t, fmt.Sprintf(`SERVER NAME VERSION STATUS MESSAGE PROJECT -https://kubernetes.default.svc test-cluster-add %v Successful %s`, GetVersions().ServerVersion, ProjectName), output) +https://kubernetes.default.svc test-cluster-add %v Successful %s`, fixture.GetVersions().ServerVersion, fixture.ProjectName), output) }) } @@ -82,7 +81,7 @@ func TestClusterAddPermissionDenied(t *testing.T) { clusterFixture. GivenWithSameState(t). - Project(ProjectName). + Project(fixture.ProjectName). Upsert(true). Server(KubernetesInternalAPIServerAddr). When(). @@ -104,18 +103,18 @@ func TestClusterAddAllowed(t *testing.T) { { Resource: "clusters", Action: "create", - Scope: ProjectName + "/*", + Scope: fixture.ProjectName + "/*", }, { Resource: "clusters", Action: "get", - Scope: ProjectName + "/*", + Scope: fixture.ProjectName + "/*", }, }, "org-admin") clusterFixture. GivenWithSameState(t). - Project(ProjectName). + Project(fixture.ProjectName). Upsert(true). Server(KubernetesInternalAPIServerAddr). When(). @@ -124,7 +123,7 @@ func TestClusterAddAllowed(t *testing.T) { Then(). AndCLIOutput(func(output string, err error) { assert.Equal(t, fmt.Sprintf(`SERVER NAME VERSION STATUS MESSAGE PROJECT -https://kubernetes.default.svc test-cluster-add-allowed %v Successful argo-project`, GetVersions().ServerVersion), output) +https://kubernetes.default.svc test-cluster-add-allowed %v Successful argo-project`, fixture.GetVersions().ServerVersion), output) }) } @@ -138,13 +137,13 @@ func TestClusterListDenied(t *testing.T) { { Resource: "clusters", Action: "create", - Scope: ProjectName + "/*", + Scope: fixture.ProjectName + "/*", }, }, "org-admin") clusterFixture. GivenWithSameState(t). - Project(ProjectName). + Project(fixture.ProjectName). Upsert(true). Server(KubernetesInternalAPIServerAddr). When(). @@ -157,11 +156,11 @@ func TestClusterListDenied(t *testing.T) { } func TestClusterSet(t *testing.T) { - EnsureCleanState(t) - defer RecordTestRun(t) + fixture.EnsureCleanState(t) + defer fixture.RecordTestRun(t) clusterFixture. GivenWithSameState(t). - Project(ProjectName). + Project(fixture.ProjectName). Name("in-cluster"). Namespaces([]string{"namespace-edit-1", "namespace-edit-2"}). Server(KubernetesInternalAPIServerAddr). @@ -176,14 +175,14 @@ func TestClusterSet(t *testing.T) { } func TestClusterGet(t *testing.T) { - SkipIfAlreadyRun(t) - EnsureCleanState(t) - defer RecordTestRun(t) - output := FailOnErr(RunCli("cluster", "get", "https://kubernetes.default.svc")).(string) + fixture.SkipIfAlreadyRun(t) + fixture.EnsureCleanState(t) + defer fixture.RecordTestRun(t) + output := FailOnErr(fixture.RunCli("cluster", "get", "https://kubernetes.default.svc")).(string) assert.Contains(t, output, "name: in-cluster") assert.Contains(t, output, "server: https://kubernetes.default.svc") - assert.Contains(t, output, fmt.Sprintf(`serverVersion: "%v"`, GetVersions().ServerVersion)) + assert.Contains(t, output, fmt.Sprintf(`serverVersion: "%v"`, fixture.GetVersions().ServerVersion)) assert.Contains(t, output, `config: tlsClientConfig: insecure: false`) @@ -192,34 +191,34 @@ func TestClusterGet(t *testing.T) { } func TestClusterNameInRestAPI(t *testing.T) { - EnsureCleanState(t) + fixture.EnsureCleanState(t) var cluster Cluster - err := DoHttpJsonRequest("GET", "/api/v1/clusters/in-cluster?id.type=name", &cluster) + err := fixture.DoHttpJsonRequest("GET", "/api/v1/clusters/in-cluster?id.type=name", &cluster) require.NoError(t, err) assert.Equal(t, "in-cluster", cluster.Name) assert.Contains(t, cluster.Server, "https://kubernetes.default.svc") - err = DoHttpJsonRequest("PUT", + err = fixture.DoHttpJsonRequest("PUT", "/api/v1/clusters/in-cluster?id.type=name&updatedFields=labels", &cluster, []byte(`{"labels":{"test": "val"}}`)...) require.NoError(t, err) assert.Equal(t, map[string]string{"test": "val"}, cluster.Labels) } func TestClusterURLInRestAPI(t *testing.T) { - EnsureCleanState(t) + fixture.EnsureCleanState(t) clusterURL := url.QueryEscape(KubernetesInternalAPIServerAddr) var cluster Cluster - err := DoHttpJsonRequest("GET", "/api/v1/clusters/"+clusterURL, &cluster) + err := fixture.DoHttpJsonRequest("GET", "/api/v1/clusters/"+clusterURL, &cluster) require.NoError(t, err) assert.Equal(t, "in-cluster", cluster.Name) assert.Contains(t, cluster.Server, "https://kubernetes.default.svc") - err = DoHttpJsonRequest("PUT", + err = fixture.DoHttpJsonRequest("PUT", fmt.Sprintf("/api/v1/clusters/%s?&updatedFields=labels", clusterURL), &cluster, []byte(`{"labels":{"test": "val"}}`)...) require.NoError(t, err) assert.Equal(t, map[string]string{"test": "val"}, cluster.Labels) @@ -235,19 +234,19 @@ func TestClusterDeleteDenied(t *testing.T) { { Resource: "clusters", Action: "create", - Scope: ProjectName + "/*", + Scope: fixture.ProjectName + "/*", }, { Resource: "clusters", Action: "get", - Scope: ProjectName + "/*", + Scope: fixture.ProjectName + "/*", }, }, "org-admin") // Attempt to remove cluster creds by name clusterFixture. GivenWithSameState(t). - Project(ProjectName). + Project(fixture.ProjectName). Upsert(true). Server(KubernetesInternalAPIServerAddr). When(). @@ -261,7 +260,7 @@ func TestClusterDeleteDenied(t *testing.T) { // Attempt to remove cluster creds by server clusterFixture. GivenWithSameState(t). - Project(ProjectName). + Project(fixture.ProjectName). Upsert(true). Server(KubernetesInternalAPIServerAddr). When(). @@ -283,24 +282,24 @@ func TestClusterDelete(t *testing.T) { { Resource: "clusters", Action: "create", - Scope: ProjectName + "/*", + Scope: fixture.ProjectName + "/*", }, { Resource: "clusters", Action: "get", - Scope: ProjectName + "/*", + Scope: fixture.ProjectName + "/*", }, { Resource: "clusters", Action: "delete", - Scope: ProjectName + "/*", + Scope: fixture.ProjectName + "/*", }, }, "org-admin") clstAction := clusterFixture. GivenWithSameState(t). Name("default"). - Project(ProjectName). + Project(fixture.ProjectName). Upsert(true). Server(KubernetesInternalAPIServerAddr). When(). diff --git a/test/e2e/clusterdecisiongenerator_e2e_test.go b/test/e2e/clusterdecisiongenerator_e2e_test.go index ee30ff6118153..83665553a42d7 100644 --- a/test/e2e/clusterdecisiongenerator_e2e_test.go +++ b/test/e2e/clusterdecisiongenerator_e2e_test.go @@ -8,7 +8,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/applicationsets" "github.com/argoproj/argo-cd/v2/test/e2e/fixture/applicationsets/utils" @@ -20,7 +19,7 @@ var tenSec = int64(10) func TestSimpleClusterDecisionResourceGeneratorExternalNamespace(t *testing.T) { externalNamespace := string(utils.ArgoCDExternalNamespace) - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: "Application", APIVersion: "argoproj.io/v1alpha1", @@ -30,22 +29,22 @@ func TestSimpleClusterDecisionResourceGeneratorExternalNamespace(t *testing.T) { Namespace: externalNamespace, Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "cluster1", Namespace: "guestbook", }, }, } - var expectedAppNewNamespace *argov1alpha1.Application - var expectedAppNewMetadata *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application + var expectedAppNewMetadata *v1alpha1.Application clusterList := []any{ map[string]any{ @@ -71,14 +70,14 @@ func TestSimpleClusterDecisionResourceGeneratorExternalNamespace(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{clusterName}}", // Server: "{{server}}", Namespace: "guestbook", @@ -94,7 +93,7 @@ func TestSimpleClusterDecisionResourceGeneratorExternalNamespace(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -104,7 +103,7 @@ func TestSimpleClusterDecisionResourceGeneratorExternalNamespace(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template, and make sure it propagates to the apps When(). @@ -120,15 +119,15 @@ func TestSimpleClusterDecisionResourceGeneratorExternalNamespace(t *testing.T) { appset.Spec.Template.Labels = map[string]string{ "label-key": "label-value", } - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewNamespace})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewNamespace})) } func TestSimpleClusterDecisionResourceGenerator(t *testing.T) { - expectedApp := argov1alpha1.Application{ + expectedApp := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -138,22 +137,22 @@ func TestSimpleClusterDecisionResourceGenerator(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "cluster1", Namespace: "guestbook", }, }, } - var expectedAppNewNamespace *argov1alpha1.Application - var expectedAppNewMetadata *argov1alpha1.Application + var expectedAppNewNamespace *v1alpha1.Application + var expectedAppNewMetadata *v1alpha1.Application clusterList := []any{ map[string]any{ @@ -177,14 +176,14 @@ func TestSimpleClusterDecisionResourceGenerator(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{clusterName}}", // Server: "{{server}}", Namespace: "guestbook", @@ -200,7 +199,7 @@ func TestSimpleClusterDecisionResourceGenerator(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedApp})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedApp})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). @@ -210,7 +209,7 @@ func TestSimpleClusterDecisionResourceGenerator(t *testing.T) { }). Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Spec.Destination.Namespace = "guestbook2" - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewNamespace})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewNamespace})). // Update the metadata fields in the appset template, and make sure it propagates to the apps When(). @@ -222,15 +221,15 @@ func TestSimpleClusterDecisionResourceGenerator(t *testing.T) { Update(func(appset *v1alpha1.ApplicationSet) { appset.Spec.Template.Annotations = map[string]string{"annotation-key": "annotation-value"} appset.Spec.Template.Labels = map[string]string{"label-key": "label-value"} - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{*expectedAppNewMetadata})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{*expectedAppNewMetadata})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{*expectedAppNewNamespace})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{*expectedAppNewNamespace})) } func TestSimpleClusterDecisionResourceGeneratorAddingCluster(t *testing.T) { - expectedAppTemplate := argov1alpha1.Application{ + expectedAppTemplate := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -240,14 +239,14 @@ func TestSimpleClusterDecisionResourceGeneratorAddingCluster(t *testing.T) { Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{clusterName}}", Namespace: "guestbook", }, @@ -288,14 +287,14 @@ func TestSimpleClusterDecisionResourceGeneratorAddingCluster(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{clusterName}}", // Server: "{{server}}", Namespace: "guestbook", @@ -312,20 +311,20 @@ func TestSimpleClusterDecisionResourceGeneratorAddingCluster(t *testing.T) { }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster1})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster1})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). CreateClusterSecret("my-secret2", "cluster2", "https://kubernetes.default.svc"). - Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster1, expectedAppCluster2})). + Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster1, expectedAppCluster2})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedAppCluster1, expectedAppCluster2})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedAppCluster1, expectedAppCluster2})) } func TestSimpleClusterDecisionResourceGeneratorDeletingClusterSecret(t *testing.T) { - expectedAppTemplate := argov1alpha1.Application{ + expectedAppTemplate := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -335,14 +334,14 @@ func TestSimpleClusterDecisionResourceGeneratorDeletingClusterSecret(t *testing. Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{name}}", Namespace: "guestbook", }, @@ -384,14 +383,14 @@ func TestSimpleClusterDecisionResourceGeneratorDeletingClusterSecret(t *testing. Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{clusterName}}", // Server: "{{server}}", Namespace: "guestbook", @@ -408,21 +407,21 @@ func TestSimpleClusterDecisionResourceGeneratorDeletingClusterSecret(t *testing. }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster1, expectedAppCluster2})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster1, expectedAppCluster2})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). DeleteClusterSecret("my-secret2"). - Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster1})). - Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedAppCluster2})). + Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster1})). + Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedAppCluster2})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedAppCluster1})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedAppCluster1})) } func TestSimpleClusterDecisionResourceGeneratorDeletingClusterFromResource(t *testing.T) { - expectedAppTemplate := argov1alpha1.Application{ + expectedAppTemplate := v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -432,14 +431,14 @@ func TestSimpleClusterDecisionResourceGeneratorDeletingClusterFromResource(t *te Namespace: fixture.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{name}}", Namespace: "guestbook", }, @@ -488,14 +487,14 @@ func TestSimpleClusterDecisionResourceGeneratorDeletingClusterFromResource(t *te Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-guestbook"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "guestbook", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{clusterName}}", // Server: "{{server}}", Namespace: "guestbook", @@ -512,15 +511,15 @@ func TestSimpleClusterDecisionResourceGeneratorDeletingClusterFromResource(t *te }, }, }, - }).Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster1, expectedAppCluster2})). + }).Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster1, expectedAppCluster2})). // Update the ApplicationSet template namespace, and verify it updates the Applications When(). StatusUpdatePlacementDecision("my-placementdecision", clusterListSmall). - Then().Expect(ApplicationsExist([]argov1alpha1.Application{expectedAppCluster1})). - Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedAppCluster2})). + Then().Expect(ApplicationsExist([]v1alpha1.Application{expectedAppCluster1})). + Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedAppCluster2})). // Delete the ApplicationSet, and verify it deletes the Applications When(). - Delete().Then().Expect(ApplicationsDoNotExist([]argov1alpha1.Application{expectedAppCluster1})) + Delete().Then().Expect(ApplicationsDoNotExist([]v1alpha1.Application{expectedAppCluster1})) } diff --git a/test/e2e/custom_tool_test.go b/test/e2e/custom_tool_test.go index f9bfc014bb847..41ab74e9426f1 100644 --- a/test/e2e/custom_tool_test.go +++ b/test/e2e/custom_tool_test.go @@ -15,7 +15,6 @@ import ( . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/test/e2e/fixture" - . "github.com/argoproj/argo-cd/v2/test/e2e/fixture" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/app" . "github.com/argoproj/argo-cd/v2/util/errors" ) @@ -32,7 +31,7 @@ func TestCustomToolWithGitCreds(t *testing.T) { CustomCACertAdded(). // add the private repo with credentials HTTPSRepoURLAdded(true). - RepoURLType(RepoURLTypeHTTPS). + RepoURLType(fixture.RepoURLTypeHTTPS). Path("cmp-gitcreds"). When(). CreateApp(). @@ -42,7 +41,7 @@ func TestCustomToolWithGitCreds(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitAskpass}") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitAskpass}") require.NoError(t, err) assert.Equal(t, "argocd", output) }) @@ -62,7 +61,7 @@ func TestCustomToolWithGitCredsTemplate(t *testing.T) { HTTPSCredentialsUserPassAdded(). // add the private repo without credentials HTTPSRepoURLAdded(false). - RepoURLType(RepoURLTypeHTTPS). + RepoURLType(fixture.RepoURLTypeHTTPS). Path("cmp-gitcredstemplate"). When(). CreateApp(). @@ -72,17 +71,17 @@ func TestCustomToolWithGitCredsTemplate(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitAskpass}") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitAskpass}") require.NoError(t, err) assert.Equal(t, "argocd", output) }). And(func(app *Application) { - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitUsername}") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitUsername}") require.NoError(t, err) assert.Empty(t, output) }). And(func(app *Application) { - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitPassword}") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitPassword}") require.NoError(t, err) assert.Empty(t, output) }) @@ -112,12 +111,12 @@ func TestCustomToolWithSSHGitCreds(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", Name(), "-o", "jsonpath={.metadata.annotations.GitSSHCommand}") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", fixture.Name(), "-o", "jsonpath={.metadata.annotations.GitSSHCommand}") require.NoError(t, err) assert.Regexp(t, `-i [^ ]+`, output, "test plugin expects $GIT_SSH_COMMAND to contain the option '-i '") }). And(func(app *Application) { - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", Name(), "-o", "jsonpath={.metadata.annotations.GitSSHCredsFileSHA}") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", fixture.Name(), "-o", "jsonpath={.metadata.annotations.GitSSHCredsFileSHA}") require.NoError(t, err) assert.Regexp(t, `\w+\s+[\/\w]+`, output, "git ssh credentials file should be able to be read, hashing the contents") }) @@ -136,7 +135,7 @@ func TestCustomToolWithSSHGitCredsDisabled(t *testing.T) { // add the private repo with ssh credentials CustomSSHKnownHostsAdded(). SSHRepoURLAdded(true). - RepoURLType(RepoURLTypeSSH). + RepoURLType(fixture.RepoURLTypeSSH). Path("cmp-gitsshcreds"). When(). IgnoreErrors(). @@ -173,27 +172,27 @@ func TestCustomToolWithEnv(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Bar}") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Bar}") require.NoError(t, err) assert.Equal(t, "baz", output) }). And(func(app *Application) { - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Foo}") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Foo}") require.NoError(t, err) assert.Equal(t, "bar", output) }). And(func(app *Application) { - expectedKubeVersion := GetVersions().ServerVersion.Format("%s.%s") - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeVersion}") + expectedKubeVersion := fixture.GetVersions().ServerVersion.Format("%s.%s") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeVersion}") require.NoError(t, err) assert.Equal(t, expectedKubeVersion, output) }). And(func(app *Application) { - expectedApiVersion := GetApiResources() + expectedApiVersion := fixture.GetApiResources() expectedApiVersionSlice := strings.Split(expectedApiVersion, ",") sort.Strings(expectedApiVersionSlice) - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeApiVersion}") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeApiVersion}") require.NoError(t, err) outputSlice := strings.Split(output, ",") sort.Strings(outputSlice) @@ -224,16 +223,16 @@ func TestCustomToolSyncAndDiffLocal(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - FailOnErr(RunCli("app", "sync", ctx.AppName(), "--local", appPath, "--local-repo-root", testdataPath)) + FailOnErr(fixture.RunCli("app", "sync", ctx.AppName(), "--local", appPath, "--local-repo-root", testdataPath)) }). And(func(app *Application) { - FailOnErr(RunCli("app", "diff", ctx.AppName(), "--local", appPath, "--local-repo-root", testdataPath)) + FailOnErr(fixture.RunCli("app", "diff", ctx.AppName(), "--local", appPath, "--local-repo-root", testdataPath)) }) } func startCMPServer(t *testing.T, configFile string) { t.Helper() - pluginSockFilePath := TmpDir + PluginSockFilePath + pluginSockFilePath := fixture.TmpDir + fixture.PluginSockFilePath t.Setenv("ARGOCD_BINARY_NAME", "argocd-cmp-server") // ARGOCD_PLUGINSOCKFILEPATH should be set as the same value as repo server env var t.Setenv("ARGOCD_PLUGINSOCKFILEPATH", pluginSockFilePath) @@ -242,7 +241,7 @@ func startCMPServer(t *testing.T, configFile string) { err := os.Mkdir(pluginSockFilePath, 0o700) require.NoError(t, err) } - FailOnErr(RunWithStdin("", "", "../../dist/argocd", "--config-dir-path", configFile)) + FailOnErr(fixture.RunWithStdin("", "", "../../dist/argocd", "--config-dir-path", configFile)) } // Discover by fileName @@ -322,22 +321,22 @@ func TestCMPDiscoverWithFindCommandWithEnv(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). And(func(app *Application) { - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Bar}") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Bar}") require.NoError(t, err) assert.Equal(t, "baz", output) }). And(func(app *Application) { - expectedKubeVersion := GetVersions().ServerVersion.Format("%s.%s") - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeVersion}") + expectedKubeVersion := fixture.GetVersions().ServerVersion.Format("%s.%s") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeVersion}") require.NoError(t, err) assert.Equal(t, expectedKubeVersion, output) }). And(func(app *Application) { - expectedApiVersion := GetApiResources() + expectedApiVersion := fixture.GetApiResources() expectedApiVersionSlice := strings.Split(expectedApiVersion, ",") sort.Strings(expectedApiVersionSlice) - output, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeApiVersion}") + output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeApiVersion}") require.NoError(t, err) outputSlice := strings.Split(output, ",") sort.Strings(outputSlice) @@ -364,7 +363,7 @@ func TestPruneResourceFromCMP(t *testing.T) { Then(). Expect(DoesNotExist()). AndAction(func() { - _, err := Run("", "kubectl", "-n", DeploymentNamespace(), "get", "deployment", "guestbook-ui") + _, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "deployment", "guestbook-ui") require.Error(t, err) }) } @@ -390,7 +389,7 @@ func TestPreserveFileModeForCMP(t *testing.T) { } func TestCMPWithSymlinkPartialFiles(t *testing.T) { - Given(t, WithTestData("testdata2")). + Given(t, fixture.WithTestData("testdata2")). And(func() { go startCMPServer(t, "./testdata2/cmp-symlink") time.Sleep(100 * time.Millisecond) @@ -407,7 +406,7 @@ func TestCMPWithSymlinkPartialFiles(t *testing.T) { } func TestCMPWithSymlinkFiles(t *testing.T) { - Given(t, WithTestData("testdata2")). + Given(t, fixture.WithTestData("testdata2")). And(func() { go startCMPServer(t, "./testdata2/cmp-symlink") time.Sleep(100 * time.Millisecond) @@ -424,7 +423,7 @@ func TestCMPWithSymlinkFiles(t *testing.T) { } func TestCMPWithSymlinkFolder(t *testing.T) { - Given(t, WithTestData("testdata2")). + Given(t, fixture.WithTestData("testdata2")). And(func() { go startCMPServer(t, "./testdata2/cmp-symlink") time.Sleep(100 * time.Millisecond) diff --git a/test/e2e/graceful_restart_test.go b/test/e2e/graceful_restart_test.go index 6f5c6960a4f1d..11c6cab5fbfb3 100644 --- a/test/e2e/graceful_restart_test.go +++ b/test/e2e/graceful_restart_test.go @@ -11,13 +11,12 @@ import ( "github.com/argoproj/argo-cd/v2/pkg/apiclient/settings" "github.com/argoproj/argo-cd/v2/test/e2e/fixture" - . "github.com/argoproj/argo-cd/v2/test/e2e/fixture" "github.com/argoproj/argo-cd/v2/util/errors" ) func checkHealth(t *testing.T, requireHealthy bool) { t.Helper() - resp, err := DoHttpRequest("GET", "/healthz?full=true", "") + resp, err := fixture.DoHttpRequest("GET", "/healthz?full=true", "") if requireHealthy { require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode) @@ -33,7 +32,7 @@ func checkHealth(t *testing.T, requireHealthy bool) { } func TestAPIServerGracefulRestart(t *testing.T) { - EnsureCleanState(t) + fixture.EnsureCleanState(t) // Should be healthy. checkHealth(t, true) @@ -47,7 +46,7 @@ func TestAPIServerGracefulRestart(t *testing.T) { } // One final time, should be healthy, or restart is considered too slow for tests checkHealth(t, true) - closer, settingsClient, err := ArgoCDClientset.NewSettingsClient() + closer, settingsClient, err := fixture.ArgoCDClientset.NewSettingsClient() if closer != nil { defer closer.Close() } diff --git a/test/e2e/helm_test.go b/test/e2e/helm_test.go index b507836841add..0ecb03e730e43 100644 --- a/test/e2e/helm_test.go +++ b/test/e2e/helm_test.go @@ -18,7 +18,6 @@ import ( . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/test/e2e/fixture" - . "github.com/argoproj/argo-cd/v2/test/e2e/fixture" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/app" projectFixture "github.com/argoproj/argo-cd/v2/test/e2e/fixture/project" "github.com/argoproj/argo-cd/v2/test/e2e/fixture/repos" @@ -37,7 +36,7 @@ func TestHelmHooksAreCreated(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(HealthIs(health.HealthStatusHealthy)). Expect(SyncStatusIs(SyncStatusCodeSynced)). - Expect(ResourceResultIs(ResourceResult{Version: "v1", Kind: "Pod", Namespace: DeploymentNamespace(), Name: "hook", Message: "pod/hook created", HookType: HookTypePreSync, HookPhase: OperationSucceeded, SyncPhase: SyncPhasePreSync})) + Expect(ResourceResultIs(ResourceResult{Version: "v1", Kind: "Pod", Namespace: fixture.DeploymentNamespace(), Name: "hook", Message: "pod/hook created", HookType: HookTypePreSync, HookPhase: OperationSucceeded, SyncPhase: SyncPhasePreSync})) } // make sure we treat Helm weights as a sync wave @@ -96,11 +95,11 @@ func TestDeclarativeHelmInvalidValuesFile(t *testing.T) { } func TestHelmRepo(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") Given(t). CustomCACertAdded(). HelmRepoAdded("custom-repo"). - RepoURLType(RepoURLTypeHelm). + RepoURLType(fixture.RepoURLTypeHelm). Chart("helm"). Revision("1.0.0"). When(). @@ -255,7 +254,7 @@ func TestHelmValuesLiteralFileRemote(t *testing.T) { } func TestHelmCrdHook(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") Given(t). Path("helm-crd"). When(). @@ -328,7 +327,7 @@ func TestHelmSetEnv(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - assert.Equal(t, Name(), FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) + assert.Equal(t, fixture.Name(), FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) }) } @@ -343,13 +342,13 @@ func TestHelmSetStringEnv(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - assert.Equal(t, Name(), FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) + assert.Equal(t, fixture.Name(), FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) }) } // make sure kube-version gets passed down to resources func TestKubeVersion(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") Given(t). Path("helm-kube-version"). When(). @@ -358,10 +357,10 @@ func TestKubeVersion(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - kubeVersion := FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", + kubeVersion := FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string) // Capabilities.KubeVersion defaults to 1.9.0, we assume here you are running a later version - assert.LessOrEqual(t, GetVersions().ServerVersion.Format("v%s.%s.0"), kubeVersion) + assert.LessOrEqual(t, fixture.GetVersions().ServerVersion.Format("v%s.%s.0"), kubeVersion) }). When(). // Make sure override works. @@ -370,14 +369,14 @@ func TestKubeVersion(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - assert.Equal(t, "v999.999.999", FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", + assert.Equal(t, "v999.999.999", FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string)) }) } // make sure api versions gets passed down to resources func TestApiVersions(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") Given(t). Path("helm-api-versions"). When(). @@ -386,7 +385,7 @@ func TestApiVersions(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - apiVersions := FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", + apiVersions := FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) // The v1 API shouldn't be going anywhere. assert.Contains(t, apiVersions, "v1") @@ -398,14 +397,14 @@ func TestApiVersions(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - apiVersions := FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", + apiVersions := FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) assert.Contains(t, apiVersions, "v1/MyTestResource") }) } func TestHelmNamespaceOverride(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") Given(t). Path("helm-namespace"). When(). @@ -421,7 +420,7 @@ func TestHelmNamespaceOverride(t *testing.T) { } func TestHelmValuesHiddenDirectory(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") Given(t). Path(".hidden-helm"). When(). @@ -436,12 +435,12 @@ func TestHelmValuesHiddenDirectory(t *testing.T) { } func TestHelmWithDependencies(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") testHelmWithDependencies(t, "helm-with-dependencies", false) } func TestHelmWithMultipleDependencies(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") Given(t).Path("helm-with-multiple-dependencies"). CustomCACertAdded(). @@ -457,7 +456,7 @@ func TestHelmWithMultipleDependencies(t *testing.T) { } func TestHelmDependenciesPermissionDenied(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") projName := "argo-helm-project-denied" projectFixture. @@ -466,7 +465,7 @@ func TestHelmDependenciesPermissionDenied(t *testing.T) { Destination("*,*"). When(). Create(). - AddSource(RepoURL(RepoURLTypeFile)) + AddSource(fixture.RepoURL(fixture.RepoURLTypeFile)) expectedErr := fmt.Sprintf("helm repos localhost:5000/myrepo are not permitted in project '%s'", projName) GivenWithSameState(t). @@ -496,7 +495,7 @@ func TestHelmDependenciesPermissionDenied(t *testing.T) { } func TestHelmWithDependenciesLegacyRepo(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") testHelmWithDependencies(t, "helm-with-dependencies", true) } @@ -513,14 +512,14 @@ func testHelmWithDependencies(t *testing.T, chartPath string, legacyRepo bool) { "-n", fixture.TestNamespace(), "--from-file=certSecret="+repos.CertPath, "--from-file=keySecret="+repos.CertKeyPath, - "--from-literal=username="+GitUsername, - "--from-literal=password="+GitPassword, + "--from-literal=username="+fixture.GitUsername, + "--from-literal=password="+fixture.GitPassword, )) FailOnErr(fixture.KubeClientset.CoreV1().Secrets(fixture.TestNamespace()).Patch(context.Background(), "helm-repo", types.MergePatchType, []byte(`{"metadata": { "labels": {"e2e.argoproj.io": "true"} }}`), metav1.PatchOptions{})) CheckError(fixture.SetHelmRepos(settings.HelmRepoCredentials{ - URL: RepoURL(RepoURLTypeHelm), + URL: fixture.RepoURL(fixture.RepoURLTypeHelm), Name: "custom-repo", KeySecret: &corev1.SecretKeySelector{LocalObjectReference: corev1.LocalObjectReference{Name: "helm-repo"}, Key: "keySecret"}, CertSecret: &corev1.SecretKeySelector{LocalObjectReference: corev1.LocalObjectReference{Name: "helm-repo"}, Key: "certSecret"}, @@ -543,7 +542,7 @@ func testHelmWithDependencies(t *testing.T, chartPath string, legacyRepo bool) { } func TestHelm3CRD(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") Given(t). Path("helm3-crd"). When(). @@ -555,12 +554,12 @@ func TestHelm3CRD(t *testing.T) { } func TestHelmRepoDiffLocal(t *testing.T) { - SkipOnEnv(t, "HELM") + fixture.SkipOnEnv(t, "HELM") helmTmp := t.TempDir() Given(t). CustomCACertAdded(). HelmRepoAdded("custom-repo"). - RepoURLType(RepoURLTypeHelm). + RepoURLType(fixture.RepoURLTypeHelm). Chart("helm"). Revision("1.0.0"). When(). @@ -574,14 +573,14 @@ func TestHelmRepoDiffLocal(t *testing.T) { Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { _ = os.Setenv("XDG_CONFIG_HOME", helmTmp) - FailOnErr(Run("", "helm", "repo", "add", "custom-repo", GetEnvWithDefault("ARGOCD_E2E_HELM_SERVICE", RepoURL(RepoURLTypeHelm)), - "--username", GitUsername, - "--password", GitPassword, + FailOnErr(fixture.Run("", "helm", "repo", "add", "custom-repo", fixture.GetEnvWithDefault("ARGOCD_E2E_HELM_SERVICE", fixture.RepoURL(fixture.RepoURLTypeHelm)), + "--username", fixture.GitUsername, + "--password", fixture.GitPassword, "--cert-file", "../fixture/certs/argocd-test-client.crt", "--key-file", "../fixture/certs/argocd-test-client.key", "--ca-file", "../fixture/certs/argocd-test-ca.crt", )) - diffOutput := FailOnErr(RunCli("app", "diff", app.Name, "--local", "testdata/helm")).(string) + diffOutput := FailOnErr(fixture.RunCli("app", "diff", app.Name, "--local", "testdata/helm")).(string) assert.Empty(t, diffOutput) }) } @@ -590,7 +589,7 @@ func TestHelmOCIRegistry(t *testing.T) { Given(t). PushChartToOCIRegistry("helm-values", "helm-values", "1.0.0"). HelmOCIRepoAdded("myrepo"). - RepoURLType(RepoURLTypeHelmOCI). + RepoURLType(fixture.RepoURLTypeHelmOCI). Chart("helm-values"). Revision("1.0.0"). When(). @@ -625,7 +624,7 @@ func TestHelmOCIRegistryWithDependencies(t *testing.T) { PushChartToOCIRegistry("helm-values", "helm-values", "1.0.0"). PushChartToOCIRegistry("helm-oci-with-dependencies", "helm-oci-with-dependencies", "1.0.0"). HelmOCIRepoAdded("myrepo"). - RepoURLType(RepoURLTypeHelmOCI). + RepoURLType(fixture.RepoURLTypeHelmOCI). Chart("helm-oci-with-dependencies"). Revision("1.0.0"). When(). @@ -660,7 +659,7 @@ func TestTemplatesHelmOCIWithDependencies(t *testing.T) { PushChartToOCIRegistry("helm-values", "helm-values", "1.0.0"). PushChartToOCIRegistry("helm-oci-with-dependencies", "helm-oci-with-dependencies", "1.0.0"). HelmoOCICredentialsWithoutUserPassAdded(). - RepoURLType(RepoURLTypeHelmOCI). + RepoURLType(fixture.RepoURLTypeHelmOCI). Chart("helm-oci-with-dependencies"). Revision("1.0.0"). When(). diff --git a/test/e2e/kustomize_test.go b/test/e2e/kustomize_test.go index 923b9d46fee9e..a49c26b1e1ad5 100644 --- a/test/e2e/kustomize_test.go +++ b/test/e2e/kustomize_test.go @@ -11,10 +11,8 @@ import ( . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/test/e2e/fixture" - . "github.com/argoproj/argo-cd/v2/test/e2e/fixture" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/app" "github.com/argoproj/argo-cd/v2/util/errors" - . "github.com/argoproj/argo-cd/v2/util/errors" ) func TestKustomize2AppSource(t *testing.T) { @@ -304,10 +302,10 @@ func TestKustomizeKubeVersion(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - kubeVersion := FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", + kubeVersion := errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string) // Capabilities.KubeVersion defaults to 1.9.0, we assume here you are running a later version - assert.LessOrEqual(t, GetVersions().ServerVersion.Format("v%s.%s.0"), kubeVersion) + assert.LessOrEqual(t, fixture.GetVersions().ServerVersion.Format("v%s.%s.0"), kubeVersion) }). When(). // Make sure override works. @@ -316,7 +314,7 @@ func TestKustomizeKubeVersion(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - assert.Equal(t, "v999.999.999", FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", + assert.Equal(t, "v999.999.999", errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string)) }) } @@ -336,7 +334,7 @@ func TestKustomizeApiVersions(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - apiVersions := FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", + apiVersions := errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) // The v1 API shouldn't be going anywhere. assert.Contains(t, apiVersions, "v1") @@ -348,7 +346,7 @@ func TestKustomizeApiVersions(t *testing.T) { Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). And(func(app *Application) { - apiVersions := FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", + apiVersions := errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) assert.Contains(t, apiVersions, "v1/MyTestResource") }) diff --git a/test/e2e/matrix_e2e_test.go b/test/e2e/matrix_e2e_test.go index e6f8781fcfcea..35b22eeba1af7 100644 --- a/test/e2e/matrix_e2e_test.go +++ b/test/e2e/matrix_e2e_test.go @@ -8,7 +8,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/applicationsets" "github.com/argoproj/argo-cd/v2/test/e2e/fixture/applicationsets/utils" @@ -16,8 +15,8 @@ import ( ) func TestListMatrixGenerator(t *testing.T) { - generateExpectedApp := func(cluster, name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(cluster, name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -27,14 +26,14 @@ func TestListMatrixGenerator(t *testing.T) { Namespace: utils.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: name, }, @@ -42,7 +41,7 @@ func TestListMatrixGenerator(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("cluster1", "kustomize-guestbook"), generateExpectedApp("cluster1", "helm-guestbook"), generateExpectedApp("cluster1", "ksonnet-guestbook"), @@ -52,8 +51,8 @@ func TestListMatrixGenerator(t *testing.T) { generateExpectedApp("cluster2", "ksonnet-guestbook"), } - var expectedAppsNewNamespace []argov1alpha1.Application - var expectedAppsNewMetadata []argov1alpha1.Application + var expectedAppsNewNamespace []v1alpha1.Application + var expectedAppsNewMetadata []v1alpha1.Application Given(t). // Create a ClusterGenerator-based ApplicationSet @@ -65,14 +64,14 @@ func TestListMatrixGenerator(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{values.name}}-{{path.basename}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "{{path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "{{path.basename}}", }, @@ -141,8 +140,8 @@ func TestListMatrixGenerator(t *testing.T) { } func TestClusterMatrixGenerator(t *testing.T) { - generateExpectedApp := func(cluster, name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(cluster, name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -152,14 +151,14 @@ func TestClusterMatrixGenerator(t *testing.T) { Namespace: utils.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: cluster, Namespace: name, }, @@ -167,7 +166,7 @@ func TestClusterMatrixGenerator(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("cluster1", "kustomize-guestbook"), generateExpectedApp("cluster1", "helm-guestbook"), generateExpectedApp("cluster1", "ksonnet-guestbook"), @@ -177,8 +176,8 @@ func TestClusterMatrixGenerator(t *testing.T) { generateExpectedApp("cluster2", "ksonnet-guestbook"), } - var expectedAppsNewNamespace []argov1alpha1.Application - var expectedAppsNewMetadata []argov1alpha1.Application + var expectedAppsNewNamespace []v1alpha1.Application + var expectedAppsNewMetadata []v1alpha1.Application Given(t). // Create a ClusterGenerator-based ApplicationSet @@ -192,14 +191,14 @@ func TestClusterMatrixGenerator(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-{{path.basename}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "{{path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{name}}", Namespace: "{{path.basename}}", }, @@ -269,8 +268,8 @@ func TestClusterMatrixGenerator(t *testing.T) { } func TestMatrixTerminalMatrixGeneratorSelector(t *testing.T) { - generateExpectedApp := func(cluster, name string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(cluster, name string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -280,14 +279,14 @@ func TestMatrixTerminalMatrixGeneratorSelector(t *testing.T) { Namespace: utils.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: name, }, @@ -295,12 +294,12 @@ func TestMatrixTerminalMatrixGeneratorSelector(t *testing.T) { } } - expectedApps1 := []argov1alpha1.Application{ + expectedApps1 := []v1alpha1.Application{ generateExpectedApp("cluster1", "kustomize-guestbook"), generateExpectedApp("cluster1", "helm-guestbook"), generateExpectedApp("cluster1", "ksonnet-guestbook"), } - expectedApps2 := []argov1alpha1.Application{ + expectedApps2 := []v1alpha1.Application{ generateExpectedApp("cluster2", "kustomize-guestbook"), generateExpectedApp("cluster2", "helm-guestbook"), generateExpectedApp("cluster2", "ksonnet-guestbook"), @@ -317,14 +316,14 @@ func TestMatrixTerminalMatrixGeneratorSelector(t *testing.T) { ApplyNestedSelectors: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{values.name}}-{{path.basename}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "{{path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "{{path.basename}}", }, @@ -421,8 +420,8 @@ func TestMatrixTerminalMatrixGeneratorSelector(t *testing.T) { } func TestMatrixTerminalMergeGeneratorSelector(t *testing.T) { - generateExpectedApp := func(name, nameSuffix string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name, nameSuffix string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -432,14 +431,14 @@ func TestMatrixTerminalMergeGeneratorSelector(t *testing.T) { Namespace: utils.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: name, }, @@ -447,10 +446,10 @@ func TestMatrixTerminalMergeGeneratorSelector(t *testing.T) { } } - expectedApps1 := []argov1alpha1.Application{ + expectedApps1 := []v1alpha1.Application{ generateExpectedApp("kustomize-guestbook", "1"), } - expectedApps2 := []argov1alpha1.Application{ + expectedApps2 := []v1alpha1.Application{ generateExpectedApp("helm-guestbook", "2"), } @@ -465,14 +464,14 @@ func TestMatrixTerminalMergeGeneratorSelector(t *testing.T) { ApplyNestedSelectors: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{path.basename}}-{{name-suffix}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "{{path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "{{path.basename}}", }, diff --git a/test/e2e/merge_e2e_test.go b/test/e2e/merge_e2e_test.go index 0cf71f2a191af..39d23cd429034 100644 --- a/test/e2e/merge_e2e_test.go +++ b/test/e2e/merge_e2e_test.go @@ -9,7 +9,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/applicationsets" "github.com/argoproj/argo-cd/v2/test/e2e/fixture/applicationsets/utils" @@ -17,8 +16,8 @@ import ( ) func TestListMergeGenerator(t *testing.T) { - generateExpectedApp := func(name, nameSuffix string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name, nameSuffix string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -28,14 +27,14 @@ func TestListMergeGenerator(t *testing.T) { Namespace: utils.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: name, }, @@ -43,13 +42,13 @@ func TestListMergeGenerator(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("kustomize-guestbook", "1"), generateExpectedApp("helm-guestbook", "2"), } - var expectedAppsNewNamespace []argov1alpha1.Application - var expectedAppsNewMetadata []argov1alpha1.Application + var expectedAppsNewNamespace []v1alpha1.Application + var expectedAppsNewMetadata []v1alpha1.Application Given(t). // Create a ClusterGenerator-based ApplicationSet @@ -61,14 +60,14 @@ func TestListMergeGenerator(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{path.basename}}-{{name-suffix}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "{{path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "{{path.basename}}", }, @@ -138,8 +137,8 @@ func TestListMergeGenerator(t *testing.T) { } func TestClusterMergeGenerator(t *testing.T) { - generateExpectedApp := func(cluster, name, nameSuffix string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(cluster, name, nameSuffix string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -149,14 +148,14 @@ func TestClusterMergeGenerator(t *testing.T) { Namespace: utils.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: cluster, Namespace: name, }, @@ -164,7 +163,7 @@ func TestClusterMergeGenerator(t *testing.T) { } } - expectedApps := []argov1alpha1.Application{ + expectedApps := []v1alpha1.Application{ generateExpectedApp("cluster1", "kustomize-guestbook", "1"), generateExpectedApp("cluster1", "helm-guestbook", "0"), generateExpectedApp("cluster1", "ksonnet-guestbook", "0"), @@ -174,8 +173,8 @@ func TestClusterMergeGenerator(t *testing.T) { generateExpectedApp("cluster2", "ksonnet-guestbook", "0"), } - var expectedAppsNewNamespace []argov1alpha1.Application - var expectedAppsNewMetadata []argov1alpha1.Application + var expectedAppsNewNamespace []v1alpha1.Application + var expectedAppsNewMetadata []v1alpha1.Application Given(t). // Create a ClusterGenerator-based ApplicationSet @@ -189,14 +188,14 @@ func TestClusterMergeGenerator(t *testing.T) { Spec: v1alpha1.ApplicationSetSpec{ Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{name}}-{{path.basename}}-{{values.name-suffix}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "{{path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Name: "{{name}}", Namespace: "{{path.basename}}", }, @@ -284,8 +283,8 @@ func TestClusterMergeGenerator(t *testing.T) { } func TestMergeTerminalMergeGeneratorSelector(t *testing.T) { - generateExpectedApp := func(name, nameSuffix string) argov1alpha1.Application { - return argov1alpha1.Application{ + generateExpectedApp := func(name, nameSuffix string) v1alpha1.Application { + return v1alpha1.Application{ TypeMeta: metav1.TypeMeta{ Kind: application.ApplicationKind, APIVersion: "argoproj.io/v1alpha1", @@ -295,14 +294,14 @@ func TestMergeTerminalMergeGeneratorSelector(t *testing.T) { Namespace: utils.TestNamespace(), Finalizers: []string{"resources-finalizer.argocd.argoproj.io"}, }, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: name, }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: name, }, @@ -310,10 +309,10 @@ func TestMergeTerminalMergeGeneratorSelector(t *testing.T) { } } - expectedApps1 := []argov1alpha1.Application{ + expectedApps1 := []v1alpha1.Application{ generateExpectedApp("kustomize-guestbook", "1"), } - expectedApps2 := []argov1alpha1.Application{ + expectedApps2 := []v1alpha1.Application{ generateExpectedApp("helm-guestbook", "2"), } @@ -328,14 +327,14 @@ func TestMergeTerminalMergeGeneratorSelector(t *testing.T) { ApplyNestedSelectors: true, Template: v1alpha1.ApplicationSetTemplate{ ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{Name: "{{path.basename}}-{{name-suffix}}"}, - Spec: argov1alpha1.ApplicationSpec{ + Spec: v1alpha1.ApplicationSpec{ Project: "default", - Source: &argov1alpha1.ApplicationSource{ + Source: &v1alpha1.ApplicationSource{ RepoURL: "https://github.com/argoproj/argocd-example-apps.git", TargetRevision: "HEAD", Path: "{{path}}", }, - Destination: argov1alpha1.ApplicationDestination{ + Destination: v1alpha1.ApplicationDestination{ Server: "https://kubernetes.default.svc", Namespace: "{{path.basename}}", }, diff --git a/test/e2e/selective_sync_test.go b/test/e2e/selective_sync_test.go index 5cbf44643a37b..98915255d5b19 100644 --- a/test/e2e/selective_sync_test.go +++ b/test/e2e/selective_sync_test.go @@ -11,7 +11,6 @@ import ( . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/test/e2e/fixture" - . "github.com/argoproj/argo-cd/v2/test/e2e/fixture" . "github.com/argoproj/argo-cd/v2/test/e2e/fixture/app" . "github.com/argoproj/argo-cd/v2/util/errors" "github.com/argoproj/argo-cd/v2/util/rand" @@ -55,14 +54,14 @@ func TestSelectiveSyncWithoutNamespace(t *testing.T) { selectedResourceNamespace := getNewNamespace(t) defer func() { if !t.Skipped() { - FailOnErr(Run("", "kubectl", "delete", "namespace", selectedResourceNamespace)) + FailOnErr(fixture.Run("", "kubectl", "delete", "namespace", selectedResourceNamespace)) } }() Given(t). Prune(true). Path("guestbook-with-namespace"). And(func() { - FailOnErr(Run("", "kubectl", "create", "namespace", selectedResourceNamespace)) + FailOnErr(fixture.Run("", "kubectl", "create", "namespace", selectedResourceNamespace)) }). SelectedResource("apps:Deployment:guestbook-ui"). When(). @@ -85,14 +84,14 @@ func TestSelectiveSyncWithNamespace(t *testing.T) { selectedResourceNamespace := getNewNamespace(t) defer func() { if !t.Skipped() { - FailOnErr(Run("", "kubectl", "delete", "namespace", selectedResourceNamespace)) + FailOnErr(fixture.Run("", "kubectl", "delete", "namespace", selectedResourceNamespace)) } }() Given(t). Prune(true). Path("guestbook-with-namespace"). And(func() { - FailOnErr(Run("", "kubectl", "create", "namespace", selectedResourceNamespace)) + FailOnErr(fixture.Run("", "kubectl", "create", "namespace", selectedResourceNamespace)) }). SelectedResource(fmt.Sprintf("apps:Deployment:%s/guestbook-ui", selectedResourceNamespace)). When(). diff --git a/util/argo/resource_tracking.go b/util/argo/resource_tracking.go index f9f1c6ca83a5a..3366d15208791 100644 --- a/util/argo/resource_tracking.go +++ b/util/argo/resource_tracking.go @@ -11,7 +11,6 @@ import ( "github.com/argoproj/argo-cd/v2/common" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/util/kube" - argokube "github.com/argoproj/argo-cd/v2/util/kube" "github.com/argoproj/argo-cd/v2/util/settings" ) @@ -69,7 +68,7 @@ func (rt *resourceTracking) getAppInstanceValue(un *unstructured.Unstructured, i if installationID != "" && un.GetAnnotations() == nil || un.GetAnnotations()[common.AnnotationInstallationID] != installationID { return nil } - appInstanceAnnotation, err := argokube.GetAppInstanceAnnotation(un, common.AnnotationKeyAppInstance) + appInstanceAnnotation, err := kube.GetAppInstanceAnnotation(un, common.AnnotationKeyAppInstance) if err != nil { return nil } @@ -91,7 +90,7 @@ func (rt *resourceTracking) GetAppName(un *unstructured.Unstructured, key string } switch trackingMethod { case TrackingMethodLabel: - label, err := argokube.GetAppInstanceLabel(un, key) + label, err := kube.GetAppInstanceLabel(un, key) if err != nil { return "" } @@ -101,7 +100,7 @@ func (rt *resourceTracking) GetAppName(un *unstructured.Unstructured, key string case TrackingMethodAnnotation: return retrieveAppInstanceValue() default: - label, err := argokube.GetAppInstanceLabel(un, key) + label, err := kube.GetAppInstanceLabel(un, key) if err != nil { return "" } @@ -145,19 +144,19 @@ func (rt *resourceTracking) SetAppInstance(un *unstructured.Unstructured, key, v setAppInstanceAnnotation := func() error { appInstanceValue := UnstructuredToAppInstanceValue(un, val, namespace) if instanceID != "" { - if err := argokube.SetAppInstanceAnnotation(un, common.AnnotationInstallationID, instanceID); err != nil { + if err := kube.SetAppInstanceAnnotation(un, common.AnnotationInstallationID, instanceID); err != nil { return err } } else { - if err := argokube.RemoveAnnotation(un, common.AnnotationInstallationID); err != nil { + if err := kube.RemoveAnnotation(un, common.AnnotationInstallationID); err != nil { return err } } - return argokube.SetAppInstanceAnnotation(un, common.AnnotationKeyAppInstance, rt.BuildAppInstanceValue(appInstanceValue)) + return kube.SetAppInstanceAnnotation(un, common.AnnotationKeyAppInstance, rt.BuildAppInstanceValue(appInstanceValue)) } switch trackingMethod { case TrackingMethodLabel: - err := argokube.SetAppInstanceLabel(un, key, val) + err := kube.SetAppInstanceLabel(un, key, val) if err != nil { return fmt.Errorf("failed to set app instance label: %w", err) } @@ -180,13 +179,13 @@ func (rt *resourceTracking) SetAppInstance(un *unstructured.Unstructured, key, v val = val[:len(val)-1] } } - err = argokube.SetAppInstanceLabel(un, key, val) + err = kube.SetAppInstanceLabel(un, key, val) if err != nil { return fmt.Errorf("failed to set app instance label: %w", err) } return nil default: - err := argokube.SetAppInstanceLabel(un, key, val) + err := kube.SetAppInstanceLabel(un, key, val) if err != nil { return fmt.Errorf("failed to set app instance label: %w", err) } @@ -241,21 +240,21 @@ func (rt *resourceTracking) Normalize(config, live *unstructured.Unstructured, l return nil } - annotation, err := argokube.GetAppInstanceAnnotation(config, common.AnnotationKeyAppInstance) + annotation, err := kube.GetAppInstanceAnnotation(config, common.AnnotationKeyAppInstance) if err != nil { return err } - err = argokube.SetAppInstanceAnnotation(live, common.AnnotationKeyAppInstance, annotation) + err = kube.SetAppInstanceAnnotation(live, common.AnnotationKeyAppInstance, annotation) if err != nil { return err } - label, err = argokube.GetAppInstanceLabel(config, labelKey) + label, err = kube.GetAppInstanceLabel(config, labelKey) if err != nil { return fmt.Errorf("failed to get app instance label: %w", err) } if label == "" { - err = argokube.RemoveLabel(live, labelKey) + err = kube.RemoveLabel(live, labelKey) if err != nil { return fmt.Errorf("failed to remove app instance label: %w", err) } diff --git a/util/db/cluster_test.go b/util/db/cluster_test.go index b1eabfcc6f074..345dd6107e1bb 100644 --- a/util/db/cluster_test.go +++ b/util/db/cluster_test.go @@ -15,7 +15,6 @@ import ( "github.com/argoproj/argo-cd/v2/common" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/util/settings" ) @@ -97,7 +96,7 @@ func Test_secretToCluster_LastAppliedConfigurationDropped(t *testing.T) { } func TestClusterToSecret(t *testing.T) { - cluster := &appv1.Cluster{ + cluster := &v1alpha1.Cluster{ Server: "server", Labels: map[string]string{"test": "label"}, Annotations: map[string]string{"test": "annotation"}, @@ -119,7 +118,7 @@ func TestClusterToSecret(t *testing.T) { } func TestClusterToSecret_LastAppliedConfigurationRejected(t *testing.T) { - cluster := &appv1.Cluster{ + cluster := &v1alpha1.Cluster{ Server: "server", Annotations: map[string]string{corev1.LastAppliedConfigAnnotation: "val2"}, Name: "test", @@ -247,8 +246,8 @@ func TestRejectCreationForInClusterWhenDisabled(t *testing.T) { kubeclientset := fake.NewClientset(argoCDConfigMapWithInClusterServerAddressDisabled, argoCDSecret) settingsManager := settings.NewSettingsManager(context.Background(), kubeclientset, fakeNamespace) db := NewDB(fakeNamespace, settingsManager, kubeclientset) - _, err := db.CreateCluster(context.Background(), &appv1.Cluster{ - Server: appv1.KubernetesInternalAPIServerAddr, + _, err := db.CreateCluster(context.Background(), &v1alpha1.Cluster{ + Server: v1alpha1.KubernetesInternalAPIServerAddr, Name: "incluster-name", }) require.Error(t, err) @@ -339,7 +338,7 @@ func TestListClusters(t *testing.T) { }, }, Data: map[string][]byte{ - "server": []byte(appv1.KubernetesInternalAPIServerAddr), + "server": []byte(v1alpha1.KubernetesInternalAPIServerAddr), "name": []byte("in-cluster"), }, } diff --git a/util/db/repository.go b/util/db/repository.go index db3f78f42558e..fd2d5e6a68c2b 100644 --- a/util/db/repository.go +++ b/util/db/repository.go @@ -11,8 +11,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - appsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" + "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/util/settings" ) @@ -41,24 +40,24 @@ const ( // repositoryBackend defines the API for types that wish to provide interaction with repository storage type repositoryBackend interface { - CreateRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) - GetRepository(ctx context.Context, repoURL, project string) (*appsv1.Repository, error) - ListRepositories(ctx context.Context, repoType *string) ([]*appsv1.Repository, error) - UpdateRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) + CreateRepository(ctx context.Context, r *v1alpha1.Repository) (*v1alpha1.Repository, error) + GetRepository(ctx context.Context, repoURL, project string) (*v1alpha1.Repository, error) + ListRepositories(ctx context.Context, repoType *string) ([]*v1alpha1.Repository, error) + UpdateRepository(ctx context.Context, r *v1alpha1.Repository) (*v1alpha1.Repository, error) DeleteRepository(ctx context.Context, repoURL, project string) error RepositoryExists(ctx context.Context, repoURL, project string, allowFallback bool) (bool, error) - CreateRepoCreds(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) - GetRepoCreds(ctx context.Context, repoURL string) (*appsv1.RepoCreds, error) + CreateRepoCreds(ctx context.Context, r *v1alpha1.RepoCreds) (*v1alpha1.RepoCreds, error) + GetRepoCreds(ctx context.Context, repoURL string) (*v1alpha1.RepoCreds, error) ListRepoCreds(ctx context.Context) ([]string, error) - UpdateRepoCreds(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) + UpdateRepoCreds(ctx context.Context, r *v1alpha1.RepoCreds) (*v1alpha1.RepoCreds, error) DeleteRepoCreds(ctx context.Context, name string) error RepoCredsExists(ctx context.Context, repoURL string) (bool, error) - GetAllHelmRepoCreds(ctx context.Context) ([]*appsv1.RepoCreds, error) + GetAllHelmRepoCreds(ctx context.Context) ([]*v1alpha1.RepoCreds, error) } -func (db *db) CreateRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) { +func (db *db) CreateRepository(ctx context.Context, r *v1alpha1.Repository) (*v1alpha1.Repository, error) { secretBackend := db.repoBackend() legacyBackend := db.legacyRepoBackend() @@ -78,7 +77,7 @@ func (db *db) CreateRepository(ctx context.Context, r *appsv1.Repository) (*apps return secretBackend.CreateRepository(ctx, r) } -func (db *db) CreateWriteRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) { +func (db *db) CreateWriteRepository(ctx context.Context, r *v1alpha1.Repository) (*v1alpha1.Repository, error) { secretBackend := db.repoWriteBackend() secretExists, err := secretBackend.RepositoryExists(ctx, r.Repo, r.Project, false) if err != nil { @@ -92,7 +91,7 @@ func (db *db) CreateWriteRepository(ctx context.Context, r *appsv1.Repository) ( return secretBackend.CreateRepository(ctx, r) } -func (db *db) GetRepository(ctx context.Context, repoURL, project string) (*appsv1.Repository, error) { +func (db *db) GetRepository(ctx context.Context, repoURL, project string) (*v1alpha1.Repository, error) { repository, err := db.getRepository(ctx, repoURL, project) if err != nil { return repository, fmt.Errorf("unable to get repository %q: %w", repoURL, err) @@ -105,7 +104,7 @@ func (db *db) GetRepository(ctx context.Context, repoURL, project string) (*apps return repository, err } -func (db *db) GetWriteRepository(ctx context.Context, repoURL, project string) (*appsv1.Repository, error) { +func (db *db) GetWriteRepository(ctx context.Context, repoURL, project string) (*v1alpha1.Repository, error) { repository, err := db.repoWriteBackend().GetRepository(ctx, repoURL, project) if err != nil { return repository, fmt.Errorf("unable to get write repository %q: %w", repoURL, err) @@ -119,15 +118,15 @@ func (db *db) GetWriteRepository(ctx context.Context, repoURL, project string) ( return repository, err } -func (db *db) GetProjectRepositories(ctx context.Context, project string) ([]*appsv1.Repository, error) { +func (db *db) GetProjectRepositories(ctx context.Context, project string) ([]*v1alpha1.Repository, error) { return db.getRepositories(settings.ByProjectRepoIndexer, project) } -func (db *db) GetProjectWriteRepositories(ctx context.Context, project string) ([]*appsv1.Repository, error) { +func (db *db) GetProjectWriteRepositories(ctx context.Context, project string) ([]*v1alpha1.Repository, error) { return db.getRepositories(settings.ByProjectRepoWriteIndexer, project) } -func (db *db) getRepositories(indexer, project string) ([]*appv1.Repository, error) { +func (db *db) getRepositories(indexer, project string) ([]*v1alpha1.Repository, error) { informer, err := db.settingsMgr.GetSecretsInformer() if err != nil { return nil, err @@ -136,7 +135,7 @@ func (db *db) getRepositories(indexer, project string) ([]*appv1.Repository, err if err != nil { return nil, err } - var res []*appv1.Repository + var res []*v1alpha1.Repository for i := range secrets { repo, err := secretToRepository(secrets[i].(*corev1.Secret)) if err != nil { @@ -163,7 +162,7 @@ func (db *db) WriteRepositoryExists(ctx context.Context, repoURL, project string return secretsBackend.RepositoryExists(ctx, repoURL, project, true) } -func (db *db) getRepository(ctx context.Context, repoURL, project string) (*appsv1.Repository, error) { +func (db *db) getRepository(ctx context.Context, repoURL, project string) (*v1alpha1.Repository, error) { secretsBackend := db.repoBackend() exists, err := secretsBackend.RepositoryExists(ctx, repoURL, project, true) if err != nil { @@ -188,22 +187,22 @@ func (db *db) getRepository(ctx context.Context, repoURL, project string) (*apps return repository, nil } - return &appsv1.Repository{Repo: repoURL}, nil + return &v1alpha1.Repository{Repo: repoURL}, nil } -func (db *db) ListRepositories(ctx context.Context) ([]*appsv1.Repository, error) { +func (db *db) ListRepositories(ctx context.Context) ([]*v1alpha1.Repository, error) { return db.listRepositories(ctx, nil, false) } -func (db *db) ListWriteRepositories(ctx context.Context) ([]*appsv1.Repository, error) { +func (db *db) ListWriteRepositories(ctx context.Context) ([]*v1alpha1.Repository, error) { return db.listRepositories(ctx, nil, true) } -func (db *db) listRepositories(ctx context.Context, repoType *string, writeCreds bool) ([]*appsv1.Repository, error) { +func (db *db) listRepositories(ctx context.Context, repoType *string, writeCreds bool) ([]*v1alpha1.Repository, error) { // TODO It would be nice to check for duplicates between secret and legacy repositories and make it so that // repositories from secrets overlay repositories from legacys. - var repositories []*appv1.Repository + var repositories []*v1alpha1.Repository if writeCreds { var err error repositories, err = db.repoWriteBackend().ListRepositories(ctx, repoType) @@ -231,7 +230,7 @@ func (db *db) listRepositories(ctx context.Context, repoType *string, writeCreds } // UpdateRepository updates a repository -func (db *db) UpdateRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) { +func (db *db) UpdateRepository(ctx context.Context, r *v1alpha1.Repository) (*v1alpha1.Repository, error) { secretsBackend := db.repoBackend() exists, err := secretsBackend.RepositoryExists(ctx, r.Repo, r.Project, false) if err != nil { @@ -251,7 +250,7 @@ func (db *db) UpdateRepository(ctx context.Context, r *appsv1.Repository) (*apps return nil, status.Errorf(codes.NotFound, "repo '%s' not found", r.Repo) } -func (db *db) UpdateWriteRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) { +func (db *db) UpdateWriteRepository(ctx context.Context, r *v1alpha1.Repository) (*v1alpha1.Repository, error) { secretBackend := db.repoWriteBackend() exists, err := secretBackend.RepositoryExists(ctx, r.Repo, r.Project, false) if err != nil { @@ -327,7 +326,7 @@ func (db *db) ListWriteRepositoryCredentials(ctx context.Context) ([]string, err } // GetRepositoryCredentials retrieves a repository credential set -func (db *db) GetRepositoryCredentials(ctx context.Context, repoURL string) (*appsv1.RepoCreds, error) { +func (db *db) GetRepositoryCredentials(ctx context.Context, repoURL string) (*v1alpha1.RepoCreds, error) { secretsBackend := db.repoBackend() exists, err := secretsBackend.RepoCredsExists(ctx, repoURL) if err != nil { @@ -356,7 +355,7 @@ func (db *db) GetRepositoryCredentials(ctx context.Context, repoURL string) (*ap } // GetWriteRepositoryCredentials retrieves a repository write credential set -func (db *db) GetWriteRepositoryCredentials(ctx context.Context, repoURL string) (*appsv1.RepoCreds, error) { +func (db *db) GetWriteRepositoryCredentials(ctx context.Context, repoURL string) (*v1alpha1.RepoCreds, error) { secretBackend := db.repoWriteBackend() exists, err := secretBackend.RepoCredsExists(ctx, repoURL) if err != nil { @@ -381,7 +380,7 @@ func (db *db) GetWriteRepositoryCredentials(ctx context.Context, repoURL string) } // GetAllHelmRepositoryCredentials retrieves all repository credentials -func (db *db) GetAllHelmRepositoryCredentials(ctx context.Context) ([]*appsv1.RepoCreds, error) { +func (db *db) GetAllHelmRepositoryCredentials(ctx context.Context) ([]*v1alpha1.RepoCreds, error) { // TODO It would be nice to check for duplicates between secret and legacy repositories and make it so that // repositories from secrets overlay repositories from legacys. @@ -399,7 +398,7 @@ func (db *db) GetAllHelmRepositoryCredentials(ctx context.Context) ([]*appsv1.Re } // CreateRepositoryCredentials creates a repository credential set -func (db *db) CreateRepositoryCredentials(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { +func (db *db) CreateRepositoryCredentials(ctx context.Context, r *v1alpha1.RepoCreds) (*v1alpha1.RepoCreds, error) { legacyBackend := db.legacyRepoBackend() secretBackend := db.repoBackend() @@ -420,7 +419,7 @@ func (db *db) CreateRepositoryCredentials(ctx context.Context, r *appsv1.RepoCre } // CreateWriteRepositoryCredentials creates a repository write credential set -func (db *db) CreateWriteRepositoryCredentials(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { +func (db *db) CreateWriteRepositoryCredentials(ctx context.Context, r *v1alpha1.RepoCreds) (*v1alpha1.RepoCreds, error) { secretBackend := db.repoWriteBackend() secretExists, err := secretBackend.RepoCredsExists(ctx, r.URL) if err != nil { @@ -435,7 +434,7 @@ func (db *db) CreateWriteRepositoryCredentials(ctx context.Context, r *appsv1.Re } // UpdateRepositoryCredentials updates a repository credential set -func (db *db) UpdateRepositoryCredentials(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { +func (db *db) UpdateRepositoryCredentials(ctx context.Context, r *v1alpha1.RepoCreds) (*v1alpha1.RepoCreds, error) { secretsBackend := db.repoBackend() exists, err := secretsBackend.RepoCredsExists(ctx, r.URL) if err != nil { @@ -456,7 +455,7 @@ func (db *db) UpdateRepositoryCredentials(ctx context.Context, r *appsv1.RepoCre } // UpdateWriteRepositoryCredentials updates a repository write credential set -func (db *db) UpdateWriteRepositoryCredentials(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { +func (db *db) UpdateWriteRepositoryCredentials(ctx context.Context, r *v1alpha1.RepoCreds) (*v1alpha1.RepoCreds, error) { secretBackend := db.repoWriteBackend() exists, err := secretBackend.RepoCredsExists(ctx, r.URL) if err != nil { @@ -505,7 +504,7 @@ func (db *db) DeleteWriteRepositoryCredentials(ctx context.Context, name string) return status.Errorf(codes.NotFound, "write repository credentials '%s' not found", name) } -func (db *db) enrichCredsToRepos(ctx context.Context, repositories []*appsv1.Repository) error { +func (db *db) enrichCredsToRepos(ctx context.Context, repositories []*v1alpha1.Repository) error { for _, repository := range repositories { if err := db.enrichCredsToRepo(ctx, repository); err != nil { return err @@ -526,7 +525,7 @@ func (db *db) legacyRepoBackend() repositoryBackend { return &legacyRepositoryBackend{db: db} } -func (db *db) enrichCredsToRepo(ctx context.Context, repository *appsv1.Repository) error { +func (db *db) enrichCredsToRepo(ctx context.Context, repository *v1alpha1.Repository) error { if !repository.HasCredentials() { creds, err := db.GetRepositoryCredentials(ctx, repository.Repo) if err == nil { diff --git a/util/localconfig/localconfig.go b/util/localconfig/localconfig.go index dc18ebedca796..ba1c8694d1366 100644 --- a/util/localconfig/localconfig.go +++ b/util/localconfig/localconfig.go @@ -10,7 +10,6 @@ import ( "github.com/golang-jwt/jwt/v5" "github.com/argoproj/argo-cd/v2/util/config" - configUtil "github.com/argoproj/argo-cd/v2/util/config" ) // LocalConfig is a local Argo CD config file @@ -80,7 +79,7 @@ func (u *User) Claims() (*jwt.RegisteredClaims, error) { // ReadLocalConfig loads up the local configuration file. Returns nil if config does not exist func ReadLocalConfig(path string) (*LocalConfig, error) { var err error - var config LocalConfig + var localconfig LocalConfig // check file permission only when argocd config exists if fi, err := os.Stat(path); err == nil { @@ -90,15 +89,15 @@ func ReadLocalConfig(path string) (*LocalConfig, error) { } } - err = configUtil.UnmarshalLocalFile(path, &config) + err = config.UnmarshalLocalFile(path, &localconfig) if os.IsNotExist(err) { return nil, nil } - err = ValidateLocalConfig(config) + err = ValidateLocalConfig(localconfig) if err != nil { return nil, err } - return &config, nil + return &localconfig, nil } func ValidateLocalConfig(config LocalConfig) error { @@ -112,12 +111,12 @@ func ValidateLocalConfig(config LocalConfig) error { } // WriteLocalConfig writes a new local configuration file. -func WriteLocalConfig(config LocalConfig, configPath string) error { +func WriteLocalConfig(localconfig LocalConfig, configPath string) error { err := os.MkdirAll(path.Dir(configPath), os.ModePerm) if err != nil { return err } - return configUtil.MarshalLocalYAMLFile(configPath, config) + return config.MarshalLocalYAMLFile(configPath, localconfig) } func DeleteLocalConfig(configPath string) error { From 10293889b7e0c1beaf8ab62b1fdf49a1c3082ced Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 6 Jan 2025 11:39:44 -0500 Subject: [PATCH 23/41] chore(deps): update dependency pygments to v2.19.0 (#21379) Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- docs/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/requirements.txt b/docs/requirements.txt index c60526537e65d..7f9d6ee45b224 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -3,7 +3,7 @@ mkdocs==1.6.1 # Thus pointing to the older version of mkdocs-material. mkdocs-material==7.1.8 markdown_include==0.8.1 -pygments==2.18.0 +pygments==2.19.0 jinja2==3.1.5 markdown==3.7 pymdown-extensions==10.13 \ No newline at end of file From cb3024c5ff33fdc393028ff27ebda021fb0de488 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Mon, 6 Jan 2025 17:41:38 +0100 Subject: [PATCH 24/41] chore: enable superfluous-else from revive (#21373) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 3 +- cmd/argocd-dex/commands/argocd_dex.go | 3 +- cmd/argocd/commands/admin/settings_rbac.go | 17 ++++----- cmd/argocd/commands/app.go | 42 +++++++++++----------- cmd/argocd/commands/cert.go | 3 +- cmd/argocd/commands/project.go | 21 +++++------ cmd/util/project.go | 20 +++++------ reposerver/gpgwatcher.go | 7 ++-- util/cli/cli.go | 3 +- util/git/client.go | 6 ++-- 10 files changed, 57 insertions(+), 68 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 54a58363ef87f..f1ea2c2676081 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -110,6 +110,7 @@ linters-settings: disabled: true # for better readability, the errors should be last in the list of returned values by a function. - name: error-return + disabled: false # for better readability, error messages should not be capitalized or end with punctuation or a newline. - name: error-strings disabled: true @@ -135,7 +136,7 @@ linters-settings: disabled: false # redundant else-blocks that can be eliminated from the code. - name: superfluous-else - disabled: true + disabled: false # prevent confusing name for variables when using `time` package - name: time-naming disabled: true diff --git a/cmd/argocd-dex/commands/argocd_dex.go b/cmd/argocd-dex/commands/argocd_dex.go index 5bdde7e572bdb..332e79b6af8a4 100644 --- a/cmd/argocd-dex/commands/argocd_dex.go +++ b/cmd/argocd-dex/commands/argocd_dex.go @@ -136,9 +136,8 @@ func NewRunDexCommand() *cobra.Command { errors.CheckError(err) } break - } else { - log.Infof("dex config unmodified") } + log.Infof("dex config unmodified") } } }, diff --git a/cmd/argocd/commands/admin/settings_rbac.go b/cmd/argocd/commands/admin/settings_rbac.go index b2d3ee2abd1e0..50246c22849f8 100644 --- a/cmd/argocd/commands/admin/settings_rbac.go +++ b/cmd/argocd/commands/admin/settings_rbac.go @@ -248,12 +248,11 @@ argocd admin settings rbac can someuser create application 'default/app' --defau fmt.Println("Yes") } os.Exit(0) - } else { - if !quiet { - fmt.Println("No") - } - os.Exit(1) } + if !quiet { + fmt.Println("No") + } + os.Exit(1) }, } clientConfig = cli.AddKubectlFlagsToCmd(command) @@ -321,13 +320,11 @@ argocd admin settings rbac validate --namespace argocd if err := rbac.ValidatePolicy(userPolicy); err == nil { fmt.Printf("Policy is valid.\n") os.Exit(0) - } else { - fmt.Printf("Policy is invalid: %v\n", err) - os.Exit(1) } - } else { - log.Fatalf("Policy is empty or could not be loaded.") + fmt.Printf("Policy is invalid: %v\n", err) + os.Exit(1) } + log.Fatalf("Policy is empty or could not be loaded.") }, } clientConfig = cli.AddKubectlFlagsToCmd(command) diff --git a/cmd/argocd/commands/app.go b/cmd/argocd/commands/app.go index 9a4ca5c977dbd..127dc96240b4a 100644 --- a/cmd/argocd/commands/app.go +++ b/cmd/argocd/commands/app.go @@ -405,11 +405,11 @@ func NewApplicationGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Com if sourceName != "" { sourceNameToPosition := getSourceNameToPositionMap(app) - if pos, ok := sourceNameToPosition[sourceName]; !ok { + pos, ok := sourceNameToPosition[sourceName] + if !ok { log.Fatalf("Unknown source name '%s'", sourceName) - } else { - sourcePosition = int(pos) } + sourcePosition = int(pos) } // check for source position if --show-params is set @@ -840,11 +840,11 @@ func NewApplicationSetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Com if sourceName != "" { sourceNameToPosition := getSourceNameToPositionMap(app) - if pos, ok := sourceNameToPosition[sourceName]; !ok { + pos, ok := sourceNameToPosition[sourceName] + if !ok { log.Fatalf("Unknown source name '%s'", sourceName) - } else { - sourcePosition = int(pos) } + sourcePosition = int(pos) } if app.Spec.HasMultipleSources() { @@ -953,11 +953,11 @@ func NewApplicationUnsetCommand(clientOpts *argocdclient.ClientOptions) *cobra.C if sourceName != "" { sourceNameToPosition := getSourceNameToPositionMap(app) - if pos, ok := sourceNameToPosition[sourceName]; !ok { + pos, ok := sourceNameToPosition[sourceName] + if !ok { log.Fatalf("Unknown source name '%s'", sourceName) - } else { - sourcePosition = int(pos) } + sourcePosition = int(pos) } if app.Spec.HasMultipleSources() { @@ -1271,11 +1271,11 @@ func NewApplicationDiffCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co sourceNameToPosition := getSourceNameToPositionMap(app) for _, name := range sourceNames { - if pos, ok := sourceNameToPosition[name]; !ok { + pos, ok := sourceNameToPosition[name] + if !ok { log.Fatalf("Unknown source name '%s'", name) - } else { - sourcePositions = append(sourcePositions, pos) } + sourcePositions = append(sourcePositions, pos) } } @@ -2033,11 +2033,11 @@ func NewApplicationSyncCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co sourceNameToPosition := getSourceNameToPositionMap(app) for _, name := range sourceNames { - if pos, ok := sourceNameToPosition[name]; !ok { + pos, ok := sourceNameToPosition[name] + if !ok { log.Fatalf("Unknown source name '%s'", name) - } else { - sourcePositions = append(sourcePositions, pos) } + sourcePositions = append(sourcePositions, pos) } } @@ -3004,11 +3004,11 @@ func NewApplicationManifestsCommand(clientOpts *argocdclient.ClientOptions) *cob sourceNameToPosition := getSourceNameToPositionMap(app) for _, name := range sourceNames { - if pos, ok := sourceNameToPosition[name]; !ok { + pos, ok := sourceNameToPosition[name] + if !ok { log.Fatalf("Unknown source name '%s'", name) - } else { - sourcePositions = append(sourcePositions, pos) } + sourcePositions = append(sourcePositions, pos) } } @@ -3339,11 +3339,11 @@ func NewApplicationRemoveSourceCommand(clientOpts *argocdclient.ClientOptions) * if sourceName != "" { sourceNameToPosition := getSourceNameToPositionMap(app) - if pos, ok := sourceNameToPosition[sourceName]; !ok { + pos, ok := sourceNameToPosition[sourceName] + if !ok { log.Fatalf("Unknown source name '%s'", sourceName) - } else { - sourcePosition = int(pos) } + sourcePosition = int(pos) } if !app.Spec.HasMultipleSources() { diff --git a/cmd/argocd/commands/cert.go b/cmd/argocd/commands/cert.go index e20243d55c141..45c78a04830ba 100644 --- a/cmd/argocd/commands/cert.go +++ b/cmd/argocd/commands/cert.go @@ -106,9 +106,8 @@ func NewCertAddTLSCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command if subjectMap[x509cert.Subject.String()] != nil { fmt.Printf("ERROR: Cert with subject '%s' already seen in the input stream.\n", x509cert.Subject.String()) continue - } else { - subjectMap[x509cert.Subject.String()] = x509cert } + subjectMap[x509cert.Subject.String()] = x509cert } serverName := args[0] diff --git a/cmd/argocd/commands/project.go b/cmd/argocd/commands/project.go index 2eaa156414c10..ae1f1365d1d31 100644 --- a/cmd/argocd/commands/project.go +++ b/cmd/argocd/commands/project.go @@ -254,11 +254,10 @@ func NewProjectRemoveSignatureKeyCommand(clientOpts *argocdclient.ClientOptions) } if index == -1 { log.Fatal("Specified signature key is not configured for project") - } else { - proj.Spec.SignatureKeys = append(proj.Spec.SignatureKeys[:index], proj.Spec.SignatureKeys[index+1:]...) - _, err = projIf.Update(ctx, &projectpkg.ProjectUpdateRequest{Project: proj}) - errors.CheckError(err) } + proj.Spec.SignatureKeys = append(proj.Spec.SignatureKeys[:index], proj.Spec.SignatureKeys[index+1:]...) + _, err = projIf.Update(ctx, &projectpkg.ProjectUpdateRequest{Project: proj}) + errors.CheckError(err) }, } @@ -352,11 +351,10 @@ func NewProjectRemoveDestinationCommand(clientOpts *argocdclient.ClientOptions) } if index == -1 { log.Fatal("Specified destination does not exist in project") - } else { - proj.Spec.Destinations = append(proj.Spec.Destinations[:index], proj.Spec.Destinations[index+1:]...) - _, err = projIf.Update(ctx, &projectpkg.ProjectUpdateRequest{Project: proj}) - errors.CheckError(err) } + proj.Spec.Destinations = append(proj.Spec.Destinations[:index], proj.Spec.Destinations[index+1:]...) + _, err = projIf.Update(ctx, &projectpkg.ProjectUpdateRequest{Project: proj}) + errors.CheckError(err) }, } @@ -456,11 +454,10 @@ func NewProjectRemoveOrphanedIgnoreCommand(clientOpts *argocdclient.ClientOption } if index == -1 { log.Fatal("Specified resource does not exist in the orphaned ignore of project") - } else { - proj.Spec.OrphanedResources.Ignore = append(proj.Spec.OrphanedResources.Ignore[:index], proj.Spec.OrphanedResources.Ignore[index+1:]...) - _, err = projIf.Update(ctx, &projectpkg.ProjectUpdateRequest{Project: proj}) - errors.CheckError(err) } + proj.Spec.OrphanedResources.Ignore = append(proj.Spec.OrphanedResources.Ignore[:index], proj.Spec.OrphanedResources.Ignore[index+1:]...) + _, err = projIf.Update(ctx, &projectpkg.ProjectUpdateRequest{Project: proj}) + errors.CheckError(err) }, } command.Flags().StringVar(&name, "name", "", "Resource name pattern") diff --git a/cmd/util/project.go b/cmd/util/project.go index 82e6b14a542bf..d54db89ad35ee 100644 --- a/cmd/util/project.go +++ b/cmd/util/project.go @@ -86,12 +86,11 @@ func (opts *ProjectOpts) GetDestinations() []v1alpha1.ApplicationDestination { parts := strings.Split(destStr, ",") if len(parts) != 2 { log.Fatalf("Expected destination of the form: server,namespace. Received: %s", destStr) - } else { - destinations = append(destinations, v1alpha1.ApplicationDestination{ - Server: parts[0], - Namespace: parts[1], - }) } + destinations = append(destinations, v1alpha1.ApplicationDestination{ + Server: parts[0], + Namespace: parts[1], + }) } return destinations } @@ -102,13 +101,12 @@ func (opts *ProjectOpts) GetDestinationServiceAccounts() []v1alpha1.ApplicationD parts := strings.Split(destStr, ",") if len(parts) != 3 { log.Fatalf("Expected destination service account of the form: server,namespace, defaultServiceAccount. Received: %s", destStr) - } else { - destinationServiceAccounts = append(destinationServiceAccounts, v1alpha1.ApplicationDestinationServiceAccount{ - Server: parts[0], - Namespace: parts[1], - DefaultServiceAccount: parts[2], - }) } + destinationServiceAccounts = append(destinationServiceAccounts, v1alpha1.ApplicationDestinationServiceAccount{ + Server: parts[0], + Namespace: parts[1], + DefaultServiceAccount: parts[2], + }) } return destinationServiceAccounts } diff --git a/reposerver/gpgwatcher.go b/reposerver/gpgwatcher.go index 35495c36086c3..e23ffb728a295 100644 --- a/reposerver/gpgwatcher.go +++ b/reposerver/gpgwatcher.go @@ -51,11 +51,10 @@ func StartGPGWatcher(sourcePath string) error { log.Infof("Retrying to re-create watcher, attempt %d of %d", attempt, maxRecreateRetries) time.Sleep(1 * time.Second) continue - } else { - log.Errorf("Maximum retries exceeded.") - close(done) - return } + log.Errorf("Maximum retries exceeded.") + close(done) + return } break } diff --git a/util/cli/cli.go b/util/cli/cli.go index 1a6383d2e93ba..d1e8492ec4bfc 100644 --- a/util/cli/cli.go +++ b/util/cli/cli.go @@ -279,9 +279,8 @@ func InteractiveEdit(filePattern string, data []byte, save func(input []byte) er if string(updated) == "" || string(updated) == string(data) { errors.CheckError(stderrors.New("edit cancelled, no valid changes were saved")) break - } else { - data = stripComments(updated) } + data = stripComments(updated) err = save(data) if err == nil { diff --git a/util/git/client.go b/util/git/client.go index f45be86bffde9..300646e22cfcb 100644 --- a/util/git/client.go +++ b/util/git/client.go @@ -137,11 +137,11 @@ var ( func init() { if countStr := os.Getenv(common.EnvGitAttemptsCount); countStr != "" { - if cnt, err := strconv.Atoi(countStr); err != nil { + cnt, err := strconv.Atoi(countStr) + if err != nil { panic(fmt.Sprintf("Invalid value in %s env variable: %v", common.EnvGitAttemptsCount, err)) - } else { - maxAttemptsCount = int(math.Max(float64(cnt), 1)) } + maxAttemptsCount = int(math.Max(float64(cnt), 1)) } maxRetryDuration = env.ParseDurationFromEnv(common.EnvGitRetryMaxDuration, common.DefaultGitRetryMaxDuration, 0, math.MaxInt64) From 9cc52247c429e686039ca6a1f48560ce90f786fc Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 6 Jan 2025 13:45:26 -0500 Subject: [PATCH 25/41] chore(deps): update dependency pygments to v2.19.1 (#21392) Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- docs/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/requirements.txt b/docs/requirements.txt index 7f9d6ee45b224..f6b11bb0a0a31 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -3,7 +3,7 @@ mkdocs==1.6.1 # Thus pointing to the older version of mkdocs-material. mkdocs-material==7.1.8 markdown_include==0.8.1 -pygments==2.19.0 +pygments==2.19.1 jinja2==3.1.5 markdown==3.7 pymdown-extensions==10.13 \ No newline at end of file From b4912cf3401c8de4c7a3afe351e031ca228a5d93 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 6 Jan 2025 13:45:59 -0500 Subject: [PATCH 26/41] [Bot] docs: Update Snyk reports (#21376) Signed-off-by: CI Co-authored-by: CI --- docs/snyk/index.md | 60 +- docs/snyk/master/argocd-iac-install.html | 2 +- .../master/argocd-iac-namespace-install.html | 2 +- docs/snyk/master/argocd-test.html | 4 +- .../master/ghcr.io_dexidp_dex_v2.41.1.html | 2 +- ..._docker_library_haproxy_2.6.17-alpine.html | 2 +- ...ws_docker_library_redis_7.0.15-alpine.html | 2 +- .../quay.io_argoproj_argocd_latest.html | 4 +- docs/snyk/master/redis_7.0.15-alpine.html | 2 +- docs/snyk/v2.11.12/argocd-iac-install.html | 2 +- .../argocd-iac-namespace-install.html | 2 +- docs/snyk/v2.11.12/argocd-test.html | 2 +- .../v2.11.12/ghcr.io_dexidp_dex_v2.38.0.html | 2 +- docs/snyk/v2.11.12/haproxy_2.6.14-alpine.html | 2 +- .../quay.io_argoproj_argocd_v2.11.12.html | 2 +- docs/snyk/v2.11.12/redis_7.0.15-alpine.html | 2 +- .../argocd-iac-install.html | 2 +- .../argocd-iac-namespace-install.html | 2 +- .../{v2.12.8 => v2.12.9}/argocd-test.html | 2 +- .../ghcr.io_dexidp_dex_v2.38.0.html | 2 +- ..._docker_library_haproxy_2.6.17-alpine.html | 2 +- ...ws_docker_library_redis_7.0.15-alpine.html | 2 +- .../quay.io_argoproj_argocd_v2.12.9.html} | 530 +++++++++-------- .../redis_7.0.15-alpine.html | 2 +- .../argocd-iac-install.html | 2 +- .../argocd-iac-namespace-install.html | 2 +- .../{v2.13.2 => v2.13.3}/argocd-test.html | 2 +- .../ghcr.io_dexidp_dex_v2.41.1.html | 2 +- ..._docker_library_haproxy_2.6.17-alpine.html | 2 +- ...ws_docker_library_redis_7.0.15-alpine.html | 2 +- .../quay.io_argoproj_argocd_v2.13.3.html} | 536 ++++++------------ .../redis_7.0.15-alpine.html | 2 +- .../argocd-iac-install.html | 2 +- .../argocd-iac-namespace-install.html | 2 +- .../argocd-test.html | 2 +- .../ghcr.io_dexidp_dex_v2.41.1.html | 2 +- ..._docker_library_haproxy_2.6.17-alpine.html | 2 +- ...ws_docker_library_redis_7.0.15-alpine.html | 2 +- .../quay.io_argoproj_argocd_v2.14.0-rc3.html | 2 +- .../redis_7.0.15-alpine.html | 2 +- 40 files changed, 522 insertions(+), 682 deletions(-) rename docs/snyk/{v2.12.8 => v2.12.9}/argocd-iac-install.html (99%) rename docs/snyk/{v2.12.8 => v2.12.9}/argocd-iac-namespace-install.html (99%) rename docs/snyk/{v2.12.8 => v2.12.9}/argocd-test.html (99%) rename docs/snyk/{v2.12.8 => v2.12.9}/ghcr.io_dexidp_dex_v2.38.0.html (99%) rename docs/snyk/{v2.14.0-rc3 => v2.12.9}/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html (99%) rename docs/snyk/{v2.12.8 => v2.12.9}/public.ecr.aws_docker_library_redis_7.0.15-alpine.html (99%) rename docs/snyk/{v2.13.2/quay.io_argoproj_argocd_v2.13.2.html => v2.12.9/quay.io_argoproj_argocd_v2.12.9.html} (94%) rename docs/snyk/{v2.14.0-rc3 => v2.12.9}/redis_7.0.15-alpine.html (99%) rename docs/snyk/{v2.13.2 => v2.13.3}/argocd-iac-install.html (99%) rename docs/snyk/{v2.13.2 => v2.13.3}/argocd-iac-namespace-install.html (99%) rename docs/snyk/{v2.13.2 => v2.13.3}/argocd-test.html (99%) rename docs/snyk/{v2.13.2 => v2.13.3}/ghcr.io_dexidp_dex_v2.41.1.html (99%) rename docs/snyk/{v2.13.2 => v2.13.3}/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html (99%) rename docs/snyk/{v2.14.0-rc3 => v2.13.3}/public.ecr.aws_docker_library_redis_7.0.15-alpine.html (99%) rename docs/snyk/{v2.12.8/quay.io_argoproj_argocd_v2.12.8.html => v2.13.3/quay.io_argoproj_argocd_v2.13.3.html} (91%) rename docs/snyk/{v2.12.8 => v2.13.3}/redis_7.0.15-alpine.html (99%) rename docs/snyk/{v2.14.0-rc3 => v2.14.0-rc4}/argocd-iac-install.html (99%) rename docs/snyk/{v2.14.0-rc3 => v2.14.0-rc4}/argocd-iac-namespace-install.html (99%) rename docs/snyk/{v2.14.0-rc3 => v2.14.0-rc4}/argocd-test.html (99%) rename docs/snyk/{v2.14.0-rc3 => v2.14.0-rc4}/ghcr.io_dexidp_dex_v2.41.1.html (99%) rename docs/snyk/{v2.12.8 => v2.14.0-rc4}/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html (99%) rename docs/snyk/{v2.13.2 => v2.14.0-rc4}/public.ecr.aws_docker_library_redis_7.0.15-alpine.html (99%) rename docs/snyk/{v2.14.0-rc3 => v2.14.0-rc4}/quay.io_argoproj_argocd_v2.14.0-rc3.html (99%) rename docs/snyk/{v2.13.2 => v2.14.0-rc4}/redis_7.0.15-alpine.html (99%) diff --git a/docs/snyk/index.md b/docs/snyk/index.md index 2af9868187af5..4d68ab3c20018 100644 --- a/docs/snyk/index.md +++ b/docs/snyk/index.md @@ -23,47 +23,47 @@ recent minor releases. | [install.yaml](master/argocd-iac-install.html) | - | - | - | - | | [namespace-install.yaml](master/argocd-iac-namespace-install.html) | - | - | - | - | -### v2.14.0-rc3 +### v2.14.0-rc4 | | Critical | High | Medium | Low | |---:|:--------:|:----:|:------:|:---:| -| [go.mod](v2.14.0-rc3/argocd-test.html) | 0 | 1 | 6 | 0 | -| [ui/yarn.lock](v2.14.0-rc3/argocd-test.html) | 0 | 0 | 1 | 0 | -| [dex:v2.41.1](v2.14.0-rc3/ghcr.io_dexidp_dex_v2.41.1.html) | 0 | 0 | 0 | 2 | -| [haproxy:2.6.17-alpine](v2.14.0-rc3/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html) | 0 | 0 | 2 | 4 | -| [redis:7.0.15-alpine](v2.14.0-rc3/public.ecr.aws_docker_library_redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | -| [argocd:v2.14.0-rc3](v2.14.0-rc3/quay.io_argoproj_argocd_v2.14.0-rc3.html) | 0 | 0 | 3 | 10 | -| [redis:7.0.15-alpine](v2.14.0-rc3/redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | -| [install.yaml](v2.14.0-rc3/argocd-iac-install.html) | - | - | - | - | -| [namespace-install.yaml](v2.14.0-rc3/argocd-iac-namespace-install.html) | - | - | - | - | +| [go.mod](v2.14.0-rc4/argocd-test.html) | 0 | 1 | 6 | 0 | +| [ui/yarn.lock](v2.14.0-rc4/argocd-test.html) | 0 | 0 | 1 | 0 | +| [dex:v2.41.1](v2.14.0-rc4/ghcr.io_dexidp_dex_v2.41.1.html) | 0 | 0 | 0 | 2 | +| [haproxy:2.6.17-alpine](v2.14.0-rc4/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html) | 0 | 0 | 2 | 4 | +| [redis:7.0.15-alpine](v2.14.0-rc4/public.ecr.aws_docker_library_redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | +| [argocd:v2.14.0-rc3](v2.14.0-rc4/quay.io_argoproj_argocd_v2.14.0-rc3.html) | 0 | 0 | 3 | 10 | +| [redis:7.0.15-alpine](v2.14.0-rc4/redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | +| [install.yaml](v2.14.0-rc4/argocd-iac-install.html) | - | - | - | - | +| [namespace-install.yaml](v2.14.0-rc4/argocd-iac-namespace-install.html) | - | - | - | - | -### v2.13.2 +### v2.13.3 | | Critical | High | Medium | Low | |---:|:--------:|:----:|:------:|:---:| -| [go.mod](v2.13.2/argocd-test.html) | 1 | 1 | 7 | 2 | -| [ui/yarn.lock](v2.13.2/argocd-test.html) | 0 | 0 | 1 | 0 | -| [dex:v2.41.1](v2.13.2/ghcr.io_dexidp_dex_v2.41.1.html) | 0 | 0 | 0 | 2 | -| [haproxy:2.6.17-alpine](v2.13.2/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html) | 0 | 0 | 2 | 4 | -| [redis:7.0.15-alpine](v2.13.2/public.ecr.aws_docker_library_redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | -| [argocd:v2.13.2](v2.13.2/quay.io_argoproj_argocd_v2.13.2.html) | 0 | 0 | 3 | 11 | -| [redis:7.0.15-alpine](v2.13.2/redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | -| [install.yaml](v2.13.2/argocd-iac-install.html) | - | - | - | - | -| [namespace-install.yaml](v2.13.2/argocd-iac-namespace-install.html) | - | - | - | - | +| [go.mod](v2.13.3/argocd-test.html) | 1 | 1 | 7 | 2 | +| [ui/yarn.lock](v2.13.3/argocd-test.html) | 0 | 0 | 1 | 0 | +| [dex:v2.41.1](v2.13.3/ghcr.io_dexidp_dex_v2.41.1.html) | 0 | 0 | 0 | 2 | +| [haproxy:2.6.17-alpine](v2.13.3/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html) | 0 | 0 | 2 | 4 | +| [redis:7.0.15-alpine](v2.13.3/public.ecr.aws_docker_library_redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | +| [argocd:v2.13.3](v2.13.3/quay.io_argoproj_argocd_v2.13.3.html) | 0 | 0 | 3 | 10 | +| [redis:7.0.15-alpine](v2.13.3/redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | +| [install.yaml](v2.13.3/argocd-iac-install.html) | - | - | - | - | +| [namespace-install.yaml](v2.13.3/argocd-iac-namespace-install.html) | - | - | - | - | -### v2.12.8 +### v2.12.9 | | Critical | High | Medium | Low | |---:|:--------:|:----:|:------:|:---:| -| [go.mod](v2.12.8/argocd-test.html) | 1 | 1 | 8 | 2 | -| [ui/yarn.lock](v2.12.8/argocd-test.html) | 0 | 0 | 1 | 0 | -| [dex:v2.38.0](v2.12.8/ghcr.io_dexidp_dex_v2.38.0.html) | 0 | 0 | 6 | 7 | -| [haproxy:2.6.17-alpine](v2.12.8/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html) | 0 | 0 | 2 | 4 | -| [redis:7.0.15-alpine](v2.12.8/public.ecr.aws_docker_library_redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | -| [argocd:v2.12.8](v2.12.8/quay.io_argoproj_argocd_v2.12.8.html) | 0 | 0 | 3 | 11 | -| [redis:7.0.15-alpine](v2.12.8/redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | -| [install.yaml](v2.12.8/argocd-iac-install.html) | - | - | - | - | -| [namespace-install.yaml](v2.12.8/argocd-iac-namespace-install.html) | - | - | - | - | +| [go.mod](v2.12.9/argocd-test.html) | 1 | 1 | 8 | 2 | +| [ui/yarn.lock](v2.12.9/argocd-test.html) | 0 | 0 | 1 | 0 | +| [dex:v2.38.0](v2.12.9/ghcr.io_dexidp_dex_v2.38.0.html) | 0 | 0 | 6 | 7 | +| [haproxy:2.6.17-alpine](v2.12.9/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html) | 0 | 0 | 2 | 4 | +| [redis:7.0.15-alpine](v2.12.9/public.ecr.aws_docker_library_redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | +| [argocd:v2.12.9](v2.12.9/quay.io_argoproj_argocd_v2.12.9.html) | 0 | 0 | 3 | 10 | +| [redis:7.0.15-alpine](v2.12.9/redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 | +| [install.yaml](v2.12.9/argocd-iac-install.html) | - | - | - | - | +| [namespace-install.yaml](v2.12.9/argocd-iac-namespace-install.html) | - | - | - | - | ### v2.11.12 diff --git a/docs/snyk/master/argocd-iac-install.html b/docs/snyk/master/argocd-iac-install.html index aa853964f37ff..bfaeaa3b36ca3 100644 --- a/docs/snyk/master/argocd-iac-install.html +++ b/docs/snyk/master/argocd-iac-install.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:22:07 am (UTC+00:00)

+

January 5th 2025, 12:21:50 am (UTC+00:00)

Scanned the following path: diff --git a/docs/snyk/master/argocd-iac-namespace-install.html b/docs/snyk/master/argocd-iac-namespace-install.html index d57dbb3d6c294..16c3b535d27a4 100644 --- a/docs/snyk/master/argocd-iac-namespace-install.html +++ b/docs/snyk/master/argocd-iac-namespace-install.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:22:17 am (UTC+00:00)

+

January 5th 2025, 12:22:00 am (UTC+00:00)

Scanned the following path: diff --git a/docs/snyk/master/argocd-test.html b/docs/snyk/master/argocd-test.html index 7cc756cc31cdc..544f1dc269d9a 100644 --- a/docs/snyk/master/argocd-test.html +++ b/docs/snyk/master/argocd-test.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:19:49 am (UTC+00:00)

+

January 5th 2025, 12:19:32 am (UTC+00:00)

Scanned the following paths: @@ -470,7 +470,7 @@

Snyk test report

7 known vulnerabilities
26 vulnerable dependency paths
-
2160 dependencies
+
2165 dependencies
diff --git a/docs/snyk/master/ghcr.io_dexidp_dex_v2.41.1.html b/docs/snyk/master/ghcr.io_dexidp_dex_v2.41.1.html index 713eca422e775..6da14eb6d1cbe 100644 --- a/docs/snyk/master/ghcr.io_dexidp_dex_v2.41.1.html +++ b/docs/snyk/master/ghcr.io_dexidp_dex_v2.41.1.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:19:59 am (UTC+00:00)

+

January 5th 2025, 12:19:42 am (UTC+00:00)

Scanned the following paths: diff --git a/docs/snyk/master/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html b/docs/snyk/master/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html index 2d456122ca91a..eef2929d7e875 100644 --- a/docs/snyk/master/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html +++ b/docs/snyk/master/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:20:04 am (UTC+00:00)

+

January 5th 2025, 12:19:47 am (UTC+00:00)

Scanned the following path: diff --git a/docs/snyk/master/public.ecr.aws_docker_library_redis_7.0.15-alpine.html b/docs/snyk/master/public.ecr.aws_docker_library_redis_7.0.15-alpine.html index 6cc380085f4c5..083b9171e256f 100644 --- a/docs/snyk/master/public.ecr.aws_docker_library_redis_7.0.15-alpine.html +++ b/docs/snyk/master/public.ecr.aws_docker_library_redis_7.0.15-alpine.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:20:10 am (UTC+00:00)

+

January 5th 2025, 12:19:52 am (UTC+00:00)

Scanned the following paths: diff --git a/docs/snyk/master/quay.io_argoproj_argocd_latest.html b/docs/snyk/master/quay.io_argoproj_argocd_latest.html index 42171a8b4d685..6341351596ac8 100644 --- a/docs/snyk/master/quay.io_argoproj_argocd_latest.html +++ b/docs/snyk/master/quay.io_argoproj_argocd_latest.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:20:31 am (UTC+00:00)

+

January 5th 2025, 12:20:11 am (UTC+00:00)

Scanned the following paths: @@ -472,7 +472,7 @@

Snyk test report

21 known vulnerabilities
101 vulnerable dependency paths
-
2383 dependencies
+
2384 dependencies
diff --git a/docs/snyk/master/redis_7.0.15-alpine.html b/docs/snyk/master/redis_7.0.15-alpine.html index bfd4c58179882..78fa1b438c41a 100644 --- a/docs/snyk/master/redis_7.0.15-alpine.html +++ b/docs/snyk/master/redis_7.0.15-alpine.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:20:35 am (UTC+00:00)

+

January 5th 2025, 12:20:17 am (UTC+00:00)

Scanned the following paths: diff --git a/docs/snyk/v2.11.12/argocd-iac-install.html b/docs/snyk/v2.11.12/argocd-iac-install.html index 7e92802a99ec8..a44daffe33933 100644 --- a/docs/snyk/v2.11.12/argocd-iac-install.html +++ b/docs/snyk/v2.11.12/argocd-iac-install.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:32:09 am (UTC+00:00)

+

January 5th 2025, 12:31:48 am (UTC+00:00)

Scanned the following path: diff --git a/docs/snyk/v2.11.12/argocd-iac-namespace-install.html b/docs/snyk/v2.11.12/argocd-iac-namespace-install.html index fbae0b8f1ad74..1c5aed9eaa1e6 100644 --- a/docs/snyk/v2.11.12/argocd-iac-namespace-install.html +++ b/docs/snyk/v2.11.12/argocd-iac-namespace-install.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:32:19 am (UTC+00:00)

+

January 5th 2025, 12:31:57 am (UTC+00:00)

Scanned the following path: diff --git a/docs/snyk/v2.11.12/argocd-test.html b/docs/snyk/v2.11.12/argocd-test.html index 12cee0b9d03d4..76c25aceac19a 100644 --- a/docs/snyk/v2.11.12/argocd-test.html +++ b/docs/snyk/v2.11.12/argocd-test.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:30:07 am (UTC+00:00)

+

January 5th 2025, 12:29:46 am (UTC+00:00)

Scanned the following paths: diff --git a/docs/snyk/v2.11.12/ghcr.io_dexidp_dex_v2.38.0.html b/docs/snyk/v2.11.12/ghcr.io_dexidp_dex_v2.38.0.html index d6452532a8855..ab9896dc14d0d 100644 --- a/docs/snyk/v2.11.12/ghcr.io_dexidp_dex_v2.38.0.html +++ b/docs/snyk/v2.11.12/ghcr.io_dexidp_dex_v2.38.0.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:30:15 am (UTC+00:00)

+

January 5th 2025, 12:29:55 am (UTC+00:00)

Scanned the following paths: diff --git a/docs/snyk/v2.11.12/haproxy_2.6.14-alpine.html b/docs/snyk/v2.11.12/haproxy_2.6.14-alpine.html index baef06587e278..0c545c2f35452 100644 --- a/docs/snyk/v2.11.12/haproxy_2.6.14-alpine.html +++ b/docs/snyk/v2.11.12/haproxy_2.6.14-alpine.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:30:21 am (UTC+00:00)

+

January 5th 2025, 12:29:59 am (UTC+00:00)

Scanned the following path: diff --git a/docs/snyk/v2.11.12/quay.io_argoproj_argocd_v2.11.12.html b/docs/snyk/v2.11.12/quay.io_argoproj_argocd_v2.11.12.html index f689807393f82..6c8bb9daaddbc 100644 --- a/docs/snyk/v2.11.12/quay.io_argoproj_argocd_v2.11.12.html +++ b/docs/snyk/v2.11.12/quay.io_argoproj_argocd_v2.11.12.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:30:41 am (UTC+00:00)

+

January 5th 2025, 12:30:23 am (UTC+00:00)

Scanned the following paths: diff --git a/docs/snyk/v2.11.12/redis_7.0.15-alpine.html b/docs/snyk/v2.11.12/redis_7.0.15-alpine.html index 1311f1b315443..d4e237e086214 100644 --- a/docs/snyk/v2.11.12/redis_7.0.15-alpine.html +++ b/docs/snyk/v2.11.12/redis_7.0.15-alpine.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:30:46 am (UTC+00:00)

+

January 5th 2025, 12:30:27 am (UTC+00:00)

Scanned the following paths: diff --git a/docs/snyk/v2.12.8/argocd-iac-install.html b/docs/snyk/v2.12.9/argocd-iac-install.html similarity index 99% rename from docs/snyk/v2.12.8/argocd-iac-install.html rename to docs/snyk/v2.12.9/argocd-iac-install.html index 42727ea03911f..879f002891810 100644 --- a/docs/snyk/v2.12.8/argocd-iac-install.html +++ b/docs/snyk/v2.12.9/argocd-iac-install.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:29:39 am (UTC+00:00)

+

January 5th 2025, 12:29:21 am (UTC+00:00)

Scanned the following path: diff --git a/docs/snyk/v2.12.8/argocd-iac-namespace-install.html b/docs/snyk/v2.12.9/argocd-iac-namespace-install.html similarity index 99% rename from docs/snyk/v2.12.8/argocd-iac-namespace-install.html rename to docs/snyk/v2.12.9/argocd-iac-namespace-install.html index ebf8158ad70ac..516a897c38e5a 100644 --- a/docs/snyk/v2.12.8/argocd-iac-namespace-install.html +++ b/docs/snyk/v2.12.9/argocd-iac-namespace-install.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:29:48 am (UTC+00:00)

+

January 5th 2025, 12:29:31 am (UTC+00:00)

Scanned the following path: diff --git a/docs/snyk/v2.12.8/argocd-test.html b/docs/snyk/v2.12.9/argocd-test.html similarity index 99% rename from docs/snyk/v2.12.8/argocd-test.html rename to docs/snyk/v2.12.9/argocd-test.html index d514945554a70..3e39e8a9ade67 100644 --- a/docs/snyk/v2.12.8/argocd-test.html +++ b/docs/snyk/v2.12.9/argocd-test.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:27:36 am (UTC+00:00)

+

January 5th 2025, 12:27:21 am (UTC+00:00)

Scanned the following paths: diff --git a/docs/snyk/v2.12.8/ghcr.io_dexidp_dex_v2.38.0.html b/docs/snyk/v2.12.9/ghcr.io_dexidp_dex_v2.38.0.html similarity index 99% rename from docs/snyk/v2.12.8/ghcr.io_dexidp_dex_v2.38.0.html rename to docs/snyk/v2.12.9/ghcr.io_dexidp_dex_v2.38.0.html index 4ac286e8a730e..899d59515b038 100644 --- a/docs/snyk/v2.12.8/ghcr.io_dexidp_dex_v2.38.0.html +++ b/docs/snyk/v2.12.9/ghcr.io_dexidp_dex_v2.38.0.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:27:44 am (UTC+00:00)

+

January 5th 2025, 12:27:28 am (UTC+00:00)

Scanned the following paths: diff --git a/docs/snyk/v2.14.0-rc3/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html b/docs/snyk/v2.12.9/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html similarity index 99% rename from docs/snyk/v2.14.0-rc3/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html rename to docs/snyk/v2.12.9/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html index 80520a7e17571..b7f843d978260 100644 --- a/docs/snyk/v2.14.0-rc3/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html +++ b/docs/snyk/v2.12.9/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:22:39 am (UTC+00:00)

+

January 5th 2025, 12:27:31 am (UTC+00:00)

Scanned the following path: diff --git a/docs/snyk/v2.12.8/public.ecr.aws_docker_library_redis_7.0.15-alpine.html b/docs/snyk/v2.12.9/public.ecr.aws_docker_library_redis_7.0.15-alpine.html similarity index 99% rename from docs/snyk/v2.12.8/public.ecr.aws_docker_library_redis_7.0.15-alpine.html rename to docs/snyk/v2.12.9/public.ecr.aws_docker_library_redis_7.0.15-alpine.html index 0e999d89a6aa9..663ea89de6912 100644 --- a/docs/snyk/v2.12.8/public.ecr.aws_docker_library_redis_7.0.15-alpine.html +++ b/docs/snyk/v2.12.9/public.ecr.aws_docker_library_redis_7.0.15-alpine.html @@ -456,7 +456,7 @@

Snyk test report

-

December 29th 2024, 12:27:52 am (UTC+00:00)

+

January 5th 2025, 12:27:35 am (UTC+00:00)

Scanned the following paths: diff --git a/docs/snyk/v2.13.2/quay.io_argoproj_argocd_v2.13.2.html b/docs/snyk/v2.12.9/quay.io_argoproj_argocd_v2.12.9.html similarity index 94% rename from docs/snyk/v2.13.2/quay.io_argoproj_argocd_v2.13.2.html rename to docs/snyk/v2.12.9/quay.io_argoproj_argocd_v2.12.9.html index 10a025ea00d8a..04ae9fcc92bad 100644 --- a/docs/snyk/v2.13.2/quay.io_argoproj_argocd_v2.13.2.html +++ b/docs/snyk/v2.12.9/quay.io_argoproj_argocd_v2.12.9.html @@ -456,23 +456,23 @@

Snyk test report

-

December 29th 2024, 12:25:36 am (UTC+00:00)

+

January 5th 2025, 12:27:53 am (UTC+00:00)

Scanned the following paths:
    -
  • quay.io/argoproj/argocd:v2.13.2/argoproj/argocd/Dockerfile (deb)
  • -
  • quay.io/argoproj/argocd:v2.13.2/argoproj/argo-cd/v2//usr/local/bin/argocd (gomodules)
  • -
  • quay.io/argoproj/argocd:v2.13.2//usr/local/bin/kustomize (gomodules)
  • -
  • quay.io/argoproj/argocd:v2.13.2/helm/v3//usr/local/bin/helm (gomodules)
  • -
  • quay.io/argoproj/argocd:v2.13.2/git-lfs/git-lfs//usr/bin/git-lfs (gomodules)
  • +
  • quay.io/argoproj/argocd:v2.12.9/argoproj/argocd/Dockerfile (deb)
  • +
  • quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2//usr/local/bin/argocd (gomodules)
  • +
  • quay.io/argoproj/argocd:v2.12.9//usr/local/bin/kustomize (gomodules)
  • +
  • quay.io/argoproj/argocd:v2.12.9/helm/v3//usr/local/bin/helm (gomodules)
  • +
  • quay.io/argoproj/argocd:v2.12.9/git-lfs/git-lfs//usr/bin/git-lfs (gomodules)
25 known vulnerabilities
106 vulnerable dependency paths
-
2354 dependencies
+
2292 dependencies
@@ -492,7 +492,7 @@

Incorrect Implementation of Authentication Algorithm

  • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2 › /usr/local/bin/argocd
  • Package Manager: golang @@ -505,7 +505,7 @@

    Incorrect Implementation of Authentication Algorithm

    Introduced through: - github.com/argoproj/argo-cd/v2@* and golang.org/x/crypto/ssh@v0.27.0 + github.com/argoproj/argo-cd/v2@* and golang.org/x/crypto/ssh@v0.23.0
  • @@ -520,7 +520,7 @@

    Detailed paths

    Introduced through: github.com/argoproj/argo-cd/v2@* › - golang.org/x/crypto/ssh@v0.27.0 + golang.org/x/crypto/ssh@v0.23.0 @@ -566,7 +566,7 @@

    Denial of Service (DoS)

    • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2 › /usr/local/bin/argocd
    • Package Manager: golang @@ -579,7 +579,7 @@

      Denial of Service (DoS)

    • Introduced through: - github.com/argoproj/argo-cd/v2@* and golang.org/x/net/html@v0.29.0 + github.com/argoproj/argo-cd/v2@* and golang.org/x/net/html@v0.25.0
    @@ -594,7 +594,7 @@

    Detailed paths

    Introduced through: github.com/argoproj/argo-cd/v2@* › - golang.org/x/net/html@v0.29.0 + golang.org/x/net/html@v0.25.0 @@ -658,7 +658,7 @@

    Insecure Storage of Sensitive Information

    • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
    • Package Manager: ubuntu:24.04 @@ -671,7 +671,7 @@

      Insecure Storage of Sensitive Information

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 and pam/libpam0g@1.5.3-5ubuntu5.1 + docker-image|quay.io/argoproj/argocd@v2.12.9 and pam/libpam0g@1.5.3-5ubuntu5.1
    @@ -684,7 +684,7 @@

    Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › pam/libpam0g@1.5.3-5ubuntu5.1 @@ -693,7 +693,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -704,7 +704,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › util-linux@2.39.3-9ubuntu6.1 › @@ -715,7 +715,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -730,7 +730,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -747,7 +747,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -766,7 +766,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › pam/libpam-modules-bin@1.5.3-5ubuntu5.1 @@ -775,7 +775,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -792,7 +792,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › pam/libpam-modules@1.5.3-5ubuntu5.1 @@ -801,7 +801,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › pam/libpam-runtime@1.5.3-5ubuntu5.1 › @@ -812,7 +812,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -823,7 +823,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -838,7 +838,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › pam/libpam-runtime@1.5.3-5ubuntu5.1 @@ -847,7 +847,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -897,7 +897,7 @@

      Improper Authentication

      • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
      • Package Manager: ubuntu:24.04 @@ -910,7 +910,7 @@

        Improper Authentication

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 and pam/libpam0g@1.5.3-5ubuntu5.1 + docker-image|quay.io/argoproj/argocd@v2.12.9 and pam/libpam0g@1.5.3-5ubuntu5.1
      @@ -923,7 +923,7 @@

      Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › pam/libpam0g@1.5.3-5ubuntu5.1 @@ -932,7 +932,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -943,7 +943,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › util-linux@2.39.3-9ubuntu6.1 › @@ -954,7 +954,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -969,7 +969,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -986,7 +986,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -1005,7 +1005,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › pam/libpam-modules-bin@1.5.3-5ubuntu5.1 @@ -1014,7 +1014,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -1031,7 +1031,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › pam/libpam-modules@1.5.3-5ubuntu5.1 @@ -1040,7 +1040,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › pam/libpam-runtime@1.5.3-5ubuntu5.1 › @@ -1051,7 +1051,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -1062,7 +1062,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -1077,7 +1077,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › pam/libpam-runtime@1.5.3-5ubuntu5.1 @@ -1086,7 +1086,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -1133,7 +1133,7 @@

        CVE-2024-26462

        • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
        • Package Manager: ubuntu:24.04 @@ -1147,7 +1147,7 @@

          CVE-2024-26462

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2, git@1:2.43.0-1ubuntu7.1 and others + docker-image|quay.io/argoproj/argocd@v2.12.9, git@1:2.43.0-1ubuntu7.1 and others
        @@ -1159,11 +1159,11 @@

        Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1174,11 +1174,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1191,11 +1191,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1206,11 +1206,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1223,11 +1223,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1242,11 +1242,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1257,7 +1257,7 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › openssh/openssh-client@1:9.6p1-3ubuntu13.5 › @@ -1268,11 +1268,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 @@ -1281,11 +1281,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › libssh/libssh-4@0.10.6-2build2 › @@ -1296,7 +1296,7 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › krb5/krb5-locales@1.20.1-6ubuntu2.2 @@ -1341,7 +1341,7 @@

          LGPL-3.0 license

          • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2 › /usr/local/bin/argocd
          • Package Manager: golang @@ -1388,6 +1388,116 @@

            Detailed paths

            More about this vulnerability

    +
    +
    +

    Denial of Service (DoS)

    +
    + +
    + medium severity +
    + +
    + +
      +
    • + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2 › /usr/local/bin/argocd +
    • +
    • + Package Manager: golang +
    • +
    • + Vulnerable module: + + github.com/rs/cors +
    • + +
    • Introduced through: + + github.com/argoproj/argo-cd/v2@* and github.com/rs/cors@v1.9.0 + +
    • +
    + +
    + + +

    Detailed paths

    + +
      +
    • + Introduced through: + github.com/argoproj/argo-cd/v2@* + › + github.com/rs/cors@v1.9.0 + + + +
    • +
    + +
    + +
    + +

    Overview

    +

    Affected versions of this package are vulnerable to Denial of Service (DoS) through the processing of malicious preflight requests that include a Access-Control-Request-Headers header with excessive commas. An attacker can induce excessive memory consumption and potentially crash the server by sending specially crafted requests.

    +

    PoC

    +
    
    +        func BenchmarkPreflightAdversarialACRH(b *testing.B) {
    +            resps := makeFakeResponses(b.N)
    +            req, _ := http.NewRequest(http.MethodOptions, dummyEndpoint, nil)
    +            req.Header.Add(headerOrigin, dummyOrigin)
    +            req.Header.Add(headerACRM, http.MethodGet)
    +            req.Header[headerACRH] = adversarialACRH
    +            handler := Default().Handler(testHandler)
    +        
    +            b.ReportAllocs()
    +            b.ResetTimer()
    +            for i := 0; i < b.N; i++ {
    +                handler.ServeHTTP(resps[i], req)
    +            }
    +        }
    +        
    +        var adversarialACRH []string
    +        
    +        func init() { // populates adversarialACRH
    +            n := int(math.Floor(math.Sqrt(http.DefaultMaxHeaderBytes)))
    +            commas := strings.Repeat(",", n)
    +            res := make([]string, n)
    +            for i := range res {
    +                res[i] = commas
    +            }
    +            adversarialACRH = res
    +        }
    +        
    +

    Details

    +

    Denial of Service (DoS) describes a family of attacks, all aimed at making a system inaccessible to its intended and legitimate users.

    +

    Unlike other vulnerabilities, DoS attacks usually do not aim at breaching security. Rather, they are focused on making websites and services unavailable to genuine users resulting in downtime.

    +

    One popular Denial of Service vulnerability is DDoS (a Distributed Denial of Service), an attack that attempts to clog network pipes to the system by generating a large volume of traffic from many machines.

    +

    When it comes to open source libraries, DoS vulnerabilities allow attackers to trigger such a crash or crippling of the service by using a flaw either in the application code or from the use of open source libraries.

    +

    Two common types of DoS vulnerabilities:

    +
      +
    • High CPU/Memory Consumption- An attacker sending crafted requests that could cause the system to take a disproportionate amount of time to process. For example, commons-fileupload:commons-fileupload.

      +
    • +
    • Crash - An attacker sending crafted requests that could cause the system to crash. For Example, npm ws package

      +
    • +
    +

    Remediation

    +

    Upgrade github.com/rs/cors to version 1.11.0 or higher.

    +

    References

    + + +
    + + +

    MPL-2.0 license

    @@ -1401,7 +1511,7 @@

    MPL-2.0 license

    • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2 › /usr/local/bin/argocd
    • Package Manager: golang @@ -1461,7 +1571,7 @@

      MPL-2.0 license

      • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2 › /usr/local/bin/argocd
      • Package Manager: golang @@ -1521,7 +1631,7 @@

        MPL-2.0 license

        • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2 › /usr/local/bin/argocd
        • Package Manager: golang @@ -1581,7 +1691,7 @@

          MPL-2.0 license

          • - Manifest file: quay.io/argoproj/argocd:v2.13.2/helm/v3 › /usr/local/bin/helm + Manifest file: quay.io/argoproj/argocd:v2.12.9/helm/v3 › /usr/local/bin/helm
          • Package Manager: golang @@ -1641,7 +1751,7 @@

            MPL-2.0 license

            • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2 › /usr/local/bin/argocd
            • Package Manager: golang @@ -1701,7 +1811,7 @@

              MPL-2.0 license

              • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2 › /usr/local/bin/argocd
              • Package Manager: golang @@ -1714,7 +1824,7 @@

                MPL-2.0 license

              • Introduced through: - github.com/argoproj/argo-cd/v2@* and github.com/gosimple/slug@v1.14.0 + github.com/argoproj/argo-cd/v2@* and github.com/gosimple/slug@v1.13.1
              @@ -1729,7 +1839,7 @@

              Detailed paths

              Introduced through: github.com/argoproj/argo-cd/v2@* › - github.com/gosimple/slug@v1.14.0 + github.com/gosimple/slug@v1.13.1 @@ -1761,7 +1871,7 @@

              Release of Invalid Pointer or Reference

              • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
              • Package Manager: ubuntu:24.04 @@ -1774,7 +1884,7 @@

                Release of Invalid Pointer or Reference

              • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 and patch@2.7.6-7build3 + docker-image|quay.io/argoproj/argocd@v2.12.9 and patch@2.7.6-7build3
              @@ -1787,7 +1897,7 @@

              Detailed paths

              • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › patch@2.7.6-7build3 @@ -1831,7 +1941,7 @@

                Double Free

                • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
                • Package Manager: ubuntu:24.04 @@ -1844,7 +1954,7 @@

                  Double Free

                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 and patch@2.7.6-7build3 + docker-image|quay.io/argoproj/argocd@v2.12.9 and patch@2.7.6-7build3
                @@ -1857,7 +1967,7 @@

                Detailed paths

                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › patch@2.7.6-7build3 @@ -1906,7 +2016,7 @@

                  CVE-2024-41996

                  • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
                  • Package Manager: ubuntu:24.04 @@ -1919,7 +2029,7 @@

                    CVE-2024-41996

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 and openssl/libssl3t64@3.0.13-0ubuntu3.4 + docker-image|quay.io/argoproj/argocd@v2.12.9 and openssl/libssl3t64@3.0.13-0ubuntu3.4
                  @@ -1932,7 +2042,7 @@

                  Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › openssl/libssl3t64@3.0.13-0ubuntu3.4 @@ -1941,7 +2051,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › coreutils@9.4-3ubuntu6 › @@ -1952,7 +2062,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › cyrus-sasl2/libsasl2-modules@2.1.28+dfsg1-5ubuntu3.1 › @@ -1963,7 +2073,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › libfido2/libfido2-1@1.14.0-1build3 › @@ -1974,7 +2084,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › openssh/openssh-client@1:9.6p1-3ubuntu13.5 › @@ -1985,7 +2095,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › ca-certificates@20240203 › @@ -1998,11 +2108,11 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › libssh/libssh-4@0.10.6-2build2 › @@ -2013,11 +2123,11 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2030,11 +2140,11 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › openldap/libldap2@2.6.7+dfsg-1~exp1ubuntu8.1 › @@ -2047,7 +2157,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › openssl@3.0.13-0ubuntu3.4 @@ -2056,7 +2166,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › ca-certificates@20240203 › @@ -2104,7 +2214,7 @@

                    Information Exposure

                    • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
                    • Package Manager: ubuntu:24.04 @@ -2117,7 +2227,7 @@

                      Information Exposure

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 and libgcrypt20@1.10.3-2build1 + docker-image|quay.io/argoproj/argocd@v2.12.9 and libgcrypt20@1.10.3-2build1
                    @@ -2130,7 +2240,7 @@

                    Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › libgcrypt20@1.10.3-2build1 @@ -2139,7 +2249,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › gnupg2/dirmngr@2.4.4-2ubuntu17 › @@ -2150,7 +2260,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › gnupg2/gpg@2.4.4-2ubuntu17 › @@ -2161,7 +2271,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › gnupg2/gpg-agent@2.4.4-2ubuntu17 › @@ -2172,7 +2282,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -2185,7 +2295,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -2198,7 +2308,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › gnupg2/gpg@2.4.4-2ubuntu17 › @@ -2211,7 +2321,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -2268,7 +2378,7 @@

                      CVE-2024-26458

                      • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
                      • Package Manager: ubuntu:24.04 @@ -2282,7 +2392,7 @@

                        CVE-2024-26458

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2, git@1:2.43.0-1ubuntu7.1 and others + docker-image|quay.io/argoproj/argocd@v2.12.9, git@1:2.43.0-1ubuntu7.1 and others
                      @@ -2294,11 +2404,11 @@

                      Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2309,11 +2419,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2326,11 +2436,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2341,11 +2451,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2358,11 +2468,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2377,11 +2487,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2392,7 +2502,7 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › openssh/openssh-client@1:9.6p1-3ubuntu13.5 › @@ -2403,11 +2513,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 @@ -2416,11 +2526,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › libssh/libssh-4@0.10.6-2build2 › @@ -2431,7 +2541,7 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › krb5/krb5-locales@1.20.1-6ubuntu2.2 @@ -2476,7 +2586,7 @@

                        CVE-2024-26461

                        • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
                        • Package Manager: ubuntu:24.04 @@ -2490,7 +2600,7 @@

                          CVE-2024-26461

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2, git@1:2.43.0-1ubuntu7.1 and others + docker-image|quay.io/argoproj/argocd@v2.12.9, git@1:2.43.0-1ubuntu7.1 and others
                        @@ -2502,11 +2612,11 @@

                        Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2517,11 +2627,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2534,11 +2644,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2549,11 +2659,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2566,11 +2676,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2585,11 +2695,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2600,7 +2710,7 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › openssh/openssh-client@1:9.6p1-3ubuntu13.5 › @@ -2611,11 +2721,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 @@ -2624,11 +2734,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › libssh/libssh-4@0.10.6-2build2 › @@ -2639,7 +2749,7 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › krb5/krb5-locales@1.20.1-6ubuntu2.2 @@ -2684,7 +2794,7 @@

                          Out-of-bounds Write

                          • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
                          • Package Manager: ubuntu:24.04 @@ -2697,7 +2807,7 @@

                            Out-of-bounds Write

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 and gnupg2/gpgv@2.4.4-2ubuntu17 + docker-image|quay.io/argoproj/argocd@v2.12.9 and gnupg2/gpgv@2.4.4-2ubuntu17
                          @@ -2710,7 +2820,7 @@

                          Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › gnupg2/gpgv@2.4.4-2ubuntu17 @@ -2719,7 +2829,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › apt@2.7.14build2 › @@ -2730,7 +2840,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › gnupg2/dirmngr@2.4.4-2ubuntu17 › @@ -2741,7 +2851,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › gnupg2/gpg-agent@2.4.4-2ubuntu17 › @@ -2752,7 +2862,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › gnupg2/gpg@2.4.4-2ubuntu17 › @@ -2763,7 +2873,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › gnupg2/dirmngr@2.4.4-2ubuntu17 @@ -2772,7 +2882,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › gnupg2/gpg@2.4.4-2ubuntu17 @@ -2781,7 +2891,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › gnupg2/gpg-agent@2.4.4-2ubuntu17 @@ -2830,7 +2940,7 @@

                            Allocation of Resources Without Limits or Throttling

                          • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
                          • Package Manager: ubuntu:24.04 @@ -2843,7 +2953,7 @@

                            Allocation of Resources Without Limits or Throttling

                            Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 and glibc/libc-bin@2.39-0ubuntu8.3 + docker-image|quay.io/argoproj/argocd@v2.12.9 and glibc/libc-bin@2.39-0ubuntu8.3
                          @@ -2856,7 +2966,7 @@

                          Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › glibc/libc-bin@2.39-0ubuntu8.3 @@ -2865,7 +2975,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › glibc/libc6@2.39-0ubuntu8.3 @@ -2911,7 +3021,7 @@

                            Insufficient Documentation of Error Handling Techniques<
                            • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2 › /usr/local/bin/argocd
                            • Package Manager: golang @@ -2980,7 +3090,7 @@

                              Insufficient Documentation of Error Handling Techniques<
                              • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argo-cd/v2 › /usr/local/bin/argocd
                              • Package Manager: golang @@ -3049,7 +3159,7 @@

                                Improper Input Validation

                                • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
                                • Package Manager: ubuntu:24.04 @@ -3063,7 +3173,7 @@

                                  Improper Input Validation

                                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2, git@1:2.43.0-1ubuntu7.1 and others + docker-image|quay.io/argoproj/argocd@v2.12.9, git@1:2.43.0-1ubuntu7.1 and others
                                @@ -3075,7 +3185,7 @@

                                Detailed paths

                                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 › @@ -3086,7 +3196,7 @@

                                  Detailed paths

                                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git@1:2.43.0-1ubuntu7.1 @@ -3095,7 +3205,7 @@

                                  Detailed paths

                                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › git-lfs@3.4.1-1ubuntu0.2 › @@ -3129,86 +3239,6 @@

                                  References

                                  More about this vulnerability

    -
    -
    -

    CVE-2024-11053

    -
    - -
    - low severity -
    - -
    - -
      -
    • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile -
    • -
    • - Package Manager: ubuntu:24.04 -
    • -
    • - Vulnerable module: - - curl/libcurl3t64-gnutls -
    • - -
    • Introduced through: - - - docker-image|quay.io/argoproj/argocd@v2.13.2, git@1:2.43.0-1ubuntu7.1 and others -
    • -
    - -
    - - -

    Detailed paths

    - -
      -
    • - Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 - › - git@1:2.43.0-1ubuntu7.1 - › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 - - - -
    • -
    - -
    - -
    - -

    NVD Description

    -

    Note: Versions mentioned in the description apply only to the upstream curl package and not the curl package as distributed by Ubuntu. - See How to fix? for Ubuntu:24.04 relevant fixed versions and status.

    -

    When asked to both use a .netrc file for credentials and to follow HTTP - redirects, curl could leak the password used for the first host to the - followed-to host under certain circumstances.

    -

    This flaw only manifests itself if the netrc file has an entry that matches - the redirect target hostname but the entry either omits just the password or - omits both login and password.

    -

    Remediation

    -

    Upgrade Ubuntu:24.04 curl to version 8.5.0-2ubuntu10.6 or higher.

    -

    References

    - - -
    - - -

    Improper Input Validation

    @@ -3222,7 +3252,7 @@

    Improper Input Validation

    • - Manifest file: quay.io/argoproj/argocd:v2.13.2/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.12.9/argoproj/argocd › Dockerfile
    • Package Manager: ubuntu:24.04 @@ -3235,7 +3265,7 @@

      Improper Input Validation

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 and coreutils@9.4-3ubuntu6 + docker-image|quay.io/argoproj/argocd@v2.12.9 and coreutils@9.4-3ubuntu6
    @@ -3248,7 +3278,7 @@

    Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.13.2 + docker-image|quay.io/argoproj/argocd@v2.12.9 › coreutils@9.4-3ubuntu6 diff --git a/docs/snyk/v2.14.0-rc3/redis_7.0.15-alpine.html b/docs/snyk/v2.12.9/redis_7.0.15-alpine.html similarity index 99% rename from docs/snyk/v2.14.0-rc3/redis_7.0.15-alpine.html rename to docs/snyk/v2.12.9/redis_7.0.15-alpine.html index 48adfb0e0926f..ca261455c3b79 100644 --- a/docs/snyk/v2.14.0-rc3/redis_7.0.15-alpine.html +++ b/docs/snyk/v2.12.9/redis_7.0.15-alpine.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:23:06 am (UTC+00:00)

      +

      January 5th 2025, 12:27:58 am (UTC+00:00)

      Scanned the following paths: diff --git a/docs/snyk/v2.13.2/argocd-iac-install.html b/docs/snyk/v2.13.3/argocd-iac-install.html similarity index 99% rename from docs/snyk/v2.13.2/argocd-iac-install.html rename to docs/snyk/v2.13.3/argocd-iac-install.html index 7634e62611150..407a1a9aa4bac 100644 --- a/docs/snyk/v2.13.2/argocd-iac-install.html +++ b/docs/snyk/v2.13.3/argocd-iac-install.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:27:07 am (UTC+00:00)

      +

      January 5th 2025, 12:26:54 am (UTC+00:00)

      Scanned the following path: diff --git a/docs/snyk/v2.13.2/argocd-iac-namespace-install.html b/docs/snyk/v2.13.3/argocd-iac-namespace-install.html similarity index 99% rename from docs/snyk/v2.13.2/argocd-iac-namespace-install.html rename to docs/snyk/v2.13.3/argocd-iac-namespace-install.html index 454a48e59e774..c58ac602882f8 100644 --- a/docs/snyk/v2.13.2/argocd-iac-namespace-install.html +++ b/docs/snyk/v2.13.3/argocd-iac-namespace-install.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:27:17 am (UTC+00:00)

      +

      January 5th 2025, 12:27:04 am (UTC+00:00)

      Scanned the following path: diff --git a/docs/snyk/v2.13.2/argocd-test.html b/docs/snyk/v2.13.3/argocd-test.html similarity index 99% rename from docs/snyk/v2.13.2/argocd-test.html rename to docs/snyk/v2.13.3/argocd-test.html index 715b3f08940df..15351ebc5f052 100644 --- a/docs/snyk/v2.13.2/argocd-test.html +++ b/docs/snyk/v2.13.3/argocd-test.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:25:01 am (UTC+00:00)

      +

      January 5th 2025, 12:24:49 am (UTC+00:00)

      Scanned the following paths: diff --git a/docs/snyk/v2.13.2/ghcr.io_dexidp_dex_v2.41.1.html b/docs/snyk/v2.13.3/ghcr.io_dexidp_dex_v2.41.1.html similarity index 99% rename from docs/snyk/v2.13.2/ghcr.io_dexidp_dex_v2.41.1.html rename to docs/snyk/v2.13.3/ghcr.io_dexidp_dex_v2.41.1.html index 95a99e4d9ac98..aa7944eb3c1ab 100644 --- a/docs/snyk/v2.13.2/ghcr.io_dexidp_dex_v2.41.1.html +++ b/docs/snyk/v2.13.3/ghcr.io_dexidp_dex_v2.41.1.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:25:09 am (UTC+00:00)

      +

      January 5th 2025, 12:24:55 am (UTC+00:00)

      Scanned the following paths: diff --git a/docs/snyk/v2.13.2/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html b/docs/snyk/v2.13.3/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html similarity index 99% rename from docs/snyk/v2.13.2/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html rename to docs/snyk/v2.13.3/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html index ee6ba492d5fe2..86192eda0feb3 100644 --- a/docs/snyk/v2.13.2/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html +++ b/docs/snyk/v2.13.3/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:25:13 am (UTC+00:00)

      +

      January 5th 2025, 12:24:59 am (UTC+00:00)

      Scanned the following path: diff --git a/docs/snyk/v2.14.0-rc3/public.ecr.aws_docker_library_redis_7.0.15-alpine.html b/docs/snyk/v2.13.3/public.ecr.aws_docker_library_redis_7.0.15-alpine.html similarity index 99% rename from docs/snyk/v2.14.0-rc3/public.ecr.aws_docker_library_redis_7.0.15-alpine.html rename to docs/snyk/v2.13.3/public.ecr.aws_docker_library_redis_7.0.15-alpine.html index 132422f01abb0..00fda04efad7d 100644 --- a/docs/snyk/v2.14.0-rc3/public.ecr.aws_docker_library_redis_7.0.15-alpine.html +++ b/docs/snyk/v2.13.3/public.ecr.aws_docker_library_redis_7.0.15-alpine.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:22:43 am (UTC+00:00)

      +

      January 5th 2025, 12:25:03 am (UTC+00:00)

      Scanned the following paths: diff --git a/docs/snyk/v2.12.8/quay.io_argoproj_argocd_v2.12.8.html b/docs/snyk/v2.13.3/quay.io_argoproj_argocd_v2.13.3.html similarity index 91% rename from docs/snyk/v2.12.8/quay.io_argoproj_argocd_v2.12.8.html rename to docs/snyk/v2.13.3/quay.io_argoproj_argocd_v2.13.3.html index 46f37d6589f92..a4a781880d761 100644 --- a/docs/snyk/v2.12.8/quay.io_argoproj_argocd_v2.12.8.html +++ b/docs/snyk/v2.13.3/quay.io_argoproj_argocd_v2.13.3.html @@ -7,7 +7,7 @@ Snyk test report - + @@ -456,23 +456,23 @@

      Snyk test report

      -

      December 29th 2024, 12:28:14 am (UTC+00:00)

      +

      January 5th 2025, 12:25:23 am (UTC+00:00)

      Scanned the following paths:
        -
      • quay.io/argoproj/argocd:v2.12.8/argoproj/argocd/Dockerfile (deb)
      • -
      • quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2//usr/local/bin/argocd (gomodules)
      • -
      • quay.io/argoproj/argocd:v2.12.8//usr/local/bin/kustomize (gomodules)
      • -
      • quay.io/argoproj/argocd:v2.12.8/helm/v3//usr/local/bin/helm (gomodules)
      • -
      • quay.io/argoproj/argocd:v2.12.8/git-lfs/git-lfs//usr/bin/git-lfs (gomodules)
      • +
      • quay.io/argoproj/argocd:v2.13.3/argoproj/argocd/Dockerfile (deb)
      • +
      • quay.io/argoproj/argocd:v2.13.3/argoproj/argo-cd/v2//usr/local/bin/argocd (gomodules)
      • +
      • quay.io/argoproj/argocd:v2.13.3//usr/local/bin/kustomize (gomodules)
      • +
      • quay.io/argoproj/argocd:v2.13.3/helm/v3//usr/local/bin/helm (gomodules)
      • +
      • quay.io/argoproj/argocd:v2.13.3/git-lfs/git-lfs//usr/bin/git-lfs (gomodules)
      -
      26 known vulnerabilities
      -
      107 vulnerable dependency paths
      -
      2292 dependencies
      +
      24 known vulnerabilities
      +
      105 vulnerable dependency paths
      +
      2354 dependencies
      @@ -492,7 +492,7 @@

      Incorrect Implementation of Authentication Algorithm

    • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argo-cd/v2 › /usr/local/bin/argocd
    • Package Manager: golang @@ -505,7 +505,7 @@

      Incorrect Implementation of Authentication Algorithm

      Introduced through: - github.com/argoproj/argo-cd/v2@* and golang.org/x/crypto/ssh@v0.23.0 + github.com/argoproj/argo-cd/v2@* and golang.org/x/crypto/ssh@v0.27.0
    @@ -520,7 +520,7 @@

    Detailed paths

    Introduced through: github.com/argoproj/argo-cd/v2@* › - golang.org/x/crypto/ssh@v0.23.0 + golang.org/x/crypto/ssh@v0.27.0 @@ -566,7 +566,7 @@

    Denial of Service (DoS)

    • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argo-cd/v2 › /usr/local/bin/argocd
    • Package Manager: golang @@ -579,7 +579,7 @@

      Denial of Service (DoS)

    • Introduced through: - github.com/argoproj/argo-cd/v2@* and golang.org/x/net/html@v0.25.0 + github.com/argoproj/argo-cd/v2@* and golang.org/x/net/html@v0.29.0
    @@ -594,7 +594,7 @@

    Detailed paths

    Introduced through: github.com/argoproj/argo-cd/v2@* › - golang.org/x/net/html@v0.25.0 + golang.org/x/net/html@v0.29.0 @@ -658,7 +658,7 @@

    Insecure Storage of Sensitive Information

    • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
    • Package Manager: ubuntu:24.04 @@ -671,7 +671,7 @@

      Insecure Storage of Sensitive Information

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 and pam/libpam0g@1.5.3-5ubuntu5.1 + docker-image|quay.io/argoproj/argocd@v2.13.3 and pam/libpam0g@1.5.3-5ubuntu5.1
    @@ -684,7 +684,7 @@

    Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › pam/libpam0g@1.5.3-5ubuntu5.1 @@ -693,7 +693,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -704,7 +704,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › util-linux@2.39.3-9ubuntu6.1 › @@ -715,7 +715,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -730,7 +730,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -747,7 +747,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -766,7 +766,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › pam/libpam-modules-bin@1.5.3-5ubuntu5.1 @@ -775,7 +775,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -792,7 +792,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › pam/libpam-modules@1.5.3-5ubuntu5.1 @@ -801,7 +801,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › pam/libpam-runtime@1.5.3-5ubuntu5.1 › @@ -812,7 +812,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -823,7 +823,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -838,7 +838,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › pam/libpam-runtime@1.5.3-5ubuntu5.1 @@ -847,7 +847,7 @@

      Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -897,7 +897,7 @@

      Improper Authentication

      • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
      • Package Manager: ubuntu:24.04 @@ -910,7 +910,7 @@

        Improper Authentication

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 and pam/libpam0g@1.5.3-5ubuntu5.1 + docker-image|quay.io/argoproj/argocd@v2.13.3 and pam/libpam0g@1.5.3-5ubuntu5.1
      @@ -923,7 +923,7 @@

      Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › pam/libpam0g@1.5.3-5ubuntu5.1 @@ -932,7 +932,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -943,7 +943,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › util-linux@2.39.3-9ubuntu6.1 › @@ -954,7 +954,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -969,7 +969,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -986,7 +986,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -1005,7 +1005,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › pam/libpam-modules-bin@1.5.3-5ubuntu5.1 @@ -1014,7 +1014,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -1031,7 +1031,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › pam/libpam-modules@1.5.3-5ubuntu5.1 @@ -1040,7 +1040,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › pam/libpam-runtime@1.5.3-5ubuntu5.1 › @@ -1051,7 +1051,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -1062,7 +1062,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -1077,7 +1077,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › pam/libpam-runtime@1.5.3-5ubuntu5.1 @@ -1086,7 +1086,7 @@

        Detailed paths

      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › shadow/login@1:4.13+dfsg1-4ubuntu3.2 › @@ -1133,7 +1133,7 @@

        CVE-2024-26462

        • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
        • Package Manager: ubuntu:24.04 @@ -1147,7 +1147,7 @@

          CVE-2024-26462

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8, git@1:2.43.0-1ubuntu7.1 and others + docker-image|quay.io/argoproj/argocd@v2.13.3, git@1:2.43.0-1ubuntu7.1 and others
        @@ -1159,11 +1159,11 @@

        Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1174,11 +1174,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1191,11 +1191,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1206,11 +1206,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1223,11 +1223,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1242,11 +1242,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -1257,7 +1257,7 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › openssh/openssh-client@1:9.6p1-3ubuntu13.5 › @@ -1268,11 +1268,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 @@ -1281,11 +1281,11 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › libssh/libssh-4@0.10.6-2build2 › @@ -1296,7 +1296,7 @@

          Detailed paths

        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › krb5/krb5-locales@1.20.1-6ubuntu2.2 @@ -1341,7 +1341,7 @@

          LGPL-3.0 license

          • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argo-cd/v2 › /usr/local/bin/argocd
          • Package Manager: golang @@ -1388,116 +1388,6 @@

            Detailed paths

            More about this vulnerability

    -
    -
    -

    Denial of Service (DoS)

    -
    - -
    - medium severity -
    - -
    - -
      -
    • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2 › /usr/local/bin/argocd -
    • -
    • - Package Manager: golang -
    • -
    • - Vulnerable module: - - github.com/rs/cors -
    • - -
    • Introduced through: - - github.com/argoproj/argo-cd/v2@* and github.com/rs/cors@v1.9.0 - -
    • -
    - -
    - - -

    Detailed paths

    - -
      -
    • - Introduced through: - github.com/argoproj/argo-cd/v2@* - › - github.com/rs/cors@v1.9.0 - - - -
    • -
    - -
    - -
    - -

    Overview

    -

    Affected versions of this package are vulnerable to Denial of Service (DoS) through the processing of malicious preflight requests that include a Access-Control-Request-Headers header with excessive commas. An attacker can induce excessive memory consumption and potentially crash the server by sending specially crafted requests.

    -

    PoC

    -
    
    -        func BenchmarkPreflightAdversarialACRH(b *testing.B) {
    -            resps := makeFakeResponses(b.N)
    -            req, _ := http.NewRequest(http.MethodOptions, dummyEndpoint, nil)
    -            req.Header.Add(headerOrigin, dummyOrigin)
    -            req.Header.Add(headerACRM, http.MethodGet)
    -            req.Header[headerACRH] = adversarialACRH
    -            handler := Default().Handler(testHandler)
    -        
    -            b.ReportAllocs()
    -            b.ResetTimer()
    -            for i := 0; i < b.N; i++ {
    -                handler.ServeHTTP(resps[i], req)
    -            }
    -        }
    -        
    -        var adversarialACRH []string
    -        
    -        func init() { // populates adversarialACRH
    -            n := int(math.Floor(math.Sqrt(http.DefaultMaxHeaderBytes)))
    -            commas := strings.Repeat(",", n)
    -            res := make([]string, n)
    -            for i := range res {
    -                res[i] = commas
    -            }
    -            adversarialACRH = res
    -        }
    -        
    -

    Details

    -

    Denial of Service (DoS) describes a family of attacks, all aimed at making a system inaccessible to its intended and legitimate users.

    -

    Unlike other vulnerabilities, DoS attacks usually do not aim at breaching security. Rather, they are focused on making websites and services unavailable to genuine users resulting in downtime.

    -

    One popular Denial of Service vulnerability is DDoS (a Distributed Denial of Service), an attack that attempts to clog network pipes to the system by generating a large volume of traffic from many machines.

    -

    When it comes to open source libraries, DoS vulnerabilities allow attackers to trigger such a crash or crippling of the service by using a flaw either in the application code or from the use of open source libraries.

    -

    Two common types of DoS vulnerabilities:

    -
      -
    • High CPU/Memory Consumption- An attacker sending crafted requests that could cause the system to take a disproportionate amount of time to process. For example, commons-fileupload:commons-fileupload.

      -
    • -
    • Crash - An attacker sending crafted requests that could cause the system to crash. For Example, npm ws package

      -
    • -
    -

    Remediation

    -

    Upgrade github.com/rs/cors to version 1.11.0 or higher.

    -

    References

    - - -
    - - -

    MPL-2.0 license

    @@ -1511,7 +1401,7 @@

    MPL-2.0 license

    • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argo-cd/v2 › /usr/local/bin/argocd
    • Package Manager: golang @@ -1571,7 +1461,7 @@

      MPL-2.0 license

      • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argo-cd/v2 › /usr/local/bin/argocd
      • Package Manager: golang @@ -1631,7 +1521,7 @@

        MPL-2.0 license

        • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argo-cd/v2 › /usr/local/bin/argocd
        • Package Manager: golang @@ -1691,7 +1581,7 @@

          MPL-2.0 license

          • - Manifest file: quay.io/argoproj/argocd:v2.12.8/helm/v3 › /usr/local/bin/helm + Manifest file: quay.io/argoproj/argocd:v2.13.3/helm/v3 › /usr/local/bin/helm
          • Package Manager: golang @@ -1751,7 +1641,7 @@

            MPL-2.0 license

            • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argo-cd/v2 › /usr/local/bin/argocd
            • Package Manager: golang @@ -1811,7 +1701,7 @@

              MPL-2.0 license

              • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argo-cd/v2 › /usr/local/bin/argocd
              • Package Manager: golang @@ -1824,7 +1714,7 @@

                MPL-2.0 license

              • Introduced through: - github.com/argoproj/argo-cd/v2@* and github.com/gosimple/slug@v1.13.1 + github.com/argoproj/argo-cd/v2@* and github.com/gosimple/slug@v1.14.0
              @@ -1839,7 +1729,7 @@

              Detailed paths

              Introduced through: github.com/argoproj/argo-cd/v2@* › - github.com/gosimple/slug@v1.13.1 + github.com/gosimple/slug@v1.14.0 @@ -1871,7 +1761,7 @@

              Release of Invalid Pointer or Reference

              • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
              • Package Manager: ubuntu:24.04 @@ -1884,7 +1774,7 @@

                Release of Invalid Pointer or Reference

              • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 and patch@2.7.6-7build3 + docker-image|quay.io/argoproj/argocd@v2.13.3 and patch@2.7.6-7build3
              @@ -1897,7 +1787,7 @@

              Detailed paths

              • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › patch@2.7.6-7build3 @@ -1941,7 +1831,7 @@

                Double Free

                • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
                • Package Manager: ubuntu:24.04 @@ -1954,7 +1844,7 @@

                  Double Free

                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 and patch@2.7.6-7build3 + docker-image|quay.io/argoproj/argocd@v2.13.3 and patch@2.7.6-7build3
                @@ -1967,7 +1857,7 @@

                Detailed paths

                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › patch@2.7.6-7build3 @@ -2016,7 +1906,7 @@

                  CVE-2024-41996

                  • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
                  • Package Manager: ubuntu:24.04 @@ -2029,7 +1919,7 @@

                    CVE-2024-41996

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 and openssl/libssl3t64@3.0.13-0ubuntu3.4 + docker-image|quay.io/argoproj/argocd@v2.13.3 and openssl/libssl3t64@3.0.13-0ubuntu3.4
                  @@ -2042,7 +1932,7 @@

                  Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › openssl/libssl3t64@3.0.13-0ubuntu3.4 @@ -2051,7 +1941,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › coreutils@9.4-3ubuntu6 › @@ -2062,7 +1952,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › cyrus-sasl2/libsasl2-modules@2.1.28+dfsg1-5ubuntu3.1 › @@ -2073,7 +1963,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › libfido2/libfido2-1@1.14.0-1build3 › @@ -2084,7 +1974,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › openssh/openssh-client@1:9.6p1-3ubuntu13.5 › @@ -2095,7 +1985,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › ca-certificates@20240203 › @@ -2108,11 +1998,11 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › libssh/libssh-4@0.10.6-2build2 › @@ -2123,11 +2013,11 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2140,11 +2030,11 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › openldap/libldap2@2.6.7+dfsg-1~exp1ubuntu8.1 › @@ -2157,7 +2047,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › openssl@3.0.13-0ubuntu3.4 @@ -2166,7 +2056,7 @@

                    Detailed paths

                  • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › ca-certificates@20240203 › @@ -2214,7 +2104,7 @@

                    Information Exposure

                    • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
                    • Package Manager: ubuntu:24.04 @@ -2227,7 +2117,7 @@

                      Information Exposure

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 and libgcrypt20@1.10.3-2build1 + docker-image|quay.io/argoproj/argocd@v2.13.3 and libgcrypt20@1.10.3-2build1
                    @@ -2240,7 +2130,7 @@

                    Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › libgcrypt20@1.10.3-2build1 @@ -2249,7 +2139,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › gnupg2/dirmngr@2.4.4-2ubuntu17 › @@ -2260,7 +2150,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › gnupg2/gpg@2.4.4-2ubuntu17 › @@ -2271,7 +2161,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › gnupg2/gpg-agent@2.4.4-2ubuntu17 › @@ -2282,7 +2172,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -2295,7 +2185,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -2308,7 +2198,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › gnupg2/gpg@2.4.4-2ubuntu17 › @@ -2321,7 +2211,7 @@

                      Detailed paths

                    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -2378,7 +2268,7 @@

                      CVE-2024-26458

                      • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
                      • Package Manager: ubuntu:24.04 @@ -2392,7 +2282,7 @@

                        CVE-2024-26458

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8, git@1:2.43.0-1ubuntu7.1 and others + docker-image|quay.io/argoproj/argocd@v2.13.3, git@1:2.43.0-1ubuntu7.1 and others
                      @@ -2404,11 +2294,11 @@

                      Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2419,11 +2309,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2436,11 +2326,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2451,11 +2341,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2468,11 +2358,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2487,11 +2377,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2502,7 +2392,7 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › openssh/openssh-client@1:9.6p1-3ubuntu13.5 › @@ -2513,11 +2403,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 @@ -2526,11 +2416,11 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › libssh/libssh-4@0.10.6-2build2 › @@ -2541,7 +2431,7 @@

                        Detailed paths

                      • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › krb5/krb5-locales@1.20.1-6ubuntu2.2 @@ -2586,7 +2476,7 @@

                        CVE-2024-26461

                        • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
                        • Package Manager: ubuntu:24.04 @@ -2600,7 +2490,7 @@

                          CVE-2024-26461

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8, git@1:2.43.0-1ubuntu7.1 and others + docker-image|quay.io/argoproj/argocd@v2.13.3, git@1:2.43.0-1ubuntu7.1 and others
                        @@ -2612,11 +2502,11 @@

                        Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2627,11 +2517,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2644,11 +2534,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2659,11 +2549,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2676,11 +2566,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2695,11 +2585,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 › @@ -2710,7 +2600,7 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › openssh/openssh-client@1:9.6p1-3ubuntu13.5 › @@ -2721,11 +2611,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2 @@ -2734,11 +2624,11 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 + curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6 › libssh/libssh-4@0.10.6-2build2 › @@ -2749,7 +2639,7 @@

                          Detailed paths

                        • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › krb5/krb5-locales@1.20.1-6ubuntu2.2 @@ -2794,7 +2684,7 @@

                          Out-of-bounds Write

                          • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
                          • Package Manager: ubuntu:24.04 @@ -2807,7 +2697,7 @@

                            Out-of-bounds Write

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 and gnupg2/gpgv@2.4.4-2ubuntu17 + docker-image|quay.io/argoproj/argocd@v2.13.3 and gnupg2/gpgv@2.4.4-2ubuntu17
                          @@ -2820,7 +2710,7 @@

                          Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › gnupg2/gpgv@2.4.4-2ubuntu17 @@ -2829,7 +2719,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › apt@2.7.14build2 › @@ -2840,7 +2730,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › gnupg2/dirmngr@2.4.4-2ubuntu17 › @@ -2851,7 +2741,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › gnupg2/gpg-agent@2.4.4-2ubuntu17 › @@ -2862,7 +2752,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › gnupg2/gpg@2.4.4-2ubuntu17 › @@ -2873,7 +2763,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › gnupg2/dirmngr@2.4.4-2ubuntu17 @@ -2882,7 +2772,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › gnupg2/gpg@2.4.4-2ubuntu17 @@ -2891,7 +2781,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › gnupg2/gpg-agent@2.4.4-2ubuntu17 @@ -2940,7 +2830,7 @@

                            Allocation of Resources Without Limits or Throttling

                          • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
                          • Package Manager: ubuntu:24.04 @@ -2953,7 +2843,7 @@

                            Allocation of Resources Without Limits or Throttling

                            Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 and glibc/libc-bin@2.39-0ubuntu8.3 + docker-image|quay.io/argoproj/argocd@v2.13.3 and glibc/libc-bin@2.39-0ubuntu8.3
                          @@ -2966,7 +2856,7 @@

                          Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › glibc/libc-bin@2.39-0ubuntu8.3 @@ -2975,7 +2865,7 @@

                            Detailed paths

                          • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › glibc/libc6@2.39-0ubuntu8.3 @@ -3021,7 +2911,7 @@

                            Insufficient Documentation of Error Handling Techniques<
                            • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argo-cd/v2 › /usr/local/bin/argocd
                            • Package Manager: golang @@ -3090,7 +2980,7 @@

                              Insufficient Documentation of Error Handling Techniques<
                              • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argo-cd/v2 › /usr/local/bin/argocd + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argo-cd/v2 › /usr/local/bin/argocd
                              • Package Manager: golang @@ -3159,7 +3049,7 @@

                                Improper Input Validation

                                • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
                                • Package Manager: ubuntu:24.04 @@ -3173,7 +3063,7 @@

                                  Improper Input Validation

                                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8, git@1:2.43.0-1ubuntu7.1 and others + docker-image|quay.io/argoproj/argocd@v2.13.3, git@1:2.43.0-1ubuntu7.1 and others
                                @@ -3185,7 +3075,7 @@

                                Detailed paths

                                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 › @@ -3196,7 +3086,7 @@

                                  Detailed paths

                                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git@1:2.43.0-1ubuntu7.1 @@ -3205,7 +3095,7 @@

                                  Detailed paths

                                • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › git-lfs@3.4.1-1ubuntu0.2 › @@ -3239,86 +3129,6 @@

                                  References

                                  More about this vulnerability

    -
    -
    -

    CVE-2024-11053

    -
    - -
    - low severity -
    - -
    - -
      -
    • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile -
    • -
    • - Package Manager: ubuntu:24.04 -
    • -
    • - Vulnerable module: - - curl/libcurl3t64-gnutls -
    • - -
    • Introduced through: - - - docker-image|quay.io/argoproj/argocd@v2.12.8, git@1:2.43.0-1ubuntu7.1 and others -
    • -
    - -
    - - -

    Detailed paths

    - -
      -
    • - Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 - › - git@1:2.43.0-1ubuntu7.1 - › - curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5 - - - -
    • -
    - -
    - -
    - -

    NVD Description

    -

    Note: Versions mentioned in the description apply only to the upstream curl package and not the curl package as distributed by Ubuntu. - See How to fix? for Ubuntu:24.04 relevant fixed versions and status.

    -

    When asked to both use a .netrc file for credentials and to follow HTTP - redirects, curl could leak the password used for the first host to the - followed-to host under certain circumstances.

    -

    This flaw only manifests itself if the netrc file has an entry that matches - the redirect target hostname but the entry either omits just the password or - omits both login and password.

    -

    Remediation

    -

    Upgrade Ubuntu:24.04 curl to version 8.5.0-2ubuntu10.6 or higher.

    -

    References

    - - -
    - - -

    Improper Input Validation

    @@ -3332,7 +3142,7 @@

    Improper Input Validation

    • - Manifest file: quay.io/argoproj/argocd:v2.12.8/argoproj/argocd › Dockerfile + Manifest file: quay.io/argoproj/argocd:v2.13.3/argoproj/argocd › Dockerfile
    • Package Manager: ubuntu:24.04 @@ -3345,7 +3155,7 @@

      Improper Input Validation

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 and coreutils@9.4-3ubuntu6 + docker-image|quay.io/argoproj/argocd@v2.13.3 and coreutils@9.4-3ubuntu6
    @@ -3358,7 +3168,7 @@

    Detailed paths

    • Introduced through: - docker-image|quay.io/argoproj/argocd@v2.12.8 + docker-image|quay.io/argoproj/argocd@v2.13.3 › coreutils@9.4-3ubuntu6 diff --git a/docs/snyk/v2.12.8/redis_7.0.15-alpine.html b/docs/snyk/v2.13.3/redis_7.0.15-alpine.html similarity index 99% rename from docs/snyk/v2.12.8/redis_7.0.15-alpine.html rename to docs/snyk/v2.13.3/redis_7.0.15-alpine.html index c8db2d3e49563..1ed9195006747 100644 --- a/docs/snyk/v2.12.8/redis_7.0.15-alpine.html +++ b/docs/snyk/v2.13.3/redis_7.0.15-alpine.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:28:19 am (UTC+00:00)

      +

      January 5th 2025, 12:25:27 am (UTC+00:00)

      Scanned the following paths: diff --git a/docs/snyk/v2.14.0-rc3/argocd-iac-install.html b/docs/snyk/v2.14.0-rc4/argocd-iac-install.html similarity index 99% rename from docs/snyk/v2.14.0-rc3/argocd-iac-install.html rename to docs/snyk/v2.14.0-rc4/argocd-iac-install.html index 5ed6c65a863a1..78734e5c999df 100644 --- a/docs/snyk/v2.14.0-rc3/argocd-iac-install.html +++ b/docs/snyk/v2.14.0-rc4/argocd-iac-install.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:24:37 am (UTC+00:00)

      +

      January 5th 2025, 12:24:21 am (UTC+00:00)

      Scanned the following path: diff --git a/docs/snyk/v2.14.0-rc3/argocd-iac-namespace-install.html b/docs/snyk/v2.14.0-rc4/argocd-iac-namespace-install.html similarity index 99% rename from docs/snyk/v2.14.0-rc3/argocd-iac-namespace-install.html rename to docs/snyk/v2.14.0-rc4/argocd-iac-namespace-install.html index ee645440da339..103bfe477df9c 100644 --- a/docs/snyk/v2.14.0-rc3/argocd-iac-namespace-install.html +++ b/docs/snyk/v2.14.0-rc4/argocd-iac-namespace-install.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:24:47 am (UTC+00:00)

      +

      January 5th 2025, 12:24:35 am (UTC+00:00)

      Scanned the following path: diff --git a/docs/snyk/v2.14.0-rc3/argocd-test.html b/docs/snyk/v2.14.0-rc4/argocd-test.html similarity index 99% rename from docs/snyk/v2.14.0-rc3/argocd-test.html rename to docs/snyk/v2.14.0-rc4/argocd-test.html index 6f9a4672ee9ed..7d02b94c83d2d 100644 --- a/docs/snyk/v2.14.0-rc3/argocd-test.html +++ b/docs/snyk/v2.14.0-rc4/argocd-test.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:22:28 am (UTC+00:00)

      +

      January 5th 2025, 12:22:11 am (UTC+00:00)

      Scanned the following paths: diff --git a/docs/snyk/v2.14.0-rc3/ghcr.io_dexidp_dex_v2.41.1.html b/docs/snyk/v2.14.0-rc4/ghcr.io_dexidp_dex_v2.41.1.html similarity index 99% rename from docs/snyk/v2.14.0-rc3/ghcr.io_dexidp_dex_v2.41.1.html rename to docs/snyk/v2.14.0-rc4/ghcr.io_dexidp_dex_v2.41.1.html index 3ea8477ce1fe2..8319c8dd81397 100644 --- a/docs/snyk/v2.14.0-rc3/ghcr.io_dexidp_dex_v2.41.1.html +++ b/docs/snyk/v2.14.0-rc4/ghcr.io_dexidp_dex_v2.41.1.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:22:34 am (UTC+00:00)

      +

      January 5th 2025, 12:22:17 am (UTC+00:00)

      Scanned the following paths: diff --git a/docs/snyk/v2.12.8/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html b/docs/snyk/v2.14.0-rc4/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html similarity index 99% rename from docs/snyk/v2.12.8/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html rename to docs/snyk/v2.14.0-rc4/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html index 66a00f577aec2..bb54a7b5ae11b 100644 --- a/docs/snyk/v2.12.8/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html +++ b/docs/snyk/v2.14.0-rc4/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:27:48 am (UTC+00:00)

      +

      January 5th 2025, 12:22:21 am (UTC+00:00)

      Scanned the following path: diff --git a/docs/snyk/v2.13.2/public.ecr.aws_docker_library_redis_7.0.15-alpine.html b/docs/snyk/v2.14.0-rc4/public.ecr.aws_docker_library_redis_7.0.15-alpine.html similarity index 99% rename from docs/snyk/v2.13.2/public.ecr.aws_docker_library_redis_7.0.15-alpine.html rename to docs/snyk/v2.14.0-rc4/public.ecr.aws_docker_library_redis_7.0.15-alpine.html index 9fb6e14241c9e..0b692b500904d 100644 --- a/docs/snyk/v2.13.2/public.ecr.aws_docker_library_redis_7.0.15-alpine.html +++ b/docs/snyk/v2.14.0-rc4/public.ecr.aws_docker_library_redis_7.0.15-alpine.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:25:18 am (UTC+00:00)

      +

      January 5th 2025, 12:22:25 am (UTC+00:00)

      Scanned the following paths: diff --git a/docs/snyk/v2.14.0-rc3/quay.io_argoproj_argocd_v2.14.0-rc3.html b/docs/snyk/v2.14.0-rc4/quay.io_argoproj_argocd_v2.14.0-rc3.html similarity index 99% rename from docs/snyk/v2.14.0-rc3/quay.io_argoproj_argocd_v2.14.0-rc3.html rename to docs/snyk/v2.14.0-rc4/quay.io_argoproj_argocd_v2.14.0-rc3.html index d79e4cab220bf..f73ca2c35aa63 100644 --- a/docs/snyk/v2.14.0-rc3/quay.io_argoproj_argocd_v2.14.0-rc3.html +++ b/docs/snyk/v2.14.0-rc4/quay.io_argoproj_argocd_v2.14.0-rc3.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:23:01 am (UTC+00:00)

      +

      January 5th 2025, 12:22:45 am (UTC+00:00)

      Scanned the following paths: diff --git a/docs/snyk/v2.13.2/redis_7.0.15-alpine.html b/docs/snyk/v2.14.0-rc4/redis_7.0.15-alpine.html similarity index 99% rename from docs/snyk/v2.13.2/redis_7.0.15-alpine.html rename to docs/snyk/v2.14.0-rc4/redis_7.0.15-alpine.html index 2cd5166fec159..cdca051edb6c0 100644 --- a/docs/snyk/v2.13.2/redis_7.0.15-alpine.html +++ b/docs/snyk/v2.14.0-rc4/redis_7.0.15-alpine.html @@ -456,7 +456,7 @@

      Snyk test report

      -

      December 29th 2024, 12:25:40 am (UTC+00:00)

      +

      January 5th 2025, 12:22:49 am (UTC+00:00)

      Scanned the following paths: From 43d2a3d93772cab395e611a75ef6026a96282915 Mon Sep 17 00:00:00 2001 From: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> Date: Mon, 6 Jan 2025 14:09:00 -0500 Subject: [PATCH 27/41] fix(ci): proto references bump (#21391) Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> --- hack/bump-major-version.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hack/bump-major-version.sh b/hack/bump-major-version.sh index 5575d1f2da4da..c15693e55450c 100755 --- a/hack/bump-major-version.sh +++ b/hack/bump-major-version.sh @@ -20,7 +20,8 @@ for file in hack/generate-proto.sh hack/update-codegen.sh hack/update-openapi.sh done echo "Incrementing the major version in proto files..." -find . -name '*.proto' -exec sed -i.bak "s/github.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" {} \; -exec sed -i.bak "s/github\.com.\argoproj\.argo_cd\.v${CURRENT_VERSION}/github\.com.\argoproj\.argo_cd\.v$((CURRENT_VERSION + 1))/g" {} \; -exec rm {}.bak \; +find . -name '*.proto' -exec sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" {} \; -exec rm {}.bak \; +find . -name '*.proto' -exec sed -i.bak "s/github\.com.\argoproj\.argo_cd\.v${CURRENT_VERSION}/github\.com.\argoproj\.argo_cd\.v$((CURRENT_VERSION + 1))/g" {} \; -exec rm {}.bak \; echo "Incrementing the major version in go files..." find . -name '*.go' -exec sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" {} \; -exec rm {}.bak \; From 76d28b50ddac6e171d839b3279580658ab700ff6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Jan 2025 14:28:17 -0500 Subject: [PATCH 28/41] chore(deps): bump golang.org/x/time from 0.8.0 to 0.9.0 (#21385) Bumps [golang.org/x/time](https://github.com/golang/time) from 0.8.0 to 0.9.0. - [Commits](https://github.com/golang/time/compare/v0.8.0...v0.9.0) --- updated-dependencies: - dependency-name: golang.org/x/time dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 97acc1ee49c16..7888c37783881 100644 --- a/go.mod +++ b/go.mod @@ -89,7 +89,7 @@ require ( golang.org/x/oauth2 v0.25.0 golang.org/x/sync v0.10.0 golang.org/x/term v0.28.0 - golang.org/x/time v0.8.0 + golang.org/x/time v0.9.0 google.golang.org/genproto/googleapis/api v0.0.0-20241104194629-dd2ea8efbc28 google.golang.org/grpc v1.69.2 google.golang.org/protobuf v1.36.1 diff --git a/go.sum b/go.sum index 008d7103981d7..67cdd54a08ce7 100644 --- a/go.sum +++ b/go.sum @@ -1283,8 +1283,8 @@ golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg= -golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= +golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= From c739478b8bb6e2657ffec762e72f1cea4dca7871 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Mon, 6 Jan 2025 20:45:11 +0100 Subject: [PATCH 29/41] chore: enable receiver-naming from revive (#21372) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 2 +- controller/sharding/cache.go | 24 +- .../generators/application_generator.go | 34 +- .../application/v1alpha1/app_project_types.go | 84 ++-- .../application/v1alpha1/repository_types.go | 60 +-- pkg/apis/application/v1alpha1/types.go | 290 +++++++------- server/server.go | 376 +++++++++--------- util/git/creds.go | 40 +- 8 files changed, 455 insertions(+), 455 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index f1ea2c2676081..3a51e14d3ebe0 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -128,7 +128,7 @@ linters-settings: disabled: false # receiver names in a method should reflect the struct name (p for Person, for example) - name: receiver-naming - disabled: true + disabled: false # redefining built in names (true, false, append, make) can lead to bugs very difficult to detect. - name: redefines-builtin-id disabled: true diff --git a/controller/sharding/cache.go b/controller/sharding/cache.go index 454b37e4cf5fe..f421efd3c624a 100644 --- a/controller/sharding/cache.go +++ b/controller/sharding/cache.go @@ -52,20 +52,20 @@ func NewClusterSharding(_ db.ArgoDB, shard, replicas int, shardingAlgorithm stri } // IsManagedCluster returns whether or not the cluster should be processed by a given shard. -func (s *ClusterSharding) IsManagedCluster(c *v1alpha1.Cluster) bool { - s.lock.RLock() - defer s.lock.RUnlock() +func (sharding *ClusterSharding) IsManagedCluster(c *v1alpha1.Cluster) bool { + sharding.lock.RLock() + defer sharding.lock.RUnlock() if c == nil { // nil cluster (in-cluster) is always managed by current clusterShard return true } clusterShard := 0 - if shard, ok := s.Shards[c.Server]; ok { + if shard, ok := sharding.Shards[c.Server]; ok { clusterShard = shard } else { log.Warnf("The cluster %s has no assigned shard.", c.Server) } - log.Debugf("Checking if cluster %s with clusterShard %d should be processed by shard %d", c.Server, clusterShard, s.Shard) - return clusterShard == s.Shard + log.Debugf("Checking if cluster %s with clusterShard %d should be processed by shard %d", c.Server, clusterShard, sharding.Shard) + return clusterShard == sharding.Shard } func (sharding *ClusterSharding) Init(clusters *v1alpha1.ClusterList, apps *v1alpha1.ApplicationList) { @@ -187,11 +187,11 @@ func hasShardingUpdates(old, new *v1alpha1.Cluster) bool { } // A read lock should be acquired before calling getClusterAccessor. -func (d *ClusterSharding) getClusterAccessor() clusterAccessor { +func (sharding *ClusterSharding) getClusterAccessor() clusterAccessor { return func() []*v1alpha1.Cluster { // no need to lock, as this is only called from the updateDistribution function - clusters := make([]*v1alpha1.Cluster, 0, len(d.Clusters)) - for _, c := range d.Clusters { + clusters := make([]*v1alpha1.Cluster, 0, len(sharding.Clusters)) + for _, c := range sharding.Clusters { clusters = append(clusters, c) } return clusters @@ -199,10 +199,10 @@ func (d *ClusterSharding) getClusterAccessor() clusterAccessor { } // A read lock should be acquired before calling getAppAccessor. -func (d *ClusterSharding) getAppAccessor() appAccessor { +func (sharding *ClusterSharding) getAppAccessor() appAccessor { return func() []*v1alpha1.Application { - apps := make([]*v1alpha1.Application, 0, len(d.Apps)) - for _, a := range d.Apps { + apps := make([]*v1alpha1.Application, 0, len(sharding.Apps)) + for _, a := range sharding.Apps { apps = append(apps, a) } return apps diff --git a/hack/gen-resources/generators/application_generator.go b/hack/gen-resources/generators/application_generator.go index 8338492ac6599..07fb900327426 100644 --- a/hack/gen-resources/generators/application_generator.go +++ b/hack/gen-resources/generators/application_generator.go @@ -29,7 +29,7 @@ func NewApplicationGenerator(argoClientSet *appclientset.Clientset, clientSet *k return &ApplicationGenerator{argoClientSet, clientSet, db} } -func (pg *ApplicationGenerator) buildRandomSource(repositories []*v1alpha1.Repository) (*v1alpha1.ApplicationSource, error) { +func (generator *ApplicationGenerator) buildRandomSource(repositories []*v1alpha1.Repository) (*v1alpha1.ApplicationSource, error) { seed := rand.New(rand.NewSource(time.Now().Unix())) repoNumber := seed.Int() % len(repositories) return &v1alpha1.ApplicationSource{ @@ -39,15 +39,15 @@ func (pg *ApplicationGenerator) buildRandomSource(repositories []*v1alpha1.Repos }, nil } -func (ag *ApplicationGenerator) buildSource(opts *util.GenerateOpts, repositories []*v1alpha1.Repository) (*v1alpha1.ApplicationSource, error) { +func (generator *ApplicationGenerator) buildSource(opts *util.GenerateOpts, repositories []*v1alpha1.Repository) (*v1alpha1.ApplicationSource, error) { switch opts.ApplicationOpts.SourceOpts.Strategy { case "Random": - return ag.buildRandomSource(repositories) + return generator.buildRandomSource(repositories) } - return ag.buildRandomSource(repositories) + return generator.buildRandomSource(repositories) } -func (pg *ApplicationGenerator) buildRandomDestination(opts *util.GenerateOpts, clusters []v1alpha1.Cluster) (*v1alpha1.ApplicationDestination, error) { +func (generator *ApplicationGenerator) buildRandomDestination(opts *util.GenerateOpts, clusters []v1alpha1.Cluster) (*v1alpha1.ApplicationDestination, error) { seed := rand.New(rand.NewSource(time.Now().Unix())) clusterNumber := seed.Int() % len(clusters) return &v1alpha1.ApplicationDestination{ @@ -56,33 +56,33 @@ func (pg *ApplicationGenerator) buildRandomDestination(opts *util.GenerateOpts, }, nil } -func (ag *ApplicationGenerator) buildDestination(opts *util.GenerateOpts, clusters []v1alpha1.Cluster) (*v1alpha1.ApplicationDestination, error) { +func (generator *ApplicationGenerator) buildDestination(opts *util.GenerateOpts, clusters []v1alpha1.Cluster) (*v1alpha1.ApplicationDestination, error) { switch opts.ApplicationOpts.DestinationOpts.Strategy { case "Random": - return ag.buildRandomDestination(opts, clusters) + return generator.buildRandomDestination(opts, clusters) } - return ag.buildRandomDestination(opts, clusters) + return generator.buildRandomDestination(opts, clusters) } -func (pg *ApplicationGenerator) Generate(opts *util.GenerateOpts) error { - settingsMgr := settings.NewSettingsManager(context.TODO(), pg.clientSet, opts.Namespace) - repositories, err := db.NewDB(opts.Namespace, settingsMgr, pg.clientSet).ListRepositories(context.TODO()) +func (generator *ApplicationGenerator) Generate(opts *util.GenerateOpts) error { + settingsMgr := settings.NewSettingsManager(context.TODO(), generator.clientSet, opts.Namespace) + repositories, err := db.NewDB(opts.Namespace, settingsMgr, generator.clientSet).ListRepositories(context.TODO()) if err != nil { return err } - clusters, err := db.NewDB(opts.Namespace, settingsMgr, pg.clientSet).ListClusters(context.TODO()) + clusters, err := db.NewDB(opts.Namespace, settingsMgr, generator.clientSet).ListClusters(context.TODO()) if err != nil { return err } - applications := pg.argoClientSet.ArgoprojV1alpha1().Applications(opts.Namespace) + applications := generator.argoClientSet.ArgoprojV1alpha1().Applications(opts.Namespace) for i := 0; i < opts.ApplicationOpts.Samples; i++ { log.Printf("Generate application #%v", i) - source, err := pg.buildSource(opts, repositories) + source, err := generator.buildSource(opts, repositories) if err != nil { return err } log.Printf("Pick source %q", source) - destination, err := pg.buildDestination(opts, clusters.Items) + destination, err := generator.buildDestination(opts, clusters.Items) if err != nil { return err } @@ -107,9 +107,9 @@ func (pg *ApplicationGenerator) Generate(opts *util.GenerateOpts) error { return nil } -func (ag *ApplicationGenerator) Clean(opts *util.GenerateOpts) error { +func (generator *ApplicationGenerator) Clean(opts *util.GenerateOpts) error { log.Printf("Clean applications") - applications := ag.argoClientSet.ArgoprojV1alpha1().Applications(opts.Namespace) + applications := generator.argoClientSet.ArgoprojV1alpha1().Applications(opts.Namespace) return applications.DeleteCollection(context.TODO(), metav1.DeleteOptions{}, metav1.ListOptions{ LabelSelector: "app.kubernetes.io/generated-by=argocd-generator", }) diff --git a/pkg/apis/application/v1alpha1/app_project_types.go b/pkg/apis/application/v1alpha1/app_project_types.go index 436e578548e3d..081b4bb178803 100644 --- a/pkg/apis/application/v1alpha1/app_project_types.go +++ b/pkg/apis/application/v1alpha1/app_project_types.go @@ -74,19 +74,19 @@ type AppProjectStatus struct { } // GetRoleByName returns the role in a project by the name with its index -func (p *AppProject) GetRoleByName(name string) (*ProjectRole, int, error) { - for i, role := range p.Spec.Roles { +func (proj *AppProject) GetRoleByName(name string) (*ProjectRole, int, error) { + for i, role := range proj.Spec.Roles { if name == role.Name { return &role, i, nil } } - return nil, -1, fmt.Errorf("role '%s' does not exist in project '%s'", name, p.Name) + return nil, -1, fmt.Errorf("role '%s' does not exist in project '%s'", name, proj.Name) } // GetJWTTokenFromSpec looks up the index of a JWTToken in a project by id (new token), if not then by the issue at time (old token) -func (p *AppProject) GetJWTTokenFromSpec(roleName string, issuedAt int64, id string) (*JWTToken, int, error) { +func (proj *AppProject) GetJWTTokenFromSpec(roleName string, issuedAt int64, id string) (*JWTToken, int, error) { // This is for backward compatibility. In the oder version, JWTTokens are stored under spec.role - role, _, err := p.GetRoleByName(roleName) + role, _, err := proj.GetRoleByName(roleName) if err != nil { return nil, -1, err } @@ -107,14 +107,14 @@ func (p *AppProject) GetJWTTokenFromSpec(roleName string, issuedAt int64, id str } } - return nil, -1, fmt.Errorf("JWT token for role '%s' issued at '%d' does not exist in project '%s'", role.Name, issuedAt, p.Name) + return nil, -1, fmt.Errorf("JWT token for role '%s' issued at '%d' does not exist in project '%s'", role.Name, issuedAt, proj.Name) } // GetJWTToken looks up the index of a JWTToken in a project by id (new token), if not then by the issue at time (old token) -func (p *AppProject) GetJWTToken(roleName string, issuedAt int64, id string) (*JWTToken, int, error) { +func (proj *AppProject) GetJWTToken(roleName string, issuedAt int64, id string) (*JWTToken, int, error) { // This is for newer version, JWTTokens are stored under status if id != "" { - for i, token := range p.Status.JWTTokensByRole[roleName].Items { + for i, token := range proj.Status.JWTTokensByRole[roleName].Items { if id == token.ID { return &token, i, nil } @@ -122,31 +122,31 @@ func (p *AppProject) GetJWTToken(roleName string, issuedAt int64, id string) (*J } if issuedAt != -1 { - for i, token := range p.Status.JWTTokensByRole[roleName].Items { + for i, token := range proj.Status.JWTTokensByRole[roleName].Items { if issuedAt == token.IssuedAt { return &token, i, nil } } } - return nil, -1, fmt.Errorf("JWT token for role '%s' issued at '%d' does not exist in project '%s'", roleName, issuedAt, p.Name) + return nil, -1, fmt.Errorf("JWT token for role '%s' issued at '%d' does not exist in project '%s'", roleName, issuedAt, proj.Name) } // RemoveJWTToken removes the specified JWT from an AppProject -func (p AppProject) RemoveJWTToken(roleIndex int, issuedAt int64, id string) error { - roleName := p.Spec.Roles[roleIndex].Name +func (proj AppProject) RemoveJWTToken(roleIndex int, issuedAt int64, id string) error { + roleName := proj.Spec.Roles[roleIndex].Name // For backward compatibility - _, jwtTokenIndex, err1 := p.GetJWTTokenFromSpec(roleName, issuedAt, id) + _, jwtTokenIndex, err1 := proj.GetJWTTokenFromSpec(roleName, issuedAt, id) if err1 == nil { - p.Spec.Roles[roleIndex].JWTTokens[jwtTokenIndex] = p.Spec.Roles[roleIndex].JWTTokens[len(p.Spec.Roles[roleIndex].JWTTokens)-1] - p.Spec.Roles[roleIndex].JWTTokens = p.Spec.Roles[roleIndex].JWTTokens[:len(p.Spec.Roles[roleIndex].JWTTokens)-1] + proj.Spec.Roles[roleIndex].JWTTokens[jwtTokenIndex] = proj.Spec.Roles[roleIndex].JWTTokens[len(proj.Spec.Roles[roleIndex].JWTTokens)-1] + proj.Spec.Roles[roleIndex].JWTTokens = proj.Spec.Roles[roleIndex].JWTTokens[:len(proj.Spec.Roles[roleIndex].JWTTokens)-1] } // New location for storing JWTToken - _, jwtTokenIndex, err2 := p.GetJWTToken(roleName, issuedAt, id) + _, jwtTokenIndex, err2 := proj.GetJWTToken(roleName, issuedAt, id) if err2 == nil { - p.Status.JWTTokensByRole[roleName].Items[jwtTokenIndex] = p.Status.JWTTokensByRole[roleName].Items[len(p.Status.JWTTokensByRole[roleName].Items)-1] - p.Status.JWTTokensByRole[roleName] = JWTTokens{Items: p.Status.JWTTokensByRole[roleName].Items[:len(p.Status.JWTTokensByRole[roleName].Items)-1]} + proj.Status.JWTTokensByRole[roleName].Items[jwtTokenIndex] = proj.Status.JWTTokensByRole[roleName].Items[len(proj.Status.JWTTokensByRole[roleName].Items)-1] + proj.Status.JWTTokensByRole[roleName] = JWTTokens{Items: proj.Status.JWTTokensByRole[roleName].Items[:len(proj.Status.JWTTokensByRole[roleName].Items)-1]} } if err1 == nil || err2 == nil { @@ -159,8 +159,8 @@ func (p AppProject) RemoveJWTToken(roleIndex int, issuedAt int64, id string) err } // TODO: document this method -func (p *AppProject) ValidateJWTTokenID(roleName string, id string) error { - role, _, err := p.GetRoleByName(roleName) +func (proj *AppProject) ValidateJWTTokenID(roleName string, id string) error { + role, _, err := proj.GetRoleByName(roleName) if err != nil { return err } @@ -175,9 +175,9 @@ func (p *AppProject) ValidateJWTTokenID(roleName string, id string) error { return nil } -func (p *AppProject) ValidateProject() error { +func (proj *AppProject) ValidateProject() error { destKeys := make(map[string]bool) - for _, dest := range p.Spec.Destinations { + for _, dest := range proj.Spec.Destinations { if dest.Name == "!*" { return status.Errorf(codes.InvalidArgument, "name has an invalid format, '!*'") } @@ -202,7 +202,7 @@ func (p *AppProject) ValidateProject() error { } srcNamespaces := make(map[string]bool) - for _, ns := range p.Spec.SourceNamespaces { + for _, ns := range proj.Spec.SourceNamespaces { if _, ok := srcNamespaces[ns]; ok { return status.Errorf(codes.InvalidArgument, "source namespace '%s' already added", ns) } @@ -210,7 +210,7 @@ func (p *AppProject) ValidateProject() error { } srcRepos := make(map[string]bool) - for _, src := range p.Spec.SourceRepos { + for _, src := range proj.Spec.SourceRepos { if src == "!*" { return status.Errorf(codes.InvalidArgument, "source repository has an invalid format, '!*'") } @@ -222,7 +222,7 @@ func (p *AppProject) ValidateProject() error { } roleNames := make(map[string]bool) - for _, role := range p.Spec.Roles { + for _, role := range proj.Spec.Roles { if _, ok := roleNames[role.Name]; ok { return status.Errorf(codes.AlreadyExists, "role '%s' already exists", role.Name) } @@ -234,7 +234,7 @@ func (p *AppProject) ValidateProject() error { if _, ok := existingPolicies[policy]; ok { return status.Errorf(codes.AlreadyExists, "policy '%s' already exists for role '%s'", policy, role.Name) } - if err := validatePolicy(p.Name, role.Name, policy); err != nil { + if err := validatePolicy(proj.Name, role.Name, policy); err != nil { return err } existingPolicies[policy] = true @@ -252,9 +252,9 @@ func (p *AppProject) ValidateProject() error { roleNames[role.Name] = true } - if p.Spec.SyncWindows.HasWindows() { + if proj.Spec.SyncWindows.HasWindows() { existingWindows := make(map[string]bool) - for _, window := range p.Spec.SyncWindows { + for _, window := range proj.Spec.SyncWindows { if window == nil { continue } @@ -273,7 +273,7 @@ func (p *AppProject) ValidateProject() error { } destServiceAccts := make(map[string]bool) - for _, destServiceAcct := range p.Spec.DestinationServiceAccounts { + for _, destServiceAcct := range proj.Spec.DestinationServiceAccounts { if strings.Contains(destServiceAcct.Server, "!") { return status.Errorf(codes.InvalidArgument, "server has an invalid format, '%s'", destServiceAcct.Server) } @@ -308,8 +308,8 @@ func (p *AppProject) ValidateProject() error { } // AddGroupToRole adds an OIDC group to a role -func (p *AppProject) AddGroupToRole(roleName, group string) (bool, error) { - role, roleIndex, err := p.GetRoleByName(roleName) +func (proj *AppProject) AddGroupToRole(roleName, group string) (bool, error) { + role, roleIndex, err := proj.GetRoleByName(roleName) if err != nil { return false, err } @@ -319,20 +319,20 @@ func (p *AppProject) AddGroupToRole(roleName, group string) (bool, error) { } } role.Groups = append(role.Groups, group) - p.Spec.Roles[roleIndex] = *role + proj.Spec.Roles[roleIndex] = *role return true, nil } // RemoveGroupFromRole removes an OIDC group from a role -func (p *AppProject) RemoveGroupFromRole(roleName, group string) (bool, error) { - role, roleIndex, err := p.GetRoleByName(roleName) +func (proj *AppProject) RemoveGroupFromRole(roleName, group string) (bool, error) { + role, roleIndex, err := proj.GetRoleByName(roleName) if err != nil { return false, err } for i, roleGroup := range role.Groups { if group == roleGroup { role.Groups = append(role.Groups[:i], role.Groups[i+1:]...) - p.Spec.Roles[roleIndex] = *role + proj.Spec.Roles[roleIndex] = *role return true, nil } } @@ -340,17 +340,17 @@ func (p *AppProject) RemoveGroupFromRole(roleName, group string) (bool, error) { } // NormalizePolicies normalizes the policies in the project -func (p *AppProject) NormalizePolicies() { - for i, role := range p.Spec.Roles { +func (proj *AppProject) NormalizePolicies() { + for i, role := range proj.Spec.Roles { var normalizedPolicies []string for _, policy := range role.Policies { - normalizedPolicies = append(normalizedPolicies, p.normalizePolicy(policy)) + normalizedPolicies = append(normalizedPolicies, proj.normalizePolicy(policy)) } - p.Spec.Roles[i].Policies = normalizedPolicies + proj.Spec.Roles[i].Policies = normalizedPolicies } } -func (p *AppProject) normalizePolicy(policy string) string { +func (proj *AppProject) normalizePolicy(policy string) string { policyComponents := strings.Split(policy, ",") normalizedPolicy := "" for _, component := range policyComponents { @@ -597,10 +597,10 @@ func jwtTokensCombine(tokens1 []JWTToken, tokens2 []JWTToken) []JWTToken { // Applications in the installation namespace are always permitted. Also, at // application creation time, its namespace may yet be empty to indicate that // the application will be created in the controller's namespace. -func (p AppProject) IsAppNamespacePermitted(app *Application, controllerNs string) bool { +func (proj AppProject) IsAppNamespacePermitted(app *Application, controllerNs string) bool { if app.Namespace == "" || app.Namespace == controllerNs { return true } - return glob.MatchStringInList(p.Spec.SourceNamespaces, app.Namespace, glob.REGEXP) + return glob.MatchStringInList(proj.Spec.SourceNamespaces, app.Namespace, glob.REGEXP) } diff --git a/pkg/apis/application/v1alpha1/repository_types.go b/pkg/apis/application/v1alpha1/repository_types.go index 047ae14b1ac97..8a222585ab2de 100644 --- a/pkg/apis/application/v1alpha1/repository_types.go +++ b/pkg/apis/application/v1alpha1/repository_types.go @@ -112,8 +112,8 @@ func (repo *Repository) IsLFSEnabled() bool { } // HasCredentials returns true when the repository has been configured with any credentials -func (m *Repository) HasCredentials() bool { - return m.Username != "" || m.Password != "" || m.SSHPrivateKey != "" || m.TLSClientCertData != "" || m.GithubAppPrivateKey != "" +func (repo *Repository) HasCredentials() bool { + return repo.Username != "" || repo.Password != "" || repo.SSHPrivateKey != "" || repo.TLSClientCertData != "" || repo.GithubAppPrivateKey != "" } // CopyCredentialsFromRepo copies all credential information from source repository to receiving repository @@ -267,49 +267,49 @@ func getCAPath(repoURL string) string { } // CopySettingsFrom copies all repository settings from source to receiver -func (m *Repository) CopySettingsFrom(source *Repository) { +func (repo *Repository) CopySettingsFrom(source *Repository) { if source != nil { - m.EnableLFS = source.EnableLFS - m.InsecureIgnoreHostKey = source.InsecureIgnoreHostKey - m.Insecure = source.Insecure - m.InheritedCreds = source.InheritedCreds + repo.EnableLFS = source.EnableLFS + repo.InsecureIgnoreHostKey = source.InsecureIgnoreHostKey + repo.Insecure = source.Insecure + repo.InheritedCreds = source.InheritedCreds } } // StringForLogging gets a string representation of the Repository which is safe to log or return to the user. -func (m *Repository) StringForLogging() string { - if m == nil { +func (repo *Repository) StringForLogging() string { + if repo == nil { return "" } - return fmt.Sprintf("&Repository{Repo: %q, Type: %q, Name: %q, Project: %q}", m.Repo, m.Type, m.Name, m.Project) + return fmt.Sprintf("&Repository{Repo: %q, Type: %q, Name: %q, Project: %q}", repo.Repo, repo.Type, repo.Name, repo.Project) } // Sanitized returns a copy of the Repository with sensitive information removed. -func (m *Repository) Sanitized() *Repository { +func (repo *Repository) Sanitized() *Repository { return &Repository{ - Repo: m.Repo, - Type: m.Type, - Name: m.Name, - Username: m.Username, - Insecure: m.IsInsecure(), - EnableLFS: m.EnableLFS, - EnableOCI: m.EnableOCI, - Proxy: m.Proxy, - NoProxy: m.NoProxy, - Project: m.Project, - ForceHttpBasicAuth: m.ForceHttpBasicAuth, - InheritedCreds: m.InheritedCreds, - GithubAppId: m.GithubAppId, - GithubAppInstallationId: m.GithubAppInstallationId, - GitHubAppEnterpriseBaseURL: m.GitHubAppEnterpriseBaseURL, + Repo: repo.Repo, + Type: repo.Type, + Name: repo.Name, + Username: repo.Username, + Insecure: repo.IsInsecure(), + EnableLFS: repo.EnableLFS, + EnableOCI: repo.EnableOCI, + Proxy: repo.Proxy, + NoProxy: repo.NoProxy, + Project: repo.Project, + ForceHttpBasicAuth: repo.ForceHttpBasicAuth, + InheritedCreds: repo.InheritedCreds, + GithubAppId: repo.GithubAppId, + GithubAppInstallationId: repo.GithubAppInstallationId, + GitHubAppEnterpriseBaseURL: repo.GitHubAppEnterpriseBaseURL, } } -func (m *Repository) Normalize() *Repository { - if m.Type == "" { - m.Type = common.DefaultRepoType +func (repo *Repository) Normalize() *Repository { + if repo.Type == "" { + repo.Type = common.DefaultRepoType } - return m + return repo } // Repositories defines a list of Repository configurations diff --git a/pkg/apis/application/v1alpha1/types.go b/pkg/apis/application/v1alpha1/types.go index db61be5c888ff..d62948721700f 100644 --- a/pkg/apis/application/v1alpha1/types.go +++ b/pkg/apis/application/v1alpha1/types.go @@ -202,12 +202,12 @@ type ApplicationSource struct { // ApplicationSources contains list of required information about the sources of an application type ApplicationSources []ApplicationSource -func (s ApplicationSources) Equals(other ApplicationSources) bool { - if len(s) != len(other) { +func (a ApplicationSources) Equals(other ApplicationSources) bool { + if len(a) != len(other) { return false } - for i := range s { - if !s[i].Equals(&other[i]) { + for i := range a { + if !a[i].Equals(&other[i]) { return false } } @@ -219,154 +219,154 @@ func (a ApplicationSources) IsZero() bool { return len(a) == 0 } -func (a *ApplicationSpec) GetSource() ApplicationSource { - if a.SourceHydrator != nil { - return a.SourceHydrator.GetSyncSource() +func (spec *ApplicationSpec) GetSource() ApplicationSource { + if spec.SourceHydrator != nil { + return spec.SourceHydrator.GetSyncSource() } // if Application has multiple sources, return the first source in sources - if a.HasMultipleSources() { - return a.Sources[0] + if spec.HasMultipleSources() { + return spec.Sources[0] } - if a.Source != nil { - return *a.Source + if spec.Source != nil { + return *spec.Source } return ApplicationSource{} } // GetHydrateToSource returns the hydrateTo source if it exists, otherwise returns the sync source. -func (a *ApplicationSpec) GetHydrateToSource() ApplicationSource { - if a.SourceHydrator != nil { - targetRevision := a.SourceHydrator.SyncSource.TargetBranch - if a.SourceHydrator.HydrateTo != nil { - targetRevision = a.SourceHydrator.HydrateTo.TargetBranch +func (spec *ApplicationSpec) GetHydrateToSource() ApplicationSource { + if spec.SourceHydrator != nil { + targetRevision := spec.SourceHydrator.SyncSource.TargetBranch + if spec.SourceHydrator.HydrateTo != nil { + targetRevision = spec.SourceHydrator.HydrateTo.TargetBranch } return ApplicationSource{ - RepoURL: a.SourceHydrator.DrySource.RepoURL, - Path: a.SourceHydrator.SyncSource.Path, + RepoURL: spec.SourceHydrator.DrySource.RepoURL, + Path: spec.SourceHydrator.SyncSource.Path, TargetRevision: targetRevision, } } return ApplicationSource{} } -func (a *ApplicationSpec) GetSources() ApplicationSources { - if a.SourceHydrator != nil { - return ApplicationSources{a.SourceHydrator.GetSyncSource()} +func (spec *ApplicationSpec) GetSources() ApplicationSources { + if spec.SourceHydrator != nil { + return ApplicationSources{spec.SourceHydrator.GetSyncSource()} } - if a.HasMultipleSources() { - return a.Sources + if spec.HasMultipleSources() { + return spec.Sources } - if a.Source != nil { - return ApplicationSources{*a.Source} + if spec.Source != nil { + return ApplicationSources{*spec.Source} } return ApplicationSources{} } -func (a *ApplicationSpec) HasMultipleSources() bool { - return a.SourceHydrator == nil && len(a.Sources) > 0 +func (spec *ApplicationSpec) HasMultipleSources() bool { + return spec.SourceHydrator == nil && len(spec.Sources) > 0 } -func (a *ApplicationSpec) GetSourcePtrByPosition(sourcePosition int) *ApplicationSource { +func (spec *ApplicationSpec) GetSourcePtrByPosition(sourcePosition int) *ApplicationSource { // if Application has multiple sources, return the first source in sources - return a.GetSourcePtrByIndex(sourcePosition - 1) + return spec.GetSourcePtrByIndex(sourcePosition - 1) } -func (a *ApplicationSpec) GetSourcePtrByIndex(sourceIndex int) *ApplicationSource { - if a.SourceHydrator != nil { - source := a.SourceHydrator.GetSyncSource() +func (spec *ApplicationSpec) GetSourcePtrByIndex(sourceIndex int) *ApplicationSource { + if spec.SourceHydrator != nil { + source := spec.SourceHydrator.GetSyncSource() return &source } // if Application has multiple sources, return the first source in sources - if a.HasMultipleSources() { + if spec.HasMultipleSources() { if sourceIndex > 0 { - return &a.Sources[sourceIndex] + return &spec.Sources[sourceIndex] } - return &a.Sources[0] + return &spec.Sources[0] } - return a.Source + return spec.Source } // AllowsConcurrentProcessing returns true if given application source can be processed concurrently -func (a *ApplicationSource) AllowsConcurrentProcessing() bool { +func (source *ApplicationSource) AllowsConcurrentProcessing() bool { switch { // Kustomize with parameters requires changing kustomization.yaml file - case a.Kustomize != nil: - return a.Kustomize.AllowsConcurrentProcessing() + case source.Kustomize != nil: + return source.Kustomize.AllowsConcurrentProcessing() } return true } // IsRef returns true when the application source is of type Ref -func (a *ApplicationSource) IsRef() bool { - return a.Ref != "" +func (source *ApplicationSource) IsRef() bool { + return source.Ref != "" } // IsHelm returns true when the application source is of type Helm -func (a *ApplicationSource) IsHelm() bool { - return a.Chart != "" +func (source *ApplicationSource) IsHelm() bool { + return source.Chart != "" } // IsHelmOci returns true when the application source is of type Helm OCI -func (a *ApplicationSource) IsHelmOci() bool { - if a.Chart == "" { +func (source *ApplicationSource) IsHelmOci() bool { + if source.Chart == "" { return false } - return helm.IsHelmOciRepo(a.RepoURL) + return helm.IsHelmOciRepo(source.RepoURL) } // IsZero returns true if the application source is considered empty -func (a *ApplicationSource) IsZero() bool { - return a == nil || - a.RepoURL == "" && - a.Path == "" && - a.TargetRevision == "" && - a.Helm.IsZero() && - a.Kustomize.IsZero() && - a.Directory.IsZero() && - a.Plugin.IsZero() +func (source *ApplicationSource) IsZero() bool { + return source == nil || + source.RepoURL == "" && + source.Path == "" && + source.TargetRevision == "" && + source.Helm.IsZero() && + source.Kustomize.IsZero() && + source.Directory.IsZero() && + source.Plugin.IsZero() } // GetNamespaceOrDefault gets the static namespace configured in the source. If none is configured, returns the given // default. -func (a *ApplicationSource) GetNamespaceOrDefault(defaultNamespace string) string { - if a == nil { +func (source *ApplicationSource) GetNamespaceOrDefault(defaultNamespace string) string { + if source == nil { return defaultNamespace } - if a.Helm != nil && a.Helm.Namespace != "" { - return a.Helm.Namespace + if source.Helm != nil && source.Helm.Namespace != "" { + return source.Helm.Namespace } - if a.Kustomize != nil && a.Kustomize.Namespace != "" { - return a.Kustomize.Namespace + if source.Kustomize != nil && source.Kustomize.Namespace != "" { + return source.Kustomize.Namespace } return defaultNamespace } // GetKubeVersionOrDefault gets the static Kubernetes API version configured in the source. If none is configured, // returns the given default. -func (a *ApplicationSource) GetKubeVersionOrDefault(defaultKubeVersion string) string { - if a == nil { +func (source *ApplicationSource) GetKubeVersionOrDefault(defaultKubeVersion string) string { + if source == nil { return defaultKubeVersion } - if a.Helm != nil && a.Helm.KubeVersion != "" { - return a.Helm.KubeVersion + if source.Helm != nil && source.Helm.KubeVersion != "" { + return source.Helm.KubeVersion } - if a.Kustomize != nil && a.Kustomize.KubeVersion != "" { - return a.Kustomize.KubeVersion + if source.Kustomize != nil && source.Kustomize.KubeVersion != "" { + return source.Kustomize.KubeVersion } return defaultKubeVersion } // GetAPIVersionsOrDefault gets the static API versions list configured in the source. If none is configured, returns // the given default. -func (a *ApplicationSource) GetAPIVersionsOrDefault(defaultAPIVersions []string) []string { - if a == nil { +func (source *ApplicationSource) GetAPIVersionsOrDefault(defaultAPIVersions []string) []string { + if source == nil { return defaultAPIVersions } - if a.Helm != nil && len(a.Helm.APIVersions) > 0 { - return a.Helm.APIVersions + if source.Helm != nil && len(source.Helm.APIVersions) > 0 { + return source.Helm.APIVersions } - if a.Kustomize != nil && len(a.Kustomize.APIVersions) > 0 { - return a.Kustomize.APIVersions + if source.Kustomize != nil && len(source.Kustomize.APIVersions) > 0 { + return source.Kustomize.APIVersions } return defaultAPIVersions } @@ -558,39 +558,39 @@ func NewHelmFileParameter(text string) (*HelmFileParameter, error) { // AddParameter adds a HelmParameter to the application source. If a parameter with the same name already // exists, its value will be overwritten. Otherwise, the HelmParameter will be appended as a new entry. -func (in *ApplicationSourceHelm) AddParameter(p HelmParameter) { +func (ash *ApplicationSourceHelm) AddParameter(p HelmParameter) { found := false - for i, cp := range in.Parameters { + for i, cp := range ash.Parameters { if cp.Name == p.Name { found = true - in.Parameters[i] = p + ash.Parameters[i] = p break } } if !found { - in.Parameters = append(in.Parameters, p) + ash.Parameters = append(ash.Parameters, p) } } // AddFileParameter adds a HelmFileParameter to the application source. If a file parameter with the same name already // exists, its value will be overwritten. Otherwise, the HelmFileParameter will be appended as a new entry. -func (in *ApplicationSourceHelm) AddFileParameter(p HelmFileParameter) { +func (ash *ApplicationSourceHelm) AddFileParameter(p HelmFileParameter) { found := false - for i, cp := range in.FileParameters { + for i, cp := range ash.FileParameters { if cp.Name == p.Name { found = true - in.FileParameters[i] = p + ash.FileParameters[i] = p break } } if !found { - in.FileParameters = append(in.FileParameters, p) + ash.FileParameters = append(ash.FileParameters, p) } } // IsZero Returns true if the Helm options in an application source are considered zero -func (h *ApplicationSourceHelm) IsZero() bool { - return h == nil || (h.Version == "") && (h.ReleaseName == "") && len(h.ValueFiles) == 0 && len(h.Parameters) == 0 && len(h.FileParameters) == 0 && h.ValuesIsEmpty() && !h.PassCredentials && !h.IgnoreMissingValueFiles && !h.SkipCrds && !h.SkipTests && !h.SkipSchemaValidation && h.KubeVersion == "" && len(h.APIVersions) == 0 && h.Namespace == "" +func (ash *ApplicationSourceHelm) IsZero() bool { + return ash == nil || (ash.Version == "") && (ash.ReleaseName == "") && len(ash.ValueFiles) == 0 && len(ash.Parameters) == 0 && len(ash.FileParameters) == 0 && ash.ValuesIsEmpty() && !ash.PassCredentials && !ash.IgnoreMissingValueFiles && !ash.SkipCrds && !ash.SkipTests && !ash.SkipSchemaValidation && ash.KubeVersion == "" && len(ash.APIVersions) == 0 && ash.Namespace == "" } // KustomizeImage represents a Kustomize image definition in the format [old_image_name=]: @@ -1169,9 +1169,9 @@ type SourceHydratorStatus struct { CurrentOperation *HydrateOperation `json:"currentOperation,omitempty" protobuf:"bytes,2,opt,name=currentOperation"` } -func (a *ApplicationStatus) FindResource(key kube.ResourceKey) (*ResourceStatus, bool) { - for i := range a.Resources { - res := a.Resources[i] +func (status *ApplicationStatus) FindResource(key kube.ResourceKey) (*ResourceStatus, bool) { + for i := range status.Resources { + res := status.Resources[i] if kube.NewResourceKey(res.Group, res.Kind, res.Namespace, res.Name) == key { return &res, true } @@ -1221,12 +1221,12 @@ const ( // If app has multisources, it will return all corresponding revisions preserving // order from the app.spec.sources. If app has only one source, it will return a // single revision in the list. -func (a *ApplicationStatus) GetRevisions() []string { +func (status *ApplicationStatus) GetRevisions() []string { revisions := []string{} - if len(a.Sync.Revisions) > 0 { - revisions = a.Sync.Revisions - } else if a.Sync.Revision != "" { - revisions = append(revisions, a.Sync.Revision) + if len(status.Sync.Revisions) > 0 { + revisions = status.Sync.Revisions + } else if status.Sync.Revision != "" { + revisions = append(revisions, status.Sync.Revision) } return revisions } @@ -2288,20 +2288,20 @@ type ResourceOverride struct { } // TODO: describe this method -func (s *ResourceOverride) UnmarshalJSON(data []byte) error { +func (ro *ResourceOverride) UnmarshalJSON(data []byte) error { raw := &rawResourceOverride{} if err := json.Unmarshal(data, &raw); err != nil { return err } - s.KnownTypeFields = raw.KnownTypeFields - s.HealthLua = raw.HealthLua - s.UseOpenLibs = raw.UseOpenLibs - s.Actions = raw.Actions - err := yaml.Unmarshal([]byte(raw.IgnoreDifferences), &s.IgnoreDifferences) + ro.KnownTypeFields = raw.KnownTypeFields + ro.HealthLua = raw.HealthLua + ro.UseOpenLibs = raw.UseOpenLibs + ro.Actions = raw.Actions + err := yaml.Unmarshal([]byte(raw.IgnoreDifferences), &ro.IgnoreDifferences) if err != nil { return err } - err = yaml.Unmarshal([]byte(raw.IgnoreResourceUpdates), &s.IgnoreResourceUpdates) + err = yaml.Unmarshal([]byte(raw.IgnoreResourceUpdates), &ro.IgnoreResourceUpdates) if err != nil { return err } @@ -2309,23 +2309,23 @@ func (s *ResourceOverride) UnmarshalJSON(data []byte) error { } // TODO: describe this method -func (s ResourceOverride) MarshalJSON() ([]byte, error) { - ignoreDifferencesData, err := yaml.Marshal(s.IgnoreDifferences) +func (ro ResourceOverride) MarshalJSON() ([]byte, error) { + ignoreDifferencesData, err := yaml.Marshal(ro.IgnoreDifferences) if err != nil { return nil, err } - ignoreResourceUpdatesData, err := yaml.Marshal(s.IgnoreResourceUpdates) + ignoreResourceUpdatesData, err := yaml.Marshal(ro.IgnoreResourceUpdates) if err != nil { return nil, err } - raw := &rawResourceOverride{s.HealthLua, s.UseOpenLibs, s.Actions, string(ignoreDifferencesData), string(ignoreResourceUpdatesData), s.KnownTypeFields} + raw := &rawResourceOverride{ro.HealthLua, ro.UseOpenLibs, ro.Actions, string(ignoreDifferencesData), string(ignoreResourceUpdatesData), ro.KnownTypeFields} return json.Marshal(raw) } // TODO: describe this method -func (o *ResourceOverride) GetActions() (ResourceActions, error) { +func (ro *ResourceOverride) GetActions() (ResourceActions, error) { var actions ResourceActions - err := yaml.Unmarshal([]byte(o.Actions), &actions) + err := yaml.Unmarshal([]byte(ro.Actions), &actions) if err != nil { return actions, err } @@ -2565,24 +2565,24 @@ type SyncWindow struct { } // HasWindows returns true if SyncWindows has one or more SyncWindow -func (s *SyncWindows) HasWindows() bool { - return s != nil && len(*s) > 0 +func (w *SyncWindows) HasWindows() bool { + return w != nil && len(*w) > 0 } // Active returns a list of sync windows that are currently active -func (s *SyncWindows) Active() (*SyncWindows, error) { - return s.active(time.Now()) +func (w *SyncWindows) Active() (*SyncWindows, error) { + return w.active(time.Now()) } -func (s *SyncWindows) active(currentTime time.Time) (*SyncWindows, error) { +func (w *SyncWindows) active(currentTime time.Time) (*SyncWindows, error) { // If SyncWindows.Active() is called outside of a UTC locale, it should be // first converted to UTC before we scan through the SyncWindows. currentTime = currentTime.In(time.UTC) - if s.HasWindows() { + if w.HasWindows() { var active SyncWindows specParser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow) - for _, w := range *s { + for _, w := range *w { schedule, sErr := specParser.Parse(w.Schedule) if sErr != nil { return nil, fmt.Errorf("cannot parse schedule '%s': %w", w.Schedule, sErr) @@ -2609,19 +2609,19 @@ func (s *SyncWindows) active(currentTime time.Time) (*SyncWindows, error) { // InactiveAllows will iterate over the SyncWindows and return all inactive allow windows // for the current time. If the current time is in an inactive allow window, syncs will // be denied. -func (s *SyncWindows) InactiveAllows() (*SyncWindows, error) { - return s.inactiveAllows(time.Now()) +func (w *SyncWindows) InactiveAllows() (*SyncWindows, error) { + return w.inactiveAllows(time.Now()) } -func (s *SyncWindows) inactiveAllows(currentTime time.Time) (*SyncWindows, error) { +func (w *SyncWindows) inactiveAllows(currentTime time.Time) (*SyncWindows, error) { // If SyncWindows.InactiveAllows() is called outside of a UTC locale, it should be // first converted to UTC before we scan through the SyncWindows. currentTime = currentTime.In(time.UTC) - if s.HasWindows() { + if w.HasWindows() { var inactive SyncWindows specParser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow) - for _, w := range *s { + for _, w := range *w { if w.Kind == "allow" { schedule, sErr := specParser.Parse(w.Schedule) if sErr != nil { @@ -2658,7 +2658,7 @@ func (w *SyncWindow) scheduleOffsetByTimeZone() time.Duration { } // AddWindow adds a sync window with the given parameters to the AppProject -func (s *AppProjectSpec) AddWindow(knd string, sch string, dur string, app []string, ns []string, cl []string, ms bool, timeZone string) error { +func (spec *AppProjectSpec) AddWindow(knd string, sch string, dur string, app []string, ns []string, cl []string, ms bool, timeZone string) error { if len(knd) == 0 || len(sch) == 0 || len(dur) == 0 { return errors.New("cannot create window: require kind, schedule, duration and one or more of applications, namespaces and clusters") } @@ -2686,18 +2686,18 @@ func (s *AppProjectSpec) AddWindow(knd string, sch string, dur string, app []str return err } - s.SyncWindows = append(s.SyncWindows, window) + spec.SyncWindows = append(spec.SyncWindows, window) return nil } // DeleteWindow deletes a sync window with the given id from the AppProject -func (s *AppProjectSpec) DeleteWindow(id int) error { +func (spec *AppProjectSpec) DeleteWindow(id int) error { var exists bool - for i := range s.SyncWindows { + for i := range spec.SyncWindows { if i == id { exists = true - s.SyncWindows = append(s.SyncWindows[:i], s.SyncWindows[i+1:]...) + spec.SyncWindows = append(spec.SyncWindows[:i], spec.SyncWindows[i+1:]...) break } } @@ -2921,10 +2921,10 @@ func (w *SyncWindow) Validate() error { } // DestinationClusters returns a list of cluster URLs allowed as destination in an AppProject -func (d AppProjectSpec) DestinationClusters() []string { +func (spec AppProjectSpec) DestinationClusters() []string { servers := make([]string, 0) - for _, d := range d.Destinations { + for _, d := range spec.Destinations { servers = append(servers, d.Server) } @@ -3214,12 +3214,12 @@ func (source *ApplicationSource) ExplicitType() (*ApplicationSourceType, error) } // Equals compares two instances of ApplicationDestination and returns true if instances are equal. -func (dest ApplicationDestination) Equals(other ApplicationDestination) bool { +func (d ApplicationDestination) Equals(other ApplicationDestination) bool { // ignore destination cluster name and isServerInferred fields during comparison // since server URL is inferred from cluster name - if dest.isServerInferred { - dest.Server = "" - dest.isServerInferred = false + if d.isServerInferred { + d.Server = "" + d.isServerInferred = false } if other.isServerInferred { @@ -3227,9 +3227,9 @@ func (dest ApplicationDestination) Equals(other ApplicationDestination) bool { other.isServerInferred = false } - if dest.isNameInferred { - dest.Name = "" - dest.isNameInferred = false + if d.isNameInferred { + d.Name = "" + d.isNameInferred = false } if other.isNameInferred { @@ -3237,7 +3237,7 @@ func (dest ApplicationDestination) Equals(other ApplicationDestination) bool { other.isNameInferred = false } - return reflect.DeepEqual(dest, other) + return reflect.DeepEqual(d, other) } // GetProject returns the application's project. This is preferred over spec.Project which may be empty @@ -3539,37 +3539,37 @@ func (d *ApplicationDestination) MarshalJSON() ([]byte, error) { // tracking values, i.e. in the format _. When the namespace // of the application is similar to the value of defaultNs, only the name of // the application is returned to keep backwards compatibility. -func (a *Application) InstanceName(defaultNs string) string { +func (app *Application) InstanceName(defaultNs string) string { // When app has no namespace set, or the namespace is the default ns, we // return just the application name - if a.Namespace == "" || a.Namespace == defaultNs { - return a.Name + if app.Namespace == "" || app.Namespace == defaultNs { + return app.Name } - return a.Namespace + "_" + a.Name + return app.Namespace + "_" + app.Name } // QualifiedName returns the full qualified name of the application, including // the name of the namespace it is created in delimited by a forward slash, // i.e. / -func (a *Application) QualifiedName() string { - if a.Namespace == "" { - return a.Name +func (app *Application) QualifiedName() string { + if app.Namespace == "" { + return app.Name } else { - return a.Namespace + "/" + a.Name + return app.Namespace + "/" + app.Name } } // RBACName returns the full qualified RBAC resource name for the application // in a backwards-compatible way. -func (a *Application) RBACName(defaultNS string) string { - return security.RBACName(defaultNS, a.Spec.GetProject(), a.Namespace, a.Name) +func (app *Application) RBACName(defaultNS string) string { + return security.RBACName(defaultNS, app.Spec.GetProject(), app.Namespace, app.Name) } // GetAnnotation returns the value of the specified annotation if it exists, // e.g., a.GetAnnotation("argocd.argoproj.io/manifest-generate-paths"). // If the annotation does not exist, it returns an empty string. -func (a *Application) GetAnnotation(annotation string) string { - v, exists := a.Annotations[annotation] +func (app *Application) GetAnnotation(annotation string) string { + v, exists := app.Annotations[annotation] if !exists { return "" } @@ -3577,8 +3577,8 @@ func (a *Application) GetAnnotation(annotation string) string { return v } -func (a *Application) IsDeletionConfirmed(since time.Time) bool { - val := a.GetAnnotation(synccommon.AnnotationDeletionApproved) +func (app *Application) IsDeletionConfirmed(since time.Time) bool { + val := app.GetAnnotation(synccommon.AnnotationDeletionApproved) if val == "" { return false } diff --git a/server/server.go b/server/server.go index c3ef5ef0ea5c4..b9c0e412dab2c 100644 --- a/server/server.go +++ b/server/server.go @@ -392,15 +392,15 @@ const ( notObjectErrMsg = "object does not implement the Object interfaces" ) -func (a *ArgoCDServer) healthCheck(r *http.Request) error { - if a.terminateRequested.Load() { +func (server *ArgoCDServer) healthCheck(r *http.Request) error { + if server.terminateRequested.Load() { return errors.New("API Server is terminating and unable to serve requests.") } - if !a.available.Load() { + if !server.available.Load() { return errors.New("API Server is not available. It either hasn't started or is restarting.") } if val, ok := r.URL.Query()["full"]; ok && len(val) > 0 && val[0] == "true" { - argoDB := db.NewDB(a.Namespace, a.settingsMgr, a.KubeClientset) + argoDB := db.NewDB(server.Namespace, server.settingsMgr, server.KubeClientset) _, err := argoDB.ListClusters(r.Context()) if err != nil && strings.Contains(err.Error(), notObjectErrMsg) { return err @@ -438,18 +438,18 @@ func (l *Listeners) Close() error { } // logInClusterWarnings checks the in-cluster configuration and prints out any warnings. -func (a *ArgoCDServer) logInClusterWarnings() error { +func (server *ArgoCDServer) logInClusterWarnings() error { labelSelector := labels.NewSelector() req, err := labels.NewRequirement(common.LabelKeySecretType, selection.Equals, []string{common.LabelValueSecretTypeCluster}) if err != nil { return fmt.Errorf("failed to construct cluster-type label selector: %w", err) } labelSelector = labelSelector.Add(*req) - secretsLister, err := a.settingsMgr.GetSecretsLister() + secretsLister, err := server.settingsMgr.GetSecretsLister() if err != nil { return fmt.Errorf("failed to get secrets lister: %w", err) } - clusterSecrets, err := secretsLister.Secrets(a.ArgoCDServerOpts.Namespace).List(labelSelector) + clusterSecrets, err := secretsLister.Secrets(server.ArgoCDServerOpts.Namespace).List(labelSelector) if err != nil { return fmt.Errorf("failed to list cluster secrets: %w", err) } @@ -465,7 +465,7 @@ func (a *ArgoCDServer) logInClusterWarnings() error { } if len(inClusterSecrets) > 0 { // Don't make this call unless we actually have in-cluster secrets, to save time. - dbSettings, err := a.settingsMgr.GetSettings() + dbSettings, err := server.settingsMgr.GetSettings() if err != nil { return fmt.Errorf("could not get DB settings: %w", err) } @@ -491,12 +491,12 @@ func startListener(host string, port int) (net.Listener, error) { return conn, realErr } -func (a *ArgoCDServer) Listen() (*Listeners, error) { - mainLn, err := startListener(a.ListenHost, a.ListenPort) +func (server *ArgoCDServer) Listen() (*Listeners, error) { + mainLn, err := startListener(server.ListenHost, server.ListenPort) if err != nil { return nil, err } - metricsLn, err := startListener(a.ListenHost, a.MetricsPort) + metricsLn, err := startListener(server.ListenHost, server.MetricsPort) if err != nil { io.Close(mainLn) return nil, err @@ -506,14 +506,14 @@ func (a *ArgoCDServer) Listen() (*Listeners, error) { dOpts = append(dOpts, grpc.WithUserAgent(fmt.Sprintf("%s/%s", common.ArgoCDUserAgentName, common.GetVersion().Version))) dOpts = append(dOpts, grpc.WithUnaryInterceptor(grpc_util.OTELUnaryClientInterceptor())) dOpts = append(dOpts, grpc.WithStreamInterceptor(grpc_util.OTELStreamClientInterceptor())) - if a.useTLS() { + if server.useTLS() { // The following sets up the dial Options for grpc-gateway to talk to gRPC server over TLS. // grpc-gateway is just translating HTTP/HTTPS requests as gRPC requests over localhost, // so we need to supply the same certificates to establish the connections that a normal, // external gRPC client would need. - tlsConfig := a.settings.TLSConfig() - if a.TLSConfigCustomizer != nil { - a.TLSConfigCustomizer(tlsConfig) + tlsConfig := server.settings.TLSConfig() + if server.TLSConfigCustomizer != nil { + server.TLSConfigCustomizer(tlsConfig) } tlsConfig.InsecureSkipVerify = true dCreds := credentials.NewTLS(tlsConfig) @@ -522,7 +522,7 @@ func (a *ArgoCDServer) Listen() (*Listeners, error) { dOpts = append(dOpts, grpc.WithTransportCredentials(insecure.NewCredentials())) } // nolint:staticcheck - conn, err := grpc.Dial(fmt.Sprintf("localhost:%d", a.ListenPort), dOpts...) + conn, err := grpc.Dial(fmt.Sprintf("localhost:%d", server.ListenPort), dOpts...) if err != nil { io.Close(mainLn) io.Close(metricsLn) @@ -532,51 +532,51 @@ func (a *ArgoCDServer) Listen() (*Listeners, error) { } // Init starts informers used by the API server -func (a *ArgoCDServer) Init(ctx context.Context) { - go a.projInformer.Run(ctx.Done()) - go a.appInformer.Run(ctx.Done()) - go a.appsetInformer.Run(ctx.Done()) - go a.configMapInformer.Run(ctx.Done()) - go a.secretInformer.Run(ctx.Done()) +func (server *ArgoCDServer) Init(ctx context.Context) { + go server.projInformer.Run(ctx.Done()) + go server.appInformer.Run(ctx.Done()) + go server.appsetInformer.Run(ctx.Done()) + go server.configMapInformer.Run(ctx.Done()) + go server.secretInformer.Run(ctx.Done()) } // Run runs the API Server // We use k8s.io/code-generator/cmd/go-to-protobuf to generate the .proto files from the API types. // k8s.io/ go-to-protobuf uses protoc-gen-gogo, which comes from gogo/protobuf (a fork of // golang/protobuf). -func (a *ArgoCDServer) Run(ctx context.Context, listeners *Listeners) { +func (server *ArgoCDServer) Run(ctx context.Context, listeners *Listeners) { defer func() { if r := recover(); r != nil { log.WithField("trace", string(debug.Stack())).Error("Recovered from panic: ", r) - a.terminateRequested.Store(true) - a.shutdown() + server.terminateRequested.Store(true) + server.shutdown() } }() - a.userStateStorage.Init(ctx) + server.userStateStorage.Init(ctx) - metricsServ := metrics.NewMetricsServer(a.MetricsHost, a.MetricsPort) - if a.RedisClient != nil { - cacheutil.CollectMetrics(a.RedisClient, metricsServ, a.userStateStorage.GetLockObject()) + metricsServ := metrics.NewMetricsServer(server.MetricsHost, server.MetricsPort) + if server.RedisClient != nil { + cacheutil.CollectMetrics(server.RedisClient, metricsServ, server.userStateStorage.GetLockObject()) } - svcSet := newArgoCDServiceSet(a) - a.serviceSet = svcSet - grpcS, appResourceTreeFn := a.newGRPCServer() + svcSet := newArgoCDServiceSet(server) + server.serviceSet = svcSet + grpcS, appResourceTreeFn := server.newGRPCServer() grpcWebS := grpcweb.WrapServer(grpcS) var httpS *http.Server var httpsS *http.Server - if a.useTLS() { - httpS = newRedirectServer(a.ListenPort, a.RootPath) - httpsS = a.newHTTPServer(ctx, a.ListenPort, grpcWebS, appResourceTreeFn, listeners.GatewayConn, metricsServ) + if server.useTLS() { + httpS = newRedirectServer(server.ListenPort, server.RootPath) + httpsS = server.newHTTPServer(ctx, server.ListenPort, grpcWebS, appResourceTreeFn, listeners.GatewayConn, metricsServ) } else { - httpS = a.newHTTPServer(ctx, a.ListenPort, grpcWebS, appResourceTreeFn, listeners.GatewayConn, metricsServ) + httpS = server.newHTTPServer(ctx, server.ListenPort, grpcWebS, appResourceTreeFn, listeners.GatewayConn, metricsServ) } - if a.RootPath != "" { - httpS.Handler = withRootPath(httpS.Handler, a) + if server.RootPath != "" { + httpS.Handler = withRootPath(httpS.Handler, server) if httpsS != nil { - httpsS.Handler = withRootPath(httpsS.Handler, a) + httpsS.Handler = withRootPath(httpsS.Handler, server) } } httpS.Handler = &bug21955Workaround{handler: httpS.Handler} @@ -590,7 +590,7 @@ func (a *ArgoCDServer) Run(ctx context.Context, listeners *Listeners) { var grpcL net.Listener var httpL net.Listener var httpsL net.Listener - if !a.useTLS() { + if !server.useTLS() { httpL = tcpm.Match(cmux.HTTP1Fast("PATCH")) grpcL = tcpm.MatchWithWriters(cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc")) } else { @@ -607,10 +607,10 @@ func (a *ArgoCDServer) Run(ctx context.Context, listeners *Listeners) { NextProtos: []string{"http/1.1", "h2"}, } tlsConfig.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) { - return a.settings.Certificate, nil + return server.settings.Certificate, nil } - if a.TLSConfigCustomizer != nil { - a.TLSConfigCustomizer(&tlsConfig) + if server.TLSConfigCustomizer != nil { + server.TLSConfigCustomizer(&tlsConfig) } tlsl = tls.NewListener(tlsl, &tlsConfig) @@ -622,26 +622,26 @@ func (a *ArgoCDServer) Run(ctx context.Context, listeners *Listeners) { // Start the muxed listeners for our servers log.Infof("argocd %s serving on port %d (url: %s, tls: %v, namespace: %s, sso: %v)", - common.GetVersion(), a.ListenPort, a.settings.URL, a.useTLS(), a.Namespace, a.settings.IsSSOConfigured()) - log.Infof("Enabled application namespace patterns: %s", a.allowedApplicationNamespacesAsString()) - - go func() { a.checkServeErr("grpcS", grpcS.Serve(grpcL)) }() - go func() { a.checkServeErr("httpS", httpS.Serve(httpL)) }() - if a.useTLS() { - go func() { a.checkServeErr("httpsS", httpsS.Serve(httpsL)) }() - go func() { a.checkServeErr("tlsm", tlsm.Serve()) }() - } - go a.watchSettings() - go a.rbacPolicyLoader(ctx) - go func() { a.checkServeErr("tcpm", tcpm.Serve()) }() - go func() { a.checkServeErr("metrics", metricsServ.Serve(listeners.Metrics)) }() - if !cache.WaitForCacheSync(ctx.Done(), a.projInformer.HasSynced, a.appInformer.HasSynced) { + common.GetVersion(), server.ListenPort, server.settings.URL, server.useTLS(), server.Namespace, server.settings.IsSSOConfigured()) + log.Infof("Enabled application namespace patterns: %s", server.allowedApplicationNamespacesAsString()) + + go func() { server.checkServeErr("grpcS", grpcS.Serve(grpcL)) }() + go func() { server.checkServeErr("httpS", httpS.Serve(httpL)) }() + if server.useTLS() { + go func() { server.checkServeErr("httpsS", httpsS.Serve(httpsL)) }() + go func() { server.checkServeErr("tlsm", tlsm.Serve()) }() + } + go server.watchSettings() + go server.rbacPolicyLoader(ctx) + go func() { server.checkServeErr("tcpm", tcpm.Serve()) }() + go func() { server.checkServeErr("metrics", metricsServ.Serve(listeners.Metrics)) }() + if !cache.WaitForCacheSync(ctx.Done(), server.projInformer.HasSynced, server.appInformer.HasSynced) { log.Fatal("Timed out waiting for project cache to sync") } shutdownFunc := func() { log.Info("API Server shutdown initiated. Shutting down servers...") - a.available.Store(false) + server.available.Store(false) shutdownCtx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() var wg gosync.WaitGroup @@ -656,7 +656,7 @@ func (a *ArgoCDServer) Run(ctx context.Context, listeners *Listeners) { } }() - if a.useTLS() { + if server.useTLS() { // Shutdown https server wg.Add(1) go func() { @@ -685,7 +685,7 @@ func (a *ArgoCDServer) Run(ctx context.Context, listeners *Listeners) { } }() - if a.useTLS() { + if server.useTLS() { // Shutdown tls server wg.Add(1) go func() { @@ -716,37 +716,37 @@ func (a *ArgoCDServer) Run(ctx context.Context, listeners *Listeners) { log.Warn("Graceful shutdown timeout. Exiting...") } } - a.shutdown = shutdownFunc - signal.Notify(a.stopCh, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) - a.available.Store(true) + server.shutdown = shutdownFunc + signal.Notify(server.stopCh, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) + server.available.Store(true) select { - case signal := <-a.stopCh: + case signal := <-server.stopCh: log.Infof("API Server received signal: %s", signal.String()) gracefulRestartSignal := GracefulRestartSignal{} if signal != gracefulRestartSignal { - a.terminateRequested.Store(true) + server.terminateRequested.Store(true) } - a.shutdown() + server.shutdown() case <-ctx.Done(): log.Infof("API Server: %s", ctx.Err()) - a.terminateRequested.Store(true) - a.shutdown() + server.terminateRequested.Store(true) + server.shutdown() } } -func (a *ArgoCDServer) Initialized() bool { - return a.projInformer.HasSynced() && a.appInformer.HasSynced() +func (server *ArgoCDServer) Initialized() bool { + return server.projInformer.HasSynced() && server.appInformer.HasSynced() } // TerminateRequested returns whether a shutdown was initiated by a signal or context cancel // as opposed to a watch. -func (a *ArgoCDServer) TerminateRequested() bool { - return a.terminateRequested.Load() +func (server *ArgoCDServer) TerminateRequested() bool { + return server.terminateRequested.Load() } // checkServeErr checks the error from a .Serve() call to decide if it was a graceful shutdown -func (a *ArgoCDServer) checkServeErr(name string, err error) { +func (server *ArgoCDServer) checkServeErr(name string, err error) { if err != nil && !errors.Is(err, http.ErrServerClosed) { log.Errorf("Error received from server %s: %v", name, err) } else { @@ -772,81 +772,81 @@ func checkOIDCConfigChange(currentOIDCConfig *settings_util.OIDCConfig, newArgoC // watchSettings watches the configmap and secret for any setting updates that would warrant a // restart of the API server. -func (a *ArgoCDServer) watchSettings() { +func (server *ArgoCDServer) watchSettings() { updateCh := make(chan *settings_util.ArgoCDSettings, 1) - a.settingsMgr.Subscribe(updateCh) + server.settingsMgr.Subscribe(updateCh) - prevURL := a.settings.URL - prevAdditionalURLs := a.settings.AdditionalURLs - prevOIDCConfig := a.settings.OIDCConfig() - prevDexCfgBytes, err := dexutil.GenerateDexConfigYAML(a.settings, a.DexTLSConfig == nil || a.DexTLSConfig.DisableTLS) + prevURL := server.settings.URL + prevAdditionalURLs := server.settings.AdditionalURLs + prevOIDCConfig := server.settings.OIDCConfig() + prevDexCfgBytes, err := dexutil.GenerateDexConfigYAML(server.settings, server.DexTLSConfig == nil || server.DexTLSConfig.DisableTLS) errorsutil.CheckError(err) - prevGitHubSecret := a.settings.WebhookGitHubSecret - prevGitLabSecret := a.settings.WebhookGitLabSecret - prevBitbucketUUID := a.settings.WebhookBitbucketUUID - prevBitbucketServerSecret := a.settings.WebhookBitbucketServerSecret - prevGogsSecret := a.settings.WebhookGogsSecret - prevExtConfig := a.settings.ExtensionConfig + prevGitHubSecret := server.settings.WebhookGitHubSecret + prevGitLabSecret := server.settings.WebhookGitLabSecret + prevBitbucketUUID := server.settings.WebhookBitbucketUUID + prevBitbucketServerSecret := server.settings.WebhookBitbucketServerSecret + prevGogsSecret := server.settings.WebhookGogsSecret + prevExtConfig := server.settings.ExtensionConfig var prevCert, prevCertKey string - if a.settings.Certificate != nil && !a.ArgoCDServerOpts.Insecure { - prevCert, prevCertKey = tlsutil.EncodeX509KeyPairString(*a.settings.Certificate) + if server.settings.Certificate != nil && !server.ArgoCDServerOpts.Insecure { + prevCert, prevCertKey = tlsutil.EncodeX509KeyPairString(*server.settings.Certificate) } for { newSettings := <-updateCh - a.settings = newSettings - newDexCfgBytes, err := dexutil.GenerateDexConfigYAML(a.settings, a.DexTLSConfig == nil || a.DexTLSConfig.DisableTLS) + server.settings = newSettings + newDexCfgBytes, err := dexutil.GenerateDexConfigYAML(server.settings, server.DexTLSConfig == nil || server.DexTLSConfig.DisableTLS) errorsutil.CheckError(err) if string(newDexCfgBytes) != string(prevDexCfgBytes) { log.Infof("dex config modified. restarting") break } - if checkOIDCConfigChange(prevOIDCConfig, a.settings) { + if checkOIDCConfigChange(prevOIDCConfig, server.settings) { log.Infof("oidc config modified. restarting") break } - if prevURL != a.settings.URL { + if prevURL != server.settings.URL { log.Infof("url modified. restarting") break } - if !reflect.DeepEqual(prevAdditionalURLs, a.settings.AdditionalURLs) { + if !reflect.DeepEqual(prevAdditionalURLs, server.settings.AdditionalURLs) { log.Infof("additionalURLs modified. restarting") break } - if prevGitHubSecret != a.settings.WebhookGitHubSecret { + if prevGitHubSecret != server.settings.WebhookGitHubSecret { log.Infof("github secret modified. restarting") break } - if prevGitLabSecret != a.settings.WebhookGitLabSecret { + if prevGitLabSecret != server.settings.WebhookGitLabSecret { log.Infof("gitlab secret modified. restarting") break } - if prevBitbucketUUID != a.settings.WebhookBitbucketUUID { + if prevBitbucketUUID != server.settings.WebhookBitbucketUUID { log.Infof("bitbucket uuid modified. restarting") break } - if prevBitbucketServerSecret != a.settings.WebhookBitbucketServerSecret { + if prevBitbucketServerSecret != server.settings.WebhookBitbucketServerSecret { log.Infof("bitbucket server secret modified. restarting") break } - if prevGogsSecret != a.settings.WebhookGogsSecret { + if prevGogsSecret != server.settings.WebhookGogsSecret { log.Infof("gogs secret modified. restarting") break } - if !reflect.DeepEqual(prevExtConfig, a.settings.ExtensionConfig) { - prevExtConfig = a.settings.ExtensionConfig + if !reflect.DeepEqual(prevExtConfig, server.settings.ExtensionConfig) { + prevExtConfig = server.settings.ExtensionConfig log.Infof("extensions configs modified. Updating proxy registry...") - err := a.extensionManager.UpdateExtensionRegistry(a.settings) + err := server.extensionManager.UpdateExtensionRegistry(server.settings) if err != nil { log.Errorf("error updating extensions configs: %s", err) } else { log.Info("extensions configs updated successfully") } } - if !a.ArgoCDServerOpts.Insecure { + if !server.ArgoCDServerOpts.Insecure { var newCert, newCertKey string - if a.settings.Certificate != nil { - newCert, newCertKey = tlsutil.EncodeX509KeyPairString(*a.settings.Certificate) + if server.settings.Certificate != nil { + newCert, newCertKey = tlsutil.EncodeX509KeyPairString(*server.settings.Certificate) } if newCert != prevCert || newCertKey != prevCertKey { log.Infof("tls certificate modified. reloading certificate") @@ -855,14 +855,14 @@ func (a *ArgoCDServer) watchSettings() { } } log.Info("shutting down settings watch") - a.settingsMgr.Unsubscribe(updateCh) + server.settingsMgr.Unsubscribe(updateCh) close(updateCh) // Triggers server restart - a.stopCh <- GracefulRestartSignal{} + server.stopCh <- GracefulRestartSignal{} } -func (a *ArgoCDServer) rbacPolicyLoader(ctx context.Context) { - err := a.enf.RunPolicyLoader(ctx, func(cm *corev1.ConfigMap) error { +func (server *ArgoCDServer) rbacPolicyLoader(ctx context.Context) { + err := server.enf.RunPolicyLoader(ctx, func(cm *corev1.ConfigMap) error { var scopes []string if scopesStr, ok := cm.Data[rbac.ConfigMapScopesKey]; len(scopesStr) > 0 && ok { scopes = make([]string, 0) @@ -872,20 +872,20 @@ func (a *ArgoCDServer) rbacPolicyLoader(ctx context.Context) { } } - a.policyEnforcer.SetScopes(scopes) + server.policyEnforcer.SetScopes(scopes) return nil }) errorsutil.CheckError(err) } -func (a *ArgoCDServer) useTLS() bool { - if a.Insecure || a.settings.Certificate == nil { +func (server *ArgoCDServer) useTLS() bool { + if server.Insecure || server.settings.Certificate == nil { return false } return true } -func (a *ArgoCDServer) newGRPCServer() (*grpc.Server, application.AppResourceTreeFn) { +func (server *ArgoCDServer) newGRPCServer() (*grpc.Server, application.AppResourceTreeFn) { if enableGRPCTimeHistogram { grpc_prometheus.EnableHandlingTimeHistogram() } @@ -929,51 +929,51 @@ func (a *ArgoCDServer) newGRPCServer() (*grpc.Server, application.AppResourceTre // This is because TLS handshaking occurs in cmux handling sOpts = append(sOpts, grpc.StreamInterceptor(grpc_middleware.ChainStreamServer( otelgrpc.StreamServerInterceptor(), //nolint:staticcheck // TODO: ignore SA1019 for depreciation: see https://github.com/argoproj/argo-cd/issues/18258 - grpc_logrus.StreamServerInterceptor(a.log), + grpc_logrus.StreamServerInterceptor(server.log), grpc_prometheus.StreamServerInterceptor, - grpc_auth.StreamServerInterceptor(a.Authenticate), + grpc_auth.StreamServerInterceptor(server.Authenticate), grpc_util.UserAgentStreamServerInterceptor(common.ArgoCDUserAgentName, clientConstraint), - grpc_util.PayloadStreamServerInterceptor(a.log, true, func(ctx context.Context, fullMethodName string, servingObject any) bool { + grpc_util.PayloadStreamServerInterceptor(server.log, true, func(ctx context.Context, fullMethodName string, servingObject any) bool { return !sensitiveMethods[fullMethodName] }), grpc_util.ErrorCodeK8sStreamServerInterceptor(), grpc_util.ErrorCodeGitStreamServerInterceptor(), - grpc_util.PanicLoggerStreamServerInterceptor(a.log), + grpc_util.PanicLoggerStreamServerInterceptor(server.log), ))) sOpts = append(sOpts, grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer( bug21955WorkaroundInterceptor, otelgrpc.UnaryServerInterceptor(), //nolint:staticcheck // TODO: ignore SA1019 for depreciation: see https://github.com/argoproj/argo-cd/issues/18258 - grpc_logrus.UnaryServerInterceptor(a.log), + grpc_logrus.UnaryServerInterceptor(server.log), grpc_prometheus.UnaryServerInterceptor, - grpc_auth.UnaryServerInterceptor(a.Authenticate), + grpc_auth.UnaryServerInterceptor(server.Authenticate), grpc_util.UserAgentUnaryServerInterceptor(common.ArgoCDUserAgentName, clientConstraint), - grpc_util.PayloadUnaryServerInterceptor(a.log, true, func(ctx context.Context, fullMethodName string, servingObject any) bool { + grpc_util.PayloadUnaryServerInterceptor(server.log, true, func(ctx context.Context, fullMethodName string, servingObject any) bool { return !sensitiveMethods[fullMethodName] }), grpc_util.ErrorCodeK8sUnaryServerInterceptor(), grpc_util.ErrorCodeGitUnaryServerInterceptor(), - grpc_util.PanicLoggerUnaryServerInterceptor(a.log), + grpc_util.PanicLoggerUnaryServerInterceptor(server.log), ))) grpcS := grpc.NewServer(sOpts...) - versionpkg.RegisterVersionServiceServer(grpcS, a.serviceSet.VersionService) - clusterpkg.RegisterClusterServiceServer(grpcS, a.serviceSet.ClusterService) - applicationpkg.RegisterApplicationServiceServer(grpcS, a.serviceSet.ApplicationService) - applicationsetpkg.RegisterApplicationSetServiceServer(grpcS, a.serviceSet.ApplicationSetService) - notificationpkg.RegisterNotificationServiceServer(grpcS, a.serviceSet.NotificationService) - repositorypkg.RegisterRepositoryServiceServer(grpcS, a.serviceSet.RepoService) - repocredspkg.RegisterRepoCredsServiceServer(grpcS, a.serviceSet.RepoCredsService) - sessionpkg.RegisterSessionServiceServer(grpcS, a.serviceSet.SessionService) - settingspkg.RegisterSettingsServiceServer(grpcS, a.serviceSet.SettingsService) - projectpkg.RegisterProjectServiceServer(grpcS, a.serviceSet.ProjectService) - accountpkg.RegisterAccountServiceServer(grpcS, a.serviceSet.AccountService) - certificatepkg.RegisterCertificateServiceServer(grpcS, a.serviceSet.CertificateService) - gpgkeypkg.RegisterGPGKeyServiceServer(grpcS, a.serviceSet.GpgkeyService) + versionpkg.RegisterVersionServiceServer(grpcS, server.serviceSet.VersionService) + clusterpkg.RegisterClusterServiceServer(grpcS, server.serviceSet.ClusterService) + applicationpkg.RegisterApplicationServiceServer(grpcS, server.serviceSet.ApplicationService) + applicationsetpkg.RegisterApplicationSetServiceServer(grpcS, server.serviceSet.ApplicationSetService) + notificationpkg.RegisterNotificationServiceServer(grpcS, server.serviceSet.NotificationService) + repositorypkg.RegisterRepositoryServiceServer(grpcS, server.serviceSet.RepoService) + repocredspkg.RegisterRepoCredsServiceServer(grpcS, server.serviceSet.RepoCredsService) + sessionpkg.RegisterSessionServiceServer(grpcS, server.serviceSet.SessionService) + settingspkg.RegisterSettingsServiceServer(grpcS, server.serviceSet.SettingsService) + projectpkg.RegisterProjectServiceServer(grpcS, server.serviceSet.ProjectService) + accountpkg.RegisterAccountServiceServer(grpcS, server.serviceSet.AccountService) + certificatepkg.RegisterCertificateServiceServer(grpcS, server.serviceSet.CertificateService) + gpgkeypkg.RegisterGPGKeyServiceServer(grpcS, server.serviceSet.GpgkeyService) // Register reflection service on gRPC server. reflection.Register(grpcS) grpc_prometheus.Register(grpcS) - errorsutil.CheckError(a.serviceSet.ProjectService.NormalizeProjs()) - return grpcS, a.serviceSet.AppResourceTreeFn + errorsutil.CheckError(server.serviceSet.ProjectService.NormalizeProjs()) + return grpcS, server.serviceSet.AppResourceTreeFn } type ArgoCDServiceSet struct { @@ -1084,27 +1084,27 @@ func newArgoCDServiceSet(a *ArgoCDServer) *ArgoCDServiceSet { } // translateGrpcCookieHeader conditionally sets a cookie on the response. -func (a *ArgoCDServer) translateGrpcCookieHeader(ctx context.Context, w http.ResponseWriter, resp golang_proto.Message) error { +func (server *ArgoCDServer) translateGrpcCookieHeader(ctx context.Context, w http.ResponseWriter, resp golang_proto.Message) error { if sessionResp, ok := resp.(*sessionpkg.SessionResponse); ok { token := sessionResp.Token - err := a.setTokenCookie(token, w) + err := server.setTokenCookie(token, w) if err != nil { return fmt.Errorf("error setting token cookie from session response: %w", err) } } else if md, ok := runtime.ServerMetadataFromContext(ctx); ok { renewToken := md.HeaderMD[renewTokenKey] if len(renewToken) > 0 { - return a.setTokenCookie(renewToken[0], w) + return server.setTokenCookie(renewToken[0], w) } } return nil } -func (a *ArgoCDServer) setTokenCookie(token string, w http.ResponseWriter) error { - cookiePath := "path=/" + strings.TrimRight(strings.TrimLeft(a.ArgoCDServerOpts.BaseHRef, "/"), "/") +func (server *ArgoCDServer) setTokenCookie(token string, w http.ResponseWriter) error { + cookiePath := "path=/" + strings.TrimRight(strings.TrimLeft(server.ArgoCDServerOpts.BaseHRef, "/"), "/") flags := []string{cookiePath, "SameSite=lax", "httpOnly"} - if !a.Insecure { + if !server.Insecure { flags = append(flags, "Secure") } cookies, err := httputil.MakeCookieMetadata(common.AuthCookieName, token, flags...) @@ -1142,7 +1142,7 @@ func compressHandler(handler http.Handler) http.Handler { // newHTTPServer returns the HTTP server to serve HTTP/HTTPS requests. This is implemented // using grpc-gateway as a proxy to the gRPC server. -func (a *ArgoCDServer) newHTTPServer(ctx context.Context, port int, grpcWebHandler http.Handler, appResourceTreeFn application.AppResourceTreeFn, conn *grpc.ClientConn, metricsReg HTTPMetricsRegistry) *http.Server { +func (server *ArgoCDServer) newHTTPServer(ctx context.Context, port int, grpcWebHandler http.Handler, appResourceTreeFn application.AppResourceTreeFn, conn *grpc.ClientConn, metricsReg HTTPMetricsRegistry) *http.Server { endpoint := fmt.Sprintf("localhost:%d", port) mux := http.NewServeMux() httpS := http.Server{ @@ -1150,8 +1150,8 @@ func (a *ArgoCDServer) newHTTPServer(ctx context.Context, port int, grpcWebHandl Handler: &handlerSwitcher{ handler: mux, urlToHandler: map[string]http.Handler{ - "/api/badge": badge.NewHandler(a.AppClientset, a.settingsMgr, a.Namespace, a.ApplicationNamespaces), - common.LogoutEndpoint: logout.NewHandler(a.AppClientset, a.settingsMgr, a.sessionMgr, a.ArgoCDServerOpts.RootPath, a.ArgoCDServerOpts.BaseHRef, a.Namespace), + "/api/badge": badge.NewHandler(server.AppClientset, server.settingsMgr, server.Namespace, server.ApplicationNamespaces), + common.LogoutEndpoint: logout.NewHandler(server.AppClientset, server.settingsMgr, server.sessionMgr, server.ArgoCDServerOpts.RootPath, server.ArgoCDServerOpts.BaseHRef, server.Namespace), }, contentTypeToHandler: map[string]http.Handler{ "application/grpc-web+proto": grpcWebHandler, @@ -1166,34 +1166,34 @@ func (a *ArgoCDServer) newHTTPServer(ctx context.Context, port int, grpcWebHandl // time.Time, but does not support custom UnmarshalJSON() and MarshalJSON() methods. Therefore // we use our own Marshaler gwMuxOpts := runtime.WithMarshalerOption(runtime.MIMEWildcard, new(grpc_util.JSONMarshaler)) - gwCookieOpts := runtime.WithForwardResponseOption(a.translateGrpcCookieHeader) + gwCookieOpts := runtime.WithForwardResponseOption(server.translateGrpcCookieHeader) gwmux := runtime.NewServeMux(gwMuxOpts, gwCookieOpts) var handler http.Handler = gwmux - if a.EnableGZip { + if server.EnableGZip { handler = compressHandler(handler) } - if len(a.ContentTypes) > 0 { - handler = enforceContentTypes(handler, a.ContentTypes) + if len(server.ContentTypes) > 0 { + handler = enforceContentTypes(handler, server.ContentTypes) } else { log.WithField(common.SecurityField, common.SecurityHigh).Warnf("Content-Type enforcement is disabled, which may make your API vulnerable to CSRF attacks") } mux.Handle("/api/", handler) - terminalOpts := application.TerminalOptions{DisableAuth: a.ArgoCDServerOpts.DisableAuth, Enf: a.enf} + terminalOpts := application.TerminalOptions{DisableAuth: server.ArgoCDServerOpts.DisableAuth, Enf: server.enf} - terminal := application.NewHandler(a.appLister, a.Namespace, a.ApplicationNamespaces, a.db, a.Cache, appResourceTreeFn, a.settings.ExecShells, a.sessionMgr, &terminalOpts). - WithFeatureFlagMiddleware(a.settingsMgr.GetSettings) - th := util_session.WithAuthMiddleware(a.DisableAuth, a.sessionMgr, terminal) + terminal := application.NewHandler(server.appLister, server.Namespace, server.ApplicationNamespaces, server.db, server.Cache, appResourceTreeFn, server.settings.ExecShells, server.sessionMgr, &terminalOpts). + WithFeatureFlagMiddleware(server.settingsMgr.GetSettings) + th := util_session.WithAuthMiddleware(server.DisableAuth, server.sessionMgr, terminal) mux.Handle("/terminal", th) // Proxy extension is currently an alpha feature and is disabled // by default. - if a.EnableProxyExtension { + if server.EnableProxyExtension { // API server won't panic if extensions fail to register. In // this case an error log will be sent and no extension route // will be added in mux. - registerExtensions(mux, a, metricsReg) + registerExtensions(mux, server, metricsReg) } mustRegisterGWHandler(versionpkg.RegisterVersionServiceHandler, ctx, gwmux, conn) @@ -1211,15 +1211,15 @@ func (a *ArgoCDServer) newHTTPServer(ctx context.Context, port int, grpcWebHandl mustRegisterGWHandler(gpgkeypkg.RegisterGPGKeyServiceHandler, ctx, gwmux, conn) // Swagger UI - swagger.ServeSwaggerUI(mux, assets.SwaggerJSON, "/swagger-ui", a.RootPath) - healthz.ServeHealthCheck(mux, a.healthCheck) + swagger.ServeSwaggerUI(mux, assets.SwaggerJSON, "/swagger-ui", server.RootPath) + healthz.ServeHealthCheck(mux, server.healthCheck) // Dex reverse proxy and client app and OAuth2 login/callback - a.registerDexHandlers(mux) + server.registerDexHandlers(mux) // Webhook handler for git events (Note: cache timeouts are hardcoded because API server does not write to cache and not really using them) - argoDB := db.NewDB(a.Namespace, a.settingsMgr, a.KubeClientset) - acdWebhookHandler := webhook.NewHandler(a.Namespace, a.ArgoCDServerOpts.ApplicationNamespaces, a.ArgoCDServerOpts.WebhookParallelism, a.AppClientset, a.settings, a.settingsMgr, a.RepoServerCache, a.Cache, argoDB, a.settingsMgr.GetMaxWebhookPayloadSize()) + argoDB := db.NewDB(server.Namespace, server.settingsMgr, server.KubeClientset) + acdWebhookHandler := webhook.NewHandler(server.Namespace, server.ArgoCDServerOpts.ApplicationNamespaces, server.ArgoCDServerOpts.WebhookParallelism, server.AppClientset, server.settings, server.settingsMgr, server.RepoServerCache, server.Cache, argoDB, server.settingsMgr.GetMaxWebhookPayloadSize()) mux.HandleFunc("/api/webhook", acdWebhookHandler.Handler) @@ -1230,16 +1230,16 @@ func (a *ArgoCDServer) newHTTPServer(ctx context.Context, port int, grpcWebHandl extensionsSharedPath := "/tmp/extensions/" var extensionsHandler http.Handler = http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { - a.serveExtensions(extensionsSharedPath, writer) + server.serveExtensions(extensionsSharedPath, writer) }) - if a.ArgoCDServerOpts.EnableGZip { + if server.ArgoCDServerOpts.EnableGZip { extensionsHandler = compressHandler(extensionsHandler) } mux.Handle("/extensions.js", extensionsHandler) // Serve UI static assets - var assetsHandler http.Handler = http.HandlerFunc(a.newStaticAssetsHandler()) - if a.ArgoCDServerOpts.EnableGZip { + var assetsHandler http.Handler = http.HandlerFunc(server.newStaticAssetsHandler()) + if server.ArgoCDServerOpts.EnableGZip { assetsHandler = compressHandler(assetsHandler) } mux.Handle("/", assetsHandler) @@ -1280,7 +1280,7 @@ func registerExtensions(mux *http.ServeMux, a *ArgoCDServer, metricsReg HTTPMetr var extensionsPattern = regexp.MustCompile(`^extension(.*)\.js$`) -func (a *ArgoCDServer) serveExtensions(extensionsSharedPath string, w http.ResponseWriter) { +func (server *ArgoCDServer) serveExtensions(extensionsSharedPath string, w http.ResponseWriter) { w.Header().Set("Content-Type", "application/javascript") err := filepath.Walk(extensionsSharedPath, func(filePath string, info os.FileInfo, err error) error { @@ -1321,17 +1321,17 @@ func (a *ArgoCDServer) serveExtensions(extensionsSharedPath string, w http.Respo } // registerDexHandlers will register dex HTTP handlers, creating the OAuth client app -func (a *ArgoCDServer) registerDexHandlers(mux *http.ServeMux) { - if !a.settings.IsSSOConfigured() { +func (server *ArgoCDServer) registerDexHandlers(mux *http.ServeMux) { + if !server.settings.IsSSOConfigured() { return } // Run dex OpenID Connect Identity Provider behind a reverse proxy (served at /api/dex) var err error - mux.HandleFunc(common.DexAPIEndpoint+"/", dexutil.NewDexHTTPReverseProxy(a.DexServerAddr, a.BaseHRef, a.DexTLSConfig)) - a.ssoClientApp, err = oidc.NewClientApp(a.settings, a.DexServerAddr, a.DexTLSConfig, a.BaseHRef, cacheutil.NewRedisCache(a.RedisClient, a.settings.UserInfoCacheExpiration(), cacheutil.RedisCompressionNone)) + mux.HandleFunc(common.DexAPIEndpoint+"/", dexutil.NewDexHTTPReverseProxy(server.DexServerAddr, server.BaseHRef, server.DexTLSConfig)) + server.ssoClientApp, err = oidc.NewClientApp(server.settings, server.DexServerAddr, server.DexTLSConfig, server.BaseHRef, cacheutil.NewRedisCache(server.RedisClient, server.settings.UserInfoCacheExpiration(), cacheutil.RedisCompressionNone)) errorsutil.CheckError(err) - mux.HandleFunc(common.LoginEndpoint, a.ssoClientApp.HandleLogin) - mux.HandleFunc(common.CallbackEndpoint, a.ssoClientApp.HandleCallback) + mux.HandleFunc(common.LoginEndpoint, server.ssoClientApp.HandleLogin) + mux.HandleFunc(common.CallbackEndpoint, server.ssoClientApp.HandleCallback) } // newRedirectServer returns an HTTP server which does a 307 redirect to the HTTPS server @@ -1366,21 +1366,21 @@ func registerDownloadHandlers(mux *http.ServeMux, base string) { } } -func (s *ArgoCDServer) getIndexData() ([]byte, error) { - s.indexDataInit.Do(func() { +func (server *ArgoCDServer) getIndexData() ([]byte, error) { + server.indexDataInit.Do(func() { data, err := ui.Embedded.ReadFile("dist/app/index.html") if err != nil { - s.indexDataErr = err + server.indexDataErr = err return } - if s.BaseHRef == "/" || s.BaseHRef == "" { - s.indexData = data + if server.BaseHRef == "/" || server.BaseHRef == "" { + server.indexData = data } else { - s.indexData = []byte(replaceBaseHRef(string(data), fmt.Sprintf(``, strings.Trim(s.BaseHRef, "/")))) + server.indexData = []byte(replaceBaseHRef(string(data), fmt.Sprintf(``, strings.Trim(server.BaseHRef, "/")))) } }) - return s.indexData, s.indexDataErr + return server.indexData, server.indexDataErr } func (server *ArgoCDServer) uiAssetExists(filename string) bool { @@ -1470,11 +1470,11 @@ func replaceBaseHRef(data string, replaceWith string) string { } // Authenticate checks for the presence of a valid token when accessing server-side resources. -func (a *ArgoCDServer) Authenticate(ctx context.Context) (context.Context, error) { - if a.DisableAuth { +func (server *ArgoCDServer) Authenticate(ctx context.Context) (context.Context, error) { + if server.DisableAuth { return ctx, nil } - claims, newToken, claimsErr := a.getClaims(ctx) + claims, newToken, claimsErr := server.getClaims(ctx) if claims != nil { // Add claims to the context to inspect for RBAC // nolint:staticcheck @@ -1494,7 +1494,7 @@ func (a *ArgoCDServer) Authenticate(ctx context.Context) (context.Context, error } if claimsErr != nil { - argoCDSettings, err := a.settingsMgr.GetSettings() + argoCDSettings, err := server.settingsMgr.GetSettings() if err != nil { return ctx, status.Errorf(codes.Internal, "unable to load settings: %v", err) } @@ -1509,7 +1509,7 @@ func (a *ArgoCDServer) Authenticate(ctx context.Context) (context.Context, error return ctx, nil } -func (a *ArgoCDServer) getClaims(ctx context.Context) (jwt.Claims, string, error) { +func (server *ArgoCDServer) getClaims(ctx context.Context) (jwt.Claims, string, error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { return nil, "", ErrNoSession @@ -1518,7 +1518,7 @@ func (a *ArgoCDServer) getClaims(ctx context.Context) (jwt.Claims, string, error if tokenString == "" { return nil, "", ErrNoSession } - claims, newToken, err := a.sessionMgr.VerifyToken(tokenString) + claims, newToken, err := server.sessionMgr.VerifyToken(tokenString) if err != nil { return claims, "", status.Errorf(codes.Unauthenticated, "invalid session: %v", err) } @@ -1534,8 +1534,8 @@ func (a *ArgoCDServer) getClaims(ctx context.Context) (jwt.Claims, string, error } } iss := jwtutil.StringField(groupClaims, "iss") - if iss != util_session.SessionManagerClaimsIssuer && a.settings.UserInfoGroupsEnabled() && a.settings.UserInfoPath() != "" { - userInfo, unauthorized, err := a.ssoClientApp.GetUserInfo(groupClaims, a.settings.IssuerURL(), a.settings.UserInfoPath()) + if iss != util_session.SessionManagerClaimsIssuer && server.settings.UserInfoGroupsEnabled() && server.settings.UserInfoPath() != "" { + userInfo, unauthorized, err := server.ssoClientApp.GetUserInfo(groupClaims, server.settings.IssuerURL(), server.settings.UserInfoPath()) if unauthorized { log.Errorf("error while quering userinfo endpoint: %v", err) return claims, "", status.Errorf(codes.Unauthenticated, "invalid session") @@ -1685,11 +1685,11 @@ func bug21955WorkaroundInterceptor(ctx context.Context, req any, _ *grpc.UnarySe // allowedApplicationNamespacesAsString returns a string containing comma-separated list // of allowed application namespaces -func (a *ArgoCDServer) allowedApplicationNamespacesAsString() string { - ns := a.Namespace - if len(a.ArgoCDServerOpts.ApplicationNamespaces) > 0 { +func (server *ArgoCDServer) allowedApplicationNamespacesAsString() string { + ns := server.Namespace + if len(server.ArgoCDServerOpts.ApplicationNamespaces) > 0 { ns += ", " - ns += strings.Join(a.ArgoCDServerOpts.ApplicationNamespaces, ", ") + ns += strings.Join(server.ArgoCDServerOpts.ApplicationNamespaces, ", ") } return ns } diff --git a/util/git/creds.go b/util/git/creds.go index aea82574934d6..de84fc42dc0af 100644 --- a/util/git/creds.go +++ b/util/git/creds.go @@ -156,35 +156,35 @@ func NewHTTPSCreds(username string, password string, clientCertData string, clie } // GetUserInfo returns the username and email address for the credentials, if they're available. -func (c HTTPSCreds) GetUserInfo(ctx context.Context) (string, string, error) { +func (creds HTTPSCreds) GetUserInfo(ctx context.Context) (string, string, error) { // Email not implemented for HTTPS creds. - return c.username, "", nil + return creds.username, "", nil } -func (c HTTPSCreds) BasicAuthHeader() string { +func (creds HTTPSCreds) BasicAuthHeader() string { h := "Authorization: Basic " - t := c.username + ":" + c.password + t := creds.username + ":" + creds.password h += base64.StdEncoding.EncodeToString([]byte(t)) return h } // Get additional required environment variables for executing git client to // access specific repository via HTTPS. -func (c HTTPSCreds) Environ() (io.Closer, []string, error) { +func (creds HTTPSCreds) Environ() (io.Closer, []string, error) { var env []string httpCloser := authFilePaths(make([]string, 0)) // GIT_SSL_NO_VERIFY is used to tell git not to validate the server's cert at // all. - if c.insecure { + if creds.insecure { env = append(env, "GIT_SSL_NO_VERIFY=true") } // In case the repo is configured for using a TLS client cert, we need to make // sure git client will use it. The certificate's key must not be password // protected. - if c.HasClientCert() { + if creds.HasClientCert() { var certFile, keyFile *os.File // We need to actually create two temp files, one for storing cert data and @@ -209,7 +209,7 @@ func (c HTTPSCreds) Environ() (io.Closer, []string, error) { // We should have both temp files by now httpCloser = authFilePaths([]string{certFile.Name(), keyFile.Name()}) - _, err = certFile.WriteString(c.clientCertData) + _, err = certFile.WriteString(creds.clientCertData) if err != nil { httpCloser.Close() return NopCloser{}, nil, err @@ -217,7 +217,7 @@ func (c HTTPSCreds) Environ() (io.Closer, []string, error) { // GIT_SSL_CERT is the full path to a client certificate to be used env = append(env, "GIT_SSL_CERT="+certFile.Name()) - _, err = keyFile.WriteString(c.clientCertKey) + _, err = keyFile.WriteString(creds.clientCertKey) if err != nil { httpCloser.Close() return NopCloser{}, nil, err @@ -228,27 +228,27 @@ func (c HTTPSCreds) Environ() (io.Closer, []string, error) { // If at least password is set, we will set ARGOCD_BASIC_AUTH_HEADER to // hold the HTTP authorization header, so auth mechanism negotiation is // skipped. This is insecure, but some environments may need it. - if c.password != "" && c.forceBasicAuth { - env = append(env, fmt.Sprintf("%s=%s", forceBasicAuthHeaderEnv, c.BasicAuthHeader())) + if creds.password != "" && creds.forceBasicAuth { + env = append(env, fmt.Sprintf("%s=%s", forceBasicAuthHeaderEnv, creds.BasicAuthHeader())) } - nonce := c.store.Add(text.FirstNonEmpty(c.username, githubAccessTokenUsername), c.password) - env = append(env, c.store.Environ(nonce)...) + nonce := creds.store.Add(text.FirstNonEmpty(creds.username, githubAccessTokenUsername), creds.password) + env = append(env, creds.store.Environ(nonce)...) return argoioutils.NewCloser(func() error { - c.store.Remove(nonce) + creds.store.Remove(nonce) return httpCloser.Close() }), env, nil } -func (g HTTPSCreds) HasClientCert() bool { - return g.clientCertData != "" && g.clientCertKey != "" +func (creds HTTPSCreds) HasClientCert() bool { + return creds.clientCertData != "" && creds.clientCertKey != "" } -func (c HTTPSCreds) GetClientCertData() string { - return c.clientCertData +func (creds HTTPSCreds) GetClientCertData() string { + return creds.clientCertData } -func (c HTTPSCreds) GetClientCertKey() string { - return c.clientCertKey +func (creds HTTPSCreds) GetClientCertKey() string { + return creds.clientCertKey } var _ Creds = SSHCreds{} From cce74a33e1276f1d668105236b502f05c5e67625 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 7 Jan 2025 09:49:51 -0500 Subject: [PATCH 30/41] chore(deps): bump golang.org/x/crypto from 0.31.0 to 0.32.0 (#21397) Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.31.0 to 0.32.0. - [Commits](https://github.com/golang/crypto/compare/v0.31.0...v0.32.0) --- updated-dependencies: - dependency-name: golang.org/x/crypto dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 7888c37783881..457f21529c330 100644 --- a/go.mod +++ b/go.mod @@ -83,7 +83,7 @@ require ( go.opentelemetry.io/otel v1.33.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.32.0 go.opentelemetry.io/otel/sdk v1.33.0 - golang.org/x/crypto v0.31.0 + golang.org/x/crypto v0.32.0 golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f golang.org/x/net v0.33.0 golang.org/x/oauth2 v0.25.0 diff --git a/go.sum b/go.sum index 67cdd54a08ce7..0621735e87970 100644 --- a/go.sum +++ b/go.sum @@ -1050,8 +1050,8 @@ golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOM golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM= -golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= -golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= +golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= From f39b425facb2a4fdc05193c85b51d145b0124d1c Mon Sep 17 00:00:00 2001 From: nmirasch Date: Tue, 7 Jan 2025 15:52:35 +0100 Subject: [PATCH 31/41] fix: CVE-2024-21538 upgrading the indirect dep cross-spawn to greater than 7.0.5 (#21259) * fix: CVE-2024-21538 upgrading the indirect dep cross-spawn to greater than 7.0.5 Signed-off-by: nmirasch * rebasing Signed-off-by: nmirasch --------- Signed-off-by: nmirasch --- ui/jest.config.js | 2 +- ui/package.json | 5 +- ui/yarn.lock | 1862 +++++++++++++++------------------------------ 3 files changed, 636 insertions(+), 1233 deletions(-) diff --git a/ui/jest.config.js b/ui/jest.config.js index a34122d0a46da..9e154efab8e3d 100644 --- a/ui/jest.config.js +++ b/ui/jest.config.js @@ -15,6 +15,6 @@ module.exports = { moduleNameMapper: { // https://github.com/facebook/jest/issues/3094 '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '/__mocks__/fileMock.js', - '.+\\.(css|styl|less|sass|scss)$': 'jest-transform-css', + '.+\\.(css|styl|less|sass|scss)$': '/__mocks__/fileMock.js', }, }; diff --git a/ui/package.json b/ui/package.json index e5b5b0a874a47..7b903964907c5 100644 --- a/ui/package.json +++ b/ui/package.json @@ -98,17 +98,16 @@ "codecov": "^3.8.3", "copy-webpack-plugin": "^6.1.1", "esbuild-loader": "^2.18.0", - "eslint": "^9.1.1", + "eslint": "^9.15.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-prettier": "^5.1.3", - "eslint-plugin-react": "^7.34.1", + "eslint-plugin-react": "^7.37.2", "globals": "^15.1.0", "html-webpack-plugin": "^5.6.0", "identity-obj-proxy": "^3.0.0", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", "jest-junit": "^6.4.0", - "jest-transform-css": "^2.0.0", "monaco-editor-webpack-plugin": "^7.1.0", "postcss": "^8.4.38", "prettier": "^3.2.5", diff --git a/ui/yarn.lock b/ui/yarn.lock index dc29f24753a2f..a4e410b1d30de 100644 --- a/ui/yarn.lock +++ b/ui/yarn.lock @@ -17,53 +17,6 @@ "@jridgewell/gen-mapping" "^0.3.5" "@jridgewell/trace-mapping" "^0.3.24" -"@ant-design/colors@^7.0.0": - version "7.0.0" - resolved "https://registry.yarnpkg.com/@ant-design/colors/-/colors-7.0.0.tgz#eb7eecead124c3533aea05d61254f0a17f2b61b3" - integrity sha512-iVm/9PfGCbC0dSMBrz7oiEXZaaGH7ceU40OJEfKmyuzR9R5CRimJYPlRiFtMQGQcbNMea/ePcoIebi4ASGYXtg== - dependencies: - "@ctrl/tinycolor" "^3.4.0" - -"@ant-design/cssinjs@^1.10.1": - version "1.10.1" - resolved "https://registry.yarnpkg.com/@ant-design/cssinjs/-/cssinjs-1.10.1.tgz#c9173f38e3d61f0883ca3c17d7cf1e30784e0dd7" - integrity sha512-PSoJS8RMzn95ZRg007dJGr6AU0Zim/O+tTN0xmXmh9CkIl4y3wuOr2Zhehaj7s130wPSYDVvahf3DKT50w/Zhw== - dependencies: - "@babel/runtime" "^7.11.1" - "@emotion/hash" "^0.8.0" - "@emotion/unitless" "^0.7.5" - classnames "^2.3.1" - csstype "^3.0.10" - rc-util "^5.27.0" - stylis "^4.0.13" - -"@ant-design/icons-svg@^4.2.1": - version "4.2.1" - resolved "https://registry.yarnpkg.com/@ant-design/icons-svg/-/icons-svg-4.2.1.tgz#8630da8eb4471a4aabdaed7d1ff6a97dcb2cf05a" - integrity sha512-EB0iwlKDGpG93hW8f85CTJTs4SvMX7tt5ceupvhALp1IF44SeUFOMhKUOYqpsoYWQKAOuTRDMqn75rEaKDp0Xw== - -"@ant-design/icons@^5.1.0": - version "5.1.4" - resolved "https://registry.yarnpkg.com/@ant-design/icons/-/icons-5.1.4.tgz#614e29e26d092c2c1c1a2acbc0d84434d8d1474e" - integrity sha512-YHKL7Jx3bM12OxvtiYDon04BsBT/6LGitYEqar3GljzWaAyMOAD8i/uF1Rsi5Us/YNdWWXBGSvZV2OZWMpJlcA== - dependencies: - "@ant-design/colors" "^7.0.0" - "@ant-design/icons-svg" "^4.2.1" - "@babel/runtime" "^7.11.2" - classnames "^2.2.6" - rc-util "^5.31.1" - -"@ant-design/react-slick@~1.0.0": - version "1.0.1" - resolved "https://registry.yarnpkg.com/@ant-design/react-slick/-/react-slick-1.0.1.tgz#af10e67ef9a233df5610c36313a5c804ccc2ae6b" - integrity sha512-ARM0TmpGdDuUVE10NwUCENQlJSInNKo5NiBjL5szu5BxWNEHNwQMcDrlVCqFbkvFLy+2CvywW8Y59QJtC0YDag== - dependencies: - "@babel/runtime" "^7.10.4" - classnames "^2.2.5" - json2mq "^0.2.0" - resize-observer-polyfill "^1.5.1" - throttle-debounce "^5.0.0" - "@babel/code-frame@^7.0.0", "@babel/code-frame@^7.5.5": version "7.5.5" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.5.5.tgz#bc0782f6d69f7b7d49531219699b988f669a8f9d" @@ -1166,20 +1119,13 @@ "@babel/helper-plugin-utils" "^7.0.0" "@babel/plugin-transform-typescript" "^7.7.2" -"@babel/runtime@^7.1.2", "@babel/runtime@^7.12.5", "@babel/runtime@^7.8.4": +"@babel/runtime@^7.1.2", "@babel/runtime@^7.8.4": version "7.14.6" resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.14.6.tgz#535203bc0892efc7dec60bdc27b2ecf6e409062d" integrity sha512-/PCB2uJ7oM44tz8YhC4Z/6PeOKXp4K588f+5M3clr1M4zbqztlo0XEfJ2LEzj/FgwfgGcIdl8n7YYjTCI0BYwg== dependencies: regenerator-runtime "^0.13.4" -"@babel/runtime@^7.10.1", "@babel/runtime@^7.10.4", "@babel/runtime@^7.11.1", "@babel/runtime@^7.11.2": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.16.7.tgz#03ff99f64106588c9c403c6ecb8c3bafbbdff1fa" - integrity sha512-9E9FJowqAsytyOY6LG+1KuueckRL+aQW+mKvXRXnuFGyRAyepJPmEo9vgMfXUA6O9u3IeEdv9MAkppFcaQwogQ== - dependencies: - regenerator-runtime "^0.13.4" - "@babel/runtime@^7.16.7": version "7.17.2" resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.17.2.tgz#66f68591605e59da47523c631416b18508779941" @@ -1187,20 +1133,6 @@ dependencies: regenerator-runtime "^0.13.4" -"@babel/runtime@^7.18.0", "@babel/runtime@^7.18.3": - version "7.19.0" - resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.19.0.tgz#22b11c037b094d27a8a2504ea4dcff00f50e2259" - integrity sha512-eR8Lo9hnDS7tqkO7NsV+mKvCmv5boaXFSZ70DnfhcgiEne8hv9oCEd36Klw74EtizEqLsy4YnW8UWwpBVolHZA== - dependencies: - regenerator-runtime "^0.13.4" - -"@babel/runtime@^7.20.0", "@babel/runtime@^7.20.7": - version "7.22.5" - resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.22.5.tgz#8564dd588182ce0047d55d7a75e93921107b57ec" - integrity sha512-ecjvYlnAaZ/KVneE/OdKYBYfgXV3Ptu6zQWmgEF7vwKhQnvVS6bjMD2XYgj+SNvQ1GfK/pjgokfPkC/2CO8CuA== - dependencies: - regenerator-runtime "^0.13.11" - "@babel/runtime@^7.21.0": version "7.21.5" resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.21.5.tgz#8492dddda9644ae3bda3b45eabe87382caee7200" @@ -1337,31 +1269,11 @@ dependencies: "@jridgewell/trace-mapping" "0.3.9" -"@ctrl/tinycolor@^3.4.0": - version "3.4.0" - resolved "https://registry.yarnpkg.com/@ctrl/tinycolor/-/tinycolor-3.4.0.tgz#c3c5ae543c897caa9c2a68630bed355be5f9990f" - integrity sha512-JZButFdZ1+/xAfpguQHoabIXkcqRRKpMrWKBkpEZZyxfY9C1DpADFB8PEqGSTeFr135SaTRfKqGKx5xSCLI7ZQ== - -"@ctrl/tinycolor@^3.6.0": - version "3.6.0" - resolved "https://registry.yarnpkg.com/@ctrl/tinycolor/-/tinycolor-3.6.0.tgz#53fa5fe9c34faee89469e48f91d51a3766108bc8" - integrity sha512-/Z3l6pXthq0JvMYdUFyX9j0MaCltlIn6mfh9jLyQwg5aPKxkyNa0PTHtU1AlFXLNk55ZuAeJRcpvq+tmLfKmaQ== - "@discoveryjs/json-ext@^0.5.0": version "0.5.7" resolved "https://registry.yarnpkg.com/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz#1d572bfbbe14b7704e0ba0f39b74815b84870d70" integrity sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw== -"@emotion/hash@^0.8.0": - version "0.8.0" - resolved "https://registry.yarnpkg.com/@emotion/hash/-/hash-0.8.0.tgz#bbbff68978fefdbe68ccb533bc8cbe1d1afb5413" - integrity sha512-kBJtf7PH6aWwZ6fka3zQ0p6SBYzx4fl1LoZXE2RrnYST9Xljm7WfKJrU4g/Xr3Beg72MLrp1AWNUmuYJTL7Cow== - -"@emotion/unitless@^0.7.5": - version "0.7.5" - resolved "https://registry.yarnpkg.com/@emotion/unitless/-/unitless-0.7.5.tgz#77211291c1900a700b8a78cfafda3160d76949ed" - integrity sha512-OWORNpfjMsSSUBVrRBVGECkhWcULOAJz9ZW8uK9qgxD+87M7jHRcvh/A96XXNhXTLmKcoYSQtBEX7lHMO7YRwg== - "@esbuild-kit/cjs-loader@^2.0.0": version "2.0.0" resolved "https://registry.yarnpkg.com/@esbuild-kit/cjs-loader/-/cjs-loader-2.0.0.tgz#f385aed0ba482cb9de28880e7401259311cacbd7" @@ -1393,15 +1305,36 @@ dependencies: eslint-visitor-keys "^3.3.0" -"@eslint-community/regexpp@^4.10.0", "@eslint-community/regexpp@^4.6.1": +"@eslint-community/regexpp@^4.10.0": version "4.10.0" resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.10.0.tgz#548f6de556857c8bb73bbee70c35dc82a2e74d63" integrity sha512-Cu96Sd2By9mCNTx2iyKOmq10v22jUVQv0lQnlGNy16oE9589yE+QADPbrMGCkA51cKZSg3Pu/aTJVTGfL/qjUA== -"@eslint/eslintrc@^3.0.2": - version "3.0.2" - resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-3.0.2.tgz#36180f8e85bf34d2fe3ccc2261e8e204a411ab4e" - integrity sha512-wV19ZEGEMAC1eHgrS7UQPqsdEiCIbTKTasEfcXAigzoXICcqZSjBZEHlZwNVvKg6UBCjSlos84XiLqsRJnIcIg== +"@eslint-community/regexpp@^4.12.1": + version "4.12.1" + resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.12.1.tgz#cfc6cffe39df390a3841cde2abccf92eaa7ae0e0" + integrity sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ== + +"@eslint/config-array@^0.19.0": + version "0.19.1" + resolved "https://registry.yarnpkg.com/@eslint/config-array/-/config-array-0.19.1.tgz#734aaea2c40be22bbb1f2a9dac687c57a6a4c984" + integrity sha512-fo6Mtm5mWyKjA/Chy1BYTdn5mGJoDNjC7C64ug20ADsRDGrA85bN3uK3MaKbeRkRuuIEAR5N33Jr1pbm411/PA== + dependencies: + "@eslint/object-schema" "^2.1.5" + debug "^4.3.1" + minimatch "^3.1.2" + +"@eslint/core@^0.9.0": + version "0.9.1" + resolved "https://registry.yarnpkg.com/@eslint/core/-/core-0.9.1.tgz#31763847308ef6b7084a4505573ac9402c51f9d1" + integrity sha512-GuUdqkyyzQI5RMIWkHhvTWLCyLo1jNK3vzkSyaExH5kHPDHcuL2VOpHjmMY+y3+NC69qAKToBqldTBgYeLSr9Q== + dependencies: + "@types/json-schema" "^7.0.15" + +"@eslint/eslintrc@^3.2.0": + version "3.2.0" + resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-3.2.0.tgz#57470ac4e2e283a6bf76044d63281196e370542c" + integrity sha512-grOjVNN8P3hjJn/eIETF1wwd12DdnwFDoyceUJLYYdkpbwq3nLi+4fqrTAONx7XDALqlL220wC/RHSC/QTI/0w== dependencies: ajv "^6.12.4" debug "^4.3.2" @@ -1413,11 +1346,28 @@ minimatch "^3.1.2" strip-json-comments "^3.1.1" -"@eslint/js@9.1.1", "@eslint/js@^9.1.1": +"@eslint/js@9.17.0": + version "9.17.0" + resolved "https://registry.yarnpkg.com/@eslint/js/-/js-9.17.0.tgz#1523e586791f80376a6f8398a3964455ecc651ec" + integrity sha512-Sxc4hqcs1kTu0iID3kcZDW3JHq2a77HO9P8CP6YEA/FpH3Ll8UXE2r/86Rz9YJLKme39S9vU5OWNjC6Xl0Cr3w== + +"@eslint/js@^9.1.1": version "9.1.1" resolved "https://registry.yarnpkg.com/@eslint/js/-/js-9.1.1.tgz#eb0f82461d12779bbafc1b5045cde3143d350a8a" integrity sha512-5WoDz3Y19Bg2BnErkZTp0en+c/i9PvgFS7MBe1+m60HjFr0hrphlAGp4yzI7pxpt4xShln4ZyYp4neJm8hmOkQ== +"@eslint/object-schema@^2.1.5": + version "2.1.5" + resolved "https://registry.yarnpkg.com/@eslint/object-schema/-/object-schema-2.1.5.tgz#8670a8f6258a2be5b2c620ff314a1d984c23eb2e" + integrity sha512-o0bhxnL89h5Bae5T318nFoFzGy+YE5i/gGkoPAgkmTVdRKTiv3p8JHevPiPaMwoloKfEiiaHlawCqaZMqRm+XQ== + +"@eslint/plugin-kit@^0.2.3": + version "0.2.4" + resolved "https://registry.yarnpkg.com/@eslint/plugin-kit/-/plugin-kit-0.2.4.tgz#2b78e7bb3755784bb13faa8932a1d994d6537792" + integrity sha512-zSkKow6H5Kdm0ZUQUB2kV5JIXqoG0+uH5YADhaEHswm664N9Db8dXSi0nMJpacpMf+MyyglF1vnZohpEg5yUtg== + dependencies: + levn "^0.4.1" + "@exodus/schemasafe@^1.0.0-rc.2": version "1.0.0-rc.3" resolved "https://registry.yarnpkg.com/@exodus/schemasafe/-/schemasafe-1.0.0-rc.3.tgz#dda2fbf3dafa5ad8c63dadff7e01d3fdf4736025" @@ -1428,29 +1378,33 @@ resolved "https://registry.yarnpkg.com/@fortawesome/fontawesome-free/-/fontawesome-free-6.5.2.tgz#310fe90cb5a8dee9698833171b98e7835404293d" integrity sha512-hRILoInAx8GNT5IMkrtIt9blOdrqHOnPBH+k70aWUAqPZPgopb9G5EQJFpaBx/S8zp2fC+mPW349Bziuk1o28Q== -"@humanwhocodes/config-array@^0.13.0": - version "0.13.0" - resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.13.0.tgz#fb907624df3256d04b9aa2df50d7aa97ec648748" - integrity sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw== +"@humanfs/core@^0.19.1": + version "0.19.1" + resolved "https://registry.yarnpkg.com/@humanfs/core/-/core-0.19.1.tgz#17c55ca7d426733fe3c561906b8173c336b40a77" + integrity sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA== + +"@humanfs/node@^0.16.6": + version "0.16.6" + resolved "https://registry.yarnpkg.com/@humanfs/node/-/node-0.16.6.tgz#ee2a10eaabd1131987bf0488fd9b820174cd765e" + integrity sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw== dependencies: - "@humanwhocodes/object-schema" "^2.0.3" - debug "^4.3.1" - minimatch "^3.0.5" + "@humanfs/core" "^0.19.1" + "@humanwhocodes/retry" "^0.3.0" "@humanwhocodes/module-importer@^1.0.1": version "1.0.1" resolved "https://registry.yarnpkg.com/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz#af5b2691a22b44be847b0ca81641c5fb6ad0172c" integrity sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA== -"@humanwhocodes/object-schema@^2.0.3": - version "2.0.3" - resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz#4a2868d75d6d6963e423bcf90b7fd1be343409d3" - integrity sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA== +"@humanwhocodes/retry@^0.3.0": + version "0.3.1" + resolved "https://registry.yarnpkg.com/@humanwhocodes/retry/-/retry-0.3.1.tgz#c72a5c76a9fbaf3488e231b13dc52c0da7bab42a" + integrity sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA== -"@humanwhocodes/retry@^0.2.3": - version "0.2.3" - resolved "https://registry.yarnpkg.com/@humanwhocodes/retry/-/retry-0.2.3.tgz#c9aa036d1afa643f1250e83150f39efb3a15a631" - integrity sha512-X38nUbachlb01YMlvPFojKoiXq+LzZvuSce70KPMPdeM1Rj03k4dR7lDslhbqXn3Ang4EU3+EAmwEAsbrjHW3g== +"@humanwhocodes/retry@^0.4.1": + version "0.4.1" + resolved "https://registry.yarnpkg.com/@humanwhocodes/retry/-/retry-0.4.1.tgz#9a96ce501bc62df46c4031fbd970e3cc6b10f07b" + integrity sha512-c7hNEllBlenFTHBky65mhq8WD2kbN9Q6gk0bTk8lSBvc554jpXSkST1iePudpt7+A/AQvuHs9EMqjHDXMY1lrA== "@istanbuljs/load-nyc-config@^1.0.0": version "1.1.0" @@ -1778,7 +1732,7 @@ resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz#5bd262af94e9d25bd1e71b05deed44876a222e8b" integrity sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A== -"@nodelib/fs.walk@^1.2.3", "@nodelib/fs.walk@^1.2.8": +"@nodelib/fs.walk@^1.2.3": version "1.2.8" resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz#e95737e8bb6746ddedf69c556953494f196fe69a" integrity sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg== @@ -1799,73 +1753,6 @@ resolved "https://registry.yarnpkg.com/@pkgr/core/-/core-0.1.1.tgz#1ec17e2edbec25c8306d424ecfbf13c7de1aaa31" integrity sha512-cq8o4cWH0ibXh9VGi5P20Tu9XF/0fFXl9EUinr9QfTM7a7p0oTA4iJRCQWppXR1Pg8dSM0UCItCkPwsk9qWWYA== -"@rc-component/color-picker@~1.2.0": - version "1.2.0" - resolved "https://registry.yarnpkg.com/@rc-component/color-picker/-/color-picker-1.2.0.tgz#964c86e85f0791703c7f1ec842e7476bcb41954d" - integrity sha512-IitJ6RWGHs7btI1AqzGPrehr5bueWLGDUyMKwDwvFunfSDo/o8g/95kUG55vC5EYLM0ZJ3SDfw45OrW5KAx3oA== - dependencies: - "@babel/runtime" "^7.10.1" - "@ctrl/tinycolor" "^3.6.0" - classnames "^2.2.6" - rc-util "^5.30.0" - -"@rc-component/context@^1.3.0": - version "1.3.0" - resolved "https://registry.yarnpkg.com/@rc-component/context/-/context-1.3.0.tgz#608ccf0abcbec9406751b17a4b35db08e481c110" - integrity sha512-6QdaCJ7Wn5UZLJs15IEfqy4Ru3OaL5ctqpQYWd5rlfV9wwzrzdt6+kgAQZV/qdB0MUPN4nhyBfRembQCIvBf+w== - dependencies: - "@babel/runtime" "^7.10.1" - rc-util "^5.27.0" - -"@rc-component/mini-decimal@^1.0.1": - version "1.1.0" - resolved "https://registry.yarnpkg.com/@rc-component/mini-decimal/-/mini-decimal-1.1.0.tgz#7b7a362b14a0a54cb5bc6fd2b82731f29f11d9b0" - integrity sha512-jS4E7T9Li2GuYwI6PyiVXmxTiM6b07rlD9Ge8uGZSCz3WlzcG5ZK7g5bbuKNeZ9pgUuPK/5guV781ujdVpm4HQ== - dependencies: - "@babel/runtime" "^7.18.0" - -"@rc-component/mutate-observer@^1.0.0": - version "1.0.0" - resolved "https://registry.yarnpkg.com/@rc-component/mutate-observer/-/mutate-observer-1.0.0.tgz#ce99af3239ed9c74ee3e7302f1c67098de920b46" - integrity sha512-okqRJSfNisXdI6CUeOLZC5ukBW/8kir2Ii4PJiKpUt+3+uS7dxwJUMxsUZquxA1rQuL8YcEmKVp/TCnR+yUdZA== - dependencies: - "@babel/runtime" "^7.18.0" - classnames "^2.3.2" - rc-util "^5.24.4" - -"@rc-component/portal@^1.0.0-8", "@rc-component/portal@^1.0.0-9", "@rc-component/portal@^1.0.2", "@rc-component/portal@^1.1.0", "@rc-component/portal@^1.1.1": - version "1.1.1" - resolved "https://registry.yarnpkg.com/@rc-component/portal/-/portal-1.1.1.tgz#1a30ffe51c240b54360cba8e8bfc5d1f559325c4" - integrity sha512-m8w3dFXX0H6UkJ4wtfrSwhe2/6M08uz24HHrF8pWfAXPwA9hwCuTE5per/C86KwNLouRpwFGcr7LfpHaa1F38g== - dependencies: - "@babel/runtime" "^7.18.0" - classnames "^2.3.2" - rc-util "^5.24.4" - -"@rc-component/tour@~1.8.0": - version "1.8.0" - resolved "https://registry.yarnpkg.com/@rc-component/tour/-/tour-1.8.0.tgz#fda8b533e36db1d4254e3ffbcefe3395c346eb1c" - integrity sha512-rrRGioHTLQlGca27G2+lw7QpRb3uuMYCUIJjj31/B44VCJS0P2tqYhOgtzvWQmaLMlWH3ZlpzotkKX13NT4XEA== - dependencies: - "@babel/runtime" "^7.18.0" - "@rc-component/portal" "^1.0.0-9" - "@rc-component/trigger" "^1.3.6" - classnames "^2.3.2" - rc-util "^5.24.4" - -"@rc-component/trigger@^1.0.4", "@rc-component/trigger@^1.13.0", "@rc-component/trigger@^1.3.6", "@rc-component/trigger@^1.5.0", "@rc-component/trigger@^1.6.2", "@rc-component/trigger@^1.7.0": - version "1.13.6" - resolved "https://registry.yarnpkg.com/@rc-component/trigger/-/trigger-1.13.6.tgz#1375303018d16ccdf88e31c6bcd131421e1fa3e7" - integrity sha512-13aF9SrR5XAd+tyV/zja0A2pbrA/zdTCXRBNIsoLp8OmhVOnqiwjP7XZYPulLsH0ioEfvtXR1yI0anJD0/J7PQ== - dependencies: - "@babel/runtime" "^7.18.3" - "@rc-component/portal" "^1.1.0" - classnames "^2.3.2" - rc-align "^4.0.0" - rc-motion "^2.0.0" - rc-resize-observer "^1.3.1" - rc-util "^5.33.0" - "@redocly/ajv@^8.6.4": version "8.6.4" resolved "https://registry.yarnpkg.com/@redocly/ajv/-/ajv-8.6.4.tgz#94053e7a9d4146d1a4feacd3813892873f229a85" @@ -2049,6 +1936,11 @@ resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.5.tgz#a6ce3e556e00fd9895dd872dd172ad0d4bd687f4" integrity sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw== +"@types/estree@^1.0.6": + version "1.0.6" + resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.6.tgz#628effeeae2064a1b4e79f78e81d87b7e5fc7b50" + integrity sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw== + "@types/express-serve-static-core@*", "@types/express-serve-static-core@^4.17.18": version "4.17.28" resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.28.tgz#c47def9f34ec81dc6328d0b1b5303d1ec98d86b8" @@ -2670,6 +2562,11 @@ acorn@^8.1.0, acorn@^8.11.3, acorn@^8.12.1, acorn@^8.4.1, acorn@^8.5.0, acorn@^8 resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.12.1.tgz#71616bdccbe25e27a54439e0046e89ca76df2248" integrity sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg== +acorn@^8.14.0: + version "8.14.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.14.0.tgz#063e2c70cac5fb4f6467f0b11152e04c682795b0" + integrity sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA== + add@^2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/add/-/add-2.0.6.tgz#248f0a9f6e5a528ef2295dbeec30532130ae2235" @@ -2746,11 +2643,6 @@ ansi-html-community@^0.0.8: resolved "https://registry.yarnpkg.com/ansi-html-community/-/ansi-html-community-0.0.8.tgz#69fbc4d6ccbe383f9736934ae34c3f8290f1bf41" integrity sha512-1APHAyr3+PCamwNw3bXCPp4HFLONZt/yIH0sZp0/469KWNTEy+qN5jQ3GVX6DMZ1UXAi34yVwtTeaG/HpBuuzw== -ansi-regex@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" - integrity sha512-TIGnTpdo+E3+pCyAluZvtED5p5wCqLdezCyhPZzKPcxvFplEt4i+W7OONCKgeZFT3+y5NZZfOOS/Bdcanm1MYA== - ansi-regex@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.1.tgz#123d6479e92ad45ad897d4054e3c7ca7db4944e1" @@ -2771,11 +2663,6 @@ ansi-regex@^6.0.1: resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.0.1.tgz#3183e38fae9a65d7cb5e53945cd5897d0260a06a" integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== -ansi-styles@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" - integrity sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4= - ansi-styles@^3.2.0, ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" @@ -2803,60 +2690,6 @@ ansi-to-react@^6.1.6: anser "^1.4.1" escape-carriage "^1.3.0" -antd@^5.6.1: - version "5.6.2" - resolved "https://registry.yarnpkg.com/antd/-/antd-5.6.2.tgz#97c8b7e37747d7b8fca1bdaf15525332906a998c" - integrity sha512-h67gKgJRs07Qrf27AiKcJSEI3nCAmaCxxvEz6DSdRl1mHc03O8zAemRA6jPQQMPS5q4k7FxIphN+2ZnzdXlU2Q== - dependencies: - "@ant-design/colors" "^7.0.0" - "@ant-design/cssinjs" "^1.10.1" - "@ant-design/icons" "^5.1.0" - "@ant-design/react-slick" "~1.0.0" - "@babel/runtime" "^7.18.3" - "@ctrl/tinycolor" "^3.6.0" - "@rc-component/color-picker" "~1.2.0" - "@rc-component/mutate-observer" "^1.0.0" - "@rc-component/tour" "~1.8.0" - "@rc-component/trigger" "^1.13.0" - classnames "^2.2.6" - copy-to-clipboard "^3.2.0" - dayjs "^1.11.1" - qrcode.react "^3.1.0" - rc-cascader "~3.12.0" - rc-checkbox "~3.1.0" - rc-collapse "~3.7.0" - rc-dialog "~9.1.0" - rc-drawer "~6.2.0" - rc-dropdown "~4.1.0" - rc-field-form "~1.32.0" - rc-image "~5.17.1" - rc-input "~1.0.4" - rc-input-number "~7.4.0" - rc-mentions "~2.3.0" - rc-menu "~9.9.2" - rc-motion "^2.7.3" - rc-notification "~5.0.4" - rc-pagination "~3.5.0" - rc-picker "~3.8.2" - rc-progress "~3.4.1" - rc-rate "~2.12.0" - rc-resize-observer "^1.2.0" - rc-segmented "~2.2.0" - rc-select "~14.5.0" - rc-slider "~10.1.0" - rc-steps "~6.0.0" - rc-switch "~4.1.0" - rc-table "~7.32.1" - rc-tabs "~12.7.0" - rc-textarea "~1.2.2" - rc-tooltip "~6.0.0" - rc-tree "~5.7.4" - rc-tree-select "~5.9.0" - rc-upload "~4.3.0" - rc-util "^5.32.0" - scroll-into-view-if-needed "^3.0.3" - throttle-debounce "^5.0.0" - anymatch@^3.0.3, anymatch@~3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716" @@ -2876,7 +2709,6 @@ arg@^4.1.0: dependencies: "@fortawesome/fontawesome-free" "^6.2.1" "@tippy.js/react" "^3.1.1" - antd "^5.6.1" classnames "^2.2.6" core-js "^3.32.1" foundation-sites "^6.4.3" @@ -2886,7 +2718,7 @@ arg@^4.1.0: react-form "^2.16.0" react-helmet "^6.1.0" react-router-dom "^4.2.2" - react-toastify "9.0.8" + react-toastify "9.0.3" rxjs "^7.8.1" typescript "^4.9.5" uuid "^9.0.0" @@ -2928,7 +2760,7 @@ array-flatten@^2.1.0: resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-2.1.2.tgz#24ef80a28c1a893617e2149b0c6d0d788293b099" integrity sha512-hNfzcOV8W4NdualtqBFPyVO+54DSJuZGY9qT4pRroB6S9e3iiido2ISIC5h9R2sPJ8H3FHCIiEnsv1lPXO3KtQ== -array-includes@^3.1.6, array-includes@^3.1.7: +array-includes@^3.1.6, array-includes@^3.1.8: version "3.1.8" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.1.8.tgz#5e370cbe172fdd5dd6530c1d4aadda25281ba97d" integrity sha512-itaWrbYbqpGXkGhZPGUulwnhVf5Hpy1xiCFsGqyIGglbBxmG5vSjxQen3/WGOjPpNEv1RtBLKxbmVXm8HpJStQ== @@ -2940,17 +2772,12 @@ array-includes@^3.1.6, array-includes@^3.1.7: get-intrinsic "^1.2.4" is-string "^1.0.7" -array-tree-filter@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/array-tree-filter/-/array-tree-filter-2.1.0.tgz#873ac00fec83749f255ac8dd083814b4f6329190" - integrity sha512-4ROwICNlNw/Hqa9v+rk5h22KjmzB1JGTMVKP2AKJBOCgb0yL0ASf0+YvCcLNNwquOHNX48jkeZIJ3a+oOQqKcw== - array-union@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== -array.prototype.findlast@^1.2.4: +array.prototype.findlast@^1.2.5: version "1.2.5" resolved "https://registry.yarnpkg.com/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz#3e4fbcb30a15a7f5bf64cf2faae22d139c2e4904" integrity sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ== @@ -2982,25 +2809,15 @@ array.prototype.flatmap@^1.3.2: es-abstract "^1.22.1" es-shim-unscopables "^1.0.0" -array.prototype.toreversed@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/array.prototype.toreversed/-/array.prototype.toreversed-1.1.2.tgz#b989a6bf35c4c5051e1dc0325151bf8088954eba" - integrity sha512-wwDCoT4Ck4Cz7sLtgUmzR5UV3YF5mFHUlbChCzZBQZ+0m2cl/DH3tKgvphv1nKgFsJ48oCSg6p91q2Vm0I/ZMA== - dependencies: - call-bind "^1.0.2" - define-properties "^1.2.0" - es-abstract "^1.22.1" - es-shim-unscopables "^1.0.0" - -array.prototype.tosorted@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/array.prototype.tosorted/-/array.prototype.tosorted-1.1.3.tgz#c8c89348337e51b8a3c48a9227f9ce93ceedcba8" - integrity sha512-/DdH4TiTmOKzyQbp/eadcCVexiCb36xJg7HshYOYJnNZFDj33GEv0P7GxsynpShhq4OLYJzbGcBDkLsDt7MnNg== +array.prototype.tosorted@^1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/array.prototype.tosorted/-/array.prototype.tosorted-1.1.4.tgz#fe954678ff53034e717ea3352a03f0b0b86f7ffc" + integrity sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA== dependencies: - call-bind "^1.0.5" + call-bind "^1.0.7" define-properties "^1.2.1" - es-abstract "^1.22.3" - es-errors "^1.1.0" + es-abstract "^1.23.3" + es-errors "^1.3.0" es-shim-unscopables "^1.0.2" arraybuffer.prototype.slice@^1.0.3: @@ -3017,16 +2834,24 @@ arraybuffer.prototype.slice@^1.0.3: is-array-buffer "^3.0.4" is-shared-array-buffer "^1.0.2" +arraybuffer.prototype.slice@^1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz#9d760d84dbdd06d0cbf92c8849615a1a7ab3183c" + integrity sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ== + dependencies: + array-buffer-byte-length "^1.0.1" + call-bind "^1.0.8" + define-properties "^1.2.1" + es-abstract "^1.23.5" + es-errors "^1.3.0" + get-intrinsic "^1.2.6" + is-array-buffer "^3.0.4" + asap@^2.0.0: version "2.0.6" resolved "https://registry.yarnpkg.com/asap/-/asap-2.0.6.tgz#e50347611d7e690943208bbdafebcbc2fb866d46" integrity sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA== -async-validator@^4.1.0: - version "4.2.5" - resolved "https://registry.yarnpkg.com/async-validator/-/async-validator-4.2.5.tgz#c96ea3332a521699d0afaaceed510a54656c6339" - integrity sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg== - async@^2.5.0, async@^2.6.2: version "2.6.4" resolved "https://registry.yarnpkg.com/async/-/async-2.6.4.tgz#706b7ff6084664cd7eae713f6f965433b5504221" @@ -3146,11 +2971,6 @@ batch@0.6.1: resolved "https://registry.yarnpkg.com/batch/-/batch-0.6.1.tgz#dc34314f4e679318093fc760272525f94bf25c16" integrity sha1-3DQxT05nkxgJP8dgJyUl+UvyXBY= -big.js@^3.1.3: - version "3.2.0" - resolved "https://registry.yarnpkg.com/big.js/-/big.js-3.2.0.tgz#a5fc298b81b9e0dca2e458824784b65c52ba588e" - integrity sha512-+hN/Zh2D08Mx65pZ/4g5bsmNiZUuChDiQfTUQ7qJr4/kuopCr88xZsAXv6mBoZEsUI4OuGHlX59qE94K2mMW8Q== - big.js@^5.2.2: version "5.2.2" resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" @@ -3293,6 +3113,14 @@ cacache@^15.0.5: tar "^6.0.2" unique-filename "^1.1.1" +call-bind-apply-helpers@^1.0.0, call-bind-apply-helpers@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.1.tgz#32e5892e6361b29b0b545ba6f7763378daca2840" + integrity sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g== + dependencies: + es-errors "^1.3.0" + function-bind "^1.1.2" + call-bind@^1.0.0, call-bind@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.2.tgz#b1d4e89e688119c3c9a903ad30abb2f6a919be3c" @@ -3312,6 +3140,24 @@ call-bind@^1.0.5, call-bind@^1.0.6, call-bind@^1.0.7: get-intrinsic "^1.2.4" set-function-length "^1.2.1" +call-bind@^1.0.8: + version "1.0.8" + resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.8.tgz#0736a9660f537e3388826f440d5ec45f744eaa4c" + integrity sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww== + dependencies: + call-bind-apply-helpers "^1.0.0" + es-define-property "^1.0.0" + get-intrinsic "^1.2.4" + set-function-length "^1.2.2" + +call-bound@^1.0.2, call-bound@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/call-bound/-/call-bound-1.0.3.tgz#41cfd032b593e39176a71533ab4f384aa04fd681" + integrity sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA== + dependencies: + call-bind-apply-helpers "^1.0.1" + get-intrinsic "^1.2.6" + call-me-maybe@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/call-me-maybe/-/call-me-maybe-1.0.1.tgz#26d208ea89e37b5cbde60250a15f031c16a4d66b" @@ -3353,18 +3199,7 @@ chalk@4.1.2: ansi-styles "^4.1.0" supports-color "^7.1.0" -chalk@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" - integrity sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg= - dependencies: - ansi-styles "^2.2.1" - escape-string-regexp "^1.0.2" - has-ansi "^2.0.0" - strip-ansi "^3.0.0" - supports-color "^2.0.0" - -chalk@^2.0.0, chalk@^2.0.1, chalk@^2.4.1, chalk@^2.4.2: +chalk@^2.0.0, chalk@^2.0.1, chalk@^2.4.2: version "2.4.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== @@ -3441,7 +3276,7 @@ cjs-module-lexer@^1.0.0: resolved "https://registry.yarnpkg.com/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz#9f84ba3244a512f3a54e5277e8eef4c489864e40" integrity sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA== -classnames@2.x, classnames@^2.2.1, classnames@^2.2.3, classnames@^2.2.5, classnames@^2.2.6, classnames@^2.3.1, classnames@^2.3.2: +classnames@^2.2.5, classnames@^2.2.6, classnames@^2.3.1: version "2.3.2" resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.3.2.tgz#351d813bf0137fcc6a76a16b88208d2560a0d924" integrity sha512-CSbhY4cFEJRe6/GQzIk5qXZ4Jeg5pcsP7b5peFSDpffpe1cqjASH/n9UTjBwOp6XpMSTwQ8Za2K5V02ueA7Tmw== @@ -3588,11 +3423,6 @@ commander@^8.3.0: resolved "https://registry.yarnpkg.com/commander/-/commander-8.3.0.tgz#4837ea1b2da67b9c616a67afbb0fafee567bca66" integrity sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww== -common-tags@1.8.0: - version "1.8.0" - resolved "https://registry.yarnpkg.com/common-tags/-/common-tags-1.8.0.tgz#8e3153e542d4a39e9b10554434afaaf98956a937" - integrity sha512-6P6g0uetGpW/sdyUy/iQQCbFF0kWVMSIVSyYz7Zgjcgh8mgw8PQzDNZeyZ5DQ2gM7LBoZPHmnjz8rUthkBG5tw== - commondir@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/commondir/-/commondir-1.0.1.tgz#ddd800da0c66127393cca5950ea968a3aaf1253b" @@ -3623,11 +3453,6 @@ compression@^1.7.4: safe-buffer "5.1.2" vary "~1.1.2" -compute-scroll-into-view@^3.0.2: - version "3.0.3" - resolved "https://registry.yarnpkg.com/compute-scroll-into-view/-/compute-scroll-into-view-3.0.3.tgz#c418900a5c56e2b04b885b54995df164535962b1" - integrity sha512-nadqwNxghAGTamwIqQSG433W6OADZx2vCo3UXHNrzTRHK/htu+7+L0zhjEoaeaQVNAi3YgqWDv8+tzf0hRfR+A== - concat-map@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" @@ -3682,13 +3507,6 @@ cookiejar@^2.1.4: resolved "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.4.tgz#ee669c1fea2cf42dc31585469d193fef0d65771b" integrity sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw== -copy-to-clipboard@^3.2.0: - version "3.3.1" - resolved "https://registry.yarnpkg.com/copy-to-clipboard/-/copy-to-clipboard-3.3.1.tgz#115aa1a9998ffab6196f93076ad6da3b913662ae" - integrity sha512-i13qo6kIHTTpCm8/Wup+0b1mVWETvu2kIMzKoK8FpkLkFxlt0znUAHcMzox+T8sPlqtZXq3CulEjQHsYiGFJUw== - dependencies: - toggle-selection "^1.0.6" - copy-webpack-plugin@^6.1.1: version "6.1.1" resolved "https://registry.yarnpkg.com/copy-webpack-plugin/-/copy-webpack-plugin-6.1.1.tgz#737a3ba21c16cc6ddca972f5cf8de25568ca0616" @@ -3729,25 +3547,6 @@ core-util-is@~1.0.0: resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= -cosmiconfig@5.0.6: - version "5.0.6" - resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-5.0.6.tgz#dca6cf680a0bd03589aff684700858c81abeeb39" - integrity sha512-6DWfizHriCrFWURP1/qyhsiFvYdlJzbCzmtFWh744+KyWsJo5+kPzUZZaMRSSItoYc0pxFX7gEO7ZC1/gN/7AQ== - dependencies: - is-directory "^0.3.1" - js-yaml "^3.9.0" - parse-json "^4.0.0" - -cosmiconfig@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-4.0.0.tgz#760391549580bbd2df1e562bc177b13c290972dc" - integrity sha512-6e5vDdrXZD+t5v0L8CrurPeybg4Fmf+FCSYxXKYVAqLUtyCSbuyqE059d0kDthTNRzKVjL7QMgNpEUlsoYH3iQ== - dependencies: - is-directory "^0.3.1" - js-yaml "^3.9.0" - parse-json "^4.0.0" - require-from-string "^2.0.1" - create-jest@^29.7.0: version "29.7.0" resolved "https://registry.yarnpkg.com/create-jest/-/create-jest-29.7.0.tgz#a355c5b3cb1e1af02ba177fe7afd7feee49a5320" @@ -3766,38 +3565,15 @@ create-require@^1.1.0: resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333" integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== -cross-spawn@6.0.5: - version "6.0.5" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-6.0.5.tgz#4a5ec7c64dfae22c3a14124dbacdee846d80cbc4" - integrity sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ== - dependencies: - nice-try "^1.0.4" - path-key "^2.0.1" - semver "^5.5.0" - shebang-command "^1.2.0" - which "^1.2.9" - -cross-spawn@^7.0.2, cross-spawn@^7.0.3: - version "7.0.3" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" - integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== +cross-spawn@^7.0.3, cross-spawn@^7.0.6: + version "7.0.6" + resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.6.tgz#8a58fe78f00dcd70c370451759dfbfaf03e8ee9f" + integrity sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA== dependencies: path-key "^3.1.0" shebang-command "^2.0.0" which "^2.0.1" -css-modules-loader-core@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/css-modules-loader-core/-/css-modules-loader-core-1.1.0.tgz#5908668294a1becd261ae0a4ce21b0b551f21d16" - integrity sha1-WQhmgpShvs0mGuCkziGwtVHyHRY= - dependencies: - icss-replace-symbols "1.1.0" - postcss "6.0.1" - postcss-modules-extract-imports "1.1.0" - postcss-modules-local-by-default "1.2.0" - postcss-modules-scope "1.1.0" - postcss-modules-values "1.3.0" - css-select@^4.1.3: version "4.1.3" resolved "https://registry.yarnpkg.com/css-select/-/css-select-4.1.3.tgz#a70440f70317f2669118ad74ff105e65849c7067" @@ -3809,24 +3585,11 @@ css-select@^4.1.3: domutils "^2.6.0" nth-check "^2.0.0" -css-selector-tokenizer@^0.7.0: - version "0.7.3" - resolved "https://registry.yarnpkg.com/css-selector-tokenizer/-/css-selector-tokenizer-0.7.3.tgz#735f26186e67c749aaf275783405cf0661fae8f1" - integrity sha512-jWQv3oCEL5kMErj4wRnK/OPoBi0D+P1FR2cDCKYPaMeD2eW3/mttav8HT4hT1CKopiJI/psEULjkClhvJo4Lvg== - dependencies: - cssesc "^3.0.0" - fastparse "^1.1.2" - css-what@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/css-what/-/css-what-5.0.1.tgz#3efa820131f4669a8ac2408f9c32e7c7de9f4cad" integrity sha512-FYDTSHb/7KXsWICVsxdmiExPjCfRC4qRFBdVwv7Ax9hMnvMmEjP9RfxTEZ3qPZGmADDn2vAKSo9UcN1jKVYscg== -cssesc@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/cssesc/-/cssesc-3.0.0.tgz#37741919903b868565e1c09ea747445cd18983ee" - integrity sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg== - cssom@^0.5.0: version "0.5.0" resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.5.0.tgz#d254fa92cd8b6fbd83811b9fbaed34663cc17c36" @@ -3844,11 +3607,6 @@ cssstyle@^2.3.0: dependencies: cssom "~0.3.6" -csstype@^3.0.10: - version "3.1.2" - resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.1.2.tgz#1d4bf9d572f11c14031f0436e1c10bc1f571f50b" - integrity sha512-I7K1Uu0MBPzaFKg4nI5Q7Vs2t+3gWWW648spaF+Rg7pI9ds18Ugn+lvg4SHczUdKlHI5LWBXyqfS8+DufyBsgQ== - csstype@^3.0.2: version "3.0.8" resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.0.8.tgz#d2266a792729fb227cd216fb572f43728e1ad340" @@ -3905,11 +3663,6 @@ date-fns@^2.30.0: dependencies: "@babel/runtime" "^7.21.0" -dayjs@^1.11.1: - version "1.11.8" - resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.8.tgz#4282f139c8c19dd6d0c7bd571e30c2d0ba7698ea" - integrity sha512-LcgxzFoWMEPO7ggRv1Y2N31hUf2R0Vj7fuy/m+Bg1K8rr+KAs1AEy4y9jd5DXe8pbHgX+srkHNS7TH6Q6ZhYeQ== - debug@2.6.9: version "2.6.9" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" @@ -4121,11 +3874,6 @@ doctrine@^2.1.0: dependencies: esutils "^2.0.2" -dom-align@^1.7.0: - version "1.12.2" - resolved "https://registry.yarnpkg.com/dom-align/-/dom-align-1.12.2.tgz#0f8164ebd0c9c21b0c790310493cd855892acd4b" - integrity sha512-pHuazgqrsTFrGU2WLDdXxCFabkdQDx72ddkraZNih1KsMcN5qsRSTR9O4VJRlwTPCPb5COYg3LOfiMHHcPInHg== - dom-converter@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/dom-converter/-/dom-converter-0.2.0.tgz#6721a9daee2e293682955b6afe416771627bb768" @@ -4201,6 +3949,15 @@ dot-case@^3.0.4: no-case "^3.0.4" tslib "^2.0.3" +dunder-proto@^1.0.0, dunder-proto@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/dunder-proto/-/dunder-proto-1.0.1.tgz#d7ae667e1dc83482f8b70fd0f6eefc50da30f58a" + integrity sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A== + dependencies: + call-bind-apply-helpers "^1.0.1" + es-errors "^1.3.0" + gopd "^1.2.0" + ee-first@1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d" @@ -4221,11 +3978,6 @@ emoji-regex@^8.0.0: resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== -emojis-list@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/emojis-list/-/emojis-list-2.1.0.tgz#4daa4d9db00f9819880c79fa457ae5b09a1fd389" - integrity sha1-TapNnbAPmBmIDHn6RXrlsJof04k= - emojis-list@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/emojis-list/-/emojis-list-3.0.0.tgz#5570662046ad29e2e916e71aae260abdff4f6a78" @@ -4278,7 +4030,61 @@ error-stack-parser@^1.3.6: dependencies: stackframe "^0.3.1" -es-abstract@^1.22.1, es-abstract@^1.22.3, es-abstract@^1.23.0, es-abstract@^1.23.1, es-abstract@^1.23.2, es-abstract@^1.23.3: +es-abstract@^1.17.5, es-abstract@^1.23.5, es-abstract@^1.23.6: + version "1.23.6" + resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.23.6.tgz#55f0e1ce7128995cc04ace0a57d7dca348345108" + integrity sha512-Ifco6n3yj2tMZDWNLyloZrytt9lqqlwvS83P3HtaETR0NUOYnIULGGHpktqYGObGy+8wc1okO25p8TjemhImvA== + dependencies: + array-buffer-byte-length "^1.0.1" + arraybuffer.prototype.slice "^1.0.4" + available-typed-arrays "^1.0.7" + call-bind "^1.0.8" + call-bound "^1.0.3" + data-view-buffer "^1.0.1" + data-view-byte-length "^1.0.1" + data-view-byte-offset "^1.0.0" + es-define-property "^1.0.1" + es-errors "^1.3.0" + es-object-atoms "^1.0.0" + es-set-tostringtag "^2.0.3" + es-to-primitive "^1.3.0" + function.prototype.name "^1.1.7" + get-intrinsic "^1.2.6" + get-symbol-description "^1.0.2" + globalthis "^1.0.4" + gopd "^1.2.0" + has-property-descriptors "^1.0.2" + has-proto "^1.2.0" + has-symbols "^1.1.0" + hasown "^2.0.2" + internal-slot "^1.1.0" + is-array-buffer "^3.0.4" + is-callable "^1.2.7" + is-data-view "^1.0.2" + is-negative-zero "^2.0.3" + is-regex "^1.2.1" + is-shared-array-buffer "^1.0.3" + is-string "^1.1.1" + is-typed-array "^1.1.13" + is-weakref "^1.1.0" + math-intrinsics "^1.0.0" + object-inspect "^1.13.3" + object-keys "^1.1.1" + object.assign "^4.1.5" + regexp.prototype.flags "^1.5.3" + safe-array-concat "^1.1.3" + safe-regex-test "^1.1.0" + string.prototype.trim "^1.2.10" + string.prototype.trimend "^1.0.9" + string.prototype.trimstart "^1.0.8" + typed-array-buffer "^1.0.2" + typed-array-byte-length "^1.0.1" + typed-array-byte-offset "^1.0.3" + typed-array-length "^1.0.7" + unbox-primitive "^1.0.2" + which-typed-array "^1.1.16" + +es-abstract@^1.22.1, es-abstract@^1.22.3, es-abstract@^1.23.0, es-abstract@^1.23.2, es-abstract@^1.23.3: version "1.23.3" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.23.3.tgz#8f0c5a35cd215312573c5a27c87dfd6c881a0aa0" integrity sha512-e+HfNH61Bj1X9/jLc5v1owaLYuHdeHHSQlkhCBiTK8rBvKaULl/beGMxwrMXjpYrv4pz22BlY570vVePA2ho4A== @@ -4337,15 +4143,20 @@ es-define-property@^1.0.0: dependencies: get-intrinsic "^1.2.4" -es-errors@^1.1.0, es-errors@^1.2.1, es-errors@^1.3.0: +es-define-property@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/es-define-property/-/es-define-property-1.0.1.tgz#983eb2f9a6724e9303f61addf011c72e09e0b0fa" + integrity sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g== + +es-errors@^1.2.1, es-errors@^1.3.0: version "1.3.0" resolved "https://registry.yarnpkg.com/es-errors/-/es-errors-1.3.0.tgz#05f75a25dab98e4fb1dcd5e1472c0546d5057c8f" integrity sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw== -es-iterator-helpers@^1.0.17: - version "1.0.19" - resolved "https://registry.yarnpkg.com/es-iterator-helpers/-/es-iterator-helpers-1.0.19.tgz#117003d0e5fec237b4b5c08aded722e0c6d50ca8" - integrity sha512-zoMwbCcH5hwUkKJkT8kDIBZSz9I6mVG//+lDCinLCGov4+r7NIy0ld8o03M0cJxl2spVf6ESYVS6/gpIfq1FFw== +es-iterator-helpers@^1.1.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/es-iterator-helpers/-/es-iterator-helpers-1.2.0.tgz#2f1a3ab998b30cb2d10b195b587c6d9ebdebf152" + integrity sha512-tpxqxncxnpw3c93u8n3VOzACmRFoVmWJqbWXvX/JfKbkhBw1oslgPrUfeSt2psuqyEJFD6N/9lg5i7bsKpoq+Q== dependencies: call-bind "^1.0.7" define-properties "^1.2.1" @@ -4354,12 +4165,13 @@ es-iterator-helpers@^1.0.17: es-set-tostringtag "^2.0.3" function-bind "^1.1.2" get-intrinsic "^1.2.4" - globalthis "^1.0.3" + globalthis "^1.0.4" + gopd "^1.0.1" has-property-descriptors "^1.0.2" has-proto "^1.0.3" has-symbols "^1.0.3" internal-slot "^1.0.7" - iterator.prototype "^1.1.2" + iterator.prototype "^1.1.3" safe-array-concat "^1.1.2" es-module-lexer@^0.10.5: @@ -4404,6 +4216,15 @@ es-to-primitive@^1.2.1: is-date-object "^1.0.1" is-symbol "^1.0.2" +es-to-primitive@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.3.0.tgz#96c89c82cc49fd8794a24835ba3e1ff87f214e18" + integrity sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g== + dependencies: + is-callable "^1.2.7" + is-date-object "^1.0.5" + is-symbol "^1.0.4" + es6-promise@^3.2.1: version "3.3.1" resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-3.3.1.tgz#a08cdde84ccdbf34d027a1451bc91d4bcd28a613" @@ -4693,7 +4514,7 @@ escape-html@~1.0.3: resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" integrity sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow== -escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5: +escape-string-regexp@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= @@ -4732,29 +4553,29 @@ eslint-plugin-prettier@^5.1.3: prettier-linter-helpers "^1.0.0" synckit "^0.8.6" -eslint-plugin-react@^7.34.1: - version "7.34.1" - resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.34.1.tgz#6806b70c97796f5bbfb235a5d3379ece5f4da997" - integrity sha512-N97CxlouPT1AHt8Jn0mhhN2RrADlUAsk1/atcT2KyA/l9Q/E6ll7OIGwNumFmWfZ9skV3XXccYS19h80rHtgkw== +eslint-plugin-react@^7.37.2: + version "7.37.2" + resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.37.2.tgz#cd0935987876ba2900df2f58339f6d92305acc7a" + integrity sha512-EsTAnj9fLVr/GZleBLFbj/sSuXeWmp1eXIN60ceYnZveqEaUCyW4X+Vh4WTdUhCkW4xutXYqTXCUSyqD4rB75w== dependencies: - array-includes "^3.1.7" - array.prototype.findlast "^1.2.4" + array-includes "^3.1.8" + array.prototype.findlast "^1.2.5" array.prototype.flatmap "^1.3.2" - array.prototype.toreversed "^1.1.2" - array.prototype.tosorted "^1.1.3" + array.prototype.tosorted "^1.1.4" doctrine "^2.1.0" - es-iterator-helpers "^1.0.17" + es-iterator-helpers "^1.1.0" estraverse "^5.3.0" + hasown "^2.0.2" jsx-ast-utils "^2.4.1 || ^3.0.0" minimatch "^3.1.2" - object.entries "^1.1.7" - object.fromentries "^2.0.7" - object.hasown "^1.1.3" - object.values "^1.1.7" + object.entries "^1.1.8" + object.fromentries "^2.0.8" + object.values "^1.2.0" prop-types "^15.8.1" resolve "^2.0.0-next.5" semver "^6.3.1" - string.prototype.matchall "^4.0.10" + string.prototype.matchall "^4.0.11" + string.prototype.repeat "^1.0.0" eslint-scope@5.1.1: version "5.1.1" @@ -4764,10 +4585,10 @@ eslint-scope@5.1.1: esrecurse "^4.3.0" estraverse "^4.1.1" -eslint-scope@^8.0.1: - version "8.0.1" - resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-8.0.1.tgz#a9601e4b81a0b9171657c343fb13111688963cfc" - integrity sha512-pL8XjgP4ZOmmwfFE8mEhSxA7ZY4C+LWyqjQ3o4yWkkmD0qcMT9kkW3zWHOczhWcjTSgqycYAgwSlXvZltv65og== +eslint-scope@^8.2.0: + version "8.2.0" + resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-8.2.0.tgz#377aa6f1cb5dc7592cfd0b7f892fd0cf352ce442" + integrity sha512-PHlWUfG6lvPc3yvP5A4PNyBL1W8fkDUccmI21JUu/+GKZBoH/W5u6usENXUrWFRsyoW5ACUjFGgAFQp5gUlb/A== dependencies: esrecurse "^4.3.0" estraverse "^5.2.0" @@ -4782,28 +4603,37 @@ eslint-visitor-keys@^4.0.0: resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-4.0.0.tgz#e3adc021aa038a2a8e0b2f8b0ce8f66b9483b1fb" integrity sha512-OtIRv/2GyiF6o/d8K7MYKKbXrOUBIK6SfkIRM4Z0dY3w+LiQ0vy3F57m0Z71bjbyeiWFiHJ8brqnmE6H6/jEuw== -eslint@^9.1.1: - version "9.1.1" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-9.1.1.tgz#39ec657ccd12813cb4a1dab2f9229dcc6e468271" - integrity sha512-b4cRQ0BeZcSEzPpY2PjFY70VbO32K7BStTGtBsnIGdTSEEQzBi8hPBcGQmTG2zUvFr9uLe0TK42bw8YszuHEqg== +eslint-visitor-keys@^4.2.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-4.2.0.tgz#687bacb2af884fcdda8a6e7d65c606f46a14cd45" + integrity sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw== + +eslint@^9.15.0: + version "9.17.0" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-9.17.0.tgz#faa1facb5dd042172fdc520106984b5c2421bb0c" + integrity sha512-evtlNcpJg+cZLcnVKwsai8fExnqjGPicK7gnUtlNuzu+Fv9bI0aLpND5T44VLQtoMEnI57LoXO9XAkIXwohKrA== dependencies: "@eslint-community/eslint-utils" "^4.2.0" - "@eslint-community/regexpp" "^4.6.1" - "@eslint/eslintrc" "^3.0.2" - "@eslint/js" "9.1.1" - "@humanwhocodes/config-array" "^0.13.0" + "@eslint-community/regexpp" "^4.12.1" + "@eslint/config-array" "^0.19.0" + "@eslint/core" "^0.9.0" + "@eslint/eslintrc" "^3.2.0" + "@eslint/js" "9.17.0" + "@eslint/plugin-kit" "^0.2.3" + "@humanfs/node" "^0.16.6" "@humanwhocodes/module-importer" "^1.0.1" - "@humanwhocodes/retry" "^0.2.3" - "@nodelib/fs.walk" "^1.2.8" + "@humanwhocodes/retry" "^0.4.1" + "@types/estree" "^1.0.6" + "@types/json-schema" "^7.0.15" ajv "^6.12.4" chalk "^4.0.0" - cross-spawn "^7.0.2" + cross-spawn "^7.0.6" debug "^4.3.2" escape-string-regexp "^4.0.0" - eslint-scope "^8.0.1" - eslint-visitor-keys "^4.0.0" - espree "^10.0.1" - esquery "^1.4.2" + eslint-scope "^8.2.0" + eslint-visitor-keys "^4.2.0" + espree "^10.3.0" + esquery "^1.5.0" esutils "^2.0.2" fast-deep-equal "^3.1.3" file-entry-cache "^8.0.0" @@ -4812,15 +4642,11 @@ eslint@^9.1.1: ignore "^5.2.0" imurmurhash "^0.1.4" is-glob "^4.0.0" - is-path-inside "^3.0.3" json-stable-stringify-without-jsonify "^1.0.1" - levn "^0.4.1" lodash.merge "^4.6.2" minimatch "^3.1.2" natural-compare "^1.4.0" optionator "^0.9.3" - strip-ansi "^6.0.1" - text-table "^0.2.0" espree@^10.0.1: version "10.0.1" @@ -4831,15 +4657,24 @@ espree@^10.0.1: acorn-jsx "^5.3.2" eslint-visitor-keys "^4.0.0" +espree@^10.3.0: + version "10.3.0" + resolved "https://registry.yarnpkg.com/espree/-/espree-10.3.0.tgz#29267cf5b0cb98735b65e64ba07e0ed49d1eed8a" + integrity sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg== + dependencies: + acorn "^8.14.0" + acorn-jsx "^5.3.2" + eslint-visitor-keys "^4.2.0" + esprima@^4.0.0, esprima@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== -esquery@^1.4.2: - version "1.5.0" - resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.5.0.tgz#6ce17738de8577694edd7361c57182ac8cb0db0b" - integrity sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg== +esquery@^1.5.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.6.0.tgz#91419234f804d852a82dceec3e16cdc22cf9dae7" + integrity sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg== dependencies: estraverse "^5.1.0" @@ -5022,11 +4857,6 @@ fastest-levenshtein@^1.0.12: resolved "https://registry.yarnpkg.com/fastest-levenshtein/-/fastest-levenshtein-1.0.12.tgz#9990f7d3a88cc5a9ffd1f1745745251700d497e2" integrity sha512-On2N+BpYJ15xIC974QNVuYGMOlEVt4s0EOI3wwMqOmK1fdDY+FN/zltPV8vosq4ad4c/gJ1KHScUn/6AWIgiow== -fastparse@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/fastparse/-/fastparse-1.1.2.tgz#91728c5a5942eced8531283c79441ee4122c35a9" - integrity sha512-483XLLxTVIwWK3QTrMGRqUfUpoOs/0hbQrl2oz4J0pAcm3A3bu84wxTFqGqkJzewCLdME38xJLJAxBABfQT8sQ== - fastq@^1.6.0: version "1.11.1" resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.11.1.tgz#5d8175aae17db61947f8b162cfc7f63264d22807" @@ -5212,7 +5042,7 @@ function-bind@^1.1.2: resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.2.tgz#2c02d864d97f3ea6c8830c464cbd11ab6eab7a1c" integrity sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA== -function.prototype.name@^1.1.5, function.prototype.name@^1.1.6: +function.prototype.name@^1.1.6: version "1.1.6" resolved "https://registry.yarnpkg.com/function.prototype.name/-/function.prototype.name-1.1.6.tgz#cdf315b7d90ee77a4c6ee216c3c3362da07533fd" integrity sha512-Z5kx79swU5P27WEayXM1tBi5Ze/lbIyiNgU3qyXUOf9b2rgXYyF9Dy9Cx+IQv/Lc8WCG6L82zwUPpSS9hGehIg== @@ -5222,18 +5052,22 @@ function.prototype.name@^1.1.5, function.prototype.name@^1.1.6: es-abstract "^1.22.1" functions-have-names "^1.2.3" +function.prototype.name@^1.1.7: + version "1.1.7" + resolved "https://registry.yarnpkg.com/function.prototype.name/-/function.prototype.name-1.1.7.tgz#9df48ea5f746bf577d7e15b5da89df8952a98e7b" + integrity sha512-2g4x+HqTJKM9zcJqBSpjoRmdcPFtJM60J3xJisTQSXBWka5XqyBN/2tNUgma1mztTXyDuUsEtYe5qcs7xYzYQA== + dependencies: + call-bind "^1.0.8" + define-properties "^1.2.1" + functions-have-names "^1.2.3" + hasown "^2.0.2" + is-callable "^1.2.7" + functions-have-names@^1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/functions-have-names/-/functions-have-names-1.2.3.tgz#0404fe4ee2ba2f607f0e0ec3c80bae994133b834" integrity sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ== -generic-names@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/generic-names/-/generic-names-1.0.3.tgz#2d786a121aee508876796939e8e3bff836c20917" - integrity sha1-LXhqEhruUIh2eWk56OO/+DbCCRc= - dependencies: - loader-utils "^0.2.16" - gensync@^1.0.0-beta.2: version "1.0.0-beta.2" resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.2.tgz#32a6ee76c3d7f52d46b2b1ae5d93fea8580a25e0" @@ -5264,6 +5098,22 @@ get-intrinsic@^1.1.3, get-intrinsic@^1.2.1, get-intrinsic@^1.2.3, get-intrinsic@ has-symbols "^1.0.3" hasown "^2.0.0" +get-intrinsic@^1.2.5, get-intrinsic@^1.2.6: + version "1.2.6" + resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.2.6.tgz#43dd3dd0e7b49b82b2dfcad10dc824bf7fc265d5" + integrity sha512-qxsEs+9A+u85HhllWJJFicJfPDhRmjzoYdl64aMWW9yRIJmSyxdn8IEkuIM530/7T+lv0TIHd8L6Q/ra0tEoeA== + dependencies: + call-bind-apply-helpers "^1.0.1" + dunder-proto "^1.0.0" + es-define-property "^1.0.1" + es-errors "^1.3.0" + es-object-atoms "^1.0.0" + function-bind "^1.1.2" + gopd "^1.2.0" + has-symbols "^1.1.0" + hasown "^2.0.2" + math-intrinsics "^1.0.0" + get-package-type@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/get-package-type/-/get-package-type-0.1.0.tgz#8de2d803cff44df3bc6c456e6668b36c3926e11a" @@ -5357,7 +5207,7 @@ globals@^15.1.0: resolved "https://registry.yarnpkg.com/globals/-/globals-15.1.0.tgz#4e03d200c8362201636b8cdfaa316d6cef67ff1e" integrity sha512-926gJqg+4mkxwYKiFvoomM4J0kWESfk3qfTvRL2/oc/tK/eTDBbrfcKnSa2KtfdxB5onoL7D3A3qIHQFpd4+UA== -globalthis@^1.0.3: +globalthis@^1.0.3, globalthis@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/globalthis/-/globalthis-1.0.4.tgz#7430ed3a975d97bfb59bcce41f5cabbafa651236" integrity sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ== @@ -5396,6 +5246,11 @@ gopd@^1.0.1: dependencies: get-intrinsic "^1.1.3" +gopd@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/gopd/-/gopd-1.2.0.tgz#89f56b8217bdbc8802bd299df6d7f1081d7e51a1" + integrity sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg== + graceful-fs@^4.1.2, graceful-fs@^4.2.11, graceful-fs@^4.2.4, graceful-fs@^4.2.6, graceful-fs@^4.2.9: version "4.2.11" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" @@ -5423,23 +5278,11 @@ harmony-reflect@^1.4.6: resolved "https://registry.yarnpkg.com/harmony-reflect/-/harmony-reflect-1.6.2.tgz#31ecbd32e648a34d030d86adb67d4d47547fe710" integrity sha512-HIp/n38R9kQjDEziXyDTuW3vvoxxyxjxFzXLrBr18uB47GnSt+G9D29fqrpM5ZkspMcPICud3XsBJQ4Y2URg8g== -has-ansi@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" - integrity sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE= - dependencies: - ansi-regex "^2.0.0" - has-bigints@^1.0.1, has-bigints@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/has-bigints/-/has-bigints-1.0.2.tgz#0871bd3e3d51626f6ca0966668ba35d5602d6eaa" integrity sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ== -has-flag@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" - integrity sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo= - has-flag@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" @@ -5462,6 +5305,13 @@ has-proto@^1.0.1, has-proto@^1.0.3: resolved "https://registry.yarnpkg.com/has-proto/-/has-proto-1.0.3.tgz#b31ddfe9b0e6e9914536a6ab286426d0214f77fd" integrity sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q== +has-proto@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/has-proto/-/has-proto-1.2.0.tgz#5de5a6eabd95fdffd9818b43055e8065e39fe9d5" + integrity sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ== + dependencies: + dunder-proto "^1.0.0" + has-symbols@^1.0.1, has-symbols@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.2.tgz#165d3070c00309752a1236a479331e3ac56f1423" @@ -5472,6 +5322,11 @@ has-symbols@^1.0.3: resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8" integrity sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A== +has-symbols@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.1.0.tgz#fc9c6a783a084951d0b971fe1018de813707a338" + integrity sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ== + has-tostringtag@^1.0.0, has-tostringtag@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/has-tostringtag/-/has-tostringtag-1.0.2.tgz#2cdc42d40bef2e5b4eeab7c01a73c54ce7ab5abc" @@ -5697,11 +5552,6 @@ iconv-lite@0.6.3: dependencies: safer-buffer ">= 2.1.2 < 3.0.0" -icss-replace-symbols@1.1.0, icss-replace-symbols@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/icss-replace-symbols/-/icss-replace-symbols-1.1.0.tgz#06ea6f83679a7749e386cfe1fe812ae5db223ded" - integrity sha1-Bupvg2ead0njhs/h/oEq5dsiPe0= - identity-obj-proxy@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/identity-obj-proxy/-/identity-obj-proxy-3.0.0.tgz#94d2bda96084453ef36fbc5aaec37e0f79f1fc14" @@ -5736,13 +5586,6 @@ immutable@^4.0.0: resolved "https://registry.yarnpkg.com/immutable/-/immutable-4.0.0.tgz#b86f78de6adef3608395efb269a91462797e2c23" integrity sha512-zIE9hX70qew5qTUjSS7wi1iwj/l7+m54KWU247nhM3v806UdGj1yDndXj+IOYxxtW9zyLI+xqFNZjTuDaLUqFw== -import-cwd@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/import-cwd/-/import-cwd-2.1.0.tgz#aa6cf36e722761285cb371ec6519f53e2435b0a9" - integrity sha1-qmzzbnInYShcs3HsZRn1PiQ1sKk= - dependencies: - import-from "^2.1.0" - import-fresh@^3.2.1: version "3.3.0" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.3.0.tgz#37162c25fcb9ebaa2e6e53d5b4d88ce17d9e0c2b" @@ -5751,13 +5594,6 @@ import-fresh@^3.2.1: parent-module "^1.0.0" resolve-from "^4.0.0" -import-from@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/import-from/-/import-from-2.1.0.tgz#335db7f2a7affd53aaa471d4b8021dee36b7f3b1" - integrity sha1-M1238qev/VOqpHHUuAId7ja387E= - dependencies: - resolve-from "^3.0.0" - import-local@^3.0.2: version "3.1.0" resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.1.0.tgz#b4479df8a5fd44f6cdce24070675676063c95cb4" @@ -5808,6 +5644,15 @@ internal-slot@^1.0.7: hasown "^2.0.0" side-channel "^1.0.4" +internal-slot@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/internal-slot/-/internal-slot-1.1.0.tgz#1eac91762947d2f7056bc838d93e13b2e9604961" + integrity sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw== + dependencies: + es-errors "^1.3.0" + hasown "^2.0.2" + side-channel "^1.1.0" + interpret@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-2.2.0.tgz#1a78a0b5965c40a5416d007ad6f50ad27c417df9" @@ -5874,6 +5719,13 @@ is-bigint@^1.0.1: dependencies: has-bigints "^1.0.1" +is-bigint@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/is-bigint/-/is-bigint-1.1.0.tgz#dda7a3445df57a42583db4228682eba7c4170672" + integrity sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ== + dependencies: + has-bigints "^1.0.2" + is-binary-path@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09" @@ -5889,9 +5741,17 @@ is-boolean-object@^1.1.0: call-bind "^1.0.2" has-tostringtag "^1.0.0" -is-callable@^1.1.3, is-callable@^1.1.4, is-callable@^1.2.7: - version "1.2.7" - resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.7.tgz#3bc2a85ea742d9e36205dcacdd72ca1fdc51b055" +is-boolean-object@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/is-boolean-object/-/is-boolean-object-1.2.1.tgz#c20d0c654be05da4fbc23c562635c019e93daf89" + integrity sha512-l9qO6eFlUETHtuihLcYOaLKByJ1f+N4kthcU9YjHy3N+B3hWv0y/2Nd0mu/7lTFnRQHTrSdXF50HQ3bl5fEnng== + dependencies: + call-bound "^1.0.2" + has-tostringtag "^1.0.2" + +is-callable@^1.1.3, is-callable@^1.1.4, is-callable@^1.2.7: + version "1.2.7" + resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.7.tgz#3bc2a85ea742d9e36205dcacdd72ca1fdc51b055" integrity sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA== is-core-module@^2.13.0: @@ -5915,6 +5775,15 @@ is-data-view@^1.0.1: dependencies: is-typed-array "^1.1.13" +is-data-view@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-data-view/-/is-data-view-1.0.2.tgz#bae0a41b9688986c2188dda6657e56b8f9e63b8e" + integrity sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw== + dependencies: + call-bound "^1.0.2" + get-intrinsic "^1.2.6" + is-typed-array "^1.1.13" + is-date-object@^1.0.1: version "1.0.4" resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.4.tgz#550cfcc03afada05eea3dd30981c7b09551f73e5" @@ -5927,10 +5796,13 @@ is-date-object@^1.0.5: dependencies: has-tostringtag "^1.0.0" -is-directory@^0.3.1: - version "0.3.1" - resolved "https://registry.yarnpkg.com/is-directory/-/is-directory-0.3.1.tgz#61339b6f2475fc772fd9c9d83f5c8575dc154ae1" - integrity sha1-YTObbyR1/Hcv2cnYP1yFddwVSuE= +is-date-object@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.1.0.tgz#ad85541996fc7aa8b2729701d27b7319f95d82f7" + integrity sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg== + dependencies: + call-bound "^1.0.2" + has-tostringtag "^1.0.2" is-docker@^2.0.0, is-docker@^2.1.1: version "2.2.1" @@ -5942,12 +5814,12 @@ is-extglob@^2.1.1: resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= -is-finalizationregistry@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-finalizationregistry/-/is-finalizationregistry-1.0.2.tgz#c8749b65f17c133313e661b1289b95ad3dbd62e6" - integrity sha512-0by5vtUJs8iFQb5TYUHHPudOR+qXYIMKtiUzvLIZITZUjknFmziyBJuLhVRc+Ds0dREFlskDNJKYIdIzu/9pfw== +is-finalizationregistry@^1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz#eefdcdc6c94ddd0674d9c85887bf93f944a97c90" + integrity sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg== dependencies: - call-bind "^1.0.2" + call-bound "^1.0.3" is-fullwidth-code-point@^3.0.0: version "3.0.0" @@ -5997,6 +5869,14 @@ is-number-object@^1.0.4: dependencies: has-tostringtag "^1.0.0" +is-number-object@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/is-number-object/-/is-number-object-1.1.1.tgz#144b21e95a1bc148205dcc2814a9134ec41b2541" + integrity sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw== + dependencies: + call-bound "^1.0.3" + has-tostringtag "^1.0.2" + is-number@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" @@ -6007,7 +5887,7 @@ is-path-cwd@^2.2.0: resolved "https://registry.yarnpkg.com/is-path-cwd/-/is-path-cwd-2.2.0.tgz#67d43b82664a7b5191fd9119127eb300048a9fdb" integrity sha512-w942bTcih8fdJPJmQHFzkS76NEP8Kzzvmw92cXsazb8intwLqPibPPdXf4ANdKV3rYMuuQYGIWtvz9JilB3NFQ== -is-path-inside@^3.0.2, is-path-inside@^3.0.3: +is-path-inside@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-3.0.3.tgz#d231362e53a07ff2b0e0ea7fed049161ffd16283" integrity sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ== @@ -6045,6 +5925,16 @@ is-regex@^1.1.4: call-bind "^1.0.2" has-tostringtag "^1.0.0" +is-regex@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.2.1.tgz#76d70a3ed10ef9be48eb577887d74205bf0cad22" + integrity sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g== + dependencies: + call-bound "^1.0.2" + gopd "^1.2.0" + has-tostringtag "^1.0.2" + hasown "^2.0.2" + is-set@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/is-set/-/is-set-2.0.3.tgz#8ab209ea424608141372ded6e0cb200ef1d9d01d" @@ -6076,6 +5966,14 @@ is-string@^1.0.5, is-string@^1.0.7: dependencies: has-tostringtag "^1.0.0" +is-string@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/is-string/-/is-string-1.1.1.tgz#92ea3f3d5c5b6e039ca8677e5ac8d07ea773cbb9" + integrity sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA== + dependencies: + call-bound "^1.0.3" + has-tostringtag "^1.0.2" + is-symbol@^1.0.2, is-symbol@^1.0.3: version "1.0.4" resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.4.tgz#a6dac93b635b063ca6872236de88910a57af139c" @@ -6083,6 +5981,15 @@ is-symbol@^1.0.2, is-symbol@^1.0.3: dependencies: has-symbols "^1.0.2" +is-symbol@^1.0.4, is-symbol@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.1.1.tgz#f47761279f532e2b05a7024a7506dbbedacd0634" + integrity sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w== + dependencies: + call-bound "^1.0.2" + has-symbols "^1.1.0" + safe-regex-test "^1.1.0" + is-typed-array@^1.1.13: version "1.1.13" resolved "https://registry.yarnpkg.com/is-typed-array/-/is-typed-array-1.1.13.tgz#d6c5ca56df62334959322d7d7dd1cca50debe229" @@ -6090,6 +5997,13 @@ is-typed-array@^1.1.13: dependencies: which-typed-array "^1.1.14" +is-typed-array@^1.1.15: + version "1.1.15" + resolved "https://registry.yarnpkg.com/is-typed-array/-/is-typed-array-1.1.15.tgz#4bfb4a45b61cee83a5a46fba778e4e8d59c0ce0b" + integrity sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ== + dependencies: + which-typed-array "^1.1.16" + is-weakmap@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/is-weakmap/-/is-weakmap-2.0.2.tgz#bf72615d649dfe5f699079c54b83e47d1ae19cfd" @@ -6102,6 +6016,13 @@ is-weakref@^1.0.2: dependencies: call-bind "^1.0.2" +is-weakref@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/is-weakref/-/is-weakref-1.1.0.tgz#47e3472ae95a63fa9cf25660bcf0c181c39770ef" + integrity sha512-SXM8Nwyys6nT5WP6pltOwKytLV7FqQ4UiibxVmW+EIosHcmCqkkjViTb5SNssDlkCiEYRP1/pdWUKVvZBmsR2Q== + dependencies: + call-bound "^1.0.2" + is-weakset@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/is-weakset/-/is-weakset-2.0.3.tgz#e801519df8c0c43e12ff2834eead84ec9e624007" @@ -6195,16 +6116,17 @@ istanbul-reports@^3.1.3: html-escaper "^2.0.0" istanbul-lib-report "^3.0.0" -iterator.prototype@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/iterator.prototype/-/iterator.prototype-1.1.2.tgz#5e29c8924f01916cb9335f1ff80619dcff22b0c0" - integrity sha512-DR33HMMr8EzwuRL8Y9D3u2BMj8+RqSE850jfGu59kS7tbmPLzGkZmVSfyCFSDxuZiEY6Rzt3T2NA/qU+NwVj1w== +iterator.prototype@^1.1.3: + version "1.1.4" + resolved "https://registry.yarnpkg.com/iterator.prototype/-/iterator.prototype-1.1.4.tgz#4ae6cf98b97fdc717b7e159d79dc25f8fc9482f1" + integrity sha512-x4WH0BWmrMmg4oHHl+duwubhrvczGlyuGAZu3nvrf0UXOfPu8IhZObFEr7DE/iv01YgVZrsOiRcqw2srkKEDIA== dependencies: - define-properties "^1.2.1" - get-intrinsic "^1.2.1" - has-symbols "^1.0.3" - reflect.getprototypeof "^1.0.4" - set-function-name "^2.0.1" + define-data-property "^1.1.4" + es-object-atoms "^1.0.0" + get-intrinsic "^1.2.6" + has-symbols "^1.1.0" + reflect.getprototypeof "^1.0.8" + set-function-name "^2.0.2" jest-changed-files@^29.7.0: version "29.7.0" @@ -6535,18 +6457,6 @@ jest-snapshot@^29.7.0: pretty-format "^29.7.0" semver "^7.5.3" -jest-transform-css@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/jest-transform-css/-/jest-transform-css-2.0.0.tgz#f384ad1922e3726201664c199fd368e657e295d3" - integrity sha512-KV5pD27qUltAVj0mZEVvqd+Ahe+WNPOVWKA1BRpIhBJ5OeUUOM46ivAznJrC5B1JrVNbMzWjPxnKl6QTsAAT3Q== - dependencies: - common-tags "1.8.0" - cosmiconfig "5.0.6" - cross-spawn "6.0.5" - postcss-load-config "2.0.0" - postcss-modules "1.3.2" - style-inject "0.3.0" - jest-util@^29.0.0, jest-util@^29.7.0: version "29.7.0" resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-29.7.0.tgz#23c2b62bfb22be82b44de98055802ff3710fc0bc" @@ -6641,7 +6551,7 @@ js-levenshtein@^1.1.3, js-levenshtein@^1.1.6: resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== -js-yaml@3.14.1, js-yaml@^3.13.1, js-yaml@^3.9.0: +js-yaml@3.14.1, js-yaml@^3.13.1: version "3.14.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.1.tgz#dae812fdb3825fa306609a8717383c50c36a0537" integrity sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g== @@ -6710,11 +6620,6 @@ json-merge-patch@^0.2.3: dependencies: deep-equal "^1.0.0" -json-parse-better-errors@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9" - integrity sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw== - json-parse-even-better-errors@^2.3.0, json-parse-even-better-errors@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" @@ -6742,18 +6647,6 @@ json-stable-stringify-without-jsonify@^1.0.1: resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" integrity sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw== -json2mq@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/json2mq/-/json2mq-0.2.0.tgz#b637bd3ba9eabe122c83e9720483aeb10d2c904a" - integrity sha1-tje9O6nqvhIsg+lyBIOusQ0skEo= - dependencies: - string-convert "^0.2.0" - -json5@^0.5.0: - version "0.5.1" - resolved "https://registry.yarnpkg.com/json5/-/json5-0.5.1.tgz#1eade7acc012034ad84e2396767ead9fa5495821" - integrity sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE= - json5@^1.0.1: version "1.0.2" resolved "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz#63d98d60f21b313b77c4d6da18bfa69d80e1d593" @@ -6821,16 +6714,6 @@ loader-runner@^4.2.0: resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-4.2.0.tgz#d7022380d66d14c5fb1d496b89864ebcfd478384" integrity sha512-92+huvxMvYlMzMt0iIOukcwYBFpkYJdpl2xsZ7LrlayO7E8SOv+JJUEK17B/dJIHAOLMfh2dZZ/Y18WgmGtYNw== -loader-utils@^0.2.16: - version "0.2.17" - resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-0.2.17.tgz#f86e6374d43205a6e6c60e9196f17c0299bfb348" - integrity sha1-+G5jdNQyBabmxg6RlvF8Apm/s0g= - dependencies: - big.js "^3.1.3" - emojis-list "^2.0.0" - json5 "^0.5.0" - object-assign "^4.0.1" - loader-utils@^1.0.2, loader-utils@^1.1.0: version "1.4.2" resolved "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.2.tgz#29a957f3a63973883eb684f10ffd3d151fec01a3" @@ -6876,11 +6759,6 @@ lodash-es@^4.17.21, lodash-es@^4.2.1: resolved "https://registry.yarnpkg.com/lodash-es/-/lodash-es-4.17.21.tgz#43e626c46e6591b7750beb2b50117390c609e3ee" integrity sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw== -lodash.camelcase@^4.3.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz#b28aa6288a2b9fc651035c7711f65ab6190331a6" - integrity sha1-soqmKIorn8ZRA1x3EfZathkDMaY= - lodash.isequal@^4.5.0: version "4.5.0" resolved "https://registry.yarnpkg.com/lodash.isequal/-/lodash.isequal-4.5.0.tgz#415c4478f2bcc30120c22ce10ed3226f7d3e18e0" @@ -6971,6 +6849,11 @@ marked@^4.0.10: resolved "https://registry.yarnpkg.com/marked/-/marked-4.0.12.tgz#2262a4e6fd1afd2f13557726238b69a48b982f7d" integrity sha512-hgibXWrEDNBWgGiK18j/4lkS6ihTe9sxtV4Q1OQppb/0zzyPSzoFANBa5MfsG/zgsWklmNnhm0XACZOH/0HBiQ== +math-intrinsics@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz#a0dd74be81e2aa5c2f27e65ce283605ee4e2b7f9" + integrity sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g== + media-typer@0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" @@ -7055,7 +6938,7 @@ minimalistic-assert@^1.0.0: resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7" integrity sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A== -minimatch@^3.0.4, minimatch@^3.0.5, minimatch@^3.1.2: +minimatch@^3.0.4, minimatch@^3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw== @@ -7204,11 +7087,6 @@ neo-async@^2.6.2: resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== -nice-try@^1.0.4: - version "1.0.5" - resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366" - integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ== - no-case@^3.0.4: version "3.0.4" resolved "https://registry.yarnpkg.com/no-case/-/no-case-3.0.4.tgz#d361fd5c9800f558551a8369fc0dcd4662b6124d" @@ -7343,6 +7221,11 @@ object-inspect@^1.13.1: resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.13.1.tgz#b96c6109324ccfef6b12216a956ca4dc2ff94bc2" integrity sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ== +object-inspect@^1.13.3: + version "1.13.3" + resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.13.3.tgz#f14c183de51130243d6d18ae149375ff50ea488a" + integrity sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA== + object-inspect@^1.9.0: version "1.12.2" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.2.tgz#c0641f26394532f28ab8d796ab954e43c009a8ea" @@ -7381,7 +7264,7 @@ object.assign@^4.1.4, object.assign@^4.1.5: has-symbols "^1.0.3" object-keys "^1.1.1" -object.entries@^1.1.7: +object.entries@^1.1.8: version "1.1.8" resolved "https://registry.yarnpkg.com/object.entries/-/object.entries-1.1.8.tgz#bffe6f282e01f4d17807204a24f8edd823599c41" integrity sha512-cmopxi8VwRIAw/fkijJohSfpef5PdN0pMQJN6VC/ZKvn0LIknWD8KtgY6KlQdEc4tIjcQ3HxSMmnvtzIscdaYQ== @@ -7390,7 +7273,7 @@ object.entries@^1.1.7: define-properties "^1.2.1" es-object-atoms "^1.0.0" -object.fromentries@^2.0.7: +object.fromentries@^2.0.8: version "2.0.8" resolved "https://registry.yarnpkg.com/object.fromentries/-/object.fromentries-2.0.8.tgz#f7195d8a9b97bd95cbc1999ea939ecd1a2b00c65" integrity sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ== @@ -7400,16 +7283,7 @@ object.fromentries@^2.0.7: es-abstract "^1.23.2" es-object-atoms "^1.0.0" -object.hasown@^1.1.3: - version "1.1.4" - resolved "https://registry.yarnpkg.com/object.hasown/-/object.hasown-1.1.4.tgz#e270ae377e4c120cdcb7656ce66884a6218283dc" - integrity sha512-FZ9LZt9/RHzGySlBARE3VF+gE26TxR38SdmqOqliuTnl9wrKulaQs+4dee1V+Io8VfxqzAfHu6YuRgUy8OHoTg== - dependencies: - define-properties "^1.2.1" - es-abstract "^1.23.2" - es-object-atoms "^1.0.0" - -object.values@^1.1.6, object.values@^1.1.7: +object.values@^1.1.6: version "1.2.0" resolved "https://registry.yarnpkg.com/object.values/-/object.values-1.2.0.tgz#65405a9d92cee68ac2d303002e0b8470a4d9ab1b" integrity sha512-yBYjY9QX2hnRmZHAjG/f13MzmBzxzYgQhFrke06TTyKY5zSTEqkOeukBzIdVA3j3ulu8Qa3MbVFShV7T2RmGtQ== @@ -7418,6 +7292,16 @@ object.values@^1.1.6, object.values@^1.1.7: define-properties "^1.2.1" es-object-atoms "^1.0.0" +object.values@^1.2.0: + version "1.2.1" + resolved "https://registry.yarnpkg.com/object.values/-/object.values-1.2.1.tgz#deed520a50809ff7f75a7cfd4bc64c7a038c6216" + integrity sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA== + dependencies: + call-bind "^1.0.8" + call-bound "^1.0.3" + define-properties "^1.2.1" + es-object-atoms "^1.0.0" + obuf@^1.0.0, obuf@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/obuf/-/obuf-1.1.2.tgz#09bea3343d41859ebd446292d11c9d4db619084e" @@ -7548,14 +7432,6 @@ parent-module@^1.0.0: dependencies: callsites "^3.0.0" -parse-json@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-4.0.0.tgz#be35f5425be1f7f6c747184f98a788cb99477ee0" - integrity sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA= - dependencies: - error-ex "^1.3.1" - json-parse-better-errors "^1.0.1" - parse-json@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.2.0.tgz#c76fc66dee54231c962b22bcc8a72cf2f99753cd" @@ -7620,11 +7496,6 @@ path-is-absolute@^1.0.0: resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= -path-key@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40" - integrity sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A= - path-key@^3.0.0, path-key@^3.1.0: version "3.1.1" resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" @@ -7740,83 +7611,6 @@ possible-typed-array-names@^1.0.0: resolved "https://registry.yarnpkg.com/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz#89bb63c6fada2c3e90adc4a647beeeb39cc7bf8f" integrity sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q== -postcss-load-config@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/postcss-load-config/-/postcss-load-config-2.0.0.tgz#f1312ddbf5912cd747177083c5ef7a19d62ee484" - integrity sha512-V5JBLzw406BB8UIfsAWSK2KSwIJ5yoEIVFb4gVkXci0QdKgA24jLmHZ/ghe/GgX0lJ0/D1uUK1ejhzEY94MChQ== - dependencies: - cosmiconfig "^4.0.0" - import-cwd "^2.0.0" - -postcss-modules-extract-imports@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/postcss-modules-extract-imports/-/postcss-modules-extract-imports-1.1.0.tgz#b614c9720be6816eaee35fb3a5faa1dba6a05ddb" - integrity sha1-thTJcgvmgW6u41+zpfqh26agXds= - dependencies: - postcss "^6.0.1" - -postcss-modules-local-by-default@1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/postcss-modules-local-by-default/-/postcss-modules-local-by-default-1.2.0.tgz#f7d80c398c5a393fa7964466bd19500a7d61c069" - integrity sha1-99gMOYxaOT+nlkRmvRlQCn1hwGk= - dependencies: - css-selector-tokenizer "^0.7.0" - postcss "^6.0.1" - -postcss-modules-scope@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/postcss-modules-scope/-/postcss-modules-scope-1.1.0.tgz#d6ea64994c79f97b62a72b426fbe6056a194bb90" - integrity sha1-1upkmUx5+XtipytCb75gVqGUu5A= - dependencies: - css-selector-tokenizer "^0.7.0" - postcss "^6.0.1" - -postcss-modules-values@1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/postcss-modules-values/-/postcss-modules-values-1.3.0.tgz#ecffa9d7e192518389f42ad0e83f72aec456ea20" - integrity sha1-7P+p1+GSUYOJ9CrQ6D9yrsRW6iA= - dependencies: - icss-replace-symbols "^1.1.0" - postcss "^6.0.1" - -postcss-modules@1.3.2: - version "1.3.2" - resolved "https://registry.yarnpkg.com/postcss-modules/-/postcss-modules-1.3.2.tgz#0a616b84387f1f60dd28a01f597687e85b7b8481" - integrity sha512-QujH5ZpPtr1fBWTKDa43Hx45gm7p19aEtHaAtkMCBZZiB/D5za2wXSMtAf94tDUZHF3F5KZcTXISUNqgEQRiDw== - dependencies: - css-modules-loader-core "^1.1.0" - generic-names "^1.0.3" - lodash.camelcase "^4.3.0" - postcss "^7.0.1" - string-hash "^1.1.1" - -postcss@6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/postcss/-/postcss-6.0.1.tgz#000dbd1f8eef217aa368b9a212c5fc40b2a8f3f2" - integrity sha1-AA29H47vIXqjaLmiEsX8QLKo8/I= - dependencies: - chalk "^1.1.3" - source-map "^0.5.6" - supports-color "^3.2.3" - -postcss@^6.0.1: - version "6.0.23" - resolved "https://registry.yarnpkg.com/postcss/-/postcss-6.0.23.tgz#61c82cc328ac60e677645f979054eb98bc0e3324" - integrity sha512-soOk1h6J3VMTZtVeVpv15/Hpdl2cBLX3CAw4TAbkpTJiNPk9YP/zWcD1ND+xEtvyuuvKzbxliTOIyvkSeSJ6ag== - dependencies: - chalk "^2.4.1" - source-map "^0.6.1" - supports-color "^5.4.0" - -postcss@^7.0.1: - version "7.0.36" - resolved "https://registry.yarnpkg.com/postcss/-/postcss-7.0.36.tgz#056f8cffa939662a8f5905950c07d5285644dfcb" - integrity sha512-BebJSIUMwJHRH0HAQoxN4u1CN86glsrwsW0q7T+/m44eXOUAxSNdHRkNZPYz5vVUbg17hFgOQDE7fZk7li3pZw== - dependencies: - chalk "^2.4.2" - source-map "^0.6.1" - supports-color "^6.1.0" - postcss@^8.4.38: version "8.4.38" resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.4.38.tgz#b387d533baf2054288e337066d81c6bee9db9e0e" @@ -7950,11 +7744,6 @@ pure-rand@^6.0.0: resolved "https://registry.yarnpkg.com/pure-rand/-/pure-rand-6.1.0.tgz#d173cf23258231976ccbdb05247c9787957604f2" integrity sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA== -qrcode.react@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/qrcode.react/-/qrcode.react-3.1.0.tgz#5c91ddc0340f768316fbdb8fff2765134c2aecd8" - integrity sha512-oyF+Urr3oAMUG/OiOuONL3HXM+53wvuH3mtIWQrYmsXoAq0DkvZp2RYUWFSMFtbdOpuS++9v+WAkzNVkMlNW6Q== - qs@6.11.0, qs@^6.11.0: version "6.11.0" resolved "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz#fd0d963446f7a65e1367e01abd85429453f0c37a" @@ -8011,440 +7800,6 @@ raw-loader@^0.5.1: resolved "https://registry.yarnpkg.com/raw-loader/-/raw-loader-0.5.1.tgz#0c3d0beaed8a01c966d9787bf778281252a979aa" integrity sha1-DD0L6u2KAclm2Xh793goElKpeao= -rc-align@^4.0.0: - version "4.0.11" - resolved "https://registry.yarnpkg.com/rc-align/-/rc-align-4.0.11.tgz#8198c62db266bc1b8ef05e56c13275bf72628a5e" - integrity sha512-n9mQfIYQbbNTbefyQnRHZPWuTEwG1rY4a9yKlIWHSTbgwI+XUMGRYd0uJ5pE2UbrNX0WvnMBA1zJ3Lrecpra/A== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "2.x" - dom-align "^1.7.0" - lodash "^4.17.21" - rc-util "^5.3.0" - resize-observer-polyfill "^1.5.1" - -rc-cascader@~3.12.0: - version "3.12.0" - resolved "https://registry.yarnpkg.com/rc-cascader/-/rc-cascader-3.12.0.tgz#709fdbede6c36f7e62d0daea76ba76b825cc7182" - integrity sha512-QTeGPTNYX33alozNy9lYg7YKpvYVwquai/mrFRR8mHlHnK7QlqJyMqbs2p7rc5eeKARKMRTUeoN5CfO+Gr9UBw== - dependencies: - "@babel/runtime" "^7.12.5" - array-tree-filter "^2.1.0" - classnames "^2.3.1" - rc-select "~14.5.0" - rc-tree "~5.7.0" - rc-util "^5.6.1" - -rc-checkbox@~3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/rc-checkbox/-/rc-checkbox-3.1.0.tgz#6be0d9d8de2cc96fb5e37f9036a1c3e360d0a42d" - integrity sha512-PAwpJFnBa3Ei+5pyqMMXdcKYKNBMS+TvSDiLdDnARnMJHC8ESxwPfm4Ao1gJiKtWLdmGfigascnCpwrHFgoOBQ== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "^2.3.2" - rc-util "^5.25.2" - -rc-collapse@~3.7.0: - version "3.7.0" - resolved "https://registry.yarnpkg.com/rc-collapse/-/rc-collapse-3.7.0.tgz#75116b7142371940ff9fdce61a9e48561b53bbfc" - integrity sha512-Cir1c89cENiK5wryd9ut+XltrIfx/+KH1/63uJIVjuXkgfrIvIy6W1fYGgEYtttbHW2fEfxg1s31W+Vm98fSRw== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "2.x" - rc-motion "^2.3.4" - rc-util "^5.27.0" - -rc-dialog@~9.1.0: - version "9.1.0" - resolved "https://registry.yarnpkg.com/rc-dialog/-/rc-dialog-9.1.0.tgz#6bf6fcc0453503b7643e54a5a445e835e3850649" - integrity sha512-5ry+JABAWEbaKyYsmITtrJbZbJys8CtMyzV8Xn4LYuXMeUx5XVHNyJRoqLFE4AzBuXXzOWeaC49cg+XkxK6kHA== - dependencies: - "@babel/runtime" "^7.10.1" - "@rc-component/portal" "^1.0.0-8" - classnames "^2.2.6" - rc-motion "^2.3.0" - rc-util "^5.21.0" - -rc-drawer@~6.2.0: - version "6.2.0" - resolved "https://registry.yarnpkg.com/rc-drawer/-/rc-drawer-6.2.0.tgz#fddf4825b0fa9d60e317b996f70278d594d1f668" - integrity sha512-spPkZ3WvP0U0vy5dyzSwlUJ/+vLFtjP/cTwSwejhQRoDBaexSZHsBhELoCZcEggI7LQ7typmtG30lAue2HEhvA== - dependencies: - "@babel/runtime" "^7.10.1" - "@rc-component/portal" "^1.1.1" - classnames "^2.2.6" - rc-motion "^2.6.1" - rc-util "^5.21.2" - -rc-dropdown@~4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/rc-dropdown/-/rc-dropdown-4.1.0.tgz#418a68939631520de80d0865d02b440eeeb4168e" - integrity sha512-VZjMunpBdlVzYpEdJSaV7WM7O0jf8uyDjirxXLZRNZ+tAC+NzD3PXPEtliFwGzVwBBdCmGuSqiS9DWcOLxQ9tw== - dependencies: - "@babel/runtime" "^7.18.3" - "@rc-component/trigger" "^1.7.0" - classnames "^2.2.6" - rc-util "^5.17.0" - -rc-field-form@~1.32.0: - version "1.32.2" - resolved "https://registry.yarnpkg.com/rc-field-form/-/rc-field-form-1.32.2.tgz#9d0cb20af265d5ed31e3bb9384096736c4a2fbc3" - integrity sha512-SzqG1YGyD2P42ztZJ7qoPQp6FV9bD51RUdKGG/5xwybU1wbFdgWTqiMXkS8UR9L4GwXVMKh5PaF2I4EBXd/Rng== - dependencies: - "@babel/runtime" "^7.18.0" - async-validator "^4.1.0" - rc-util "^5.32.2" - -rc-image@~5.17.1: - version "5.17.1" - resolved "https://registry.yarnpkg.com/rc-image/-/rc-image-5.17.1.tgz#71835b12c30fcef533de0dbbbaf13caa86454612" - integrity sha512-oR4eviLyQxd/5A7pn843w2/Z1wuBA27L2lS4agq0sjl2z97ssNIVEzRzgwgB0ZxVZG/qSu9Glit2Zgzb/n+blQ== - dependencies: - "@babel/runtime" "^7.11.2" - "@rc-component/portal" "^1.0.2" - classnames "^2.2.6" - rc-dialog "~9.1.0" - rc-motion "^2.6.2" - rc-util "^5.0.6" - -rc-input-number@~7.4.0: - version "7.4.2" - resolved "https://registry.yarnpkg.com/rc-input-number/-/rc-input-number-7.4.2.tgz#7c52d26b986461aa16e486d469dc0476d97c6ea3" - integrity sha512-yGturTw7WGP+M1GbJ+UTAO7L4buxeW6oilhL9Sq3DezsRS8/9qec4UiXUbeoiX9bzvRXH11JvgskBtxSp4YSNg== - dependencies: - "@babel/runtime" "^7.10.1" - "@rc-component/mini-decimal" "^1.0.1" - classnames "^2.2.5" - rc-util "^5.28.0" - -rc-input@~1.0.0, rc-input@~1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/rc-input/-/rc-input-1.0.4.tgz#2f2c73c884f41e80685bb2eb7b9d5533e8540a77" - integrity sha512-clY4oneVHRtKHYf/HCxT/MO+4BGzCIywSNLosXWOm7fcQAS0jQW7n0an8Raa8JMB8kpxc8m28p7SNwFZmlMj6g== - dependencies: - "@babel/runtime" "^7.11.1" - classnames "^2.2.1" - rc-util "^5.18.1" - -rc-mentions@~2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/rc-mentions/-/rc-mentions-2.3.0.tgz#bb457c9664093be82baf33628b145f7c2bd49577" - integrity sha512-gNpsSKsBHSXvyAA1ZowVTqXSWUIw7+OI9wmjL87KcYURvtm9nDo8R0KtOc2f1PT7q9McUpFzhm6AvQdIly0aRA== - dependencies: - "@babel/runtime" "^7.10.1" - "@rc-component/trigger" "^1.5.0" - classnames "^2.2.6" - rc-input "~1.0.0" - rc-menu "~9.9.0" - rc-textarea "~1.2.0" - rc-util "^5.22.5" - -rc-menu@~9.9.0, rc-menu@~9.9.2: - version "9.9.2" - resolved "https://registry.yarnpkg.com/rc-menu/-/rc-menu-9.9.2.tgz#733aa5b794bd801577726e448b6cfeda0436e1e5" - integrity sha512-kVJwaQn5VUu6DIddxd/jz3QupTPg0tNYq+mpFP8wYsRF5JgzPA9fPVw+CfwlTPwA1w7gzEY42S8pj6M3uev5CQ== - dependencies: - "@babel/runtime" "^7.10.1" - "@rc-component/trigger" "^1.6.2" - classnames "2.x" - rc-motion "^2.4.3" - rc-overflow "^1.2.8" - rc-util "^5.27.0" - -rc-motion@^2.0.0, rc-motion@^2.0.1, rc-motion@^2.3.0, rc-motion@^2.3.4, rc-motion@^2.4.3, rc-motion@^2.4.4: - version "2.4.4" - resolved "https://registry.yarnpkg.com/rc-motion/-/rc-motion-2.4.4.tgz#e995d5fa24fc93065c24f714857cf2677d655bb0" - integrity sha512-ms7n1+/TZQBS0Ydd2Q5P4+wJTSOrhIrwNxLXCZpR7Fa3/oac7Yi803HDALc2hLAKaCTQtw9LmQeB58zcwOsqlQ== - dependencies: - "@babel/runtime" "^7.11.1" - classnames "^2.2.1" - rc-util "^5.2.1" - -rc-motion@^2.6.0, rc-motion@^2.7.3: - version "2.7.3" - resolved "https://registry.yarnpkg.com/rc-motion/-/rc-motion-2.7.3.tgz#126155bb3e687174fb3b92fddade2835c963b04d" - integrity sha512-2xUvo8yGHdOHeQbdI8BtBsCIrWKchEmFEIskf0nmHtJsou+meLd/JE+vnvSX2JxcBrJtXY2LuBpxAOxrbY/wMQ== - dependencies: - "@babel/runtime" "^7.11.1" - classnames "^2.2.1" - rc-util "^5.21.0" - -rc-motion@^2.6.1, rc-motion@^2.6.2: - version "2.6.2" - resolved "https://registry.yarnpkg.com/rc-motion/-/rc-motion-2.6.2.tgz#3d31f97e41fb8e4f91a4a4189b6a98ac63342869" - integrity sha512-4w1FaX3dtV749P8GwfS4fYnFG4Rb9pxvCYPc/b2fw1cmlHJWNNgOFIz7ysiD+eOrzJSvnLJWlNQQncpNMXwwpg== - dependencies: - "@babel/runtime" "^7.11.1" - classnames "^2.2.1" - rc-util "^5.21.0" - -rc-notification@~5.0.4: - version "5.0.4" - resolved "https://registry.yarnpkg.com/rc-notification/-/rc-notification-5.0.4.tgz#4ad33d4aa291528fee9095b0be80ae41f1728a38" - integrity sha512-3535oellIRlt1LspERfK8yvCqb8Gio3R02rULciaSc1xe3H7ArTU/khlUTv1ddGzua4HhmF4D4Rwz/+mBxETvg== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "2.x" - rc-motion "^2.6.0" - rc-util "^5.20.1" - -rc-overflow@^1.0.0: - version "1.2.2" - resolved "https://registry.yarnpkg.com/rc-overflow/-/rc-overflow-1.2.2.tgz#95b0222016c0cdbdc0db85f569c262e7706a5f22" - integrity sha512-X5kj9LDU1ue5wHkqvCprJWLKC+ZLs3p4He/oxjZ1Q4NKaqKBaYf5OdSzRSgh3WH8kSdrfU8LjvlbWnHgJOEkNQ== - dependencies: - "@babel/runtime" "^7.11.1" - classnames "^2.2.1" - rc-resize-observer "^1.0.0" - rc-util "^5.5.1" - -rc-overflow@^1.2.8: - version "1.3.1" - resolved "https://registry.yarnpkg.com/rc-overflow/-/rc-overflow-1.3.1.tgz#03224cf90c66aa570eb0deeb4eff6cc96401e979" - integrity sha512-RY0nVBlfP9CkxrpgaLlGzkSoh9JhjJLu6Icqs9E7CW6Ewh9s0peF9OHIex4OhfoPsR92LR0fN6BlCY9Z4VoUtA== - dependencies: - "@babel/runtime" "^7.11.1" - classnames "^2.2.1" - rc-resize-observer "^1.0.0" - rc-util "^5.19.2" - -rc-pagination@~3.5.0: - version "3.5.0" - resolved "https://registry.yarnpkg.com/rc-pagination/-/rc-pagination-3.5.0.tgz#8692a62f3c24d8bfe58f1b3059bc5262ddce5d87" - integrity sha512-lUBVtVVUn7gGsq4mTyVpcZQr+AMcljbMiL/HcCmSdFrcsK0iZVKwwbXDxhz2IV0JXUs9Hzepr5sQFaF+9ad/pQ== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "^2.2.1" - rc-util "^5.32.2" - -rc-picker@~3.8.2: - version "3.8.2" - resolved "https://registry.yarnpkg.com/rc-picker/-/rc-picker-3.8.2.tgz#1dc377a628cd94416e03974483daa36940a411b0" - integrity sha512-q6jnMwBoOi6tFA4xohrKIhzq80Fc3dH0Kiw5VRx6Tf1db7y27PBFCLwu6f66niXidZKD8F4R0M9VIui/jkL4cg== - dependencies: - "@babel/runtime" "^7.10.1" - "@rc-component/trigger" "^1.5.0" - classnames "^2.2.1" - rc-util "^5.30.0" - -rc-progress@~3.4.1: - version "3.4.2" - resolved "https://registry.yarnpkg.com/rc-progress/-/rc-progress-3.4.2.tgz#f8df9ee95e790490171ab6b31bf07303cdc79980" - integrity sha512-iAGhwWU+tsayP+Jkl9T4+6rHeQTG9kDz8JAHZk4XtQOcYN5fj9H34NXNEdRdZx94VUDHMqCb1yOIvi8eJRh67w== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "^2.2.6" - rc-util "^5.16.1" - -rc-rate@~2.12.0: - version "2.12.0" - resolved "https://registry.yarnpkg.com/rc-rate/-/rc-rate-2.12.0.tgz#0182deffed3b009cdcc61660da8746c39ed91ed5" - integrity sha512-g092v5iZCdVzbjdn28FzvWebK2IutoVoiTeqoLTj9WM7SjA/gOJIw5/JFZMRyJYYVe1jLAU2UhAfstIpCNRozg== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "^2.2.5" - rc-util "^5.0.1" - -rc-resize-observer@^1.0.0, rc-resize-observer@^1.1.0: - version "1.1.2" - resolved "https://registry.yarnpkg.com/rc-resize-observer/-/rc-resize-observer-1.1.2.tgz#214bc5d0de19e0a5fcd7d8352d9c1560dd7531b7" - integrity sha512-Qp+1x6D88FxyWBFRYP95IV9A1o0xlkC6qhiTX3YakE+o86QH9IzC7UVnltwmm4Q8uYH+E3F/HRmEiuxXJECdSw== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "^2.2.1" - rc-util "^5.15.0" - resize-observer-polyfill "^1.5.1" - -rc-resize-observer@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/rc-resize-observer/-/rc-resize-observer-1.2.0.tgz#9f46052f81cdf03498be35144cb7c53fd282c4c7" - integrity sha512-6W+UzT3PyDM0wVCEHfoW3qTHPTvbdSgiA43buiy8PzmeMnfgnDeb9NjdimMXMl3/TcrvvWl5RRVdp+NqcR47pQ== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "^2.2.1" - rc-util "^5.15.0" - resize-observer-polyfill "^1.5.1" - -rc-resize-observer@^1.3.1: - version "1.3.1" - resolved "https://registry.yarnpkg.com/rc-resize-observer/-/rc-resize-observer-1.3.1.tgz#b61b9f27048001243617b81f95e53d7d7d7a6a3d" - integrity sha512-iFUdt3NNhflbY3mwySv5CA1TC06zdJ+pfo0oc27xpf4PIOvfZwZGtD9Kz41wGYqC4SLio93RVAirSSpYlV/uYg== - dependencies: - "@babel/runtime" "^7.20.7" - classnames "^2.2.1" - rc-util "^5.27.0" - resize-observer-polyfill "^1.5.1" - -rc-segmented@~2.2.0: - version "2.2.2" - resolved "https://registry.yarnpkg.com/rc-segmented/-/rc-segmented-2.2.2.tgz#a34f12ce6c0975fc3042ae7656bcd18e1744798e" - integrity sha512-Mq52M96QdHMsNdE/042ibT5vkcGcD5jxKp7HgPC2SRofpia99P5fkfHy1pEaajLMF/kj0+2Lkq1UZRvqzo9mSA== - dependencies: - "@babel/runtime" "^7.11.1" - classnames "^2.2.1" - rc-motion "^2.4.4" - rc-util "^5.17.0" - -rc-select@~14.5.0: - version "14.5.2" - resolved "https://registry.yarnpkg.com/rc-select/-/rc-select-14.5.2.tgz#1ac1ab58c874696cfa01cb15e1fc9a7bba81b29e" - integrity sha512-Np/lDHvxCnVhVsheQjSV1I/OMJTWJf1n10wq8q1AGy3ytyYLfjNpi6uaz/pmjsbbiSddSWzJnNZCli9LmgBZsA== - dependencies: - "@babel/runtime" "^7.10.1" - "@rc-component/trigger" "^1.5.0" - classnames "2.x" - rc-motion "^2.0.1" - rc-overflow "^1.0.0" - rc-util "^5.16.1" - rc-virtual-list "^3.5.2" - -rc-slider@~10.1.0: - version "10.1.1" - resolved "https://registry.yarnpkg.com/rc-slider/-/rc-slider-10.1.1.tgz#5e82036e60b61021aba3ea0e353744dd7c74e104" - integrity sha512-gn8oXazZISEhnmRinI89Z/JD/joAaM35jp+gDtIVSTD/JJMCCBqThqLk1SVJmvtfeiEF/kKaFY0+qt4SDHFUDw== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "^2.2.5" - rc-util "^5.27.0" - -rc-steps@~6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/rc-steps/-/rc-steps-6.0.0.tgz#f7148f8097d5d135f19b96c1b4f4b50ad6093753" - integrity sha512-+KfMZIty40mYCQSDvYbZ1jwnuObLauTiIskT1hL4FFOBHP6ZOr8LK0m143yD3kEN5XKHSEX1DIwCj3AYZpoeNQ== - dependencies: - "@babel/runtime" "^7.16.7" - classnames "^2.2.3" - rc-util "^5.16.1" - -rc-switch@~4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/rc-switch/-/rc-switch-4.1.0.tgz#f37d81b4e0c5afd1274fd85367b17306bf25e7d7" - integrity sha512-TI8ufP2Az9oEbvyCeVE4+90PDSljGyuwix3fV58p7HV2o4wBnVToEyomJRVyTaZeqNPAp+vqeo4Wnj5u0ZZQBg== - dependencies: - "@babel/runtime" "^7.21.0" - classnames "^2.2.1" - rc-util "^5.30.0" - -rc-table@~7.32.1: - version "7.32.1" - resolved "https://registry.yarnpkg.com/rc-table/-/rc-table-7.32.1.tgz#7130a94727ac3870a6ddb9778b6f8496e388bce0" - integrity sha512-fHMQteKMocUC9I9Vex3eBLH7QsiaMR/qtzh3B1Ty2PoNGwVTwVdDFyRL05zch+JU3KnNNczgQeVvtf/p//gdrQ== - dependencies: - "@babel/runtime" "^7.10.1" - "@rc-component/context" "^1.3.0" - classnames "^2.2.5" - rc-resize-observer "^1.1.0" - rc-util "^5.27.1" - -rc-tabs@~12.7.0: - version "12.7.1" - resolved "https://registry.yarnpkg.com/rc-tabs/-/rc-tabs-12.7.1.tgz#6bfd11cc7b2bec08600eb0aba41966b230c38906" - integrity sha512-NrltXEYIyiDP5JFu85NQwc9eR+7e50r/6MNXYDyG1EMIFNc7BgDppzdpnD3nW4NHYWw5wLIThCURGib48OCTBg== - dependencies: - "@babel/runtime" "^7.11.2" - classnames "2.x" - rc-dropdown "~4.1.0" - rc-menu "~9.9.0" - rc-motion "^2.6.2" - rc-resize-observer "^1.0.0" - rc-util "^5.16.0" - -rc-textarea@~1.2.0, rc-textarea@~1.2.2: - version "1.2.3" - resolved "https://registry.yarnpkg.com/rc-textarea/-/rc-textarea-1.2.3.tgz#bdaea2931ad2571583e9e27e627b8a9b5dbe7de7" - integrity sha512-YvN8IskIVBRRzcS4deT0VAMim31+T3IoVX4yoCJ+b/iVCvw7yf0usR7x8OaHiUOUoURKcn/3lfGjmtzplcy99g== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "^2.2.1" - rc-input "~1.0.4" - rc-resize-observer "^1.0.0" - rc-util "^5.27.0" - -rc-tooltip@~6.0.0: - version "6.0.1" - resolved "https://registry.yarnpkg.com/rc-tooltip/-/rc-tooltip-6.0.1.tgz#6a5e33bd6c3f6afe8851ea90e7af43e5c26b3cc6" - integrity sha512-MdvPlsD1fDSxKp9+HjXrc/CxLmA/s11QYIh1R7aExxfodKP7CZA++DG1AjrW80F8IUdHYcR43HAm0Y2BYPelHA== - dependencies: - "@babel/runtime" "^7.11.2" - "@rc-component/trigger" "^1.0.4" - classnames "^2.3.1" - -rc-tree-select@~5.9.0: - version "5.9.0" - resolved "https://registry.yarnpkg.com/rc-tree-select/-/rc-tree-select-5.9.0.tgz#e8af859ff7751d22b6f4d98941cf13f775686475" - integrity sha512-oh3blESzLfLCBPSiVDtZ2irzrWWZUMeHvnSwRvFo79br8Z+K/1OhXhXBZmROvfKwaH8YUugAQy8B2j5EGQbdyA== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "2.x" - rc-select "~14.5.0" - rc-tree "~5.7.0" - rc-util "^5.16.1" - -rc-tree@~5.7.0, rc-tree@~5.7.4: - version "5.7.6" - resolved "https://registry.yarnpkg.com/rc-tree/-/rc-tree-5.7.6.tgz#0d0bea9351517a18f5065cf3106cfc06bb740bd1" - integrity sha512-Dzam4VFcohXfcw+K4syq177RKqdqYun1XRc6etAEpRvsTruo4udhcsPrsEfOrRkrhnmkO58Q9F1/lgvm2dznVQ== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "2.x" - rc-motion "^2.0.1" - rc-util "^5.16.1" - rc-virtual-list "^3.5.1" - -rc-upload@~4.3.0: - version "4.3.3" - resolved "https://registry.yarnpkg.com/rc-upload/-/rc-upload-4.3.3.tgz#e237aa525e5313fa16f4d04d27f53c2f0e157bb8" - integrity sha512-YoJ0phCRenMj1nzwalXzciKZ9/FAaCrFu84dS5pphwucTC8GUWClcDID/WWNGsLFcM97NqIboDqrV82rVRhW/w== - dependencies: - "@babel/runtime" "^7.10.1" - classnames "^2.2.5" - rc-util "^5.2.0" - -rc-util@^5.0.1, rc-util@^5.0.6, rc-util@^5.15.0, rc-util@^5.16.1, rc-util@^5.2.0, rc-util@^5.2.1, rc-util@^5.3.0, rc-util@^5.5.1, rc-util@^5.6.1: - version "5.16.1" - resolved "https://registry.yarnpkg.com/rc-util/-/rc-util-5.16.1.tgz#374db7cb735512f05165ddc3d6b2c61c21b8b4e3" - integrity sha512-kSCyytvdb3aRxQacS/71ta6c+kBWvM1v8/2h9d/HaNWauc3qB8pLnF20PJ8NajkNN8gb+rR1l0eWO+D4Pz+LLQ== - dependencies: - "@babel/runtime" "^7.12.5" - react-is "^16.12.0" - shallowequal "^1.1.0" - -rc-util@^5.16.0, rc-util@^5.24.4, rc-util@^5.25.2, rc-util@^5.27.0, rc-util@^5.27.1, rc-util@^5.28.0, rc-util@^5.30.0, rc-util@^5.31.1, rc-util@^5.32.0, rc-util@^5.32.2, rc-util@^5.33.0: - version "5.34.0" - resolved "https://registry.yarnpkg.com/rc-util/-/rc-util-5.34.0.tgz#3bec84f98c1dbf5305d89cda124aa8a0c9615f97" - integrity sha512-+zCDJ1gq+KwqbaZPAk7PGlNAssoTcnZSnTsr5KMYDBhzdPNFxyuglnewWMP5PyP/kAC6uW4r9Ejc08M+Lei04A== - dependencies: - "@babel/runtime" "^7.18.3" - react-is "^16.12.0" - -rc-util@^5.17.0, rc-util@^5.18.1: - version "5.20.1" - resolved "https://registry.yarnpkg.com/rc-util/-/rc-util-5.20.1.tgz#323590df56175f60b1a67d2ba76f04c3c2cb84cd" - integrity sha512-2IEyErPAYl0Up5gBu71e8IkOs+/SL9XRUvnGhtsr7IHlXLx2OsbQKTDpWacJbzLCmNcgJylDGj1kiklx+zagRA== - dependencies: - "@babel/runtime" "^7.12.5" - react-is "^16.12.0" - shallowequal "^1.1.0" - -rc-util@^5.19.2, rc-util@^5.20.1, rc-util@^5.21.0, rc-util@^5.21.2, rc-util@^5.22.5: - version "5.24.2" - resolved "https://registry.yarnpkg.com/rc-util/-/rc-util-5.24.2.tgz#b90057dd880e1ba2bea63028ef1892101a48bc0c" - integrity sha512-MWd0ZEV7xSwN4HM9jz9BwpnMzwCPjYJ7K90lePsrdgAkrmm8U7b4BOTIsv/84BQsaF7N3ejNkcrZ3AfEwc9HXA== - dependencies: - "@babel/runtime" "^7.18.3" - react-is "^16.12.0" - shallowequal "^1.1.0" - -rc-virtual-list@^3.5.1, rc-virtual-list@^3.5.2: - version "3.5.2" - resolved "https://registry.yarnpkg.com/rc-virtual-list/-/rc-virtual-list-3.5.2.tgz#5e1028869bae900eacbae6788d4eca7210736006" - integrity sha512-sE2G9hTPjVmatQni8OP2Kx33+Oth6DMKm67OblBBmgMBJDJQOOFpSGH7KZ6Pm85rrI2IGxDRXZCr0QhYOH2pfQ== - dependencies: - "@babel/runtime" "^7.20.0" - classnames "^2.2.6" - rc-resize-observer "^1.0.0" - rc-util "^5.15.0" - react-autocomplete@1.8.1, react-autocomplete@^1.8.1: version "1.8.1" resolved "https://registry.yarnpkg.com/react-autocomplete/-/react-autocomplete-1.8.1.tgz#ebbbc400006aa91ad538b2d14727b9e7e5d06310" @@ -8523,7 +7878,7 @@ react-hot-loader@^3.1.3: redbox-react "^1.3.6" source-map "^0.6.1" -react-is@^16.12.0, react-is@^16.13.1: +react-is@^16.13.1: version "16.13.1" resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4" integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ== @@ -8628,10 +7983,10 @@ react-test-renderer@16.8.3: react-is "^16.8.3" scheduler "^0.13.3" -react-toastify@9.0.8: - version "9.0.8" - resolved "https://registry.yarnpkg.com/react-toastify/-/react-toastify-9.0.8.tgz#3876c89fc6211a29027b3075010b5ec39ebe4f7e" - integrity sha512-EwM+teWt49HSHx+67qI08yLAW1zAsBxCXLCsUfxHYv1W7/R3ZLhrqKalh7j+kjgPna1h5LQMSMwns4tB4ww2yQ== +react-toastify@9.0.3: + version "9.0.3" + resolved "https://registry.yarnpkg.com/react-toastify/-/react-toastify-9.0.3.tgz#8e6d22651c85cb584c5ebd0b5e2c3bf0d7ec06ee" + integrity sha512-0QZJk0SqYBxouRBGCFU3ymvjlwimRRhVH7SzqGRiVrQ001KSoUNbGKx9Yq42aoPv18n45yJzEFG82zqv3HnASg== dependencies: clsx "^1.1.1" @@ -8753,18 +8108,19 @@ redux@^3.7.2: loose-envify "^1.1.0" symbol-observable "^1.0.3" -reflect.getprototypeof@^1.0.4: - version "1.0.6" - resolved "https://registry.yarnpkg.com/reflect.getprototypeof/-/reflect.getprototypeof-1.0.6.tgz#3ab04c32a8390b770712b7a8633972702d278859" - integrity sha512-fmfw4XgoDke3kdI6h4xcUz1dG8uaiv5q9gcEwLS4Pnth2kxT+GZ7YehS1JTMGBQmtV7Y4GFGbs2re2NqhdozUg== +reflect.getprototypeof@^1.0.6, reflect.getprototypeof@^1.0.8, reflect.getprototypeof@^1.0.9: + version "1.0.9" + resolved "https://registry.yarnpkg.com/reflect.getprototypeof/-/reflect.getprototypeof-1.0.9.tgz#c905f3386008de95a62315f3ea8630404be19e2f" + integrity sha512-r0Ay04Snci87djAsI4U+WNRcSw5S4pOH7qFjd/veA5gC7TbqESR3tcj28ia95L/fYUDw11JKP7uqUKUAfVvV5Q== dependencies: - call-bind "^1.0.7" + call-bind "^1.0.8" define-properties "^1.2.1" - es-abstract "^1.23.1" + dunder-proto "^1.0.1" + es-abstract "^1.23.6" es-errors "^1.3.0" - get-intrinsic "^1.2.4" - globalthis "^1.0.3" - which-builtin-type "^1.1.3" + get-intrinsic "^1.2.6" + gopd "^1.2.0" + which-builtin-type "^1.2.1" reftools@^1.1.9: version "1.1.9" @@ -8823,6 +8179,16 @@ regexp.prototype.flags@^1.5.2: es-errors "^1.3.0" set-function-name "^2.0.1" +regexp.prototype.flags@^1.5.3: + version "1.5.3" + resolved "https://registry.yarnpkg.com/regexp.prototype.flags/-/regexp.prototype.flags-1.5.3.tgz#b3ae40b1d2499b8350ab2c3fe6ef3845d3a96f42" + integrity sha512-vqlC04+RQoFalODCbCumG2xIOvapzVMHwsyIGM/SIE8fRhFFsXeH8/QQ+s0T0kDAhKc4k30s73/0ydkHQz6HlQ== + dependencies: + call-bind "^1.0.7" + define-properties "^1.2.1" + es-errors "^1.3.0" + set-function-name "^2.0.2" + regexpu-core@^4.7.1: version "4.7.1" resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-4.7.1.tgz#2dea5a9a07233298fbf0db91fa9abc4c6e0f8ad6" @@ -8868,7 +8234,7 @@ require-directory@^2.1.1: resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= -require-from-string@^2.0.1, require-from-string@^2.0.2: +require-from-string@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-2.0.2.tgz#89a7fdd938261267318eafe14f9c32e598c36909" integrity sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw== @@ -8878,11 +8244,6 @@ requires-port@^1.0.0: resolved "https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff" integrity sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8= -resize-observer-polyfill@^1.5.1: - version "1.5.1" - resolved "https://registry.yarnpkg.com/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz#0e9020dd3d21024458d4ebd27e23e40269810464" - integrity sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg== - resolve-cwd@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-3.0.0.tgz#0f0075f1bb2544766cf73ba6a6e2adfebcb13f2d" @@ -8890,11 +8251,6 @@ resolve-cwd@^3.0.0: dependencies: resolve-from "^5.0.0" -resolve-from@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-3.0.0.tgz#b22c7af7d9d6881bc8b6e653335eebcb0a188748" - integrity sha1-six699nWiBvItuZTM17rywoYh0g= - resolve-from@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" @@ -8981,6 +8337,17 @@ safe-array-concat@^1.1.2: has-symbols "^1.0.3" isarray "^2.0.5" +safe-array-concat@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/safe-array-concat/-/safe-array-concat-1.1.3.tgz#c9e54ec4f603b0bbb8e7e5007a5ee7aecd1538c3" + integrity sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q== + dependencies: + call-bind "^1.0.8" + call-bound "^1.0.2" + get-intrinsic "^1.2.6" + has-symbols "^1.1.0" + isarray "^2.0.5" + safe-buffer@5.1.2, safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" @@ -9000,6 +8367,15 @@ safe-regex-test@^1.0.3: es-errors "^1.3.0" is-regex "^1.1.4" +safe-regex-test@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/safe-regex-test/-/safe-regex-test-1.1.0.tgz#7f87dfb67a3150782eaaf18583ff5d1711ac10c1" + integrity sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw== + dependencies: + call-bound "^1.0.2" + es-errors "^1.3.0" + is-regex "^1.2.1" + "safer-buffer@>= 2.1.2 < 3", "safer-buffer@>= 2.1.2 < 3.0.0": version "2.1.2" resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" @@ -9080,13 +8456,6 @@ schema-utils@^4.0.0: ajv-formats "^2.1.1" ajv-keywords "^5.0.0" -scroll-into-view-if-needed@^3.0.3: - version "3.0.10" - resolved "https://registry.yarnpkg.com/scroll-into-view-if-needed/-/scroll-into-view-if-needed-3.0.10.tgz#38fbfe770d490baff0fb2ba34ae3539f6ec44e13" - integrity sha512-t44QCeDKAPf1mtQH3fYpWz8IM/DyvHLjs8wUvvwMYxk5moOqCzrMSxK6HQVD0QVmVjXFavoFIPRVrMuJPKAvtg== - dependencies: - compute-scroll-into-view "^3.0.2" - select-hose@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/select-hose/-/select-hose-2.0.0.tgz#625d8658f865af43ec962bfc376a37359a4994ca" @@ -9208,7 +8577,7 @@ serve-static@1.16.0: parseurl "~1.3.3" send "0.18.0" -set-function-length@^1.2.1: +set-function-length@^1.2.1, set-function-length@^1.2.2: version "1.2.2" resolved "https://registry.yarnpkg.com/set-function-length/-/set-function-length-1.2.2.tgz#aac72314198eaed975cf77b2c3b6b880695e5449" integrity sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg== @@ -9252,18 +8621,6 @@ shallow-equal@^1.2.1: resolved "https://registry.yarnpkg.com/shallow-equal/-/shallow-equal-1.2.1.tgz#4c16abfa56043aa20d050324efa68940b0da79da" integrity sha512-S4vJDjHHMBaiZuT9NPb616CSmLf618jawtv3sufLl6ivK8WocjAo58cXwbRV1cgqxH0Qbv+iUt6m05eqEa2IRA== -shallowequal@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/shallowequal/-/shallowequal-1.1.0.tgz#188d521de95b9087404fd4dcb68b13df0ae4e7f8" - integrity sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ== - -shebang-command@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" - integrity sha1-RKrGW2lbAzmJaMOfNj/uXer98eo= - dependencies: - shebang-regex "^1.0.0" - shebang-command@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" @@ -9271,11 +8628,6 @@ shebang-command@^2.0.0: dependencies: shebang-regex "^3.0.0" -shebang-regex@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" - integrity sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM= - shebang-regex@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" @@ -9325,6 +8677,35 @@ should@^13.2.1: should-type-adaptors "^1.0.1" should-util "^1.0.0" +side-channel-list@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/side-channel-list/-/side-channel-list-1.0.0.tgz#10cb5984263115d3b7a0e336591e290a830af8ad" + integrity sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA== + dependencies: + es-errors "^1.3.0" + object-inspect "^1.13.3" + +side-channel-map@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/side-channel-map/-/side-channel-map-1.0.1.tgz#d6bb6b37902c6fef5174e5f533fab4c732a26f42" + integrity sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA== + dependencies: + call-bound "^1.0.2" + es-errors "^1.3.0" + get-intrinsic "^1.2.5" + object-inspect "^1.13.3" + +side-channel-weakmap@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz#11dda19d5368e40ce9ec2bdc1fb0ecbc0790ecea" + integrity sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A== + dependencies: + call-bound "^1.0.2" + es-errors "^1.3.0" + get-intrinsic "^1.2.5" + object-inspect "^1.13.3" + side-channel-map "^1.0.1" + side-channel@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.0.4.tgz#efce5c8fdc104ee751b25c58d4290011fa5ea2cf" @@ -9344,6 +8725,17 @@ side-channel@^1.0.6: get-intrinsic "^1.2.4" object-inspect "^1.13.1" +side-channel@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.1.0.tgz#c3fcff9c4da932784873335ec9765fa94ff66bc9" + integrity sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw== + dependencies: + es-errors "^1.3.0" + object-inspect "^1.13.3" + side-channel-list "^1.0.0" + side-channel-map "^1.0.1" + side-channel-weakmap "^1.0.2" + signal-exit@^3.0.3, signal-exit@^3.0.7: version "3.0.7" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9" @@ -9419,7 +8811,7 @@ source-map@0.5.6: resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.6.tgz#75ce38f52bf0733c5a7f0c118d81334a2bb5f412" integrity sha1-dc449SvwczxafwwRjYEzSiu19BI= -source-map@^0.5.0, source-map@^0.5.6: +source-map@^0.5.0: version "0.5.7" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w= @@ -9505,16 +8897,6 @@ stream-events@^1.0.5: dependencies: stubs "^3.0.0" -string-convert@^0.2.0: - version "0.2.1" - resolved "https://registry.yarnpkg.com/string-convert/-/string-convert-0.2.1.tgz#6982cc3049fbb4cd85f8b24568b9d9bf39eeff97" - integrity sha1-aYLMMEn7tM2F+LJFaLnZvznu/5c= - -string-hash@^1.1.1: - version "1.1.3" - resolved "https://registry.yarnpkg.com/string-hash/-/string-hash-1.1.3.tgz#e8aafc0ac1855b4666929ed7dd1275df5d6c811b" - integrity sha1-6Kr8CsGFW0Zmkp7X3RJ1311sgRs= - string-length@^4.0.1: version "4.0.2" resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.2.tgz#a8a8dc7bd5c1a82b9b3c8b87e125f66871b6e57a" @@ -9541,7 +8923,7 @@ string-width@^4.2.3: is-fullwidth-code-point "^3.0.0" strip-ansi "^6.0.1" -string.prototype.matchall@^4.0.10: +string.prototype.matchall@^4.0.11: version "4.0.11" resolved "https://registry.yarnpkg.com/string.prototype.matchall/-/string.prototype.matchall-4.0.11.tgz#1092a72c59268d2abaad76582dccc687c0297e0a" integrity sha512-NUdh0aDavY2og7IbBPenWqR9exH+E26Sv8e0/eTe1tltDGZL+GtBkDAnnyBtmekfK6/Dq3MkcGtzXFEd1LQrtg== @@ -9559,6 +8941,27 @@ string.prototype.matchall@^4.0.10: set-function-name "^2.0.2" side-channel "^1.0.6" +string.prototype.repeat@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/string.prototype.repeat/-/string.prototype.repeat-1.0.0.tgz#e90872ee0308b29435aa26275f6e1b762daee01a" + integrity sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w== + dependencies: + define-properties "^1.1.3" + es-abstract "^1.17.5" + +string.prototype.trim@^1.2.10: + version "1.2.10" + resolved "https://registry.yarnpkg.com/string.prototype.trim/-/string.prototype.trim-1.2.10.tgz#40b2dd5ee94c959b4dcfb1d65ce72e90da480c81" + integrity sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA== + dependencies: + call-bind "^1.0.8" + call-bound "^1.0.2" + define-data-property "^1.1.4" + define-properties "^1.2.1" + es-abstract "^1.23.5" + es-object-atoms "^1.0.0" + has-property-descriptors "^1.0.2" + string.prototype.trim@^1.2.9: version "1.2.9" resolved "https://registry.yarnpkg.com/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz#b6fa326d72d2c78b6df02f7759c73f8f6274faa4" @@ -9578,6 +8981,16 @@ string.prototype.trimend@^1.0.8: define-properties "^1.2.1" es-object-atoms "^1.0.0" +string.prototype.trimend@^1.0.9: + version "1.0.9" + resolved "https://registry.yarnpkg.com/string.prototype.trimend/-/string.prototype.trimend-1.0.9.tgz#62e2731272cd285041b36596054e9f66569b6942" + integrity sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ== + dependencies: + call-bind "^1.0.8" + call-bound "^1.0.2" + define-properties "^1.2.1" + es-object-atoms "^1.0.0" + string.prototype.trimstart@^1.0.8: version "1.0.8" resolved "https://registry.yarnpkg.com/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz#7ee834dda8c7c17eff3118472bb35bfedaa34dde" @@ -9594,13 +9007,6 @@ string_decoder@^1.1.1, string_decoder@~1.1.1: dependencies: safe-buffer "~5.1.0" -strip-ansi@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" - integrity sha512-VhumSSbBqDTP8p2ZLKj40UjBCV4+v8bUSEpUb4KjRgWk9pbqGF4REFj6KEagidb2f/M6AzC0EmFyDNGaw9OCzg== - dependencies: - ansi-regex "^2.0.0" - strip-ansi@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" @@ -9649,11 +9055,6 @@ stubs@^3.0.0: resolved "https://registry.yarnpkg.com/stubs/-/stubs-3.0.0.tgz#e8d2ba1fa9c90570303c030b6900f7d5f89abe5b" integrity sha1-6NK6H6nJBXAwPAMLaQD31fiavls= -style-inject@0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/style-inject/-/style-inject-0.3.0.tgz#d21c477affec91811cc82355832a700d22bf8dd3" - integrity sha512-IezA2qp+vcdlhJaVm5SOdPPTUu0FCEqfNSli2vRuSIBbu5Nq5UvygTk/VzeCqfLz2Atj3dVII5QBKGZRZ0edzw== - style-loader@^0.20.1: version "0.20.3" resolved "https://registry.yarnpkg.com/style-loader/-/style-loader-0.20.3.tgz#ebef06b89dec491bcb1fdb3452e913a6fd1c10c4" @@ -9667,11 +9068,6 @@ style-loader@^3.3.1: resolved "https://registry.yarnpkg.com/style-loader/-/style-loader-3.3.1.tgz#057dfa6b3d4d7c7064462830f9113ed417d38575" integrity sha512-GPcQ+LDJbrcxHORTRes6Jy2sfvK2kS6hpSfI/fXhPt+spVzxF6LJ1dHLN9zIGmVaaP044YKaIatFaufENRiDoQ== -stylis@^4.0.13: - version "4.2.0" - resolved "https://registry.yarnpkg.com/stylis/-/stylis-4.2.0.tgz#79daee0208964c8fe695a42fcffcac633a211a51" - integrity sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw== - superagent@^8.1.2: version "8.1.2" resolved "https://registry.yarnpkg.com/superagent/-/superagent-8.1.2.tgz#03cb7da3ec8b32472c9d20f6c2a57c7f3765f30b" @@ -9688,32 +9084,13 @@ superagent@^8.1.2: qs "^6.11.0" semver "^7.3.8" -supports-color@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" - integrity sha1-U10EXOa2Nj+kARcIRimZXp3zJMc= - -supports-color@^3.2.3: - version "3.2.3" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.2.3.tgz#65ac0504b3954171d8a64946b2ae3cbb8a5f54f6" - integrity sha1-ZawFBLOVQXHYpklGsq48u4pfVPY= - dependencies: - has-flag "^1.0.0" - -supports-color@^5.3.0, supports-color@^5.4.0: +supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== dependencies: has-flag "^3.0.0" -supports-color@^6.1.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-6.1.0.tgz#0764abc69c63d5ac842dd4867e8d025e880df8f3" - integrity sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ== - dependencies: - has-flag "^3.0.0" - supports-color@^7.1.0: version "7.2.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da" @@ -9836,16 +9213,6 @@ test-exclude@^6.0.0: glob "^7.1.4" minimatch "^3.0.4" -text-table@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" - integrity sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw== - -throttle-debounce@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/throttle-debounce/-/throttle-debounce-5.0.0.tgz#a17a4039e82a2ed38a5e7268e4132d6960d41933" - integrity sha512-2iQTSgkkc1Zyk0MeVrt/3BvuOXYPl/R8Z0U2xxo9rjwNciaHDG3R+Lm6dh4EeUci49DanvBnuqI6jshoQQRGEg== - thunky@^1.0.2: version "1.1.0" resolved "https://registry.yarnpkg.com/thunky/-/thunky-1.1.0.tgz#5abaf714a9405db0504732bbccd2cedd9ef9537d" @@ -9890,11 +9257,6 @@ to-regex-range@^5.0.1: dependencies: is-number "^7.0.0" -toggle-selection@^1.0.6: - version "1.0.6" - resolved "https://registry.yarnpkg.com/toggle-selection/-/toggle-selection-1.0.6.tgz#6e45b1263f2017fa0acc7d89d78b15b8bf77da32" - integrity sha1-bkWxJj8gF/oKzH2J14sVuL932jI= - toidentifier@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35" @@ -10043,6 +9405,19 @@ typed-array-byte-offset@^1.0.2: has-proto "^1.0.3" is-typed-array "^1.1.13" +typed-array-byte-offset@^1.0.3: + version "1.0.4" + resolved "https://registry.yarnpkg.com/typed-array-byte-offset/-/typed-array-byte-offset-1.0.4.tgz#ae3698b8ec91a8ab945016108aef00d5bff12355" + integrity sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ== + dependencies: + available-typed-arrays "^1.0.7" + call-bind "^1.0.8" + for-each "^0.3.3" + gopd "^1.2.0" + has-proto "^1.2.0" + is-typed-array "^1.1.15" + reflect.getprototypeof "^1.0.9" + typed-array-length@^1.0.6: version "1.0.6" resolved "https://registry.yarnpkg.com/typed-array-length/-/typed-array-length-1.0.6.tgz#57155207c76e64a3457482dfdc1c9d1d3c4c73a3" @@ -10055,6 +9430,18 @@ typed-array-length@^1.0.6: is-typed-array "^1.1.13" possible-typed-array-names "^1.0.0" +typed-array-length@^1.0.7: + version "1.0.7" + resolved "https://registry.yarnpkg.com/typed-array-length/-/typed-array-length-1.0.7.tgz#ee4deff984b64be1e118b0de8c9c877d5ce73d3d" + integrity sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg== + dependencies: + call-bind "^1.0.7" + for-each "^0.3.3" + gopd "^1.0.1" + is-typed-array "^1.1.13" + possible-typed-array-names "^1.0.0" + reflect.getprototypeof "^1.0.6" + typescript-eslint@^7.8.0: version "7.8.0" resolved "https://registry.yarnpkg.com/typescript-eslint/-/typescript-eslint-7.8.0.tgz#d2a73d4caac35d4d9825bfdfac06a9bf2ba175e4" @@ -10481,25 +9868,37 @@ which-boxed-primitive@^1.0.2: is-string "^1.0.5" is-symbol "^1.0.3" -which-builtin-type@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/which-builtin-type/-/which-builtin-type-1.1.3.tgz#b1b8443707cc58b6e9bf98d32110ff0c2cbd029b" - integrity sha512-YmjsSMDBYsM1CaFiayOVT06+KJeXf0o5M/CAd4o1lTadFAtacTUM49zoYxr/oroopFDfhvN6iEcBxUyc3gvKmw== +which-boxed-primitive@^1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz#d76ec27df7fa165f18d5808374a5fe23c29b176e" + integrity sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA== dependencies: - function.prototype.name "^1.1.5" - has-tostringtag "^1.0.0" + is-bigint "^1.1.0" + is-boolean-object "^1.2.1" + is-number-object "^1.1.1" + is-string "^1.1.1" + is-symbol "^1.1.1" + +which-builtin-type@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/which-builtin-type/-/which-builtin-type-1.2.1.tgz#89183da1b4907ab089a6b02029cc5d8d6574270e" + integrity sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q== + dependencies: + call-bound "^1.0.2" + function.prototype.name "^1.1.6" + has-tostringtag "^1.0.2" is-async-function "^2.0.0" - is-date-object "^1.0.5" - is-finalizationregistry "^1.0.2" + is-date-object "^1.1.0" + is-finalizationregistry "^1.1.0" is-generator-function "^1.0.10" - is-regex "^1.1.4" + is-regex "^1.2.1" is-weakref "^1.0.2" isarray "^2.0.5" - which-boxed-primitive "^1.0.2" - which-collection "^1.0.1" - which-typed-array "^1.1.9" + which-boxed-primitive "^1.1.0" + which-collection "^1.0.2" + which-typed-array "^1.1.16" -which-collection@^1.0.1: +which-collection@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/which-collection/-/which-collection-1.0.2.tgz#627ef76243920a107e7ce8e96191debe4b16c2a0" integrity sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw== @@ -10509,7 +9908,7 @@ which-collection@^1.0.1: is-weakmap "^2.0.2" is-weakset "^2.0.3" -which-typed-array@^1.1.14, which-typed-array@^1.1.15, which-typed-array@^1.1.9: +which-typed-array@^1.1.14, which-typed-array@^1.1.15: version "1.1.15" resolved "https://registry.yarnpkg.com/which-typed-array/-/which-typed-array-1.1.15.tgz#264859e9b11a649b388bfaaf4f767df1f779b38d" integrity sha512-oV0jmFtUky6CXfkqehVvBP/LSWJ2sy4vWMioiENyJLePrBO/yKyV9OyJySfAKosh+RYkIl5zJCNZ8/4JncrpdA== @@ -10520,12 +9919,17 @@ which-typed-array@^1.1.14, which-typed-array@^1.1.15, which-typed-array@^1.1.9: gopd "^1.0.1" has-tostringtag "^1.0.2" -which@^1.2.9: - version "1.3.1" - resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" - integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== +which-typed-array@^1.1.16: + version "1.1.18" + resolved "https://registry.yarnpkg.com/which-typed-array/-/which-typed-array-1.1.18.tgz#df2389ebf3fbb246a71390e90730a9edb6ce17ad" + integrity sha512-qEcY+KJYlWyLH9vNbsr6/5j59AXk5ni5aakf8ldzBvGde6Iz4sxZGkJyWSAueTG7QhOvNRYb1lDdFmL5Td0QKA== dependencies: - isexe "^2.0.0" + available-typed-arrays "^1.0.7" + call-bind "^1.0.8" + call-bound "^1.0.3" + for-each "^0.3.3" + gopd "^1.2.0" + has-tostringtag "^1.0.2" which@^2.0.1: version "2.0.2" From 50c49ec8f91997970e1b22b605f94153d51fe622 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Tue, 7 Jan 2025 15:56:38 +0100 Subject: [PATCH 32/41] chore: enable unnecessary-stmt from revive (#21398) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 3 +++ .../scm_provider/bitbucket_server_test.go | 21 +++++++------------ cmd/argocd/commands/admin/backup.go | 3 +-- controller/cache/cache.go | 3 +-- controller/cache/info.go | 3 +-- .../generators/application_generator.go | 6 ++---- pkg/apis/application/v1alpha1/types.go | 3 +-- server/application/application.go | 3 +-- util/grpc/errors.go | 3 +-- util/kube/kube.go | 3 +-- util/kustomize/kustomize_test.go | 3 +-- util/lua/custom_actions_test.go | 3 +-- util/lua/lua.go | 3 +-- util/rbac/rbac.go | 18 +++++++--------- 14 files changed, 30 insertions(+), 48 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 3a51e14d3ebe0..acd1813a353cf 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -143,6 +143,9 @@ linters-settings: # warns when an exported function or method returns a value of an un-exported type. - name: unexported-return disabled: true + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unnecessary-stmt + - name: unnecessary-stmt + disabled: false # spots and proposes to remove unreachable code. also helps to spot errors - name: unreachable-code disabled: false diff --git a/applicationset/services/scm_provider/bitbucket_server_test.go b/applicationset/services/scm_provider/bitbucket_server_test.go index 5b4a957fea1ab..211d86cafd4f8 100644 --- a/applicationset/services/scm_provider/bitbucket_server_test.go +++ b/applicationset/services/scm_provider/bitbucket_server_test.go @@ -307,8 +307,7 @@ func TestGetBranchesBranchPagination(t *testing.T) { func TestGetBranchesDefaultOnly(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Empty(t, r.Header.Get("Authorization")) - switch r.RequestURI { - case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default": + if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" { _, err := io.WriteString(w, `{ "id": "refs/heads/default", "displayId": "default", @@ -350,8 +349,7 @@ func TestGetBranchesDefaultOnly(t *testing.T) { func TestGetBranchesMissingDefault(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Empty(t, r.Header.Get("Authorization")) - switch r.RequestURI { - case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default": + if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" { http.Error(w, "Not found", http.StatusNotFound) } defaultHandler(t)(w, r) @@ -373,8 +371,7 @@ func TestGetBranchesMissingDefault(t *testing.T) { func TestGetBranchesEmptyRepo(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Empty(t, r.Header.Get("Authorization")) - switch r.RequestURI { - case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default": + if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" { return } })) @@ -395,8 +392,7 @@ func TestGetBranchesEmptyRepo(t *testing.T) { func TestGetBranchesErrorDefaultBranch(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Empty(t, r.Header.Get("Authorization")) - switch r.RequestURI { - case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default": + if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" { http.Error(w, "Internal server error", http.StatusInternalServerError) } defaultHandler(t)(w, r) @@ -510,8 +506,7 @@ func TestListReposBearerAuth(t *testing.T) { func TestListReposDefaultBranch(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Empty(t, r.Header.Get("Authorization")) - switch r.RequestURI { - case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default": + if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" { _, err := io.WriteString(w, `{ "id": "refs/heads/default", "displayId": "default", @@ -547,8 +542,7 @@ func TestListReposDefaultBranch(t *testing.T) { func TestListReposMissingDefaultBranch(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Empty(t, r.Header.Get("Authorization")) - switch r.RequestURI { - case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default": + if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" { http.Error(w, "Not found", http.StatusNotFound) } defaultHandler(t)(w, r) @@ -564,8 +558,7 @@ func TestListReposMissingDefaultBranch(t *testing.T) { func TestListReposErrorDefaultBranch(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Empty(t, r.Header.Get("Authorization")) - switch r.RequestURI { - case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default": + if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" { http.Error(w, "Internal server error", http.StatusInternalServerError) } defaultHandler(t)(w, r) diff --git a/cmd/argocd/commands/admin/backup.go b/cmd/argocd/commands/admin/backup.go index 7b58cd49fae8d..7725ed1d9e5ae 100644 --- a/cmd/argocd/commands/admin/backup.go +++ b/cmd/argocd/commands/admin/backup.go @@ -383,8 +383,7 @@ func checkAppHasNoNeedToStopOperation(liveObj unstructured.Unstructured, stopOpe if !stopOperation { return true } - switch liveObj.GetKind() { - case application.ApplicationKind: + if liveObj.GetKind() == application.ApplicationKind { return liveObj.Object["operation"] == nil } return true diff --git a/controller/cache/cache.go b/controller/cache/cache.go index b4c9819184e88..b649b02d3c1ce 100644 --- a/controller/cache/cache.go +++ b/controller/cache/cache.go @@ -438,8 +438,7 @@ func isResourceQuotaConflictErr(err error) bool { func isTransientNetworkErr(err error) bool { var netErr net.Error - switch { - case errors.As(err, &netErr): + if errors.As(err, &netErr) { var dnsErr *net.DNSError var opErr *net.OpError var unknownNetworkErr net.UnknownNetworkError diff --git a/controller/cache/info.go b/controller/cache/info.go index 8dfa6e1c51bd5..de531d9a9777f 100644 --- a/controller/cache/info.go +++ b/controller/cache/info.go @@ -58,8 +58,7 @@ func populateNodeInfo(un *unstructured.Unstructured, res *ResourceInfo, customLa populateHostNodeInfo(un, res) } case "extensions", "networking.k8s.io": - switch gvk.Kind { - case kube.IngressKind: + if gvk.Kind == kube.IngressKind { populateIngressInfo(un, res) } case "networking.istio.io": diff --git a/hack/gen-resources/generators/application_generator.go b/hack/gen-resources/generators/application_generator.go index 07fb900327426..9a1437d9dd6a8 100644 --- a/hack/gen-resources/generators/application_generator.go +++ b/hack/gen-resources/generators/application_generator.go @@ -40,8 +40,7 @@ func (generator *ApplicationGenerator) buildRandomSource(repositories []*v1alpha } func (generator *ApplicationGenerator) buildSource(opts *util.GenerateOpts, repositories []*v1alpha1.Repository) (*v1alpha1.ApplicationSource, error) { - switch opts.ApplicationOpts.SourceOpts.Strategy { - case "Random": + if opts.ApplicationOpts.SourceOpts.Strategy == "Random" { return generator.buildRandomSource(repositories) } return generator.buildRandomSource(repositories) @@ -57,8 +56,7 @@ func (generator *ApplicationGenerator) buildRandomDestination(opts *util.Generat } func (generator *ApplicationGenerator) buildDestination(opts *util.GenerateOpts, clusters []v1alpha1.Cluster) (*v1alpha1.ApplicationDestination, error) { - switch opts.ApplicationOpts.DestinationOpts.Strategy { - case "Random": + if opts.ApplicationOpts.DestinationOpts.Strategy == "Random" { return generator.buildRandomDestination(opts, clusters) } return generator.buildRandomDestination(opts, clusters) diff --git a/pkg/apis/application/v1alpha1/types.go b/pkg/apis/application/v1alpha1/types.go index d62948721700f..fe2a17f920b0c 100644 --- a/pkg/apis/application/v1alpha1/types.go +++ b/pkg/apis/application/v1alpha1/types.go @@ -288,9 +288,8 @@ func (spec *ApplicationSpec) GetSourcePtrByIndex(sourceIndex int) *ApplicationSo // AllowsConcurrentProcessing returns true if given application source can be processed concurrently func (source *ApplicationSource) AllowsConcurrentProcessing() bool { - switch { // Kustomize with parameters requires changing kustomization.yaml file - case source.Kustomize != nil: + if source.Kustomize != nil { return source.Kustomize.AllowsConcurrentProcessing() } return true diff --git a/server/application/application.go b/server/application/application.go index b260c4ca1f6b2..59d8a755e4d18 100644 --- a/server/application/application.go +++ b/server/application/application.go @@ -2477,8 +2477,7 @@ func (s *Server) RunResourceAction(ctx context.Context, q *application.ResourceA if err != nil { return nil, err } - switch impactedResource.K8SOperation { - case lua.CreateOperation: + if impactedResource.K8SOperation == lua.CreateOperation { createOptions := metav1.CreateOptions{DryRun: []string{"All"}} _, err := s.kubectl.CreateResource(ctx, config, newObj.GroupVersionKind(), newObj.GetName(), newObj.GetNamespace(), newObj, createOptions) if err != nil { diff --git a/util/grpc/errors.go b/util/grpc/errors.go index 755e9bae89d1a..4af523852135a 100644 --- a/util/grpc/errors.go +++ b/util/grpc/errors.go @@ -24,8 +24,7 @@ func gitErrToGRPC(err error) error { errMsg = grpcStatus.Message() } - switch errMsg { - case giterr.ErrRepositoryNotFound.Error(): + if errMsg == giterr.ErrRepositoryNotFound.Error() { err = rewrapError(errors.New(errMsg), codes.NotFound) } return err diff --git a/util/kube/kube.go b/util/kube/kube.go index 6cd1378a2c71f..f6362a78dfc56 100644 --- a/util/kube/kube.go +++ b/util/kube/kube.go @@ -78,8 +78,7 @@ func SetAppInstanceLabel(target *unstructured.Unstructured, key, val string) err } } case "batch": - switch gvk.Kind { - case kube.JobKind: + if gvk.Kind == kube.JobKind { templateLabels, ok, err := unstructured.NestedMap(target.UnstructuredContent(), "spec", "template", "metadata", "labels") if err != nil { return err diff --git a/util/kustomize/kustomize_test.go b/util/kustomize/kustomize_test.go index eb0395fd0c7a9..01ea8d9b963be 100644 --- a/util/kustomize/kustomize_test.go +++ b/util/kustomize/kustomize_test.go @@ -119,8 +119,7 @@ func TestKustomizeBuild(t *testing.T) { } for _, image := range images { - switch image { - case "nginx": + if image == "nginx" { assert.Equal(t, "1.15.5", image) } } diff --git a/util/lua/custom_actions_test.go b/util/lua/custom_actions_test.go index aee5c59a9ac0d..dc8662bc5e294 100644 --- a/util/lua/custom_actions_test.go +++ b/util/lua/custom_actions_test.go @@ -26,8 +26,7 @@ func (t testNormalizer) Normalize(un *unstructured.Unstructured) error { if un == nil { return nil } - switch un.GetKind() { - case "Job": + if un.GetKind() == "Job" { 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) diff --git a/util/lua/lua.go b/util/lua/lua.go index 6f3501e31d7e0..c51ee9d46a797 100644 --- a/util/lua/lua.go +++ b/util/lua/lua.go @@ -356,8 +356,7 @@ func isActionDisabled(actionsMap any) bool { return false } for key, val := range actions { - switch vv := val.(type) { - case bool: + if vv, ok := val.(bool); ok { if key == "disabled" { return vv } diff --git a/util/rbac/rbac.go b/util/rbac/rbac.go index f977e092074cf..77a8a4cbbdca6 100644 --- a/util/rbac/rbac.go +++ b/util/rbac/rbac.go @@ -249,17 +249,15 @@ func (e *Enforcer) EnforceErr(rvals ...any) error { for i, rval := range rvals[1:] { rvalsStrs[i] = fmt.Sprintf("%s", rval) } - switch s := rvals[0].(type) { - case jwt.Claims: + if s, ok := rvals[0].(jwt.Claims); ok { claims, err := jwtutil.MapClaims(s) - if err != nil { - break - } - if sub := jwtutil.StringField(claims, "sub"); sub != "" { - rvalsStrs = append(rvalsStrs, "sub: "+sub) - } - if issuedAtTime, err := jwtutil.IssuedAtTime(claims); err == nil { - rvalsStrs = append(rvalsStrs, "iat: "+issuedAtTime.Format(time.RFC3339)) + if err == nil { + if sub := jwtutil.StringField(claims, "sub"); sub != "" { + rvalsStrs = append(rvalsStrs, "sub: "+sub) + } + if issuedAtTime, err := jwtutil.IssuedAtTime(claims); err == nil { + rvalsStrs = append(rvalsStrs, "iat: "+issuedAtTime.Format(time.RFC3339)) + } } } errMsg = fmt.Sprintf("%s: %s", errMsg, strings.Join(rvalsStrs, ", ")) From b04a7c101dfa4512e12145d5241685ab337d6532 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Tue, 7 Jan 2025 16:08:51 +0100 Subject: [PATCH 33/41] chore: enable context-as-argument from revive (#21371) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 5 ++- .../controllers/requeue_after_test.go | 2 +- applicationset/generators/cluster.go | 2 +- applicationset/generators/cluster_test.go | 4 +- .../generator_spec_processor_test.go | 2 +- applicationset/generators/matrix_test.go | 4 +- applicationset/generators/plugin.go | 2 +- applicationset/generators/plugin_test.go | 2 +- applicationset/generators/utils.go | 4 +- cmd/argocd/commands/app.go | 20 +++++----- cmd/argocd/commands/app_actions.go | 6 +-- cmd/argocd/commands/project.go | 4 +- controller/appcontroller.go | 16 ++++---- controller/sync.go | 2 +- server/application/application.go | 38 +++++++++---------- server/applicationset/applicationset.go | 12 +++--- server/applicationset/applicationset_test.go | 4 +- server/cluster/cluster.go | 6 +-- server/project/project.go | 14 +++---- server/repository/repository.go | 2 +- server/server.go | 28 +++++++------- util/argo/argo.go | 12 +++--- util/argo/argo_test.go | 4 +- util/grpc/logging.go | 6 +-- util/kube/util.go | 2 +- util/kube/util_test.go | 16 ++++---- util/settings/settings.go | 2 +- 27 files changed, 112 insertions(+), 109 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index acd1813a353cf..c952308576aee 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -92,7 +92,10 @@ linters-settings: disabled: true # context.Context() should be the first parameter of a function when provided as argument. - name: context-as-argument - disabled: true + disabled: false + arguments: + # Allow functions with test or bench signatures. + - allowTypesBefore: "*testing.T,testing.TB" # Basic types should not be used as a key in `context.WithValue` - name: context-keys-type disabled: true diff --git a/applicationset/controllers/requeue_after_test.go b/applicationset/controllers/requeue_after_test.go index 7ee01e9d73e12..39b3f580aee46 100644 --- a/applicationset/controllers/requeue_after_test.go +++ b/applicationset/controllers/requeue_after_test.go @@ -60,7 +60,7 @@ func TestRequeueAfter(t *testing.T) { scmConfig := generators.NewSCMConfig("", []string{""}, true, nil, true) terminalGenerators := map[string]generators.Generator{ "List": generators.NewListGenerator(), - "Clusters": generators.NewClusterGenerator(k8sClient, ctx, appClientset, "argocd"), + "Clusters": generators.NewClusterGenerator(ctx, k8sClient, appClientset, "argocd"), "Git": generators.NewGitGenerator(mockServer, "namespace"), "SCMProvider": generators.NewSCMProviderGenerator(fake.NewClientBuilder().WithObjects(&corev1.Secret{}).Build(), scmConfig), "ClusterDecisionResource": generators.NewDuckTypeGenerator(ctx, fakeDynClient, appClientset, "argocd"), diff --git a/applicationset/generators/cluster.go b/applicationset/generators/cluster.go index bcc5c55f8473f..fcac04b3cad0d 100644 --- a/applicationset/generators/cluster.go +++ b/applicationset/generators/cluster.go @@ -33,7 +33,7 @@ type ClusterGenerator struct { var render = &utils.Render{} -func NewClusterGenerator(c client.Client, ctx context.Context, clientset kubernetes.Interface, namespace string) Generator { +func NewClusterGenerator(ctx context.Context, c client.Client, clientset kubernetes.Interface, namespace string) Generator { settingsManager := settings.NewSettingsManager(ctx, clientset, namespace) g := &ClusterGenerator{ diff --git a/applicationset/generators/cluster_test.go b/applicationset/generators/cluster_test.go index 10c114f39dcae..6c28b18a4aadc 100644 --- a/applicationset/generators/cluster_test.go +++ b/applicationset/generators/cluster_test.go @@ -315,7 +315,7 @@ func TestGenerateParams(t *testing.T) { testCase.clientError, } - clusterGenerator := NewClusterGenerator(cl, context.Background(), appClientset, "namespace") + clusterGenerator := NewClusterGenerator(context.Background(), cl, appClientset, "namespace") applicationSetInfo := argoprojiov1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ @@ -853,7 +853,7 @@ func TestGenerateParamsGoTemplate(t *testing.T) { testCase.clientError, } - clusterGenerator := NewClusterGenerator(cl, context.Background(), appClientset, "namespace") + clusterGenerator := NewClusterGenerator(context.Background(), cl, appClientset, "namespace") applicationSetInfo := argoprojiov1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ diff --git a/applicationset/generators/generator_spec_processor_test.go b/applicationset/generators/generator_spec_processor_test.go index a208e5781f264..ac333a7bcf26d 100644 --- a/applicationset/generators/generator_spec_processor_test.go +++ b/applicationset/generators/generator_spec_processor_test.go @@ -342,7 +342,7 @@ func getMockClusterGenerator() Generator { appClientset := kubefake.NewSimpleClientset(runtimeClusters...) fakeClient := fake.NewClientBuilder().WithObjects(clusters...).Build() - return NewClusterGenerator(fakeClient, context.Background(), appClientset, "namespace") + return NewClusterGenerator(context.Background(), fakeClient, appClientset, "namespace") } func getMockGitGenerator() Generator { diff --git a/applicationset/generators/matrix_test.go b/applicationset/generators/matrix_test.go index fb597e86a5365..db609c0426de6 100644 --- a/applicationset/generators/matrix_test.go +++ b/applicationset/generators/matrix_test.go @@ -644,7 +644,7 @@ func TestInterpolatedMatrixGenerate(t *testing.T) { fakeClient, testCase.clientError, } - clusterGenerator := NewClusterGenerator(cl, context.Background(), appClientset, "namespace") + clusterGenerator := NewClusterGenerator(context.Background(), cl, appClientset, "namespace") for _, g := range testCaseCopy.baseGenerators { gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{ @@ -827,7 +827,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) { fakeClient, testCase.clientError, } - clusterGenerator := NewClusterGenerator(cl, context.Background(), appClientset, "namespace") + clusterGenerator := NewClusterGenerator(context.Background(), cl, appClientset, "namespace") for _, g := range testCaseCopy.baseGenerators { gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{ diff --git a/applicationset/generators/plugin.go b/applicationset/generators/plugin.go index 4bebfbd88eb07..8525474ebb46e 100644 --- a/applicationset/generators/plugin.go +++ b/applicationset/generators/plugin.go @@ -32,7 +32,7 @@ type PluginGenerator struct { namespace string } -func NewPluginGenerator(client client.Client, ctx context.Context, clientset kubernetes.Interface, namespace string) Generator { +func NewPluginGenerator(ctx context.Context, client client.Client, clientset kubernetes.Interface, namespace string) Generator { g := &PluginGenerator{ client: client, ctx: ctx, diff --git a/applicationset/generators/plugin_test.go b/applicationset/generators/plugin_test.go index f9ce9bdd48a5b..e238e6fa61c63 100644 --- a/applicationset/generators/plugin_test.go +++ b/applicationset/generators/plugin_test.go @@ -671,7 +671,7 @@ func TestPluginGenerateParams(t *testing.T) { fakeClientWithCache := fake.NewClientBuilder().WithObjects([]client.Object{testCase.configmap, testCase.secret}...).Build() - pluginGenerator := NewPluginGenerator(fakeClientWithCache, ctx, fakeClient, "default") + pluginGenerator := NewPluginGenerator(ctx, fakeClientWithCache, fakeClient, "default") applicationSetInfo := argoprojiov1alpha1.ApplicationSet{ ObjectMeta: metav1.ObjectMeta{ diff --git a/applicationset/generators/utils.go b/applicationset/generators/utils.go index 84bdda6101006..0892b50b3552d 100644 --- a/applicationset/generators/utils.go +++ b/applicationset/generators/utils.go @@ -13,12 +13,12 @@ import ( func GetGenerators(ctx context.Context, c client.Client, k8sClient kubernetes.Interface, namespace string, argoCDService services.Repos, dynamicClient dynamic.Interface, scmConfig SCMConfig) map[string]Generator { terminalGenerators := map[string]Generator{ "List": NewListGenerator(), - "Clusters": NewClusterGenerator(c, ctx, k8sClient, namespace), + "Clusters": NewClusterGenerator(ctx, c, k8sClient, namespace), "Git": NewGitGenerator(argoCDService, namespace), "SCMProvider": NewSCMProviderGenerator(c, scmConfig), "ClusterDecisionResource": NewDuckTypeGenerator(ctx, dynamicClient, k8sClient, namespace), "PullRequest": NewPullRequestGenerator(c, scmConfig), - "Plugin": NewPluginGenerator(c, ctx, k8sClient, namespace), + "Plugin": NewPluginGenerator(ctx, c, k8sClient, namespace), } nestedGenerators := map[string]Generator{ diff --git a/cmd/argocd/commands/app.go b/cmd/argocd/commands/app.go index 127dc96240b4a..2a9eca19f6116 100644 --- a/cmd/argocd/commands/app.go +++ b/cmd/argocd/commands/app.go @@ -274,7 +274,7 @@ func hasAppChanged(appReq, appRes *argoappv1.Application, upsert bool) bool { return true } -func parentChildDetails(appIf application.ApplicationServiceClient, ctx context.Context, appName string, appNs string) (map[string]argoappv1.ResourceNode, map[string][]string, map[string]struct{}) { +func parentChildDetails(ctx context.Context, appIf application.ApplicationServiceClient, appName string, appNs string) (map[string]argoappv1.ResourceNode, map[string][]string, map[string]struct{}) { mapUidToNode := make(map[string]argoappv1.ResourceNode) mapParentToChild := make(map[string][]string) parentNode := make(map[string]struct{}) @@ -299,7 +299,7 @@ func parentChildDetails(appIf application.ApplicationServiceClient, ctx context. return mapUidToNode, mapParentToChild, parentNode } -func printHeader(acdClient argocdclient.Client, app *argoappv1.Application, ctx context.Context, windows *argoappv1.SyncWindows, showOperation bool, showParams bool, sourcePosition int) { +func printHeader(ctx context.Context, acdClient argocdclient.Client, app *argoappv1.Application, windows *argoappv1.SyncWindows, showOperation bool, showParams bool, sourcePosition int) { aURL := appURL(ctx, acdClient, app.Name) printAppSummaryTable(app, aURL, windows) @@ -434,7 +434,7 @@ func NewApplicationGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Com err := PrintResource(app, output) errors.CheckError(err) case "wide", "": - printHeader(acdClient, app, ctx, windows, showOperation, showParams, sourcePosition) + printHeader(ctx, acdClient, app, windows, showOperation, showParams, sourcePosition) if len(app.Status.Resources) > 0 { fmt.Println() w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) @@ -442,14 +442,14 @@ func NewApplicationGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Com _ = w.Flush() } case "tree": - printHeader(acdClient, app, ctx, windows, showOperation, showParams, sourcePosition) + printHeader(ctx, acdClient, app, windows, showOperation, showParams, sourcePosition) mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState := resourceParentChild(ctx, acdClient, appName, appNs) if len(mapUidToNode) > 0 { fmt.Println() printTreeView(mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState) } case "tree=detailed": - printHeader(acdClient, app, ctx, windows, showOperation, showParams, sourcePosition) + printHeader(ctx, acdClient, app, windows, showOperation, showParams, sourcePosition) mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState := resourceParentChild(ctx, acdClient, appName, appNs) if len(mapUidToNode) > 0 { fmt.Println() @@ -1340,7 +1340,7 @@ func NewApplicationDiffCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co diffOption.cluster = cluster } } - proj := getProject(c, clientOpts, ctx, app.Spec.Project) + proj := getProject(ctx, c, clientOpts, app.Spec.Project) foundDiffs := findandPrintDiff(ctx, app, proj.Project, resources, argoSettings, diffOption, ignoreNormalizerOpts) if foundDiffs && exitCode { os.Exit(diffExitCode) @@ -2158,7 +2158,7 @@ func NewApplicationSyncCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co errors.CheckError(err) argoio.Close(conn) - proj := getProject(c, clientOpts, ctx, app.Spec.Project) + proj := getProject(ctx, c, clientOpts, app.Spec.Project) localObjsStrings = getLocalObjectsString(ctx, app, proj.Project, local, localRepoRoot, argoSettings.AppLabelKey, cluster.Info.ServerVersion, cluster.Info.APIVersions, argoSettings.KustomizeOptions, argoSettings.TrackingMethod) errors.CheckError(err) diffOption.local = local @@ -2234,7 +2234,7 @@ func NewApplicationSyncCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co foundDiffs := false fmt.Printf("====== Previewing differences between live and desired state of application %s ======\n", appQualifiedName) - proj := getProject(c, clientOpts, ctx, app.Spec.Project) + proj := getProject(ctx, c, clientOpts, app.Spec.Project) foundDiffs = findandPrintDiff(ctx, app, proj.Project, resources, argoSettings, diffOption, ignoreNormalizerOpts) if foundDiffs { if !diffChangesConfirm { @@ -2490,7 +2490,7 @@ func checkResourceStatus(watch watchOpts, healthStatus string, syncStatus string // constructs the necessary data structures to print the app as a tree. func resourceParentChild(ctx context.Context, acdClient argocdclient.Client, appName string, appNs string) (map[string]argoappv1.ResourceNode, map[string][]string, map[string]struct{}, map[string]*resourceState) { _, appIf := acdClient.NewApplicationClientOrDie() - mapUidToNode, mapParentToChild, parentNode := parentChildDetails(appIf, ctx, appName, appNs) + mapUidToNode, mapParentToChild, parentNode := parentChildDetails(ctx, appIf, appName, appNs) app, err := appIf.Get(ctx, &application.ApplicationQuery{Name: ptr.To(appName), AppNamespace: ptr.To(appNs)}) errors.CheckError(err) mapNodeNameToResourceState := make(map[string]*resourceState) @@ -3032,7 +3032,7 @@ func NewApplicationManifestsCommand(clientOpts *argocdclient.ClientOptions) *cob cluster, err := clusterIf.Get(context.Background(), &clusterpkg.ClusterQuery{Name: app.Spec.Destination.Name, Server: app.Spec.Destination.Server}) errors.CheckError(err) - proj := getProject(c, clientOpts, ctx, app.Spec.Project) + proj := getProject(ctx, c, clientOpts, app.Spec.Project) // nolint:staticcheck unstructureds = getLocalObjects(context.Background(), app, proj.Project, local, localRepoRoot, argoSettings.AppLabelKey, cluster.ServerVersion, cluster.Info.APIVersions, argoSettings.KustomizeOptions, argoSettings.TrackingMethod) } else if len(revisions) > 0 && len(sourcePositions) > 0 { diff --git a/cmd/argocd/commands/app_actions.go b/cmd/argocd/commands/app_actions.go index 69a36683dd357..e9e4c7ccd30a1 100644 --- a/cmd/argocd/commands/app_actions.go +++ b/cmd/argocd/commands/app_actions.go @@ -84,7 +84,7 @@ func NewApplicationResourceActionsListCommand(clientOpts *argocdclient.ClientOpt appName, appNs := argo.ParseFromQualifiedName(args[0], "") conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie() defer io.Close(conn) - resources, err := getActionableResourcesForApplication(appIf, ctx, &appNs, &appName) + resources, err := getActionableResourcesForApplication(ctx, appIf, &appNs, &appName) errors.CheckError(err) filteredObjects, err := util.FilterResources(command.Flags().Changed("group"), resources, group, kind, namespace, resourceName, true) errors.CheckError(err) @@ -176,7 +176,7 @@ func NewApplicationResourceActionsRunCommand(clientOpts *argocdclient.ClientOpti conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie() defer io.Close(conn) - resources, err := getActionableResourcesForApplication(appIf, ctx, &appNs, &appName) + resources, err := getActionableResourcesForApplication(ctx, appIf, &appNs, &appName) errors.CheckError(err) filteredObjects, err := util.FilterResources(command.Flags().Changed("group"), resources, group, kind, namespace, resourceName, all) errors.CheckError(err) @@ -207,7 +207,7 @@ func NewApplicationResourceActionsRunCommand(clientOpts *argocdclient.ClientOpti return command } -func getActionableResourcesForApplication(appIf applicationpkg.ApplicationServiceClient, ctx context.Context, appNs *string, appName *string) ([]*v1alpha1.ResourceDiff, error) { +func getActionableResourcesForApplication(ctx context.Context, appIf applicationpkg.ApplicationServiceClient, appNs *string, appName *string) ([]*v1alpha1.ResourceDiff, error) { resources, err := appIf.ManagedResources(ctx, &applicationpkg.ResourcesQuery{ ApplicationName: appName, AppNamespace: appNs, diff --git a/cmd/argocd/commands/project.go b/cmd/argocd/commands/project.go index ae1f1365d1d31..50ae57354a3eb 100644 --- a/cmd/argocd/commands/project.go +++ b/cmd/argocd/commands/project.go @@ -1024,7 +1024,7 @@ func NewProjectGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command os.Exit(1) } projName := args[0] - detailedProject := getProject(c, clientOpts, ctx, projName) + detailedProject := getProject(ctx, c, clientOpts, projName) switch output { case "yaml", "json": @@ -1041,7 +1041,7 @@ func NewProjectGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command return command } -func getProject(c *cobra.Command, clientOpts *argocdclient.ClientOptions, ctx context.Context, projName string) *projectpkg.DetailedProjectsResponse { +func getProject(ctx context.Context, c *cobra.Command, clientOpts *argocdclient.ClientOptions, projName string) *projectpkg.DetailedProjectsResponse { conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie() defer argoio.Close(conn) detailedProject, err := projIf.GetDetailedProject(ctx, &projectpkg.ProjectQuery{Name: projName}) diff --git a/controller/appcontroller.go b/controller/appcontroller.go index 910f4fc1ae06d..e4d5eda967c60 100644 --- a/controller/appcontroller.go +++ b/controller/appcontroller.go @@ -381,7 +381,7 @@ func (projCache *appProjCache) GetAppProject(ctx context.Context) (*appv1.AppPro if projCache.appProj != nil { return projCache.appProj, nil } - proj, err := argo.GetAppProjectByName(projCache.name, applisters.NewAppProjectLister(projCache.ctrl.projInformer.GetIndexer()), projCache.ctrl.namespace, projCache.ctrl.settingsMgr, projCache.ctrl.db, ctx) + proj, err := argo.GetAppProjectByName(ctx, projCache.name, applisters.NewAppProjectLister(projCache.ctrl.projInformer.GetIndexer()), projCache.ctrl.namespace, projCache.ctrl.settingsMgr, projCache.ctrl.db) if err != nil { return nil, err } @@ -1027,7 +1027,7 @@ func (ctrl *ApplicationController) processAppOperationQueueItem() (processNext b Message: err.Error(), }) message := fmt.Sprintf("Unable to delete application resources: %v", err.Error()) - ctrl.logAppEvent(app, argo.EventInfo{Reason: argo.EventReasonStatusRefreshed, Type: corev1.EventTypeWarning}, message, context.TODO()) + ctrl.logAppEvent(context.TODO(), app, argo.EventInfo{Reason: argo.EventReasonStatusRefreshed, Type: corev1.EventTypeWarning}, message) } ts.AddCheckpoint("finalize_application_deletion_ms") } @@ -1563,7 +1563,7 @@ func (ctrl *ApplicationController) setOperationState(app *appv1.Application, sta eventInfo.Type = corev1.EventTypeWarning messages = append(messages, "failed:", state.Message) } - ctrl.logAppEvent(app, eventInfo, strings.Join(messages, " "), context.TODO()) + ctrl.logAppEvent(context.TODO(), app, eventInfo, strings.Join(messages, " ")) ctrl.metricsServer.IncSync(app, state) } } @@ -1994,11 +1994,11 @@ func (ctrl *ApplicationController) persistAppStatus(orig *appv1.Application, new logCtx := getAppLog(orig) if orig.Status.Sync.Status != newStatus.Sync.Status { message := fmt.Sprintf("Updated sync status: %s -> %s", orig.Status.Sync.Status, newStatus.Sync.Status) - ctrl.logAppEvent(orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: corev1.EventTypeNormal}, message, context.TODO()) + ctrl.logAppEvent(context.TODO(), orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: corev1.EventTypeNormal}, message) } if orig.Status.Health.Status != newStatus.Health.Status { message := fmt.Sprintf("Updated health status: %s -> %s", orig.Status.Health.Status, newStatus.Health.Status) - ctrl.logAppEvent(orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: corev1.EventTypeNormal}, message, context.TODO()) + ctrl.logAppEvent(context.TODO(), orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: corev1.EventTypeNormal}, message) } var newAnnotations map[string]string if orig.GetAnnotations() != nil { @@ -2181,7 +2181,7 @@ func (ctrl *ApplicationController) autoSync(app *appv1.Application, syncStatus * target = desiredCommitSHA } message := fmt.Sprintf("Initiated automated sync to '%s'", target) - ctrl.logAppEvent(app, argo.EventInfo{Reason: argo.EventReasonOperationStarted, Type: corev1.EventTypeNormal}, message, context.TODO()) + ctrl.logAppEvent(context.TODO(), app, argo.EventInfo{Reason: argo.EventReasonOperationStarted, Type: corev1.EventTypeNormal}, message) logCtx.Info(message) return nil, setOpTime } @@ -2533,8 +2533,8 @@ func (ctrl *ApplicationController) getAppList(options metav1.ListOptions) (*appv return appList, nil } -func (ctrl *ApplicationController) logAppEvent(a *appv1.Application, eventInfo argo.EventInfo, message string, ctx context.Context) { - eventLabels := argo.GetAppEventLabels(a, applisters.NewAppProjectLister(ctrl.projInformer.GetIndexer()), ctrl.namespace, ctrl.settingsMgr, ctrl.db, ctx) +func (ctrl *ApplicationController) logAppEvent(ctx context.Context, a *appv1.Application, eventInfo argo.EventInfo, message string) { + eventLabels := argo.GetAppEventLabels(ctx, a, applisters.NewAppProjectLister(ctrl.projInformer.GetIndexer()), ctrl.namespace, ctrl.settingsMgr, ctrl.db) ctrl.auditLogger.LogAppEvent(a, eventInfo, message, "", eventLabels) } diff --git a/controller/sync.go b/controller/sync.go index 9910254acf40a..bb39bfdaef7d3 100644 --- a/controller/sync.go +++ b/controller/sync.go @@ -174,7 +174,7 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha } } - proj, err := argo.GetAppProject(app, listersv1alpha1.NewAppProjectLister(m.projInformer.GetIndexer()), m.namespace, m.settingsMgr, m.db, context.TODO()) + proj, err := argo.GetAppProject(context.TODO(), app, listersv1alpha1.NewAppProjectLister(m.projInformer.GetIndexer()), m.namespace, m.settingsMgr, m.db) if err != nil { state.Phase = common.OperationError state.Message = fmt.Sprintf("Failed to load application project: %v", err) diff --git a/server/application/application.go b/server/application/application.go index 59d8a755e4d18..1e24c59ad333d 100644 --- a/server/application/application.go +++ b/server/application/application.go @@ -351,7 +351,7 @@ func (s *Server) Create(ctx context.Context, q *application.ApplicationCreateReq created, err := s.appclientset.ArgoprojV1alpha1().Applications(appNs).Create(ctx, a, metav1.CreateOptions{}) if err == nil { - s.logAppEvent(created, ctx, argo.EventReasonResourceCreated, "created application") + s.logAppEvent(ctx, created, argo.EventReasonResourceCreated, "created application") s.waitSync(created) return created, nil } @@ -384,7 +384,7 @@ func (s *Server) Create(ctx context.Context, q *application.ApplicationCreateReq if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceApplications, rbacpolicy.ActionUpdate, a.RBACName(s.ns)); err != nil { return nil, err } - updated, err := s.updateApp(existing, a, ctx, true) + updated, err := s.updateApp(ctx, existing, a, true) if err != nil { return nil, fmt.Errorf("error updating application: %w", err) } @@ -617,7 +617,7 @@ func (s *Server) GetManifestsWithFiles(stream application.ApplicationService_Get source := a.Spec.GetSource() - proj, err := argo.GetAppProject(a, applisters.NewAppProjectLister(s.projInformer.GetIndexer()), s.ns, s.settingsMgr, s.db, ctx) + proj, err := argo.GetAppProject(ctx, a, applisters.NewAppProjectLister(s.projInformer.GetIndexer()), s.ns, s.settingsMgr, s.db) if err != nil { return fmt.Errorf("error getting app project: %w", err) } @@ -888,7 +888,7 @@ func (s *Server) validateAndUpdateApp(ctx context.Context, newApp *v1alpha1.Appl return nil, fmt.Errorf("error validating and normalizing app: %w", err) } - a, err := s.updateApp(app, newApp, ctx, merge) + a, err := s.updateApp(ctx, app, newApp, merge) if err != nil { return nil, fmt.Errorf("error updating application: %w", err) } @@ -928,7 +928,7 @@ func (s *Server) waitSync(app *v1alpha1.Application) { logCtx.Warnf("waitSync failed: timed out") } -func (s *Server) updateApp(app *v1alpha1.Application, newApp *v1alpha1.Application, ctx context.Context, merge bool) (*v1alpha1.Application, error) { +func (s *Server) updateApp(ctx context.Context, app *v1alpha1.Application, newApp *v1alpha1.Application, merge bool) (*v1alpha1.Application, error) { for i := 0; i < 10; i++ { app.Spec = newApp.Spec if merge { @@ -943,7 +943,7 @@ func (s *Server) updateApp(app *v1alpha1.Application, newApp *v1alpha1.Applicati res, err := s.appclientset.ArgoprojV1alpha1().Applications(app.Namespace).Update(ctx, app, metav1.UpdateOptions{}) if err == nil { - s.logAppEvent(app, ctx, argo.EventReasonResourceUpdated, "updated application spec") + s.logAppEvent(ctx, app, argo.EventReasonResourceUpdated, "updated application spec") s.waitSync(res) return res, nil } @@ -1045,7 +1045,7 @@ func (s *Server) Patch(ctx context.Context, q *application.ApplicationPatchReque } func (s *Server) getAppProject(ctx context.Context, a *v1alpha1.Application, logCtx *log.Entry) (*v1alpha1.AppProject, error) { - proj, err := argo.GetAppProject(a, applisters.NewAppProjectLister(s.projInformer.GetIndexer()), s.ns, s.settingsMgr, s.db, ctx) + proj, err := argo.GetAppProject(ctx, a, applisters.NewAppProjectLister(s.projInformer.GetIndexer()), s.ns, s.settingsMgr, s.db) if err == nil { return proj, nil } @@ -1127,7 +1127,7 @@ func (s *Server) Delete(ctx context.Context, q *application.ApplicationDeleteReq if err != nil { return nil, fmt.Errorf("error deleting application: %w", err) } - s.logAppEvent(a, ctx, argo.EventReasonResourceDeleted, "deleted application") + s.logAppEvent(ctx, a, argo.EventReasonResourceDeleted, "deleted application") return &application.ApplicationResponse{}, nil } @@ -1445,7 +1445,7 @@ func (s *Server) PatchResource(ctx context.Context, q *application.ApplicationRe if err != nil { return nil, fmt.Errorf("erro marshaling manifest object: %w", err) } - s.logAppEvent(a, ctx, argo.EventReasonResourceUpdated, fmt.Sprintf("patched resource %s/%s '%s'", q.GetGroup(), q.GetKind(), q.GetResourceName())) + s.logAppEvent(ctx, a, argo.EventReasonResourceUpdated, fmt.Sprintf("patched resource %s/%s '%s'", q.GetGroup(), q.GetKind(), q.GetResourceName())) m := string(data) return &application.ApplicationResourceResponse{ Manifest: &m, @@ -1484,7 +1484,7 @@ func (s *Server) DeleteResource(ctx context.Context, q *application.ApplicationR if err != nil { return nil, fmt.Errorf("error deleting resource: %w", err) } - s.logAppEvent(a, ctx, argo.EventReasonResourceDeleted, fmt.Sprintf("deleted resource %s/%s '%s'", q.GetGroup(), q.GetKind(), q.GetResourceName())) + s.logAppEvent(ctx, a, argo.EventReasonResourceDeleted, fmt.Sprintf("deleted resource %s/%s '%s'", q.GetGroup(), q.GetKind(), q.GetResourceName())) return &application.ApplicationResponse{}, nil } @@ -2005,7 +2005,7 @@ func (s *Server) Sync(ctx context.Context, syncReq *application.ApplicationSyncR if syncReq.Manifests != nil { reason = fmt.Sprintf("initiated %ssync locally", partial) } - s.logAppEvent(a, ctx, argo.EventReasonOperationStarted, reason) + s.logAppEvent(ctx, a, argo.EventReasonOperationStarted, reason) return a, nil } @@ -2109,7 +2109,7 @@ func (s *Server) Rollback(ctx context.Context, rollbackReq *application.Applicat if err != nil { return nil, fmt.Errorf("error setting app operation: %w", err) } - s.logAppEvent(a, ctx, argo.EventReasonOperationStarted, fmt.Sprintf("initiated rollback to %d", rollbackReq.GetId())) + s.logAppEvent(ctx, a, argo.EventReasonOperationStarted, fmt.Sprintf("initiated rollback to %d", rollbackReq.GetId())) return a, nil } @@ -2306,7 +2306,7 @@ func (s *Server) TerminateOperation(ctx context.Context, termOpReq *application. updated, err := s.appclientset.ArgoprojV1alpha1().Applications(appNs).Update(ctx, a, metav1.UpdateOptions{}) if err == nil { s.waitSync(updated) - s.logAppEvent(a, ctx, argo.EventReasonResourceUpdated, "terminated running operation") + s.logAppEvent(ctx, a, argo.EventReasonResourceUpdated, "terminated running operation") return &application.OperationTerminateResponse{}, nil } if !apierrors.IsConflict(err) { @@ -2322,18 +2322,18 @@ func (s *Server) TerminateOperation(ctx context.Context, termOpReq *application. return nil, status.Errorf(codes.Internal, "Failed to terminate app. Too many conflicts") } -func (s *Server) logAppEvent(a *v1alpha1.Application, ctx context.Context, reason string, action string) { +func (s *Server) logAppEvent(ctx context.Context, a *v1alpha1.Application, reason string, action string) { eventInfo := argo.EventInfo{Type: corev1.EventTypeNormal, Reason: reason} user := session.Username(ctx) if user == "" { user = "Unknown user" } message := fmt.Sprintf("%s %s", user, action) - eventLabels := argo.GetAppEventLabels(a, applisters.NewAppProjectLister(s.projInformer.GetIndexer()), s.ns, s.settingsMgr, s.db, ctx) + eventLabels := argo.GetAppEventLabels(ctx, a, applisters.NewAppProjectLister(s.projInformer.GetIndexer()), s.ns, s.settingsMgr, s.db) s.auditLogger.LogAppEvent(a, eventInfo, message, user, eventLabels) } -func (s *Server) logResourceEvent(res *v1alpha1.ResourceNode, ctx context.Context, reason string, action string) { +func (s *Server) logResourceEvent(ctx context.Context, res *v1alpha1.ResourceNode, reason string, action string) { eventInfo := argo.EventInfo{Type: corev1.EventTypeNormal, Reason: reason} user := session.Username(ctx) if user == "" { @@ -2514,10 +2514,10 @@ func (s *Server) RunResourceAction(ctx context.Context, q *application.ResourceA } if res == nil { - s.logAppEvent(a, ctx, argo.EventReasonResourceActionRan, "ran action "+q.GetAction()) + s.logAppEvent(ctx, a, argo.EventReasonResourceActionRan, "ran action "+q.GetAction()) } else { - s.logAppEvent(a, ctx, argo.EventReasonResourceActionRan, fmt.Sprintf("ran action %s on resource %s/%s/%s", q.GetAction(), res.Group, res.Kind, res.Name)) - s.logResourceEvent(res, ctx, argo.EventReasonResourceActionRan, "ran action "+q.GetAction()) + s.logAppEvent(ctx, a, argo.EventReasonResourceActionRan, fmt.Sprintf("ran action %s on resource %s/%s/%s", q.GetAction(), res.Group, res.Kind, res.Name)) + s.logResourceEvent(ctx, res, argo.EventReasonResourceActionRan, "ran action "+q.GetAction()) } return &application.ApplicationResponse{}, nil } diff --git a/server/applicationset/applicationset.go b/server/applicationset/applicationset.go index 1b00fea5ebd3e..87d23df72a472 100644 --- a/server/applicationset/applicationset.go +++ b/server/applicationset/applicationset.go @@ -225,7 +225,7 @@ func (s *Server) Create(ctx context.Context, q *applicationset.ApplicationSetCre created, err := s.appclientset.ArgoprojV1alpha1().ApplicationSets(namespace).Create(ctx, appset, metav1.CreateOptions{}) if err == nil { - s.logAppSetEvent(created, ctx, argo.EventReasonResourceCreated, "created ApplicationSet") + s.logAppSetEvent(ctx, created, argo.EventReasonResourceCreated, "created ApplicationSet") s.waitSync(created) return created, nil } @@ -256,7 +256,7 @@ func (s *Server) Create(ctx context.Context, q *applicationset.ApplicationSetCre if err = s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceApplicationSets, rbacpolicy.ActionUpdate, appset.RBACName(s.ns)); err != nil { return nil, err } - updated, err := s.updateAppSet(existing, appset, ctx, true) + updated, err := s.updateAppSet(ctx, existing, appset, true) if err != nil { return nil, fmt.Errorf("error updating ApplicationSets: %w", err) } @@ -285,7 +285,7 @@ func (s *Server) generateApplicationSetApps(ctx context.Context, logEntry *log.E return apps, nil } -func (s *Server) updateAppSet(appset *v1alpha1.ApplicationSet, newAppset *v1alpha1.ApplicationSet, ctx context.Context, merge bool) (*v1alpha1.ApplicationSet, error) { +func (s *Server) updateAppSet(ctx context.Context, appset *v1alpha1.ApplicationSet, newAppset *v1alpha1.ApplicationSet, merge bool) (*v1alpha1.ApplicationSet, error) { if appset != nil && appset.Spec.Template.Spec.Project != newAppset.Spec.Template.Spec.Project { // When changing projects, caller must have applicationset create and update privileges in new project // NOTE: the update check was already verified in the caller to this function @@ -310,7 +310,7 @@ func (s *Server) updateAppSet(appset *v1alpha1.ApplicationSet, newAppset *v1alph res, err := s.appclientset.ArgoprojV1alpha1().ApplicationSets(s.ns).Update(ctx, appset, metav1.UpdateOptions{}) if err == nil { - s.logAppSetEvent(appset, ctx, argo.EventReasonResourceUpdated, "updated ApplicationSets spec") + s.logAppSetEvent(ctx, appset, argo.EventReasonResourceUpdated, "updated ApplicationSets spec") s.waitSync(res) return res, nil } @@ -345,7 +345,7 @@ func (s *Server) Delete(ctx context.Context, q *applicationset.ApplicationSetDel if err != nil { return nil, fmt.Errorf("error deleting ApplicationSets: %w", err) } - s.logAppSetEvent(appset, ctx, argo.EventReasonResourceDeleted, "deleted ApplicationSets") + s.logAppSetEvent(ctx, appset, argo.EventReasonResourceDeleted, "deleted ApplicationSets") return &applicationset.ApplicationSetResponse{}, nil } @@ -495,7 +495,7 @@ func (s *Server) waitSync(appset *v1alpha1.ApplicationSet) { logCtx.Warnf("waitSync failed: timed out") } -func (s *Server) logAppSetEvent(a *v1alpha1.ApplicationSet, ctx context.Context, reason string, action string) { +func (s *Server) logAppSetEvent(ctx context.Context, a *v1alpha1.ApplicationSet, reason string, action string) { eventInfo := argo.EventInfo{Type: corev1.EventTypeNormal, Reason: reason} user := session.Username(ctx) if user == "" { diff --git a/server/applicationset/applicationset_test.go b/server/applicationset/applicationset_test.go index 05c614eb45bd3..10ec15c00c7ab 100644 --- a/server/applicationset/applicationset_test.go +++ b/server/applicationset/applicationset_test.go @@ -528,7 +528,7 @@ func TestUpdateAppSet(t *testing.T) { t.Run("Update merge", func(t *testing.T) { appServer := newTestAppSetServer(appSet) - updated, err := appServer.updateAppSet(appSet, newAppSet, context.Background(), true) + updated, err := appServer.updateAppSet(context.Background(), appSet, newAppSet, true) require.NoError(t, err) assert.Equal(t, map[string]string{ @@ -544,7 +544,7 @@ func TestUpdateAppSet(t *testing.T) { t.Run("Update no merge", func(t *testing.T) { appServer := newTestAppSetServer(appSet) - updated, err := appServer.updateAppSet(appSet, newAppSet, context.Background(), false) + updated, err := appServer.updateAppSet(context.Background(), appSet, newAppSet, false) require.NoError(t, err) assert.Equal(t, map[string]string{ diff --git a/server/cluster/cluster.go b/server/cluster/cluster.go index c2419de6feffe..4d56ea31fded1 100644 --- a/server/cluster/cluster.go +++ b/server/cluster/cluster.go @@ -361,12 +361,12 @@ func (s *Server) Delete(ctx context.Context, q *cluster.ClusterQuery) (*cluster. return nil, common.PermissionDeniedAPIError } for _, server := range servers { - if err := enforceAndDelete(s, ctx, server, c.Project); err != nil { + if err := enforceAndDelete(ctx, s, server, c.Project); err != nil { return nil, fmt.Errorf("failed to enforce and delete cluster server: %w", err) } } } else { - if err := enforceAndDelete(s, ctx, q.Server, c.Project); err != nil { + if err := enforceAndDelete(ctx, s, q.Server, c.Project); err != nil { return nil, fmt.Errorf("failed to enforce and delete cluster server: %w", err) } } @@ -374,7 +374,7 @@ func (s *Server) Delete(ctx context.Context, q *cluster.ClusterQuery) (*cluster. return &cluster.ClusterResponse{}, nil } -func enforceAndDelete(s *Server, ctx context.Context, server, project string) error { +func enforceAndDelete(ctx context.Context, s *Server, server, project string) error { if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceClusters, rbacpolicy.ActionDelete, CreateClusterRBACObject(project, server)); err != nil { log.WithField("cluster", server).Warnf("encountered permissions issue while processing request: %v", err) return common.PermissionDeniedAPIError diff --git a/server/project/project.go b/server/project/project.go index ac0d0cf27f191..47db95122f607 100644 --- a/server/project/project.go +++ b/server/project/project.go @@ -157,7 +157,7 @@ func (s *Server) createToken(ctx context.Context, q *project.ProjectTokenCreateR if err != nil { return nil, err } - s.logEvent(prj, ctx, argo.EventReasonResourceCreated, "created token") + s.logEvent(ctx, prj, argo.EventReasonResourceCreated, "created token") return &project.ProjectTokenResponse{Token: jwtToken}, nil } @@ -241,7 +241,7 @@ func (s *Server) deleteToken(ctx context.Context, q *project.ProjectTokenDeleteR if err != nil { return nil, err } - s.logEvent(prj, ctx, argo.EventReasonResourceDeleted, "deleted token") + s.logEvent(ctx, prj, argo.EventReasonResourceDeleted, "deleted token") return &project.EmptyResponse{}, nil } @@ -279,7 +279,7 @@ func (s *Server) Create(ctx context.Context, q *project.ProjectCreateRequest) (* } } if err == nil { - s.logEvent(res, ctx, argo.EventReasonResourceCreated, "created project") + s.logEvent(ctx, res, argo.EventReasonResourceCreated, "created project") } return res, err } @@ -305,7 +305,7 @@ func (s *Server) GetDetailedProject(ctx context.Context, q *project.ProjectQuery if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionGet, q.Name); err != nil { return nil, err } - proj, repositories, clusters, err := argo.GetAppProjectWithScopedResources(q.Name, listersv1alpha1.NewAppProjectLister(s.projInformer.GetIndexer()), s.ns, s.settingsMgr, s.db, ctx) + proj, repositories, clusters, err := argo.GetAppProjectWithScopedResources(ctx, q.Name, listersv1alpha1.NewAppProjectLister(s.projInformer.GetIndexer()), s.ns, s.settingsMgr, s.db) if err != nil { return nil, err } @@ -439,7 +439,7 @@ func (s *Server) Update(ctx context.Context, q *project.ProjectUpdateRequest) (* res, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Update(ctx, q.Project, metav1.UpdateOptions{}) if err == nil { - s.logEvent(res, ctx, argo.EventReasonResourceUpdated, "updated project") + s.logEvent(ctx, res, argo.EventReasonResourceUpdated, "updated project") } return res, err } @@ -471,7 +471,7 @@ func (s *Server) Delete(ctx context.Context, q *project.ProjectQuery) (*project. } err = s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Delete(ctx, q.Name, metav1.DeleteOptions{}) if err == nil { - s.logEvent(p, ctx, argo.EventReasonResourceDeleted, "deleted project") + s.logEvent(ctx, p, argo.EventReasonResourceDeleted, "deleted project") } return &project.EmptyResponse{}, err } @@ -492,7 +492,7 @@ func (s *Server) ListEvents(ctx context.Context, q *project.ProjectQuery) (*core return s.kubeclientset.CoreV1().Events(s.ns).List(ctx, metav1.ListOptions{FieldSelector: fieldSelector}) } -func (s *Server) logEvent(a *v1alpha1.AppProject, ctx context.Context, reason string, action string) { +func (s *Server) logEvent(ctx context.Context, a *v1alpha1.AppProject, reason string, action string) { eventInfo := argo.EventInfo{Type: corev1.EventTypeNormal, Reason: reason} user := session.Username(ctx) if user == "" { diff --git a/server/repository/repository.go b/server/repository/repository.go index b2bee86f19fdd..6906a0c913002 100644 --- a/server/repository/repository.go +++ b/server/repository/repository.go @@ -752,7 +752,7 @@ func (s *Server) testRepo(ctx context.Context, repo *v1alpha1.Repository) error } func (s *Server) isRepoPermittedInProject(ctx context.Context, repo string, projName string) error { - proj, err := argo.GetAppProjectByName(projName, applisters.NewAppProjectLister(s.projLister.GetIndexer()), s.namespace, s.settings, s.db, ctx) + proj, err := argo.GetAppProjectByName(ctx, projName, applisters.NewAppProjectLister(s.projLister.GetIndexer()), s.namespace, s.settings, s.db) if err != nil { return err } diff --git a/server/server.go b/server/server.go index b9c0e412dab2c..412a48297258f 100644 --- a/server/server.go +++ b/server/server.go @@ -1196,19 +1196,19 @@ func (server *ArgoCDServer) newHTTPServer(ctx context.Context, port int, grpcWeb registerExtensions(mux, server, metricsReg) } - mustRegisterGWHandler(versionpkg.RegisterVersionServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(clusterpkg.RegisterClusterServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(applicationpkg.RegisterApplicationServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(applicationsetpkg.RegisterApplicationSetServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(notificationpkg.RegisterNotificationServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(repositorypkg.RegisterRepositoryServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(repocredspkg.RegisterRepoCredsServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(sessionpkg.RegisterSessionServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(settingspkg.RegisterSettingsServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(projectpkg.RegisterProjectServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(accountpkg.RegisterAccountServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(certificatepkg.RegisterCertificateServiceHandler, ctx, gwmux, conn) - mustRegisterGWHandler(gpgkeypkg.RegisterGPGKeyServiceHandler, ctx, gwmux, conn) + mustRegisterGWHandler(ctx, versionpkg.RegisterVersionServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, clusterpkg.RegisterClusterServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, applicationpkg.RegisterApplicationServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, applicationsetpkg.RegisterApplicationSetServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, notificationpkg.RegisterNotificationServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, repositorypkg.RegisterRepositoryServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, repocredspkg.RegisterRepoCredsServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, sessionpkg.RegisterSessionServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, settingspkg.RegisterSettingsServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, projectpkg.RegisterProjectServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, accountpkg.RegisterAccountServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, certificatepkg.RegisterCertificateServiceHandler, gwmux, conn) + mustRegisterGWHandler(ctx, gpgkeypkg.RegisterGPGKeyServiceHandler, gwmux, conn) // Swagger UI swagger.ServeSwaggerUI(mux, assets.SwaggerJSON, "/swagger-ui", server.RootPath) @@ -1458,7 +1458,7 @@ func isMainJsBundle(url *url.URL) bool { type registerFunc func(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error // mustRegisterGWHandler is a convenience function to register a gateway handler -func mustRegisterGWHandler(register registerFunc, ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) { +func mustRegisterGWHandler(ctx context.Context, register registerFunc, mux *runtime.ServeMux, conn *grpc.ClientConn) { err := register(ctx, mux, conn) if err != nil { panic(err) diff --git a/util/argo/argo.go b/util/argo/argo.go index 7ff14f76d235f..810b9a5decaee 100644 --- a/util/argo/argo.go +++ b/util/argo/argo.go @@ -692,7 +692,7 @@ func APIResourcesToStrings(resources []kube.APIResourceInfo, includeKinds bool) } // GetAppProjectWithScopedResources returns a project from an application with scoped resources -func GetAppProjectWithScopedResources(name string, projLister applicationsv1.AppProjectLister, ns string, settingsManager *settings.SettingsManager, db db.ArgoDB, ctx context.Context) (*argoappv1.AppProject, argoappv1.Repositories, []*argoappv1.Cluster, error) { +func GetAppProjectWithScopedResources(ctx context.Context, name string, projLister applicationsv1.AppProjectLister, ns string, settingsManager *settings.SettingsManager, db db.ArgoDB) (*argoappv1.AppProject, argoappv1.Repositories, []*argoappv1.Cluster, error) { projOrig, err := projLister.AppProjects(ns).Get(name) if err != nil { return nil, nil, nil, fmt.Errorf("error getting app project %q: %w", name, err) @@ -715,7 +715,7 @@ func GetAppProjectWithScopedResources(name string, projLister applicationsv1.App } // GetAppProjectByName returns a project from an application based on name -func GetAppProjectByName(name string, projLister applicationsv1.AppProjectLister, ns string, settingsManager *settings.SettingsManager, db db.ArgoDB, ctx context.Context) (*argoappv1.AppProject, error) { +func GetAppProjectByName(ctx context.Context, name string, projLister applicationsv1.AppProjectLister, ns string, settingsManager *settings.SettingsManager, db db.ArgoDB) (*argoappv1.AppProject, error) { projOrig, err := projLister.AppProjects(ns).Get(name) if err != nil { return nil, fmt.Errorf("error getting app project %q: %w", name, err) @@ -746,8 +746,8 @@ func GetAppProjectByName(name string, projLister applicationsv1.AppProjectLister // GetAppProject returns a project from an application. It will also ensure // that the application is allowed to use the project. -func GetAppProject(app *argoappv1.Application, projLister applicationsv1.AppProjectLister, ns string, settingsManager *settings.SettingsManager, db db.ArgoDB, ctx context.Context) (*argoappv1.AppProject, error) { - proj, err := GetAppProjectByName(app.Spec.GetProject(), projLister, ns, settingsManager, db, ctx) +func GetAppProject(ctx context.Context, app *argoappv1.Application, projLister applicationsv1.AppProjectLister, ns string, settingsManager *settings.SettingsManager, db db.ArgoDB) (*argoappv1.AppProject, error) { + proj, err := GetAppProjectByName(ctx, app.Spec.GetProject(), projLister, ns, settingsManager, db) if err != nil { return nil, err } @@ -1214,7 +1214,7 @@ func IsValidContainerName(name string) bool { // If matched, the corresponding labels are returned to be added to the generated event. In case of a conflict // between labels on the Application and AppProject, the Application label values are prioritized and added to the event. // Furthermore, labels specified in `resource.excludeEventLabelKeys` in argocd-cm are removed from the event labels, if they were included. -func GetAppEventLabels(app *argoappv1.Application, projLister applicationsv1.AppProjectLister, ns string, settingsManager *settings.SettingsManager, db db.ArgoDB, ctx context.Context) map[string]string { +func GetAppEventLabels(ctx context.Context, app *argoappv1.Application, projLister applicationsv1.AppProjectLister, ns string, settingsManager *settings.SettingsManager, db db.ArgoDB) map[string]string { eventLabels := make(map[string]string) // Get all app & app-project labels @@ -1222,7 +1222,7 @@ func GetAppEventLabels(app *argoappv1.Application, projLister applicationsv1.App if labels == nil { labels = make(map[string]string) } - proj, err := GetAppProject(app, projLister, ns, settingsManager, db, ctx) + proj, err := GetAppProject(ctx, app, projLister, ns, settingsManager, db) if err == nil { for k, v := range proj.Labels { _, found := labels[k] diff --git a/util/argo/argo_test.go b/util/argo/argo_test.go index db17a641f8745..c45cab489cd9b 100644 --- a/util/argo/argo_test.go +++ b/util/argo/argo_test.go @@ -81,7 +81,7 @@ func TestGetAppProjectWithNoProjDefined(t *testing.T) { kubeClient := fake.NewClientset(&cm) settingsMgr := settings.NewSettingsManager(context.Background(), kubeClient, test.FakeArgoCDNamespace) argoDB := db.NewDB("default", settingsMgr, kubeClient) - proj, err := GetAppProject(&testApp, applisters.NewAppProjectLister(informer.GetIndexer()), namespace, settingsMgr, argoDB, ctx) + proj, err := GetAppProject(ctx, &testApp, applisters.NewAppProjectLister(informer.GetIndexer()), namespace, settingsMgr, argoDB) require.NoError(t, err) assert.Equal(t, proj.Name, projName) } @@ -1699,7 +1699,7 @@ func TestGetAppEventLabels(t *testing.T) { settingsMgr := settings.NewSettingsManager(context.Background(), kubeClient, test.FakeArgoCDNamespace) argoDB := db.NewDB("default", settingsMgr, kubeClient) - eventLabels := GetAppEventLabels(&app, applisters.NewAppProjectLister(informer.GetIndexer()), test.FakeArgoCDNamespace, settingsMgr, argoDB, ctx) + eventLabels := GetAppEventLabels(ctx, &app, applisters.NewAppProjectLister(informer.GetIndexer()), test.FakeArgoCDNamespace, settingsMgr, argoDB) assert.Equal(t, len(tt.expectedEventLabels), len(eventLabels)) for ek, ev := range tt.expectedEventLabels { v, found := eventLabels[ek] diff --git a/util/grpc/logging.go b/util/grpc/logging.go index 6708092cf3602..8111cf3c8bc8a 100644 --- a/util/grpc/logging.go +++ b/util/grpc/logging.go @@ -15,7 +15,7 @@ import ( "google.golang.org/grpc" ) -func logRequest(entry *logrus.Entry, info string, pbMsg any, ctx context.Context, logClaims bool) { +func logRequest(ctx context.Context, entry *logrus.Entry, info string, pbMsg any, logClaims bool) { if logClaims { claims := ctx.Value("claims") mapClaims, ok := claims.(jwt.MapClaims) @@ -65,7 +65,7 @@ func (l *loggingServerStream) SendMsg(m any) 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) + logRequest(l.ServerStream.Context(), l.entry, l.info, m, l.logClaims) } return err } @@ -87,7 +87,7 @@ func PayloadUnaryServerInterceptor(entry *logrus.Entry, logClaims bool, decider return handler(ctx, req) } logEntry := entry.WithFields(ctx_logrus.Extract(ctx).Data) - logRequest(logEntry, "received unary call "+info.FullMethod, req, ctx, logClaims) + logRequest(ctx, logEntry, "received unary call "+info.FullMethod, req, logClaims) resp, err := handler(ctx, req) return resp, err } diff --git a/util/kube/util.go b/util/kube/util.go index 97ae94a6bf1b6..b5e4c2498fff7 100644 --- a/util/kube/util.go +++ b/util/kube/util.go @@ -21,7 +21,7 @@ type kubeUtil struct { type updateFn func(s *corev1.Secret, new bool) error // NewKubeUtil NewUtil returns a new kubeUtil receiver -func NewKubeUtil(client kubernetes.Interface, ctx context.Context) *kubeUtil { +func NewKubeUtil(ctx context.Context, client kubernetes.Interface) *kubeUtil { return &kubeUtil{client: client, ctx: ctx} } diff --git a/util/kube/util_test.go b/util/kube/util_test.go index 7ced9b6ef745a..1145b77eda333 100644 --- a/util/kube/util_test.go +++ b/util/kube/util_test.go @@ -50,7 +50,7 @@ func Test_CreateOrUpdateSecretField(t *testing.T) { client := fake.NewClientset(secret) t.Run("Change field in existing secret", func(t *testing.T) { - ku := NewKubeUtil(client, context.TODO()) + ku := NewKubeUtil(context.TODO(), client) err := ku.CreateOrUpdateSecretField("test", "test-secret", "password", "barfoo") require.NoError(t, err) s, err := getSecret(client, "test", "test-secret") @@ -65,7 +65,7 @@ func Test_CreateOrUpdateSecretField(t *testing.T) { }) t.Run("Change field in non-existing secret", func(t *testing.T) { - ku := NewKubeUtil(client, context.TODO()) + ku := NewKubeUtil(context.TODO(), client) err := ku.CreateOrUpdateSecretField("test", "nonexist-secret", "password", "foobaz") require.NoError(t, err) s, err := getSecret(client, "test", "nonexist-secret") @@ -80,7 +80,7 @@ func Test_CreateOrUpdateSecretField(t *testing.T) { }) t.Run("Change field in existing secret with labels", func(t *testing.T) { - ku := NewKubeUtil(client, context.TODO()).WithAnnotations(annotations).WithLabels(labels) + ku := NewKubeUtil(context.TODO(), client).WithAnnotations(annotations).WithLabels(labels) err := ku.CreateOrUpdateSecretField("test", "test-secret", "password", "barfoo") require.NoError(t, err) s, err := getSecret(client, "test", "test-secret") @@ -95,7 +95,7 @@ func Test_CreateOrUpdateSecretField(t *testing.T) { }) t.Run("Change field in existing secret with labels", func(t *testing.T) { - ku := NewKubeUtil(client, context.TODO()).WithAnnotations(annotations).WithLabels(labels) + ku := NewKubeUtil(context.TODO(), client).WithAnnotations(annotations).WithLabels(labels) err := ku.CreateOrUpdateSecretField("test", "nonexisting-secret", "password", "barfoo") require.NoError(t, err) s, err := getSecret(client, "test", "nonexisting-secret") @@ -136,7 +136,7 @@ func Test_CreateOrUpdateSecretData(t *testing.T) { client := fake.NewClientset(secret) t.Run("Change data in existing secret with merge", func(t *testing.T) { - ku := NewKubeUtil(client, context.TODO()) + ku := NewKubeUtil(context.TODO(), client) err := ku.CreateOrUpdateSecretData("test", "test-secret", data1, true) require.NoError(t, err) s, err := getSecret(client, "test", "test-secret") @@ -147,7 +147,7 @@ func Test_CreateOrUpdateSecretData(t *testing.T) { }) t.Run("Change data in non-existing secret with merge", func(t *testing.T) { - ku := NewKubeUtil(client, context.TODO()) + ku := NewKubeUtil(context.TODO(), client) err := ku.CreateOrUpdateSecretData("test", "nonexist-secret", data1, true) require.NoError(t, err) s, err := getSecret(client, "test", "nonexist-secret") @@ -157,7 +157,7 @@ func Test_CreateOrUpdateSecretData(t *testing.T) { }) t.Run("Change data in existing secret without merge", func(t *testing.T) { - ku := NewKubeUtil(client, context.TODO()) + ku := NewKubeUtil(context.TODO(), client) err := ku.CreateOrUpdateSecretData("test", "test-secret", data2, false) require.NoError(t, err) s, err := getSecret(client, "test", "test-secret") @@ -169,7 +169,7 @@ func Test_CreateOrUpdateSecretData(t *testing.T) { }) t.Run("Change data in non-existing secret without merge", func(t *testing.T) { - ku := NewKubeUtil(client, context.TODO()) + ku := NewKubeUtil(context.TODO(), client) err := ku.CreateOrUpdateSecretData("test", "nonexist-secret", data2, false) require.NoError(t, err) s, err := getSecret(client, "test", "nonexist-secret") diff --git a/util/settings/settings.go b/util/settings/settings.go index 29ec6bfc2874c..0fec981957713 100644 --- a/util/settings/settings.go +++ b/util/settings/settings.go @@ -2176,7 +2176,7 @@ func (mgr *SettingsManager) InitializeSettings(insecureModeEnabled bool) (*ArgoC if err != nil { return err } - ku := kube.NewKubeUtil(mgr.clientset, mgr.ctx) + ku := kube.NewKubeUtil(mgr.ctx, mgr.clientset) err = ku.CreateOrUpdateSecretField(mgr.namespace, initialPasswordSecretName, initialPasswordSecretField, initialPassword) if err != nil { return err From 53bc19b5f20d56613c57c664f462ad2a484d9424 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Tue, 7 Jan 2025 16:12:56 +0100 Subject: [PATCH 34/41] chore: enable unused-parameter from revive (#21365) * chore: enable unused-parameter from revive Signed-off-by: Matthieu MOREL * apply recommandations Signed-off-by: Matthieu MOREL --------- Signed-off-by: Matthieu MOREL --- .golangci.yaml | 2 +- .../applicationset_controller_test.go | 42 ++++++------ .../controllers/requeue_after_test.go | 2 +- applicationset/generators/list.go | 2 +- applicationset/generators/plugin.go | 2 +- applicationset/generators/pull_request.go | 6 +- applicationset/generators/scm_provider.go | 8 +-- applicationset/metrics/fake.go | 3 +- .../services/internal/http/client.go | 6 +- .../services/internal/http/client_test.go | 10 ++- .../services/plugin/plugin_service.go | 6 +- .../services/plugin/plugin_service_test.go | 2 +- .../services/pull_request/azure_devops.go | 2 +- .../pull_request/bitbucket_cloud_test.go | 2 +- .../pull_request/bitbucket_server_test.go | 2 +- applicationset/services/pull_request/fake.go | 2 +- applicationset/services/pull_request/gitea.go | 3 +- .../services/pull_request/gitea_test.go | 2 +- .../services/pull_request/gitlab.go | 4 +- .../services/pull_request/gitlab_test.go | 14 ++-- applicationset/services/repo_service_test.go | 18 ++--- .../services/scm_provider/azure_devops.go | 4 +- .../services/scm_provider/bitbucket_cloud.go | 8 +-- .../scm_provider/bitbucket_cloud_test.go | 4 +- .../scm_provider/bitbucket_server_test.go | 2 +- applicationset/services/scm_provider/gitea.go | 8 +-- .../services/scm_provider/gitea_test.go | 4 +- .../services/scm_provider/gitlab.go | 4 +- .../services/scm_provider/gitlab_test.go | 8 +-- applicationset/utils/applicationset_lister.go | 6 +- applicationset/utils/selector.go | 4 +- applicationset/utils/utils_test.go | 2 +- applicationset/webhook/webhook_test.go | 6 +- .../commands/argocd_application_controller.go | 2 +- .../commands/applicationset_controller.go | 2 +- .../commands/argocd_cmp_server.go | 2 +- .../commands/argocd_commit_server.go | 2 +- cmd/argocd-dex/commands/argocd_dex.go | 4 +- .../commands/argocd_git_ask_pass.go | 2 +- cmd/argocd-k8s-auth/commands/aws.go | 2 +- cmd/argocd-k8s-auth/commands/aws_test.go | 6 +- cmd/argocd-k8s-auth/commands/azure.go | 2 +- cmd/argocd-k8s-auth/commands/gcp.go | 2 +- .../commands/controller.go | 2 +- .../commands/argocd_repo_server.go | 2 +- cmd/argocd-server/commands/argocd_server.go | 2 +- cmd/argocd/commands/account.go | 6 +- cmd/argocd/commands/admin/app.go | 8 +-- cmd/argocd/commands/admin/app_test.go | 2 +- cmd/argocd/commands/admin/backup.go | 2 +- cmd/argocd/commands/admin/cluster.go | 8 +-- cmd/argocd/commands/admin/dashboard.go | 2 +- cmd/argocd/commands/admin/initial_password.go | 2 +- cmd/argocd/commands/admin/project.go | 2 +- .../commands/admin/redis_initial_password.go | 2 +- cmd/argocd/commands/admin/settings.go | 4 +- cmd/argocd/commands/app.go | 2 +- cmd/argocd/commands/app_test.go | 66 +++++++++---------- cmd/argocd/commands/applicationset.go | 2 +- cmd/argocd/commands/bcrypt.go | 2 +- cmd/argocd/commands/cert.go | 4 +- cmd/argocd/commands/cluster.go | 2 +- cmd/argocd/commands/cluster_test.go | 2 +- cmd/argocd/commands/configure.go | 2 +- cmd/argocd/commands/gpg.go | 4 +- cmd/argocd/commands/project.go | 2 +- cmd/argocd/commands/repo.go | 2 +- cmd/argocd/commands/repocreds.go | 2 +- cmd/argocd/commands/version.go | 2 +- cmpserver/plugin/plugin.go | 2 +- commitserver/commit/commit.go | 2 +- controller/appcontroller.go | 6 +- controller/appcontroller_test.go | 32 ++++----- controller/cache/cache.go | 2 +- controller/cache/cache_test.go | 10 +-- controller/clusterinfoupdater_test.go | 6 +- controller/metrics/metrics_test.go | 6 +- controller/sharding/sharding.go | 4 +- controller/state.go | 6 +- controller/state_test.go | 26 ++++---- controller/sync.go | 9 +-- hack/dev-mounter/main.go | 4 +- hack/gen-catalog/main.go | 4 +- hack/gen-resources/cmd/commands/cmd.go | 4 +- hack/known_types/main.go | 2 +- pkg/apiclient/grpcproxy.go | 2 +- .../v1alpha1/applicationset_types.go | 2 +- pkg/apis/application/v1alpha1/types_test.go | 4 +- reposerver/cache/cache_test.go | 2 +- reposerver/repository/repository.go | 14 ++-- reposerver/repository/repository_test.go | 52 +++++++-------- server/account/account.go | 2 +- server/account/account_test.go | 34 +++++----- server/application/application_test.go | 38 +++++------ server/application/logs_test.go | 2 +- server/application/websocket.go | 2 +- server/application/websocket_test.go | 4 +- server/applicationset/applicationset_test.go | 2 +- server/cluster/cluster_test.go | 14 ++-- server/extension/extension_test.go | 4 +- server/gpgkey/gpgkey.go | 2 +- server/notification/notification.go | 6 +- server/project/project.go | 2 +- server/project/project_test.go | 4 +- server/repocreds/repocreds.go | 4 +- server/repository/repository_test.go | 38 +++++------ server/server.go | 10 +-- server/server_test.go | 4 +- server/session/session.go | 6 +- server/settings/settings.go | 4 +- server/version/version.go | 2 +- test/e2e/accounts_test.go | 12 ++-- test/e2e/admin_test.go | 2 +- test/e2e/app_deletion_test.go | 2 +- test/e2e/app_management_ns_test.go | 50 +++++++------- test/e2e/app_management_test.go | 18 ++--- test/e2e/app_multiple_sources_test.go | 8 +-- test/e2e/app_sync_options_test.go | 2 +- test/e2e/cluster_test.go | 18 ++--- test/e2e/custom_tool_test.go | 30 ++++----- test/e2e/deployment_test.go | 6 +- test/e2e/fixture/app/expectation.go | 6 +- .../fixture/applicationsets/expectation.go | 2 +- test/e2e/fixture/cluster/actions.go | 4 +- test/e2e/git_submodule_test.go | 6 +- test/e2e/helm_test.go | 14 ++-- test/e2e/jsonnet_test.go | 4 +- test/e2e/kustomize_test.go | 12 ++-- test/e2e/scoped_repository_test.go | 28 ++++---- test/manifests_test.go | 2 +- test/testdata.go | 4 +- util/argo/argo.go | 4 +- util/argo/argo_test.go | 8 +-- util/argo/resource_tracking.go | 4 +- util/cache/inmemory.go | 4 +- util/cache/redis.go | 2 +- util/cache/redis_hook.go | 2 +- util/cli/cli.go | 2 +- util/clusterauth/clusterauth_test.go | 2 +- util/config/reader_test.go | 2 +- util/db/certificate.go | 4 +- util/db/cluster.go | 6 +- util/db/cluster_norace_test.go | 2 +- util/db/cluster_test.go | 2 +- util/db/db.go | 4 +- util/db/gpgkeys.go | 2 +- util/db/mocks/ArgoDB.go | 36 +++++----- util/db/repository.go | 4 +- util/db/repository_legacy.go | 26 ++++---- util/db/repository_secrets.go | 14 ++-- util/db/repository_secrets_test.go | 6 +- util/db/repository_test.go | 2 +- util/dex/dex.go | 2 +- util/dex/dex_test.go | 6 +- util/git/client.go | 4 +- util/git/creds.go | 14 ++-- util/git/creds_test.go | 2 +- util/gpg/gpg.go | 2 +- util/grpc/errors.go | 8 +-- util/grpc/grpc.go | 4 +- util/grpc/logging_test.go | 8 +-- util/grpc/sanitizer.go | 2 +- util/grpc/sanitizer_test.go | 2 +- util/grpc/useragent.go | 4 +- util/healthz/healthz_test.go | 2 +- util/helm/cmd.go | 2 +- util/kube/failureretrywrapper.go | 2 +- util/kube/util.go | 2 +- util/lua/custom_actions_test.go | 2 +- util/lua/health_test.go | 2 +- .../expression/strings/strings_test.go | 2 +- util/oidc/oidc_test.go | 10 +-- util/rbac/rbac.go | 8 +-- util/rbac/rbac_norace_test.go | 2 +- util/rbac/rbac_test.go | 8 +-- util/session/sessionmanager_test.go | 4 +- util/settings/settings.go | 6 +- util/swagger/swagger.go | 2 +- util/test/testutil.go | 4 +- 179 files changed, 613 insertions(+), 620 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index c952308576aee..2f7c742c1c186 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -154,7 +154,7 @@ linters-settings: disabled: false # Functions or methods with unused parameters can be a symptom of an unfinished refactoring or a bug. - name: unused-parameter - disabled: true + disabled: false # Since Go 1.18, interface{} has an alias: any. This rule proposes to replace instances of interface{} with any. - name: use-any disabled: false diff --git a/applicationset/controllers/applicationset_controller_test.go b/applicationset/controllers/applicationset_controller_test.go index 480222b8dd1f2..efa17b22170da 100644 --- a/applicationset/controllers/applicationset_controller_test.go +++ b/applicationset/controllers/applicationset_controller_test.go @@ -1055,7 +1055,7 @@ func TestCreateOrUpdateInCluster(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(initObjs...).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, @@ -1163,7 +1163,7 @@ func TestRemoveFinalizerOnInvalidDestination_FinalizerTypes(t *testing.T) { objects := append([]runtime.Object{}, secret) kubeclientset := kubefake.NewSimpleClientset(objects...) - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -1322,7 +1322,7 @@ func TestRemoveFinalizerOnInvalidDestination_DestinationTypes(t *testing.T) { objects := append([]runtime.Object{}, secret) kubeclientset := kubefake.NewSimpleClientset(objects...) - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -1409,7 +1409,7 @@ func TestRemoveOwnerReferencesOnDeleteAppSet(t *testing.T) { initObjs := []crtclient.Object{&app, &appSet} client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(initObjs...).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, @@ -1608,7 +1608,7 @@ func TestCreateApplications(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(initObjs...).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, @@ -1750,7 +1750,7 @@ func TestDeleteInCluster(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(initObjs...).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, @@ -1796,7 +1796,7 @@ func TestGetMinRequeueAfter(t *testing.T) { require.NoError(t, err) client := fake.NewClientBuilder().WithScheme(scheme).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() generator := v1alpha1.ApplicationSetGenerator{ List: &v1alpha1.ListGenerator{}, @@ -1867,7 +1867,7 @@ func TestRequeueGeneratorFails(t *testing.T) { generatorMock.On("GenerateParams", &generator, mock.AnythingOfType("*v1alpha1.ApplicationSet"), mock.Anything). Return([]map[string]any{}, errors.New("Simulated error generating params that could be related to an external service/API call")) - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, @@ -1919,7 +1919,7 @@ func TestValidateGeneratedApplications(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(myProject).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() // Test a subset of the validations that 'validateGeneratedApplications' performs for _, cc := range []struct { @@ -2123,7 +2123,7 @@ func TestReconcilerValidationProjectErrorBehaviour(t *testing.T) { kubeclientset := kubefake.NewSimpleClientset() client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appSet, &project).WithStatusSubresource(&appSet).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2322,7 +2322,7 @@ func TestSetApplicationSetStatusCondition(t *testing.T) { for _, testCase := range testCases { client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&testCase.appset).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).WithStatusSubresource(&testCase.appset).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2411,7 +2411,7 @@ func applicationsUpdateSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp kubeclientset := kubefake.NewSimpleClientset(objects...) client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appSet, &defaultProject).WithStatusSubresource(&appSet).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2587,7 +2587,7 @@ func applicationsDeleteSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp kubeclientset := kubefake.NewSimpleClientset(objects...) client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appSet, &defaultProject).WithStatusSubresource(&appSet).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2776,7 +2776,7 @@ func TestPolicies(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appSet, &defaultProject).WithStatusSubresource(&appSet).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2935,7 +2935,7 @@ func TestSetApplicationSetApplicationStatus(t *testing.T) { } { t.Run(cc.name, func(t *testing.T) { client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&cc.appSet).WithStatusSubresource(&cc.appSet).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2966,7 +2966,7 @@ func TestBuildAppDependencyList(t *testing.T) { require.NoError(t, err) client := fake.NewClientBuilder().WithScheme(scheme).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() for _, cc := range []struct { name string @@ -3722,7 +3722,7 @@ func TestBuildAppSyncMap(t *testing.T) { require.NoError(t, err) client := fake.NewClientBuilder().WithScheme(scheme).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() for _, cc := range []struct { name string @@ -5312,7 +5312,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) { kubeclientset := kubefake.NewSimpleClientset([]runtime.Object{}...) client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&cc.appSet).WithStatusSubresource(&cc.appSet).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -6062,7 +6062,7 @@ func TestUpdateApplicationSetApplicationStatusProgress(t *testing.T) { kubeclientset := kubefake.NewSimpleClientset([]runtime.Object{}...) client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&cc.appSet).WithStatusSubresource(&cc.appSet).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -6274,7 +6274,7 @@ func TestUpdateResourceStatus(t *testing.T) { kubeclientset := kubefake.NewSimpleClientset([]runtime.Object{}...) client := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&cc.appSet).WithObjects(&cc.appSet).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -6365,7 +6365,7 @@ func TestResourceStatusAreOrdered(t *testing.T) { kubeclientset := kubefake.NewSimpleClientset([]runtime.Object{}...) client := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&cc.appSet).WithObjects(&cc.appSet).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) diff --git a/applicationset/controllers/requeue_after_test.go b/applicationset/controllers/requeue_after_test.go index 39b3f580aee46..6d7b4ef925e83 100644 --- a/applicationset/controllers/requeue_after_test.go +++ b/applicationset/controllers/requeue_after_test.go @@ -90,7 +90,7 @@ func TestRequeueAfter(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, Scheme: scheme, diff --git a/applicationset/generators/list.go b/applicationset/generators/list.go index 7ef4c73ce2a0d..b3cb0ffae31bc 100644 --- a/applicationset/generators/list.go +++ b/applicationset/generators/list.go @@ -21,7 +21,7 @@ func NewListGenerator() Generator { return g } -func (g *ListGenerator) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) time.Duration { +func (g *ListGenerator) GetRequeueAfter(_ *argoprojiov1alpha1.ApplicationSetGenerator) time.Duration { return NoRequeueAfter } diff --git a/applicationset/generators/plugin.go b/applicationset/generators/plugin.go index 8525474ebb46e..bdf66f76eaef2 100644 --- a/applicationset/generators/plugin.go +++ b/applicationset/generators/plugin.go @@ -106,7 +106,7 @@ func (g *PluginGenerator) getPluginFromGenerator(ctx context.Context, appSetName } } - pluginClient, err := plugin.NewPluginService(ctx, appSetName, cm["baseUrl"], token, requestTimeout) + pluginClient, err := plugin.NewPluginService(appSetName, cm["baseUrl"], token, requestTimeout) if err != nil { return nil, fmt.Errorf("error initializing plugin client: %w", err) } diff --git a/applicationset/generators/pull_request.go b/applicationset/generators/pull_request.go index fb9c46ee0f9ba..ffc0b7ddf6145 100644 --- a/applicationset/generators/pull_request.go +++ b/applicationset/generators/pull_request.go @@ -144,7 +144,7 @@ func (g *PullRequestGenerator) selectServiceProvider(ctx context.Context, genera if err != nil { return nil, fmt.Errorf("error fetching Secret token: %w", err) } - return pullrequest.NewGitLabService(ctx, token, providerConfig.API, providerConfig.Project, providerConfig.Labels, providerConfig.PullRequestState, g.scmRootCAPath, providerConfig.Insecure, caCerts) + return pullrequest.NewGitLabService(token, providerConfig.API, providerConfig.Project, providerConfig.Labels, providerConfig.PullRequestState, g.scmRootCAPath, providerConfig.Insecure, caCerts) } if generatorConfig.Gitea != nil { providerConfig := generatorConfig.Gitea @@ -152,7 +152,7 @@ func (g *PullRequestGenerator) selectServiceProvider(ctx context.Context, genera if err != nil { return nil, fmt.Errorf("error fetching Secret token: %w", err) } - return pullrequest.NewGiteaService(ctx, token, providerConfig.API, providerConfig.Owner, providerConfig.Repo, providerConfig.Insecure) + return pullrequest.NewGiteaService(token, providerConfig.API, providerConfig.Owner, providerConfig.Repo, providerConfig.Insecure) } if generatorConfig.BitbucketServer != nil { providerConfig := generatorConfig.BitbucketServer @@ -204,7 +204,7 @@ func (g *PullRequestGenerator) selectServiceProvider(ctx context.Context, genera if err != nil { return nil, fmt.Errorf("error fetching Secret token: %w", err) } - return pullrequest.NewAzureDevOpsService(ctx, token, providerConfig.API, providerConfig.Organization, providerConfig.Project, providerConfig.Repo, providerConfig.Labels) + return pullrequest.NewAzureDevOpsService(token, providerConfig.API, providerConfig.Organization, providerConfig.Project, providerConfig.Repo, providerConfig.Labels) } return nil, errors.New("no Pull Request provider implementation configured") } diff --git a/applicationset/generators/scm_provider.go b/applicationset/generators/scm_provider.go index 3bbc8664c7016..15663eae30f2b 100644 --- a/applicationset/generators/scm_provider.go +++ b/applicationset/generators/scm_provider.go @@ -160,7 +160,7 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha if err != nil { return nil, fmt.Errorf("error fetching Gitlab token: %w", err) } - provider, err = scm_provider.NewGitlabProvider(ctx, providerConfig.Group, token, providerConfig.API, providerConfig.AllBranches, providerConfig.IncludeSubgroups, providerConfig.WillIncludeSharedProjects(), providerConfig.Insecure, g.scmRootCAPath, providerConfig.Topic, caCerts) + provider, err = scm_provider.NewGitlabProvider(providerConfig.Group, token, providerConfig.API, providerConfig.AllBranches, providerConfig.IncludeSubgroups, providerConfig.WillIncludeSharedProjects(), providerConfig.Insecure, g.scmRootCAPath, providerConfig.Topic, caCerts) if err != nil { return nil, fmt.Errorf("error initializing Gitlab service: %w", err) } @@ -169,7 +169,7 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha if err != nil { return nil, fmt.Errorf("error fetching Gitea token: %w", err) } - provider, err = scm_provider.NewGiteaProvider(ctx, providerConfig.Gitea.Owner, token, providerConfig.Gitea.API, providerConfig.Gitea.AllBranches, providerConfig.Gitea.Insecure) + provider, err = scm_provider.NewGiteaProvider(providerConfig.Gitea.Owner, token, providerConfig.Gitea.API, providerConfig.Gitea.AllBranches, providerConfig.Gitea.Insecure) if err != nil { return nil, fmt.Errorf("error initializing Gitea service: %w", err) } @@ -206,7 +206,7 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha if err != nil { return nil, fmt.Errorf("error fetching Azure Devops access token: %w", err) } - provider, err = scm_provider.NewAzureDevOpsProvider(ctx, token, providerConfig.AzureDevOps.Organization, providerConfig.AzureDevOps.API, providerConfig.AzureDevOps.TeamProject, providerConfig.AzureDevOps.AllBranches) + provider, err = scm_provider.NewAzureDevOpsProvider(token, providerConfig.AzureDevOps.Organization, providerConfig.AzureDevOps.API, providerConfig.AzureDevOps.TeamProject, providerConfig.AzureDevOps.AllBranches) if err != nil { return nil, fmt.Errorf("error initializing Azure Devops service: %w", err) } @@ -215,7 +215,7 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha if err != nil { return nil, fmt.Errorf("error fetching Bitbucket cloud appPassword: %w", err) } - provider, err = scm_provider.NewBitBucketCloudProvider(ctx, providerConfig.Bitbucket.Owner, providerConfig.Bitbucket.User, appPassword, providerConfig.Bitbucket.AllBranches) + provider, err = scm_provider.NewBitBucketCloudProvider(providerConfig.Bitbucket.Owner, providerConfig.Bitbucket.User, appPassword, providerConfig.Bitbucket.AllBranches) if err != nil { return nil, fmt.Errorf("error initializing Bitbucket cloud service: %w", err) } diff --git a/applicationset/metrics/fake.go b/applicationset/metrics/fake.go index 9c1d55d2f24d2..aebddde651233 100644 --- a/applicationset/metrics/fake.go +++ b/applicationset/metrics/fake.go @@ -2,11 +2,10 @@ package metrics import ( "github.com/prometheus/client_golang/prometheus" - ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" ) // Fake implementation for testing -func NewFakeAppsetMetrics(client ctrlclient.WithWatch) *ApplicationsetMetrics { +func NewFakeAppsetMetrics() *ApplicationsetMetrics { reconcileHistogram := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "argocd_appset_reconcile", diff --git a/applicationset/services/internal/http/client.go b/applicationset/services/internal/http/client.go index 07e3565eeb75d..b16bd873e6d8b 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 any, options []ClientOptionFunc) (*http.Request, error) { +func (c *Client) NewRequestWithContext(ctx context.Context, method, path string, body any) (*http.Request, error) { // Make sure the given URL end with a slash if !strings.HasSuffix(c.baseURL, "/") { c.baseURL += "/" @@ -82,7 +82,7 @@ func (c *Client) NewRequest(method, path string, body any, options []ClientOptio } } - req, err := http.NewRequest(method, c.baseURL+path, buf) + req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, buf) if err != nil { return nil, err } @@ -102,7 +102,7 @@ func (c *Client) NewRequest(method, path string, body any, options []ClientOptio return req, nil } -func (c *Client) Do(ctx context.Context, req *http.Request, v any) (*http.Response, error) { +func (c *Client) Do(req *http.Request, v any) (*http.Response, error) { resp, err := c.client.Do(req) if err != nil { return nil, err diff --git a/applicationset/services/internal/http/client_test.go b/applicationset/services/internal/http/client_test.go index 2799b99668ea5..3385f2264255c 100644 --- a/applicationset/services/internal/http/client_test.go +++ b/applicationset/services/internal/http/client_test.go @@ -15,7 +15,7 @@ import ( ) func TestClient(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, err := w.Write([]byte("Hello, World!")) if err != nil { @@ -30,8 +30,6 @@ func TestClient(t *testing.T) { } func TestClientDo(t *testing.T) { - ctx := context.Background() - for _, c := range []struct { name string params map[string]string @@ -48,7 +46,7 @@ func TestClientDo(t *testing.T) { "pkey1": "val1", "pkey2": "val2", }, - fakeServer: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fakeServer: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, err := w.Write([]byte(`[{ "key1": "val1", @@ -120,12 +118,12 @@ func TestClientDo(t *testing.T) { client, err := NewClient(cc.fakeServer.URL, cc.clientOptionFns...) require.NoError(t, err, "NewClient returned unexpected error") - req, err := client.NewRequest("POST", "", cc.params, nil) + req, err := client.NewRequestWithContext(context.Background(), http.MethodPost, "", cc.params) require.NoError(t, err, "NewRequest returned unexpected error") var data []map[string]any - resp, err := client.Do(ctx, req, &data) + resp, err := client.Do(req, &data) if cc.expectedError != nil { assert.EqualError(t, err, cc.expectedError.Error()) diff --git a/applicationset/services/plugin/plugin_service.go b/applicationset/services/plugin/plugin_service.go index 4064718c94662..233f1db401458 100644 --- a/applicationset/services/plugin/plugin_service.go +++ b/applicationset/services/plugin/plugin_service.go @@ -34,7 +34,7 @@ type Service struct { appSetName string } -func NewPluginService(ctx context.Context, appSetName string, baseURL string, token string, requestTimeout int) (*Service, error) { +func NewPluginService(appSetName string, baseURL string, token string, requestTimeout int) (*Service, error) { var clientOptionFns []internalhttp.ClientOptionFunc clientOptionFns = append(clientOptionFns, internalhttp.WithToken(token)) @@ -55,14 +55,14 @@ func NewPluginService(ctx context.Context, appSetName string, baseURL string, to } func (p *Service) List(ctx context.Context, parameters v1alpha1.PluginParameters) (*ServiceResponse, error) { - req, err := p.client.NewRequest(http.MethodPost, "api/v1/getparams.execute", ServiceRequest{ApplicationSetName: p.appSetName, Input: v1alpha1.PluginInput{Parameters: parameters}}, nil) + req, err := p.client.NewRequestWithContext(ctx, http.MethodPost, "api/v1/getparams.execute", ServiceRequest{ApplicationSetName: p.appSetName, Input: v1alpha1.PluginInput{Parameters: parameters}}) if err != nil { return nil, fmt.Errorf("NewRequest returned unexpected error: %w", err) } var data ServiceResponse - _, err = p.client.Do(ctx, req, &data) + _, err = p.client.Do(req, &data) if err != nil { return nil, fmt.Errorf("error get api '%s': %w", p.appSetName, err) } diff --git a/applicationset/services/plugin/plugin_service_test.go b/applicationset/services/plugin/plugin_service_test.go index c6e795c40371b..b5643619e0bbc 100644 --- a/applicationset/services/plugin/plugin_service_test.go +++ b/applicationset/services/plugin/plugin_service_test.go @@ -31,7 +31,7 @@ func TestPlugin(t *testing.T) { ts := httptest.NewServer(handler) defer ts.Close() - client, err := NewPluginService(context.Background(), "plugin-test", ts.URL, token, 0) + client, err := NewPluginService("plugin-test", ts.URL, token, 0) require.NoError(t, err) data, err := client.List(context.Background(), nil) diff --git a/applicationset/services/pull_request/azure_devops.go b/applicationset/services/pull_request/azure_devops.go index 78cf29f01aa7f..ed46d029b6f15 100644 --- a/applicationset/services/pull_request/azure_devops.go +++ b/applicationset/services/pull_request/azure_devops.go @@ -41,7 +41,7 @@ var ( _ AzureDevOpsClientFactory = &devopsFactoryImpl{} ) -func NewAzureDevOpsService(ctx context.Context, token, url, organization, project, repo string, labels []string) (PullRequestService, error) { +func NewAzureDevOpsService(token, url, organization, project, repo string, labels []string) (PullRequestService, error) { organizationUrl := buildURL(url, organization) var connection *azuredevops.Connection diff --git a/applicationset/services/pull_request/bitbucket_cloud_test.go b/applicationset/services/pull_request/bitbucket_cloud_test.go index 411f6148c85d6..740734de6c348 100644 --- a/applicationset/services/pull_request/bitbucket_cloud_test.go +++ b/applicationset/services/pull_request/bitbucket_cloud_test.go @@ -241,7 +241,7 @@ func TestListPullRequestPaginationCloud(t *testing.T) { } func TestListResponseErrorCloud(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) defer ts.Close() diff --git a/applicationset/services/pull_request/bitbucket_server_test.go b/applicationset/services/pull_request/bitbucket_server_test.go index b9da370830fc0..1ee0c2c2140ca 100644 --- a/applicationset/services/pull_request/bitbucket_server_test.go +++ b/applicationset/services/pull_request/bitbucket_server_test.go @@ -303,7 +303,7 @@ func TestListPullRequestTLS(t *testing.T) { } func TestListResponseError(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) defer ts.Close() diff --git a/applicationset/services/pull_request/fake.go b/applicationset/services/pull_request/fake.go index 845df70d6675f..50d4969e847d5 100644 --- a/applicationset/services/pull_request/fake.go +++ b/applicationset/services/pull_request/fake.go @@ -18,6 +18,6 @@ func NewFakeService(_ context.Context, listPullReuests []*PullRequest, listError }, nil } -func (g *FakeService) List(ctx context.Context) ([]*PullRequest, error) { +func (g *FakeService) List(_ context.Context) ([]*PullRequest, error) { return g.listPullReuests, g.listError } diff --git a/applicationset/services/pull_request/gitea.go b/applicationset/services/pull_request/gitea.go index 5f32e4dc307cf..b86574fbcc929 100644 --- a/applicationset/services/pull_request/gitea.go +++ b/applicationset/services/pull_request/gitea.go @@ -18,7 +18,7 @@ type GiteaService struct { var _ PullRequestService = (*GiteaService)(nil) -func NewGiteaService(ctx context.Context, token, url, owner, repo string, insecure bool) (PullRequestService, error) { +func NewGiteaService(token, url, owner, repo string, insecure bool) (PullRequestService, error) { if token == "" { token = os.Getenv("GITEA_TOKEN") } @@ -49,6 +49,7 @@ func (g *GiteaService) List(ctx context.Context) ([]*PullRequest, error) { opts := gitea.ListPullRequestsOptions{ State: gitea.StateOpen, } + g.client.SetContext(ctx) prs, _, err := g.client.ListRepoPullRequests(g.owner, g.repo, opts) if err != nil { return nil, err diff --git a/applicationset/services/pull_request/gitea_test.go b/applicationset/services/pull_request/gitea_test.go index ab58a049e52b1..6b2bca7d132b3 100644 --- a/applicationset/services/pull_request/gitea_test.go +++ b/applicationset/services/pull_request/gitea_test.go @@ -251,7 +251,7 @@ func TestGiteaList(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { giteaMockHandler(t)(w, r) })) - host, err := NewGiteaService(context.Background(), "", ts.URL, "test-argocd", "pr-test", false) + host, err := NewGiteaService("", ts.URL, "test-argocd", "pr-test", false) require.NoError(t, err) prs, err := host.List(context.Background()) require.NoError(t, err) diff --git a/applicationset/services/pull_request/gitlab.go b/applicationset/services/pull_request/gitlab.go index 8443847fce97a..aaa31a8c87079 100644 --- a/applicationset/services/pull_request/gitlab.go +++ b/applicationset/services/pull_request/gitlab.go @@ -21,7 +21,7 @@ type GitLabService struct { var _ PullRequestService = (*GitLabService)(nil) -func NewGitLabService(ctx context.Context, token, url, project string, labels []string, pullRequestState string, scmRootCAPath string, insecure bool, caCerts []byte) (PullRequestService, error) { +func NewGitLabService(token, url, project string, labels []string, pullRequestState string, scmRootCAPath string, insecure bool, caCerts []byte) (PullRequestService, error) { var clientOptionFns []gitlab.ClientOptionFunc // Set a custom Gitlab base URL if one is provided @@ -74,7 +74,7 @@ func (g *GitLabService) List(ctx context.Context) ([]*PullRequest, error) { pullRequests := []*PullRequest{} for { - mrs, resp, err := g.client.MergeRequests.ListProjectMergeRequests(g.project, opts) + mrs, resp, err := g.client.MergeRequests.ListProjectMergeRequests(g.project, opts, gitlab.WithContext(ctx)) if err != nil { return nil, fmt.Errorf("error listing merge requests for project '%s': %w", g.project, err) } diff --git a/applicationset/services/pull_request/gitlab_test.go b/applicationset/services/pull_request/gitlab_test.go index 18467fe08815d..f46982823e927 100644 --- a/applicationset/services/pull_request/gitlab_test.go +++ b/applicationset/services/pull_request/gitlab_test.go @@ -35,7 +35,7 @@ func TestGitLabServiceCustomBaseURL(t *testing.T) { writeMRListResponse(t, w) }) - svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", nil, "", "", false, nil) + svc, err := NewGitLabService("", server.URL, "278964", nil, "", "", false, nil) require.NoError(t, err) _, err = svc.List(context.Background()) @@ -54,7 +54,7 @@ func TestGitLabServiceToken(t *testing.T) { writeMRListResponse(t, w) }) - svc, err := NewGitLabService(context.Background(), "token-123", server.URL, "278964", nil, "", "", false, nil) + svc, err := NewGitLabService("token-123", server.URL, "278964", nil, "", "", false, nil) require.NoError(t, err) _, err = svc.List(context.Background()) @@ -73,7 +73,7 @@ func TestList(t *testing.T) { writeMRListResponse(t, w) }) - svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", []string{}, "", "", false, nil) + svc, err := NewGitLabService("", server.URL, "278964", []string{}, "", "", false, nil) require.NoError(t, err) prs, err := svc.List(context.Background()) @@ -99,7 +99,7 @@ func TestListWithLabels(t *testing.T) { writeMRListResponse(t, w) }) - svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", []string{"feature", "ready"}, "", "", false, nil) + svc, err := NewGitLabService("", server.URL, "278964", []string{"feature", "ready"}, "", "", false, nil) require.NoError(t, err) _, err = svc.List(context.Background()) @@ -118,7 +118,7 @@ func TestListWithState(t *testing.T) { writeMRListResponse(t, w) }) - svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", []string{}, "opened", "", false, nil) + svc, err := NewGitLabService("", server.URL, "278964", []string{}, "opened", "", false, nil) require.NoError(t, err) _, err = svc.List(context.Background()) @@ -161,7 +161,7 @@ func TestListWithStateTLS(t *testing.T) { for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { - ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { writeMRListResponse(t, w) })) defer ts.Close() @@ -180,7 +180,7 @@ func TestListWithStateTLS(t *testing.T) { } } - svc, err := NewGitLabService(context.Background(), "", ts.URL, "278964", []string{}, "opened", "", test.tlsInsecure, certs) + svc, err := NewGitLabService("", ts.URL, "278964", []string{}, "opened", "", test.tlsInsecure, certs) require.NoError(t, err) _, err = svc.List(context.Background()) diff --git a/applicationset/services/repo_service_test.go b/applicationset/services/repo_service_test.go index 249d758a79b12..e9d97cc012605 100644 --- a/applicationset/services/repo_service_test.go +++ b/applicationset/services/repo_service_test.go @@ -39,12 +39,12 @@ func TestGetDirectories(t *testing.T) { wantErr assert.ErrorAssertionFunc }{ {name: "ErrorGettingRepos", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return nil, errors.New("unable to get repos") }, }, args: args{}, want: nil, wantErr: assert.Error}, {name: "ErrorGettingDirs", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -54,7 +54,7 @@ func TestGetDirectories(t *testing.T) { }, }, args: args{}, want: nil, wantErr: assert.Error}, {name: "HappyCase", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -66,7 +66,7 @@ func TestGetDirectories(t *testing.T) { }, }, args: args{}, want: []string{"foo", "foo/bar", "bar/foo"}, wantErr: assert.NoError}, {name: "ErrorVerifyingCommit", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -122,12 +122,12 @@ func TestGetFiles(t *testing.T) { wantErr assert.ErrorAssertionFunc }{ {name: "ErrorGettingRepos", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return nil, errors.New("unable to get repos") }, }, args: args{}, want: nil, wantErr: assert.Error}, {name: "ErrorGettingFiles", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -137,7 +137,7 @@ func TestGetFiles(t *testing.T) { }, }, args: args{}, want: nil, wantErr: assert.Error}, {name: "HappyCase", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -155,7 +155,7 @@ func TestGetFiles(t *testing.T) { "bar.yaml": []byte("yay: appsets"), }, wantErr: assert.NoError}, {name: "ErrorVerifyingCommit", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -189,7 +189,7 @@ func TestGetFiles(t *testing.T) { } func TestNewArgoCDService(t *testing.T) { - service, err := NewArgoCDService(func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + service, err := NewArgoCDService(func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, false, &repo_mocks.Clientset{}, false) require.NoError(t, err) diff --git a/applicationset/services/scm_provider/azure_devops.go b/applicationset/services/scm_provider/azure_devops.go index b43f57b96930b..4c198e10cfeb4 100644 --- a/applicationset/services/scm_provider/azure_devops.go +++ b/applicationset/services/scm_provider/azure_devops.go @@ -57,7 +57,7 @@ var ( _ AzureDevOpsClientFactory = &devopsFactoryImpl{} ) -func NewAzureDevOpsProvider(ctx context.Context, accessToken string, org string, url string, project string, allBranches bool) (*AzureDevOpsProvider, error) { +func NewAzureDevOpsProvider(accessToken string, org string, url string, project string, allBranches bool) (*AzureDevOpsProvider, error) { if accessToken == "" { return nil, errors.New("no access token provided") } @@ -72,7 +72,7 @@ func NewAzureDevOpsProvider(ctx context.Context, accessToken string, org string, return &AzureDevOpsProvider{organization: org, teamProject: project, accessToken: accessToken, clientFactory: &devopsFactoryImpl{connection: connection}, allBranches: allBranches}, nil } -func (g *AzureDevOpsProvider) ListRepos(ctx context.Context, cloneProtocol string) ([]*Repository, error) { +func (g *AzureDevOpsProvider) ListRepos(ctx context.Context, _ string) ([]*Repository, error) { gitClient, err := g.clientFactory.GetClient(ctx) if err != nil { return nil, fmt.Errorf("failed to get Azure DevOps client: %w", err) diff --git a/applicationset/services/scm_provider/bitbucket_cloud.go b/applicationset/services/scm_provider/bitbucket_cloud.go index 7b40d99e8c103..a91ed1dbf0d99 100644 --- a/applicationset/services/scm_provider/bitbucket_cloud.go +++ b/applicationset/services/scm_provider/bitbucket_cloud.go @@ -52,7 +52,7 @@ func (c *ExtendedClient) GetContents(repo *Repository, path string) (bool, error var _ SCMProviderService = &BitBucketCloudProvider{} -func NewBitBucketCloudProvider(ctx context.Context, owner string, user string, password string, allBranches bool) (*BitBucketCloudProvider, error) { +func NewBitBucketCloudProvider(owner string, user string, password string, allBranches bool) (*BitBucketCloudProvider, error) { client := &ExtendedClient{ bitbucket.NewBasicAuth(user, password), user, @@ -62,7 +62,7 @@ func NewBitBucketCloudProvider(ctx context.Context, owner string, user string, p return &BitBucketCloudProvider{client: client, owner: owner, allBranches: allBranches}, nil } -func (g *BitBucketCloudProvider) GetBranches(ctx context.Context, repo *Repository) ([]*Repository, error) { +func (g *BitBucketCloudProvider) GetBranches(_ context.Context, repo *Repository) ([]*Repository, error) { repos := []*Repository{} branches, err := g.listBranches(repo) if err != nil { @@ -87,7 +87,7 @@ func (g *BitBucketCloudProvider) GetBranches(ctx context.Context, repo *Reposito return repos, nil } -func (g *BitBucketCloudProvider) ListRepos(ctx context.Context, cloneProtocol string) ([]*Repository, error) { +func (g *BitBucketCloudProvider) ListRepos(_ context.Context, cloneProtocol string) ([]*Repository, error) { if cloneProtocol == "" { cloneProtocol = "ssh" } @@ -117,7 +117,7 @@ func (g *BitBucketCloudProvider) ListRepos(ctx context.Context, cloneProtocol st return repos, nil } -func (g *BitBucketCloudProvider) RepoHasPath(ctx context.Context, repo *Repository, path string) (bool, error) { +func (g *BitBucketCloudProvider) RepoHasPath(_ context.Context, repo *Repository, path string) (bool, error) { contents, err := g.client.GetContents(repo, path) if err != nil { return false, err diff --git a/applicationset/services/scm_provider/bitbucket_cloud_test.go b/applicationset/services/scm_provider/bitbucket_cloud_test.go index d4127dbbf4002..8633d4b7e7c84 100644 --- a/applicationset/services/scm_provider/bitbucket_cloud_test.go +++ b/applicationset/services/scm_provider/bitbucket_cloud_test.go @@ -87,7 +87,7 @@ func TestBitbucketHasRepo(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { - provider, _ := NewBitBucketCloudProvider(context.Background(), c.owner, "user", "password", false) + provider, _ := NewBitBucketCloudProvider(c.owner, "user", "password", false) repo := &Repository{ Organization: c.owner, Repository: c.repo, @@ -487,7 +487,7 @@ func TestBitbucketListRepos(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { - provider, _ := NewBitBucketCloudProvider(context.Background(), c.owner, "user", "password", c.allBranches) + provider, _ := NewBitBucketCloudProvider(c.owner, "user", "password", c.allBranches) rawRepos, err := ListRepos(context.Background(), provider, c.filters, c.proto) if c.hasError { require.Error(t, err) diff --git a/applicationset/services/scm_provider/bitbucket_server_test.go b/applicationset/services/scm_provider/bitbucket_server_test.go index 211d86cafd4f8..753e8f75f7834 100644 --- a/applicationset/services/scm_provider/bitbucket_server_test.go +++ b/applicationset/services/scm_provider/bitbucket_server_test.go @@ -369,7 +369,7 @@ func TestGetBranchesMissingDefault(t *testing.T) { } func TestGetBranchesEmptyRepo(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { assert.Empty(t, r.Header.Get("Authorization")) if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" { return diff --git a/applicationset/services/scm_provider/gitea.go b/applicationset/services/scm_provider/gitea.go index 9f0650f2d64f8..b633d0c5efa4d 100644 --- a/applicationset/services/scm_provider/gitea.go +++ b/applicationset/services/scm_provider/gitea.go @@ -19,7 +19,7 @@ type GiteaProvider struct { var _ SCMProviderService = &GiteaProvider{} -func NewGiteaProvider(ctx context.Context, owner, token, url string, allBranches, insecure bool) (*GiteaProvider, error) { +func NewGiteaProvider(owner, token, url string, allBranches, insecure bool) (*GiteaProvider, error) { if token == "" { token = os.Getenv("GITEA_TOKEN") } @@ -46,7 +46,7 @@ func NewGiteaProvider(ctx context.Context, owner, token, url string, allBranches }, nil } -func (g *GiteaProvider) GetBranches(ctx context.Context, repo *Repository) ([]*Repository, error) { +func (g *GiteaProvider) GetBranches(_ context.Context, repo *Repository) ([]*Repository, error) { if !g.allBranches { branch, status, err := g.client.GetRepoBranch(g.owner, repo.Repository, repo.Branch) if status.StatusCode == http.StatusNotFound { @@ -87,7 +87,7 @@ func (g *GiteaProvider) GetBranches(ctx context.Context, repo *Repository) ([]*R return repos, nil } -func (g *GiteaProvider) ListRepos(ctx context.Context, cloneProtocol string) ([]*Repository, error) { +func (g *GiteaProvider) ListRepos(_ context.Context, cloneProtocol string) ([]*Repository, error) { repos := []*Repository{} repoOpts := gitea.ListOrgReposOptions{} giteaRepos, _, err := g.client.ListOrgRepos(g.owner, repoOpts) @@ -126,7 +126,7 @@ func (g *GiteaProvider) ListRepos(ctx context.Context, cloneProtocol string) ([] return repos, nil } -func (g *GiteaProvider) RepoHasPath(ctx context.Context, repo *Repository, path string) (bool, error) { +func (g *GiteaProvider) RepoHasPath(_ context.Context, repo *Repository, path string) (bool, error) { _, resp, err := g.client.GetContents(repo.Organization, repo.Repository, repo.Branch, path) if resp != nil && resp.StatusCode == http.StatusNotFound { return false, nil diff --git a/applicationset/services/scm_provider/gitea_test.go b/applicationset/services/scm_provider/gitea_test.go index 1253d30c9a88e..6ca88c8be4952 100644 --- a/applicationset/services/scm_provider/gitea_test.go +++ b/applicationset/services/scm_provider/gitea_test.go @@ -304,7 +304,7 @@ func TestGiteaListRepos(t *testing.T) { defer ts.Close() for _, c := range cases { t.Run(c.name, func(t *testing.T) { - provider, _ := NewGiteaProvider(context.Background(), "test-argocd", "", ts.URL, c.allBranches, false) + provider, _ := NewGiteaProvider("test-argocd", "", ts.URL, c.allBranches, false) rawRepos, err := ListRepos(context.Background(), provider, c.filters, c.proto) if c.hasError { require.Error(t, err) @@ -334,7 +334,7 @@ func TestGiteaHasPath(t *testing.T) { giteaMockHandler(t)(w, r) })) defer ts.Close() - host, _ := NewGiteaProvider(context.Background(), "gitea", "", ts.URL, false, false) + host, _ := NewGiteaProvider("gitea", "", ts.URL, false, false) repo := &Repository{ Organization: "gitea", Repository: "go-sdk", diff --git a/applicationset/services/scm_provider/gitlab.go b/applicationset/services/scm_provider/gitlab.go index c1f9016abf668..fb1fc5804053c 100644 --- a/applicationset/services/scm_provider/gitlab.go +++ b/applicationset/services/scm_provider/gitlab.go @@ -24,7 +24,7 @@ type GitlabProvider struct { var _ SCMProviderService = &GitlabProvider{} -func NewGitlabProvider(ctx context.Context, organization string, token string, url string, allBranches, includeSubgroups, includeSharedProjects, insecure bool, scmRootCAPath, topic string, caCerts []byte) (*GitlabProvider, error) { +func NewGitlabProvider(organization string, token string, url string, allBranches, includeSubgroups, includeSharedProjects, insecure bool, scmRootCAPath, topic string, caCerts []byte) (*GitlabProvider, error) { // Undocumented environment variable to set a default token, to be used in testing to dodge anonymous rate limits. if token == "" { token = os.Getenv("GITLAB_TOKEN") @@ -75,7 +75,7 @@ func (g *GitlabProvider) GetBranches(ctx context.Context, repo *Repository) ([]* return repos, nil } -func (g *GitlabProvider) ListRepos(ctx context.Context, cloneProtocol string) ([]*Repository, error) { +func (g *GitlabProvider) ListRepos(_ context.Context, cloneProtocol string) ([]*Repository, error) { opt := &gitlab.ListGroupProjectsOptions{ ListOptions: gitlab.ListOptions{PerPage: 100}, IncludeSubGroups: &g.includeSubgroups, diff --git a/applicationset/services/scm_provider/gitlab_test.go b/applicationset/services/scm_provider/gitlab_test.go index 4443086333ccb..dca058aacad8b 100644 --- a/applicationset/services/scm_provider/gitlab_test.go +++ b/applicationset/services/scm_provider/gitlab_test.go @@ -1124,7 +1124,7 @@ func TestGitlabListRepos(t *testing.T) { })) for _, c := range cases { t.Run(c.name, func(t *testing.T) { - provider, _ := NewGitlabProvider(context.Background(), "test-argocd-proton", "", ts.URL, c.allBranches, c.includeSubgroups, c.includeSharedProjects, c.insecure, "", c.topic, nil) + provider, _ := NewGitlabProvider("test-argocd-proton", "", ts.URL, c.allBranches, c.includeSubgroups, c.includeSharedProjects, c.insecure, "", c.topic, nil) rawRepos, err := ListRepos(context.Background(), provider, c.filters, c.proto) if c.hasError { require.Error(t, err) @@ -1163,7 +1163,7 @@ func TestGitlabHasPath(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gitlabMockHandler(t)(w, r) })) - host, _ := NewGitlabProvider(context.Background(), "test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil) + host, _ := NewGitlabProvider("test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil) repo := &Repository{ Organization: "test-argocd-proton", Repository: "argocd", @@ -1209,7 +1209,7 @@ func TestGitlabGetBranches(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gitlabMockHandler(t)(w, r) })) - host, _ := NewGitlabProvider(context.Background(), "test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil) + host, _ := NewGitlabProvider("test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil) repo := &Repository{ RepositoryId: 27084533, @@ -1286,7 +1286,7 @@ func TestGetBranchesTLS(t *testing.T) { } } - host, err := NewGitlabProvider(context.Background(), "test-argocd-proton", "", ts.URL, false, true, true, test.tlsInsecure, "", "", certs) + host, err := NewGitlabProvider("test-argocd-proton", "", ts.URL, false, true, true, test.tlsInsecure, "", "", certs) require.NoError(t, err) repo := &Repository{ RepositoryId: 27084533, diff --git a/applicationset/utils/applicationset_lister.go b/applicationset/utils/applicationset_lister.go index 5e9d65936333a..c9a5ecf944bca 100644 --- a/applicationset/utils/applicationset_lister.go +++ b/applicationset/utils/applicationset_lister.go @@ -19,7 +19,7 @@ func NewAppsetLister(client ctrlclient.Client) ApplicationSetLister { return &AppsetLister{Client: client} } -func (l *AppsetLister) List(selector labels.Selector) (ret []*ApplicationSet, err error) { +func (l *AppsetLister) List(_ labels.Selector) (ret []*ApplicationSet, err error) { return clientListAppsets(l.Client, ctrlclient.ListOptions{}) } @@ -37,11 +37,11 @@ type appsetNamespaceLister struct { Namespace string } -func (n *appsetNamespaceLister) List(selector labels.Selector) (ret []*ApplicationSet, err error) { +func (n *appsetNamespaceLister) List(_ labels.Selector) (ret []*ApplicationSet, err error) { return clientListAppsets(n.Client, ctrlclient.ListOptions{Namespace: n.Namespace}) } -func (n *appsetNamespaceLister) Get(name string) (*ApplicationSet, error) { +func (n *appsetNamespaceLister) Get(_ string) (*ApplicationSet, error) { appset := ApplicationSet{} err := n.Client.Get(context.TODO(), ctrlclient.ObjectKeyFromObject(&appset), &appset) return &appset, err diff --git a/applicationset/utils/selector.go b/applicationset/utils/selector.go index 556b186b5883f..eae03242363d8 100644 --- a/applicationset/utils/selector.go +++ b/applicationset/utils/selector.go @@ -69,11 +69,11 @@ func (s internalSelector) Add(reqs ...Requirement) Selector { type nothingSelector struct{} -func (n nothingSelector) Matches(l labels.Labels) bool { +func (n nothingSelector) Matches(_ labels.Labels) bool { return false } -func (n nothingSelector) Add(r ...Requirement) Selector { +func (n nothingSelector) Add(_ ...Requirement) Selector { return n } diff --git a/applicationset/utils/utils_test.go b/applicationset/utils/utils_test.go index 6c66186649ef3..b64b0735fc87f 100644 --- a/applicationset/utils/utils_test.go +++ b/applicationset/utils/utils_test.go @@ -565,7 +565,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { 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]any{ - "foo": func(test *string) { + "foo": func(_ *string) { }, }, }, diff --git a/applicationset/webhook/webhook_test.go b/applicationset/webhook/webhook_test.go index 1d5ba90d0dddf..07e8539548eab 100644 --- a/applicationset/webhook/webhook_test.go +++ b/applicationset/webhook/webhook_test.go @@ -35,15 +35,15 @@ type generatorMock struct { mock.Mock } -func (g *generatorMock) GetTemplate(appSetGenerator *v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate { +func (g *generatorMock) GetTemplate(_ *v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate { return &v1alpha1.ApplicationSetTemplate{} } -func (g *generatorMock) GenerateParams(appSetGenerator *v1alpha1.ApplicationSetGenerator, _ *v1alpha1.ApplicationSet, client client.Client) ([]map[string]any, error) { +func (g *generatorMock) GenerateParams(_ *v1alpha1.ApplicationSetGenerator, _ *v1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) { return []map[string]any{}, nil } -func (g *generatorMock) GetRequeueAfter(appSetGenerator *v1alpha1.ApplicationSetGenerator) time.Duration { +func (g *generatorMock) GetRequeueAfter(_ *v1alpha1.ApplicationSetGenerator) time.Duration { d, _ := time.ParseDuration("10s") return d } diff --git a/cmd/argocd-application-controller/commands/argocd_application_controller.go b/cmd/argocd-application-controller/commands/argocd_application_controller.go index ec364baf5b9b7..80b7abe2961af 100644 --- a/cmd/argocd-application-controller/commands/argocd_application_controller.go +++ b/cmd/argocd-application-controller/commands/argocd_application_controller.go @@ -97,7 +97,7 @@ func NewCommand() *cobra.Command { Short: "Run ArgoCD Application Controller", Long: "ArgoCD application controller is a Kubernetes controller that continuously monitors running applications and compares the current, live state against the desired target state (as specified in the repo). This command runs Application Controller in the foreground. It can be configured by following options.", DisableAutoGenTag: true, - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx, cancel := context.WithCancel(c.Context()) defer cancel() diff --git a/cmd/argocd-applicationset-controller/commands/applicationset_controller.go b/cmd/argocd-applicationset-controller/commands/applicationset_controller.go index ffd925a8c09ee..1ff5329574149 100644 --- a/cmd/argocd-applicationset-controller/commands/applicationset_controller.go +++ b/cmd/argocd-applicationset-controller/commands/applicationset_controller.go @@ -81,7 +81,7 @@ func NewCommand() *cobra.Command { command := cobra.Command{ Use: "controller", Short: "Starts Argo CD ApplicationSet controller", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx := c.Context() vers := common.GetVersion() diff --git a/cmd/argocd-cmp-server/commands/argocd_cmp_server.go b/cmd/argocd-cmp-server/commands/argocd_cmp_server.go index 9d1894695f5af..4c917e7679a28 100644 --- a/cmd/argocd-cmp-server/commands/argocd_cmp_server.go +++ b/cmd/argocd-cmp-server/commands/argocd_cmp_server.go @@ -36,7 +36,7 @@ func NewCommand() *cobra.Command { Short: "Run ArgoCD ConfigManagementPlugin Server", Long: "ArgoCD ConfigManagementPlugin Server is an internal service which runs as sidecar container in reposerver deployment. The following configuration options are available:", DisableAutoGenTag: true, - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx := c.Context() vers := common.GetVersion() diff --git a/cmd/argocd-commit-server/commands/argocd_commit_server.go b/cmd/argocd-commit-server/commands/argocd_commit_server.go index 5c07bc0c1469c..eee928b0084f3 100644 --- a/cmd/argocd-commit-server/commands/argocd_commit_server.go +++ b/cmd/argocd-commit-server/commands/argocd_commit_server.go @@ -38,7 +38,7 @@ func NewCommand() *cobra.Command { Use: "argocd-commit-server", Short: "Run Argo CD Commit Server", Long: "Argo CD Commit Server is an internal service which commits and pushes hydrated manifests to git. This command runs Commit Server in the foreground.", - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, _ []string) error { vers := common.GetVersion() vers.LogStartupInfo( "Argo CD Commit Server", diff --git a/cmd/argocd-dex/commands/argocd_dex.go b/cmd/argocd-dex/commands/argocd_dex.go index 332e79b6af8a4..62a785460489d 100644 --- a/cmd/argocd-dex/commands/argocd_dex.go +++ b/cmd/argocd-dex/commands/argocd_dex.go @@ -52,7 +52,7 @@ func NewRunDexCommand() *cobra.Command { command := cobra.Command{ Use: "rundex", Short: "Runs dex generating a config using settings from the Argo CD configmap and secret", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx := c.Context() vers := common.GetVersion() @@ -159,7 +159,7 @@ func NewGenDexConfigCommand() *cobra.Command { command := cobra.Command{ Use: "gendexcfg", Short: "Generates a dex config from Argo CD settings", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx := c.Context() cli.SetLogFormat(cmdutil.LogFormat) diff --git a/cmd/argocd-git-ask-pass/commands/argocd_git_ask_pass.go b/cmd/argocd-git-ask-pass/commands/argocd_git_ask_pass.go index 73673e977b883..b815f1c7a1426 100644 --- a/cmd/argocd-git-ask-pass/commands/argocd_git_ask_pass.go +++ b/cmd/argocd-git-ask-pass/commands/argocd_git_ask_pass.go @@ -25,7 +25,7 @@ func NewCommand() *cobra.Command { Use: cliName, Short: "Argo CD git credential helper", DisableAutoGenTag: true, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() if len(os.Args) != 2 { diff --git a/cmd/argocd-k8s-auth/commands/aws.go b/cmd/argocd-k8s-auth/commands/aws.go index 1794a5bf57b39..a8e4a2f7574e8 100644 --- a/cmd/argocd-k8s-auth/commands/aws.go +++ b/cmd/argocd-k8s-auth/commands/aws.go @@ -41,7 +41,7 @@ func newAWSCommand() *cobra.Command { ) command := &cobra.Command{ Use: "aws", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() presignedURLString, err := getSignedRequestWithRetry(ctx, time.Minute, 5*time.Second, clusterName, roleARN, profile, getSignedRequest) diff --git a/cmd/argocd-k8s-auth/commands/aws_test.go b/cmd/argocd-k8s-auth/commands/aws_test.go index 37d9e9ea0477b..bacfab0f57150 100644 --- a/cmd/argocd-k8s-auth/commands/aws_test.go +++ b/cmd/argocd-k8s-auth/commands/aws_test.go @@ -17,7 +17,7 @@ func TestGetSignedRequestWithRetry(t *testing.T) { // given t.Parallel() mock := &signedRequestMock{ - returnFunc: func(m *signedRequestMock) (string, error) { + returnFunc: func(_ *signedRequestMock) (string, error) { return "token", nil }, } @@ -52,7 +52,7 @@ func TestGetSignedRequestWithRetry(t *testing.T) { // given t.Parallel() mock := &signedRequestMock{ - returnFunc: func(m *signedRequestMock) (string, error) { + returnFunc: func(_ *signedRequestMock) (string, error) { return "", errors.New("some error") }, } @@ -71,7 +71,7 @@ type signedRequestMock struct { returnFunc func(m *signedRequestMock) (string, error) } -func (m *signedRequestMock) getSignedRequestMock(clusterName, roleARN string, profile string) (string, error) { +func (m *signedRequestMock) getSignedRequestMock(_, _ string, _ string) (string, error) { m.getSignedRequestCalls++ return m.returnFunc(m) } diff --git a/cmd/argocd-k8s-auth/commands/azure.go b/cmd/argocd-k8s-auth/commands/azure.go index 287b8d457aee1..f04b1e3c041cc 100644 --- a/cmd/argocd-k8s-auth/commands/azure.go +++ b/cmd/argocd-k8s-auth/commands/azure.go @@ -22,7 +22,7 @@ const ( func newAzureCommand() *cobra.Command { command := &cobra.Command{ Use: "azure", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { o := token.OptionsWithEnv() if o.LoginMethod == "" { // no environment variable overrides // we'll use default of WorkloadIdentityLogin for the login flow diff --git a/cmd/argocd-k8s-auth/commands/gcp.go b/cmd/argocd-k8s-auth/commands/gcp.go index 388d274072488..5d6eda55679dd 100644 --- a/cmd/argocd-k8s-auth/commands/gcp.go +++ b/cmd/argocd-k8s-auth/commands/gcp.go @@ -24,7 +24,7 @@ var defaultGCPScopes = []string{ func newGCPCommand() *cobra.Command { command := &cobra.Command{ Use: "gcp", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() // Preferred way to retrieve GCP credentials diff --git a/cmd/argocd-notification/commands/controller.go b/cmd/argocd-notification/commands/controller.go index 152dab6a078f3..bdbb152b17799 100644 --- a/cmd/argocd-notification/commands/controller.go +++ b/cmd/argocd-notification/commands/controller.go @@ -66,7 +66,7 @@ func NewCommand() *cobra.Command { command := cobra.Command{ Use: "controller", Short: "Starts Argo CD Notifications controller", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, _ []string) error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/cmd/argocd-repo-server/commands/argocd_repo_server.go b/cmd/argocd-repo-server/commands/argocd_repo_server.go index 19d9a2a1e4b12..86a345c000fd5 100644 --- a/cmd/argocd-repo-server/commands/argocd_repo_server.go +++ b/cmd/argocd-repo-server/commands/argocd_repo_server.go @@ -83,7 +83,7 @@ func NewCommand() *cobra.Command { Short: "Run ArgoCD Repository Server", Long: "ArgoCD Repository Server is an internal service which maintains a local cache of the Git repository holding the application manifests, and is responsible for generating and returning the Kubernetes manifests. This command runs Repository Server in the foreground. It can be configured by following options.", DisableAutoGenTag: true, - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx := c.Context() vers := common.GetVersion() diff --git a/cmd/argocd-server/commands/argocd_server.go b/cmd/argocd-server/commands/argocd_server.go index 403cfdae16633..75845f9fd9bb7 100644 --- a/cmd/argocd-server/commands/argocd_server.go +++ b/cmd/argocd-server/commands/argocd_server.go @@ -103,7 +103,7 @@ func NewCommand() *cobra.Command { Short: "Run the ArgoCD API server", Long: "The API server is a gRPC/REST server which exposes the API consumed by the Web UI, CLI, and CI/CD systems. This command runs API server in the foreground. It can be configured by following options.", DisableAutoGenTag: true, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() vers := common.GetVersion() diff --git a/cmd/argocd/commands/account.go b/cmd/argocd/commands/account.go index 4307990f81528..733a26803efc4 100644 --- a/cmd/argocd/commands/account.go +++ b/cmd/argocd/commands/account.go @@ -262,7 +262,7 @@ func NewAccountListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman Use: "list", Short: "List accounts", Example: "argocd account list", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, client := headless.NewClientOrDie(clientOpts, c).NewAccountClientOrDie() @@ -309,7 +309,7 @@ argocd account get # Get details for an account by name argocd account get --account `, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() clientset := headless.NewClientOrDie(clientOpts, c) @@ -382,7 +382,7 @@ argocd account generate-token # Generate token for the account with the specified name argocd account generate-token --account `, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() clientset := headless.NewClientOrDie(clientOpts, c) diff --git a/cmd/argocd/commands/admin/app.go b/cmd/argocd/commands/admin/app.go index c60484c6ffcbe..f106aa1b961f4 100644 --- a/cmd/argocd/commands/admin/app.go +++ b/cmd/argocd/commands/admin/app.go @@ -371,7 +371,7 @@ func reconcileApplications( appClientset, 1*time.Hour, appinformers.WithNamespace(namespace), - appinformers.WithTweakListOptions(func(options *metav1.ListOptions) {}), + appinformers.WithTweakListOptions(func(_ *metav1.ListOptions) {}), ) appInformer := appInformerFactory.Argoproj().V1alpha1().Applications().Informer() @@ -384,9 +384,9 @@ func reconcileApplications( appLister := appInformerFactory.Argoproj().V1alpha1().Applications().Lister() projLister := appInformerFactory.Argoproj().V1alpha1().AppProjects().Lister() - server, err := metrics.NewMetricsServer("", appLister, func(obj any) bool { + server, err := metrics.NewMetricsServer("", appLister, func(_ any) bool { return true - }, func(r *http.Request) error { + }, func(_ *http.Request) error { return nil }, []string{}, []string{}) if err != nil { @@ -453,5 +453,5 @@ func reconcileApplications( } func newLiveStateCache(argoDB db.ArgoDB, appInformer kubecache.SharedIndexInformer, settingsMgr *settings.SettingsManager, server *metrics.MetricsServer) cache.LiveStateCache { - return cache.NewLiveStateCache(argoDB, appInformer, settingsMgr, kubeutil.NewKubectl(), server, func(managedByApp map[string]bool, ref corev1.ObjectReference) {}, &sharding.ClusterSharding{}, argo.NewResourceTracking()) + return cache.NewLiveStateCache(argoDB, appInformer, settingsMgr, kubeutil.NewKubectl(), server, func(_ map[string]bool, _ corev1.ObjectReference) {}, &sharding.ClusterSharding{}, argo.NewResourceTracking()) } diff --git a/cmd/argocd/commands/admin/app_test.go b/cmd/argocd/commands/admin/app_test.go index 964d23ccab696..a851575c0155e 100644 --- a/cmd/argocd/commands/admin/app_test.go +++ b/cmd/argocd/commands/admin/app_test.go @@ -110,7 +110,7 @@ func TestGetReconcileResults_Refresh(t *testing.T) { liveStateCache.On("IsNamespaced", mock.Anything, mock.Anything).Return(true, nil) result, err := reconcileApplications(ctx, kubeClientset, appClientset, "default", &repoServerClientset, "", - func(argoDB db.ArgoDB, appInformer cache.SharedIndexInformer, settingsMgr *settings.SettingsManager, server *metrics.MetricsServer) statecache.LiveStateCache { + func(_ db.ArgoDB, _ cache.SharedIndexInformer, _ *settings.SettingsManager, _ *metrics.MetricsServer) statecache.LiveStateCache { return &liveStateCache }, false, diff --git a/cmd/argocd/commands/admin/backup.go b/cmd/argocd/commands/admin/backup.go index 7725ed1d9e5ae..8245409cd85e4 100644 --- a/cmd/argocd/commands/admin/backup.go +++ b/cmd/argocd/commands/admin/backup.go @@ -36,7 +36,7 @@ func NewExportCommand() *cobra.Command { command := cobra.Command{ Use: "export", Short: "Export all Argo CD data to stdout (default) or a file", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() config, err := clientConfig.ClientConfig() diff --git a/cmd/argocd/commands/admin/cluster.go b/cmd/argocd/commands/admin/cluster.go index 2f90687d388c6..124a75f67aeae 100644 --- a/cmd/argocd/commands/admin/cluster.go +++ b/cmd/argocd/commands/admin/cluster.go @@ -194,7 +194,7 @@ func NewClusterShardsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comm command := cobra.Command{ Use: "shards", Short: "Print information about each controller shard and the estimated portion of Kubernetes resources it is responsible for.", - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { ctx := cmd.Context() log.SetLevel(log.WarnLevel) @@ -321,12 +321,12 @@ func NewClusterNamespacesCommand() *cobra.Command { command := cobra.Command{ Use: "namespaces", Short: "Print information namespaces which Argo CD manages in each cluster.", - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { ctx := cmd.Context() log.SetLevel(log.WarnLevel) - err := runClusterNamespacesCommand(ctx, clientConfig, func(appClient *versioned.Clientset, _ db.ArgoDB, clusters map[string][]string) error { + err := runClusterNamespacesCommand(ctx, clientConfig, func(_ *versioned.Clientset, _ db.ArgoDB, clusters map[string][]string) error { w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) _, _ = fmt.Fprintf(w, "CLUSTER\tNAMESPACES\n") @@ -486,7 +486,7 @@ argocd admin cluster stats --shard=1 #In a multi-cluster environment to print stats for a specific cluster say(target-cluster) argocd admin cluster stats target-cluster`, - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { ctx := cmd.Context() log.SetLevel(log.WarnLevel) diff --git a/cmd/argocd/commands/admin/dashboard.go b/cmd/argocd/commands/admin/dashboard.go index 41abce130e833..3a416e81a2c1d 100644 --- a/cmd/argocd/commands/admin/dashboard.go +++ b/cmd/argocd/commands/admin/dashboard.go @@ -27,7 +27,7 @@ func NewDashboardCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command cmd := &cobra.Command{ Use: "dashboard", Short: "Starts Argo CD Web UI locally", - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { ctx := cmd.Context() compression, err := cache.CompressionTypeFromString(compressionStr) diff --git a/cmd/argocd/commands/admin/initial_password.go b/cmd/argocd/commands/admin/initial_password.go index fa1352b0075c2..97bf490949d33 100644 --- a/cmd/argocd/commands/admin/initial_password.go +++ b/cmd/argocd/commands/admin/initial_password.go @@ -21,7 +21,7 @@ func NewInitialPasswordCommand() *cobra.Command { command := cobra.Command{ Use: "initial-password", Short: "Prints initial password to log in to Argo CD for the first time", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { config, err := clientConfig.ClientConfig() errors.CheckError(err) namespace, _, err := clientConfig.Namespace() diff --git a/cmd/argocd/commands/admin/project.go b/cmd/argocd/commands/admin/project.go index e943c99f31237..480d3f283a3ad 100644 --- a/cmd/argocd/commands/admin/project.go +++ b/cmd/argocd/commands/admin/project.go @@ -106,7 +106,7 @@ func getModification(modification string, resource string, scope string, permiss return fmt.Sprintf("%s, %s, %s/%s, %s", resource, action, proj, scope, permission) }, nil case "remove": - return func(proj string, action string) string { + return func(_ string, _ string) string { return "" }, nil } diff --git a/cmd/argocd/commands/admin/redis_initial_password.go b/cmd/argocd/commands/admin/redis_initial_password.go index 82085f9ec6771..b527b33589a8d 100644 --- a/cmd/argocd/commands/admin/redis_initial_password.go +++ b/cmd/argocd/commands/admin/redis_initial_password.go @@ -40,7 +40,7 @@ func NewRedisInitialPasswordCommand() *cobra.Command { command := cobra.Command{ Use: "redis-initial-password", Short: "Ensure the Redis password exists, creating a new one if necessary.", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { namespace, _, err := clientConfig.Namespace() errors.CheckError(err) diff --git a/cmd/argocd/commands/admin/settings.go b/cmd/argocd/commands/admin/settings.go index 3dda4b36526c6..2e576cc7da512 100644 --- a/cmd/argocd/commands/admin/settings.go +++ b/cmd/argocd/commands/admin/settings.go @@ -295,7 +295,7 @@ argocd admin settings validate --argocd-cm-path ./argocd-cm.yaml #Validates accounts and plugins settings in Kubernetes cluster of current kubeconfig context argocd admin settings validate --group accounts --group plugins --load-cluster-settings`, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() settingsManager, err := cmdCtx.createSettingsManager(ctx) @@ -511,7 +511,7 @@ argocd admin settings resource-overrides health ./deploy.yaml --argocd-cm-path . os.Exit(1) } - executeResourceOverrideCommand(ctx, cmdCtx, args, func(res unstructured.Unstructured, override v1alpha1.ResourceOverride, overrides map[string]v1alpha1.ResourceOverride) { + executeResourceOverrideCommand(ctx, cmdCtx, args, func(res unstructured.Unstructured, _ v1alpha1.ResourceOverride, overrides map[string]v1alpha1.ResourceOverride) { gvk := res.GroupVersionKind() resHealth, err := healthutil.GetResourceHealth(&res, lua.ResourceHealthOverrides(overrides)) diff --git a/cmd/argocd/commands/app.go b/cmd/argocd/commands/app.go index 2a9eca19f6116..37b0e45a4793f 100644 --- a/cmd/argocd/commands/app.go +++ b/cmd/argocd/commands/app.go @@ -1664,7 +1664,7 @@ func NewApplicationListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co argocd app list -l app.kubernetes.io/instance argocd app list -l '!app.kubernetes.io/instance' argocd app list -l 'app.kubernetes.io/instance notin (my-app,other-app)'`, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie() diff --git a/cmd/argocd/commands/app_test.go b/cmd/argocd/commands/app_test.go index c3536bc3c5406..3e413dfa53668 100644 --- a/cmd/argocd/commands/app_test.go +++ b/cmd/argocd/commands/app_test.go @@ -1029,7 +1029,7 @@ func TestTargetObjects_invalid(t *testing.T) { assert.Error(t, err) } -func TestCheckForDeleteEvent(t *testing.T) { +func TestCheckForDeleteEvent(_ *testing.T) { ctx := context.Background() fakeClient := new(fakeAcdClient) @@ -1942,7 +1942,7 @@ type customAcdClient struct { *fakeAcdClient } -func (c *customAcdClient) WatchApplicationWithRetry(ctx context.Context, appName string, revision string) chan *v1alpha1.ApplicationWatchEvent { +func (c *customAcdClient) WatchApplicationWithRetry(ctx context.Context, _ string, _ string) chan *v1alpha1.ApplicationWatchEvent { appEventsCh := make(chan *v1alpha1.ApplicationWatchEvent) _, appClient := c.NewApplicationClientOrDie() app, _ := appClient.Get(ctx, &applicationpkg.ApplicationQuery{}) @@ -1982,19 +1982,19 @@ func (c *fakeConnection) Close() error { type fakeSettingsServiceClient struct{} -func (f fakeSettingsServiceClient) Get(ctx context.Context, in *settingspkg.SettingsQuery, opts ...grpc.CallOption) (*settingspkg.Settings, error) { +func (f fakeSettingsServiceClient) Get(_ context.Context, _ *settingspkg.SettingsQuery, _ ...grpc.CallOption) (*settingspkg.Settings, error) { return &settingspkg.Settings{ URL: "http://localhost:8080", }, nil } -func (f fakeSettingsServiceClient) GetPlugins(ctx context.Context, in *settingspkg.SettingsQuery, opts ...grpc.CallOption) (*settingspkg.SettingsPluginsResponse, error) { +func (f fakeSettingsServiceClient) GetPlugins(_ context.Context, _ *settingspkg.SettingsQuery, _ ...grpc.CallOption) (*settingspkg.SettingsPluginsResponse, error) { return nil, nil } type fakeAppServiceClient struct{} -func (c *fakeAppServiceClient) Get(ctx context.Context, in *applicationpkg.ApplicationQuery, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Get(_ context.Context, _ *applicationpkg.ApplicationQuery, _ ...grpc.CallOption) (*v1alpha1.Application, error) { time := metav1.Date(2020, time.November, 10, 23, 0, 0, 0, time.UTC) return &v1alpha1.Application{ ObjectMeta: metav1.ObjectMeta{ @@ -2062,111 +2062,111 @@ func (c *fakeAppServiceClient) Get(ctx context.Context, in *applicationpkg.Appli }, nil } -func (c *fakeAppServiceClient) List(ctx context.Context, in *applicationpkg.ApplicationQuery, opts ...grpc.CallOption) (*v1alpha1.ApplicationList, error) { +func (c *fakeAppServiceClient) List(_ context.Context, _ *applicationpkg.ApplicationQuery, _ ...grpc.CallOption) (*v1alpha1.ApplicationList, error) { return nil, nil } -func (c *fakeAppServiceClient) ListResourceEvents(ctx context.Context, in *applicationpkg.ApplicationResourceEventsQuery, opts ...grpc.CallOption) (*corev1.EventList, error) { +func (c *fakeAppServiceClient) ListResourceEvents(_ context.Context, _ *applicationpkg.ApplicationResourceEventsQuery, _ ...grpc.CallOption) (*corev1.EventList, error) { return nil, nil } -func (c *fakeAppServiceClient) Watch(ctx context.Context, in *applicationpkg.ApplicationQuery, opts ...grpc.CallOption) (applicationpkg.ApplicationService_WatchClient, error) { +func (c *fakeAppServiceClient) Watch(_ context.Context, _ *applicationpkg.ApplicationQuery, _ ...grpc.CallOption) (applicationpkg.ApplicationService_WatchClient, error) { return nil, nil } -func (c *fakeAppServiceClient) Create(ctx context.Context, in *applicationpkg.ApplicationCreateRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Create(_ context.Context, _ *applicationpkg.ApplicationCreateRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) { return nil, nil } -func (c *fakeAppServiceClient) GetApplicationSyncWindows(ctx context.Context, in *applicationpkg.ApplicationSyncWindowsQuery, opts ...grpc.CallOption) (*applicationpkg.ApplicationSyncWindowsResponse, error) { +func (c *fakeAppServiceClient) GetApplicationSyncWindows(_ context.Context, _ *applicationpkg.ApplicationSyncWindowsQuery, _ ...grpc.CallOption) (*applicationpkg.ApplicationSyncWindowsResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) RevisionMetadata(ctx context.Context, in *applicationpkg.RevisionMetadataQuery, opts ...grpc.CallOption) (*v1alpha1.RevisionMetadata, error) { +func (c *fakeAppServiceClient) RevisionMetadata(_ context.Context, _ *applicationpkg.RevisionMetadataQuery, _ ...grpc.CallOption) (*v1alpha1.RevisionMetadata, error) { return nil, nil } -func (c *fakeAppServiceClient) RevisionChartDetails(ctx context.Context, in *applicationpkg.RevisionMetadataQuery, opts ...grpc.CallOption) (*v1alpha1.ChartDetails, error) { +func (c *fakeAppServiceClient) RevisionChartDetails(_ context.Context, _ *applicationpkg.RevisionMetadataQuery, _ ...grpc.CallOption) (*v1alpha1.ChartDetails, error) { return nil, nil } -func (c *fakeAppServiceClient) GetManifests(ctx context.Context, in *applicationpkg.ApplicationManifestQuery, opts ...grpc.CallOption) (*apiclient.ManifestResponse, error) { +func (c *fakeAppServiceClient) GetManifests(_ context.Context, _ *applicationpkg.ApplicationManifestQuery, _ ...grpc.CallOption) (*apiclient.ManifestResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) GetManifestsWithFiles(ctx context.Context, opts ...grpc.CallOption) (applicationpkg.ApplicationService_GetManifestsWithFilesClient, error) { +func (c *fakeAppServiceClient) GetManifestsWithFiles(_ context.Context, _ ...grpc.CallOption) (applicationpkg.ApplicationService_GetManifestsWithFilesClient, error) { return nil, nil } -func (c *fakeAppServiceClient) Update(ctx context.Context, in *applicationpkg.ApplicationUpdateRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Update(_ context.Context, _ *applicationpkg.ApplicationUpdateRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) { return nil, nil } -func (c *fakeAppServiceClient) UpdateSpec(ctx context.Context, in *applicationpkg.ApplicationUpdateSpecRequest, opts ...grpc.CallOption) (*v1alpha1.ApplicationSpec, error) { +func (c *fakeAppServiceClient) UpdateSpec(_ context.Context, _ *applicationpkg.ApplicationUpdateSpecRequest, _ ...grpc.CallOption) (*v1alpha1.ApplicationSpec, error) { return nil, nil } -func (c *fakeAppServiceClient) Patch(ctx context.Context, in *applicationpkg.ApplicationPatchRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Patch(_ context.Context, _ *applicationpkg.ApplicationPatchRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) { return nil, nil } -func (c *fakeAppServiceClient) Delete(ctx context.Context, in *applicationpkg.ApplicationDeleteRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { +func (c *fakeAppServiceClient) Delete(_ context.Context, _ *applicationpkg.ApplicationDeleteRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) Sync(ctx context.Context, in *applicationpkg.ApplicationSyncRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Sync(_ context.Context, _ *applicationpkg.ApplicationSyncRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) { return nil, nil } -func (c *fakeAppServiceClient) ManagedResources(ctx context.Context, in *applicationpkg.ResourcesQuery, opts ...grpc.CallOption) (*applicationpkg.ManagedResourcesResponse, error) { +func (c *fakeAppServiceClient) ManagedResources(_ context.Context, _ *applicationpkg.ResourcesQuery, _ ...grpc.CallOption) (*applicationpkg.ManagedResourcesResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) ResourceTree(ctx context.Context, in *applicationpkg.ResourcesQuery, opts ...grpc.CallOption) (*v1alpha1.ApplicationTree, error) { +func (c *fakeAppServiceClient) ResourceTree(_ context.Context, _ *applicationpkg.ResourcesQuery, _ ...grpc.CallOption) (*v1alpha1.ApplicationTree, error) { return nil, nil } -func (c *fakeAppServiceClient) WatchResourceTree(ctx context.Context, in *applicationpkg.ResourcesQuery, opts ...grpc.CallOption) (applicationpkg.ApplicationService_WatchResourceTreeClient, error) { +func (c *fakeAppServiceClient) WatchResourceTree(_ context.Context, _ *applicationpkg.ResourcesQuery, _ ...grpc.CallOption) (applicationpkg.ApplicationService_WatchResourceTreeClient, error) { return nil, nil } -func (c *fakeAppServiceClient) Rollback(ctx context.Context, in *applicationpkg.ApplicationRollbackRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Rollback(_ context.Context, _ *applicationpkg.ApplicationRollbackRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) { return nil, nil } -func (c *fakeAppServiceClient) TerminateOperation(ctx context.Context, in *applicationpkg.OperationTerminateRequest, opts ...grpc.CallOption) (*applicationpkg.OperationTerminateResponse, error) { +func (c *fakeAppServiceClient) TerminateOperation(_ context.Context, _ *applicationpkg.OperationTerminateRequest, _ ...grpc.CallOption) (*applicationpkg.OperationTerminateResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) GetResource(ctx context.Context, in *applicationpkg.ApplicationResourceRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) { +func (c *fakeAppServiceClient) GetResource(_ context.Context, _ *applicationpkg.ApplicationResourceRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) PatchResource(ctx context.Context, in *applicationpkg.ApplicationResourcePatchRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) { +func (c *fakeAppServiceClient) PatchResource(_ context.Context, _ *applicationpkg.ApplicationResourcePatchRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) ListResourceActions(ctx context.Context, in *applicationpkg.ApplicationResourceRequest, opts ...grpc.CallOption) (*applicationpkg.ResourceActionsListResponse, error) { +func (c *fakeAppServiceClient) ListResourceActions(_ context.Context, _ *applicationpkg.ApplicationResourceRequest, _ ...grpc.CallOption) (*applicationpkg.ResourceActionsListResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) RunResourceAction(ctx context.Context, in *applicationpkg.ResourceActionRunRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { +func (c *fakeAppServiceClient) RunResourceAction(_ context.Context, _ *applicationpkg.ResourceActionRunRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) DeleteResource(ctx context.Context, in *applicationpkg.ApplicationResourceDeleteRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { +func (c *fakeAppServiceClient) DeleteResource(_ context.Context, _ *applicationpkg.ApplicationResourceDeleteRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) PodLogs(ctx context.Context, in *applicationpkg.ApplicationPodLogsQuery, opts ...grpc.CallOption) (applicationpkg.ApplicationService_PodLogsClient, error) { +func (c *fakeAppServiceClient) PodLogs(_ context.Context, _ *applicationpkg.ApplicationPodLogsQuery, _ ...grpc.CallOption) (applicationpkg.ApplicationService_PodLogsClient, error) { return nil, nil } -func (c *fakeAppServiceClient) ListLinks(ctx context.Context, in *applicationpkg.ListAppLinksRequest, opts ...grpc.CallOption) (*applicationpkg.LinksResponse, error) { +func (c *fakeAppServiceClient) ListLinks(_ context.Context, _ *applicationpkg.ListAppLinksRequest, _ ...grpc.CallOption) (*applicationpkg.LinksResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) ListResourceLinks(ctx context.Context, in *applicationpkg.ApplicationResourceRequest, opts ...grpc.CallOption) (*applicationpkg.LinksResponse, error) { +func (c *fakeAppServiceClient) ListResourceLinks(_ context.Context, _ *applicationpkg.ApplicationResourceRequest, _ ...grpc.CallOption) (*applicationpkg.LinksResponse, error) { return nil, nil } @@ -2284,7 +2284,7 @@ func (c *fakeAcdClient) NewAccountClientOrDie() (io.Closer, accountpkg.AccountSe return nil, nil } -func (c *fakeAcdClient) WatchApplicationWithRetry(ctx context.Context, appName string, revision string) chan *v1alpha1.ApplicationWatchEvent { +func (c *fakeAcdClient) WatchApplicationWithRetry(_ context.Context, _ string, _ string) chan *v1alpha1.ApplicationWatchEvent { appEventsCh := make(chan *v1alpha1.ApplicationWatchEvent) go func() { diff --git a/cmd/argocd/commands/applicationset.go b/cmd/argocd/commands/applicationset.go index 64ed8d3b450e0..55364876ee8df 100644 --- a/cmd/argocd/commands/applicationset.go +++ b/cmd/argocd/commands/applicationset.go @@ -293,7 +293,7 @@ func NewApplicationSetListCommand(clientOpts *argocdclient.ClientOptions) *cobra # List all ApplicationSets argocd appset list `), - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationSetClientOrDie() diff --git a/cmd/argocd/commands/bcrypt.go b/cmd/argocd/commands/bcrypt.go index d2557ef4111e1..7b0b1a75afb73 100644 --- a/cmd/argocd/commands/bcrypt.go +++ b/cmd/argocd/commands/bcrypt.go @@ -16,7 +16,7 @@ func NewBcryptCmd() *cobra.Command { Short: "Generate bcrypt hash for any password", Example: `# Generate bcrypt hash for any password argocd account bcrypt --password YOUR_PASSWORD`, - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { bytePassword := []byte(password) // Hashing the password hash, err := bcrypt.GenerateFromPassword(bytePassword, bcrypt.DefaultCost) diff --git a/cmd/argocd/commands/cert.go b/cmd/argocd/commands/cert.go index 45c78a04830ba..6580b192f3c61 100644 --- a/cmd/argocd/commands/cert.go +++ b/cmd/argocd/commands/cert.go @@ -148,7 +148,7 @@ func NewCertAddSSHCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command command := &cobra.Command{ Use: "add-ssh --batch", Short: "Add SSH known host entries for repository servers", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, certIf := headless.NewClientOrDie(clientOpts, c).NewCertClientOrDie() @@ -276,7 +276,7 @@ func NewCertListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { command := &cobra.Command{ Use: "list", Short: "List configured certificates", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() if certType != "" { diff --git a/cmd/argocd/commands/cluster.go b/cmd/argocd/commands/cluster.go index 165b162356fe2..38435fba4a658 100644 --- a/cmd/argocd/commands/cluster.go +++ b/cmd/argocd/commands/cluster.go @@ -496,7 +496,7 @@ func NewClusterListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman command := &cobra.Command{ Use: "list", Short: "List configured clusters", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, clusterIf := headless.NewClientOrDie(clientOpts, c).NewClusterClientOrDie() diff --git a/cmd/argocd/commands/cluster_test.go b/cmd/argocd/commands/cluster_test.go index 311713a30fbf4..53086c1f95e77 100644 --- a/cmd/argocd/commands/cluster_test.go +++ b/cmd/argocd/commands/cluster_test.go @@ -26,7 +26,7 @@ func Test_getQueryBySelector(t *testing.T) { assert.Equal(t, "https://my-server", query.Server) } -func Test_printClusterTable(t *testing.T) { +func Test_printClusterTable(_ *testing.T) { printClusterTable([]v1alpha1.Cluster{ { Server: "my-server", diff --git a/cmd/argocd/commands/configure.go b/cmd/argocd/commands/configure.go index 15c4bef41e4ea..d61bbe2d45610 100644 --- a/cmd/argocd/commands/configure.go +++ b/cmd/argocd/commands/configure.go @@ -24,7 +24,7 @@ argocd configure --prompts-enabled=true # Disable optional interactive prompts argocd configure --prompts-enabled=false`, - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { localCfg, err := localconfig.ReadLocalConfig(globalClientOpts.ConfigPath) errors.CheckError(err) diff --git a/cmd/argocd/commands/gpg.go b/cmd/argocd/commands/gpg.go index 02cd7adea1a50..1390306b76791 100644 --- a/cmd/argocd/commands/gpg.go +++ b/cmd/argocd/commands/gpg.go @@ -54,7 +54,7 @@ func NewGPGListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { argocd gpg list -o yaml `), - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, gpgIf := headless.NewClientOrDie(clientOpts, c).NewGPGKeyClientOrDie() @@ -133,7 +133,7 @@ func NewGPGAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { argocd gpg add --from /path/to/keyfile `), - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() if fromFile == "" { diff --git a/cmd/argocd/commands/project.go b/cmd/argocd/commands/project.go index 50ae57354a3eb..9332b4474771c 100644 --- a/cmd/argocd/commands/project.go +++ b/cmd/argocd/commands/project.go @@ -828,7 +828,7 @@ func NewProjectListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman # List all available projects in yaml format argocd proj list -o yaml `), - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie() diff --git a/cmd/argocd/commands/repo.go b/cmd/argocd/commands/repo.go index 33a39fbb679c0..3202a7442c55b 100644 --- a/cmd/argocd/commands/repo.go +++ b/cmd/argocd/commands/repo.go @@ -307,7 +307,7 @@ func NewRepoListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { command := &cobra.Command{ Use: "list", Short: "List configured repositories", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, repoIf := headless.NewClientOrDie(clientOpts, c).NewRepoClientOrDie() diff --git a/cmd/argocd/commands/repocreds.go b/cmd/argocd/commands/repocreds.go index 1cc99bf872aee..c0de970a5fe93 100644 --- a/cmd/argocd/commands/repocreds.go +++ b/cmd/argocd/commands/repocreds.go @@ -268,7 +268,7 @@ func NewRepoCredsListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comm # List all repo urls in url format argocd repocreds list -o url `), - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, repoIf := headless.NewClientOrDie(clientOpts, c).NewRepoCredsClientOrDie() diff --git a/cmd/argocd/commands/version.go b/cmd/argocd/commands/version.go index ee7385d06d8f9..293fd50bee61f 100644 --- a/cmd/argocd/commands/version.go +++ b/cmd/argocd/commands/version.go @@ -39,7 +39,7 @@ func NewVersionCmd(clientOpts *argocdclient.ClientOptions, serverVersion *versio # Print only client and server core version strings in YAML format argocd version --short -o yaml `, - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { ctx := cmd.Context() cv := common.GetVersion() diff --git a/cmpserver/plugin/plugin.go b/cmpserver/plugin/plugin.go index ba149c39d16df..9e87e2d74ecf1 100644 --- a/cmpserver/plugin/plugin.go +++ b/cmpserver/plugin/plugin.go @@ -425,7 +425,7 @@ func getParametersAnnouncement(ctx context.Context, appDir string, announcements return repoResponse, nil } -func (s *Service) CheckPluginConfiguration(ctx context.Context, _ *empty.Empty) (*apiclient.CheckPluginConfigurationResponse, error) { +func (s *Service) CheckPluginConfiguration(_ context.Context, _ *empty.Empty) (*apiclient.CheckPluginConfigurationResponse, error) { isDiscoveryConfigured := s.isDiscoveryConfigured() response := &apiclient.CheckPluginConfigurationResponse{IsDiscoveryConfigured: isDiscoveryConfigured, ProvideGitCreds: s.initConstants.PluginConfig.Spec.ProvideGitCreds} diff --git a/commitserver/commit/commit.go b/commitserver/commit/commit.go index 52e7548b36341..f351388f20a4d 100644 --- a/commitserver/commit/commit.go +++ b/commitserver/commit/commit.go @@ -34,7 +34,7 @@ func NewService(gitCredsStore git.CredsStore, metricsServer *metrics.Server) *Se // CommitHydratedManifests handles a commit request. It clones the repository, checks out the sync branch, checks out // the target branch, clears the repository contents, writes the manifests to the repository, commits the changes, and // pushes the changes. It returns the hydrated revision SHA and an error if one occurred. -func (s *Service) CommitHydratedManifests(ctx context.Context, r *apiclient.CommitHydratedManifestsRequest) (*apiclient.CommitHydratedManifestsResponse, error) { +func (s *Service) CommitHydratedManifests(_ context.Context, r *apiclient.CommitHydratedManifestsRequest) (*apiclient.CommitHydratedManifestsResponse, error) { // This method is intentionally short. It's a wrapper around handleCommitRequest that adds metrics and logging. // Keep logic here minimal and put most of the logic in handleCommitRequest. startTime := time.Now() diff --git a/controller/appcontroller.go b/controller/appcontroller.go index e4d5eda967c60..ebb52582be456 100644 --- a/controller/appcontroller.go +++ b/controller/appcontroller.go @@ -239,7 +239,7 @@ func NewApplicationController( } } }, - UpdateFunc: func(old, new any) { + UpdateFunc: func(_, new any) { if key, err := cache.MetaNamespaceKeyFunc(new); err == nil { ctrl.projectRefreshQueue.AddRateLimited(key) if projMeta, ok := new.(metav1.Object); ok { @@ -270,7 +270,7 @@ func NewApplicationController( deploymentInformer = factory.Apps().V1().Deployments() } - readinessHealthCheck := func(r *http.Request) error { + readinessHealthCheck := func(_ *http.Request) error { if dynamicClusterDistributionEnabled { applicationControllerName := env.StringFromEnv(common.EnvAppControllerName, common.DefaultApplicationControllerName) appControllerDeployment, err := deploymentInformer.Lister().Deployments(settingsMgr.GetNamespace()).Get(applicationControllerName) @@ -587,7 +587,7 @@ func (ctrl *ApplicationController) getResourceTree(a *appv1.Application, managed managedResourcesKeys = append(managedResourcesKeys, kube.GetResourceKey(live)) } } - err = ctrl.stateCache.IterateHierarchyV2(a.Spec.Destination.Server, managedResourcesKeys, func(child appv1.ResourceNode, appName string) bool { + err = ctrl.stateCache.IterateHierarchyV2(a.Spec.Destination.Server, managedResourcesKeys, func(child appv1.ResourceNode, _ string) bool { permitted, _ := proj.IsResourcePermitted(schema.GroupKind{Group: child.ResourceRef.Group, Kind: child.ResourceRef.Kind}, child.Namespace, a.Spec.Destination, func(project string) ([]*appv1.Cluster, error) { clusters, err := ctrl.db.GetProjectClusters(context.TODO(), project) if err != nil { diff --git a/controller/appcontroller_test.go b/controller/appcontroller_test.go index 350fa959c3c39..2a5b15a646ee2 100644 --- a/controller/appcontroller_test.go +++ b/controller/appcontroller_test.go @@ -880,11 +880,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -932,11 +932,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -966,11 +966,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -994,7 +994,7 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -1033,11 +1033,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -1077,11 +1077,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -1124,11 +1124,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -1307,7 +1307,7 @@ func TestSetOperationStateOnDeletedApp(t *testing.T) { fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) fakeAppCs.ReactionChain = nil patched := false - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, apierrors.NewNotFound(schema.GroupResource{}, "my-app") }) @@ -1338,7 +1338,7 @@ func TestSetOperationStateLogRetries(t *testing.T) { fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) fakeAppCs.ReactionChain = nil patched := false - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { if !patched { patched = true return true, &v1alpha1.Application{}, errors.New("fake error") @@ -1935,7 +1935,7 @@ func TestFinalizeProjectDeletion_HasApplications(t *testing.T) { fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) patched := false - fakeAppCs.PrependReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.PrependReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) diff --git a/controller/cache/cache.go b/controller/cache/cache.go index b649b02d3c1ce..f3c86f409b135 100644 --- a/controller/cache/cache.go +++ b/controller/cache/cache.go @@ -618,7 +618,7 @@ func (c *liveStateCache) getCluster(server string) (clustercache.ClusterCache, e c.onObjectUpdated(toNotify, ref) }) - _ = clusterCache.OnEvent(func(event watch.EventType, un *unstructured.Unstructured) { + _ = clusterCache.OnEvent(func(_ watch.EventType, un *unstructured.Unstructured) { gvk := un.GroupVersionKind() c.metricsServer.IncClusterEventsCount(cluster.Server, gvk.Group, gvk.Kind) }) diff --git a/controller/cache/cache_test.go b/controller/cache/cache_test.go index 076633444ee49..c02a8fb2c64b7 100644 --- a/controller/cache/cache_test.go +++ b/controller/cache/cache_test.go @@ -40,7 +40,7 @@ func (n netError) Error() string { return string(n) } func (n netError) Timeout() bool { return false } func (n netError) Temporary() bool { return false } -func TestHandleModEvent_HasChanges(t *testing.T) { +func TestHandleModEvent_HasChanges(_ *testing.T) { clusterCache := &mocks.ClusterCache{} clusterCache.On("Invalidate", mock.Anything, mock.Anything).Return(nil).Once() clusterCache.On("EnsureSynced").Return(nil).Once() @@ -72,7 +72,7 @@ func TestHandleModEvent_ClusterExcluded(t *testing.T) { clustersCache := liveStateCache{ db: nil, appInformer: nil, - onObjectUpdated: func(managedByApp map[string]bool, ref corev1.ObjectReference) { + onObjectUpdated: func(_ map[string]bool, _ corev1.ObjectReference) { }, kubectl: nil, settingsMgr: &argosettings.SettingsManager{}, @@ -97,7 +97,7 @@ func TestHandleModEvent_ClusterExcluded(t *testing.T) { assert.Len(t, clustersCache.clusters, 1) } -func TestHandleModEvent_NoChanges(t *testing.T) { +func TestHandleModEvent_NoChanges(_ *testing.T) { clusterCache := &mocks.ClusterCache{} clusterCache.On("Invalidate", mock.Anything).Panic("should not invalidate") clusterCache.On("EnsureSynced").Return(nil).Panic("should not re-sync") @@ -174,7 +174,7 @@ func TestHandleDeleteEvent_CacheDeadlock(t *testing.T) { handleDeleteWasCalled.Lock() engineHoldsEngineLock.Lock() - gitopsEngineClusterCache.On("EnsureSynced").Run(func(args mock.Arguments) { + gitopsEngineClusterCache.On("EnsureSynced").Run(func(_ mock.Arguments) { gitopsEngineClusterCacheLock.Lock() t.Log("EnsureSynced: Engine has engine lock") engineHoldsEngineLock.Unlock() @@ -188,7 +188,7 @@ func TestHandleDeleteEvent_CacheDeadlock(t *testing.T) { ensureSyncedCompleted.Unlock() }).Return(nil).Once() - gitopsEngineClusterCache.On("Invalidate").Run(func(args mock.Arguments) { + gitopsEngineClusterCache.On("Invalidate").Run(func(_ mock.Arguments) { // Allow EnsureSynced to continue now that we're in the deadlock condition handleDeleteWasCalled.Unlock() // Wait until gitops engine holds the gitops lock diff --git a/controller/clusterinfoupdater_test.go b/controller/clusterinfoupdater_test.go index 4467f44b3c4bb..b6ae81dc2768a 100644 --- a/controller/clusterinfoupdater_test.go +++ b/controller/clusterinfoupdater_test.go @@ -102,7 +102,7 @@ func TestClusterSecretUpdater(t *testing.T) { } func TestUpdateClusterLabels(t *testing.T) { - shouldNotBeInvoked := func(ctx context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { + shouldNotBeInvoked := func(_ context.Context, _ *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { shouldNotHappen := errors.New("if an error happens here, something's wrong") require.NoError(t, shouldNotHappen) return nil, shouldNotHappen @@ -160,7 +160,7 @@ func TestUpdateClusterLabels(t *testing.T) { Server: "kubernetes.svc.local", Labels: map[string]string{"argocd.argoproj.io/kubernetes-version": "1.27", "argocd.argoproj.io/auto-label-cluster-info": "true"}, }, - func(ctx context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { + func(_ context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { assert.Equal(t, "1.28", cluster.Labels["argocd.argoproj.io/kubernetes-version"]) return nil, nil }, @@ -176,7 +176,7 @@ func TestUpdateClusterLabels(t *testing.T) { Server: "kubernetes.svc.local", Labels: map[string]string{"argocd.argoproj.io/kubernetes-version": "1.27", "argocd.argoproj.io/auto-label-cluster-info": "true"}, }, - func(ctx context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { + func(_ context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { assert.Equal(t, "1.28", cluster.Labels["argocd.argoproj.io/kubernetes-version"]) return nil, errors.New("some error happened while saving") }, diff --git a/controller/metrics/metrics_test.go b/controller/metrics/metrics_test.go index 5410e274e386c..d50b51a53487c 100644 --- a/controller/metrics/metrics_test.go +++ b/controller/metrics/metrics_test.go @@ -171,11 +171,11 @@ status: status: Healthy ` -var noOpHealthCheck = func(r *http.Request) error { +var noOpHealthCheck = func(_ *http.Request) error { return nil } -var appFilter = func(obj any) bool { +var appFilter = func(_ any) bool { return true } @@ -203,7 +203,7 @@ func newFakeLister(fakeAppYAMLs ...string) (context.CancelFunc, applister.Applic fakeApps = append(fakeApps, a) } appClientset := appclientset.NewSimpleClientset(fakeApps...) - factory := appinformer.NewSharedInformerFactoryWithOptions(appClientset, 0, appinformer.WithNamespace("argocd"), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(appClientset, 0, appinformer.WithNamespace("argocd"), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) appInformer := factory.Argoproj().V1alpha1().Applications().Informer() go appInformer.Run(ctx.Done()) if !cache.WaitForCacheSync(ctx.Done(), appInformer.HasSynced) { diff --git a/controller/sharding/sharding.go b/controller/sharding/sharding.go index 1ae2052efd56f..4c087cd169a79 100644 --- a/controller/sharding/sharding.go +++ b/controller/sharding/sharding.go @@ -63,7 +63,7 @@ type shardApplicationControllerMapping struct { // and returns whether or not the cluster should be processed by a given shard. It calls the distributionFunction // to determine which shard will process the cluster, and if the given shard is equal to the calculated shard // the function will return true. -func GetClusterFilter(db db.ArgoDB, distributionFunction DistributionFunction, replicas, shard int) ClusterFilterFunction { +func GetClusterFilter(_ db.ArgoDB, distributionFunction DistributionFunction, replicas, shard int) ClusterFilterFunction { return func(c *v1alpha1.Cluster) bool { clusterShard := 0 if c != nil && c.Shard != nil { @@ -255,7 +255,7 @@ func getAppDistribution(getCluster clusterAccessor, getApps appAccessor) map[str // NoShardingDistributionFunction returns a DistributionFunction that will process all cluster by shard 0 // the function is created for API compatibility purposes and is not supposed to be activated. func NoShardingDistributionFunction() DistributionFunction { - return func(c *v1alpha1.Cluster) int { return 0 } + return func(_ *v1alpha1.Cluster) int { return 0 } } // InferShard extracts the shard index based on its hostname. diff --git a/controller/state.go b/controller/state.go index c981bb1cc0c81..d4c822ce66b38 100644 --- a/controller/state.go +++ b/controller/state.go @@ -780,7 +780,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1 } gvk := obj.GroupVersionKind() - isSelfReferencedObj := m.isSelfReferencedObj(liveObj, targetObj, app.GetName(), appLabelKey, trackingMethod, installationID) + isSelfReferencedObj := m.isSelfReferencedObj(liveObj, targetObj, app.GetName(), trackingMethod, installationID) resState := v1alpha1.ResourceStatus{ Namespace: obj.GetNamespace(), @@ -1108,7 +1108,7 @@ func NewAppStateManager( // group and kind) match the properties of the live object, or if the tracking method // used does not provide the required properties for matching. // Reference: https://github.com/argoproj/argo-cd/issues/8683 -func (m *appStateManager) isSelfReferencedObj(live, config *unstructured.Unstructured, appName, appLabelKey string, trackingMethod v1alpha1.TrackingMethod, installationID string) bool { +func (m *appStateManager) isSelfReferencedObj(live, config *unstructured.Unstructured, appName string, trackingMethod v1alpha1.TrackingMethod, installationID string) bool { if live == nil { return true } @@ -1141,7 +1141,7 @@ func (m *appStateManager) isSelfReferencedObj(live, config *unstructured.Unstruc // to match the properties from the live object. Cluster scoped objects // carry the app's destination namespace in the tracking annotation, // but are unique in GVK + name combination. - appInstance := m.resourceTracking.GetAppInstance(live, appLabelKey, trackingMethod, installationID) + appInstance := m.resourceTracking.GetAppInstance(live, trackingMethod, installationID) if appInstance != nil { return isSelfReferencedObj(live, *appInstance) } diff --git a/controller/state_test.go b/controller/state_test.go index 6c5f74c18d54d..2cb1bbd231518 100644 --- a/controller/state_test.go +++ b/controller/state_test.go @@ -1410,8 +1410,8 @@ func TestIsLiveResourceManaged(t *testing.T) { configObj := managedObj.DeepCopy() // then - assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) - assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, argo.TrackingMethodLabel, "")) + assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, argo.TrackingMethodAnnotation, "")) }) t.Run("will return true if tracked with label", func(t *testing.T) { // given @@ -1419,43 +1419,43 @@ func TestIsLiveResourceManaged(t *testing.T) { configObj := managedObjWithLabel.DeepCopy() // then - assert.True(t, manager.isSelfReferencedObj(managedObjWithLabel, configObj, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) + assert.True(t, manager.isSelfReferencedObj(managedObjWithLabel, configObj, appName, argo.TrackingMethodLabel, "")) }) t.Run("will handle if trackingId has wrong resource name and config is nil", func(t *testing.T) { // given t.Parallel() // then - assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongName, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) - assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongName, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongName, nil, appName, argo.TrackingMethodLabel, "")) + assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongName, nil, appName, argo.TrackingMethodAnnotation, "")) }) t.Run("will handle if trackingId has wrong resource group and config is nil", func(t *testing.T) { // given t.Parallel() // then - assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongGroup, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) - assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongGroup, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongGroup, nil, appName, argo.TrackingMethodLabel, "")) + assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongGroup, nil, appName, argo.TrackingMethodAnnotation, "")) }) t.Run("will handle if trackingId has wrong kind and config is nil", func(t *testing.T) { // given t.Parallel() // then - assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongKind, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) - assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongKind, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongKind, nil, appName, argo.TrackingMethodLabel, "")) + assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongKind, nil, appName, argo.TrackingMethodAnnotation, "")) }) t.Run("will handle if trackingId has wrong namespace and config is nil", func(t *testing.T) { // given t.Parallel() // then - assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongNamespace, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) - assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongNamespace, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotationAndLabel, "")) + assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongNamespace, nil, appName, argo.TrackingMethodLabel, "")) + assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongNamespace, nil, appName, argo.TrackingMethodAnnotationAndLabel, "")) }) t.Run("will return true if live is nil", func(t *testing.T) { t.Parallel() - assert.True(t, manager.isSelfReferencedObj(nil, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(nil, nil, appName, argo.TrackingMethodAnnotation, "")) }) t.Run("will handle upgrade in desired state APIGroup", func(t *testing.T) { @@ -1465,7 +1465,7 @@ func TestIsLiveResourceManaged(t *testing.T) { delete(config.GetAnnotations(), common.AnnotationKeyAppInstance) // then - assert.True(t, manager.isSelfReferencedObj(managedWrongAPIGroup, config, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(managedWrongAPIGroup, config, appName, argo.TrackingMethodAnnotation, "")) }) } diff --git a/controller/sync.go b/controller/sync.go index bb39bfdaef7d3..a54d0b4d9b0f7 100644 --- a/controller/sync.go +++ b/controller/sync.go @@ -307,11 +307,6 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha reconciliationResult.Target = patchedTargets } - appLabelKey, err := m.settingsMgr.GetAppInstanceLabelKey() - if err != nil { - log.Errorf("Could not get appInstanceLabelKey: %v", err) - return - } installationID, err := m.settingsMgr.GetInstallationID() if err != nil { log.Errorf("Could not get installation ID: %v", err) @@ -368,7 +363,7 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha return (len(syncOp.Resources) == 0 || isPostDeleteHook(target) || argo.ContainsSyncResource(key.Name, key.Namespace, schema.GroupVersionKind{Kind: key.Kind, Group: key.Group}, syncOp.Resources)) && - m.isSelfReferencedObj(live, target, app.GetName(), appLabelKey, trackingMethod, installationID) + m.isSelfReferencedObj(live, target, app.GetName(), trackingMethod, installationID) }), sync.WithManifestValidation(!syncOp.SyncOptions.HasOption(common.SyncOptionsDisableValidation)), sync.WithSyncWaveHook(delayBetweenSyncWaves), @@ -572,7 +567,7 @@ func hasSharedResourceCondition(app *v1alpha1.Application) (bool, string) { // Note, this is not foolproof, since a proper fix would require the CRD record // status.observedGeneration coupled with a health.lua that verifies // status.observedGeneration == metadata.generation -func delayBetweenSyncWaves(phase common.SyncPhase, wave int, finalWave bool) error { +func delayBetweenSyncWaves(_ common.SyncPhase, _ int, finalWave bool) error { if !finalWave { delaySec := 2 if delaySecStr := os.Getenv(EnvVarSyncWaveDelay); delaySecStr != "" { diff --git a/hack/dev-mounter/main.go b/hack/dev-mounter/main.go index 59f5fbb918ee6..a50904dd07950 100644 --- a/hack/dev-mounter/main.go +++ b/hack/dev-mounter/main.go @@ -34,7 +34,7 @@ func newCommand() *cobra.Command { configMaps []string ) command := cobra.Command{ - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { config, err := clientConfig.ClientConfig() errors.CheckError(err) ns, _, err := clientConfig.Namespace() @@ -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 any) { + UpdateFunc: func(_, newObj any) { handledConfigMap(newObj) }, }) diff --git a/hack/gen-catalog/main.go b/hack/gen-catalog/main.go index decc4a39eda26..2c16b72aeab1c 100644 --- a/hack/gen-catalog/main.go +++ b/hack/gen-catalog/main.go @@ -42,7 +42,7 @@ func main() { func newCatalogCommand() *cobra.Command { return &cobra.Command{ Use: "catalog", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { cm := corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", @@ -89,7 +89,7 @@ func newCatalogCommand() *cobra.Command { func newDocsCommand() *cobra.Command { return &cobra.Command{ Use: "docs", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { var builtItDocsData bytes.Buffer wd, err := os.Getwd() dieOnError(err, "Failed to get current working directory") diff --git a/hack/gen-resources/cmd/commands/cmd.go b/hack/gen-resources/cmd/commands/cmd.go index 5804e4cda8910..9124e7fc07408 100644 --- a/hack/gen-resources/cmd/commands/cmd.go +++ b/hack/gen-resources/cmd/commands/cmd.go @@ -53,7 +53,7 @@ func NewGenerateCommand(opts *util.GenerateOpts) *cobra.Command { Use: "generate [-f file]", Short: "Generate entities", Long: "Generate entities", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { log.Printf("Retrieve configuration from %s", file) err := util.Parse(opts, file) if err != nil { @@ -97,7 +97,7 @@ func NewCleanCommand(opts *util.GenerateOpts) *cobra.Command { Use: "clean", Short: "Clean entities", Long: "Clean entities", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { argoClientSet := util.ConnectToK8sArgoClientSet() clientSet := util.ConnectToK8sClientSet() settingsMgr := settings.NewSettingsManager(context.TODO(), clientSet, opts.Namespace) diff --git a/hack/known_types/main.go b/hack/known_types/main.go index ca2cf23a380f7..b6c914fd19b02 100644 --- a/hack/known_types/main.go +++ b/hack/known_types/main.go @@ -27,7 +27,7 @@ func newCommand() *cobra.Command { command := &cobra.Command{ Use: "go run github.com/argoproj/argo-cd/hack/known_types ALIAS PACKAGE_PATH OUTPUT_PATH", Example: "go run github.com/argoproj/argo-cd/hack/known_types corev1 k8s.io/api/core/v1 corev1_known_types.go", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, args []string) error { if len(args) < 3 { return errors.New("alias and package are not specified") } diff --git a/pkg/apiclient/grpcproxy.go b/pkg/apiclient/grpcproxy.go index 70fcafb805f7d..97a8be3449fc5 100644 --- a/pkg/apiclient/grpcproxy.go +++ b/pkg/apiclient/grpcproxy.go @@ -118,7 +118,7 @@ func (c *client) startGRPCProxy() (*grpc.Server, net.Listener, error) { MinTime: common.GetGRPCKeepAliveEnforcementMinimum(), }, ), - grpc.UnknownServiceHandler(func(srv any, stream grpc.ServerStream) error { + grpc.UnknownServiceHandler(func(_ 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/applicationset_types.go b/pkg/apis/application/v1alpha1/applicationset_types.go index 16f9eeecd5d85..1497dd54f41dd 100644 --- a/pkg/apis/application/v1alpha1/applicationset_types.go +++ b/pkg/apis/application/v1alpha1/applicationset_types.go @@ -908,7 +908,7 @@ func (a *ApplicationSet) RefreshRequired() bool { // If the applicationset has a pre-existing condition of a type that is not in the evaluated list, // it will be preserved. If the applicationset has a pre-existing condition of a type, status, reason that // is in the evaluated list, but not in the incoming conditions list, it will be removed. -func (status *ApplicationSetStatus) SetConditions(conditions []ApplicationSetCondition, evaluatedTypes map[ApplicationSetConditionType]bool) { +func (status *ApplicationSetStatus) SetConditions(conditions []ApplicationSetCondition, _ map[ApplicationSetConditionType]bool) { applicationSetConditions := make([]ApplicationSetCondition, 0) now := metav1.Now() for i := range conditions { diff --git a/pkg/apis/application/v1alpha1/types_test.go b/pkg/apis/application/v1alpha1/types_test.go index 754ff50beca17..27e14da50c9a5 100644 --- a/pkg/apis/application/v1alpha1/types_test.go +++ b/pkg/apis/application/v1alpha1/types_test.go @@ -235,7 +235,7 @@ func TestAppProject_IsDestinationPermitted(t *testing.T) { Destinations: data.projDest, }, } - permitted, _ := proj.IsDestinationPermitted(data.appDest, func(project string) ([]*Cluster, error) { + permitted, _ := proj.IsDestinationPermitted(data.appDest, func(_ string) ([]*Cluster, error) { return []*Cluster{}, nil }) assert.Equal(t, data.isPermitted, permitted) @@ -402,7 +402,7 @@ func TestAppProject_IsNegatedDestinationPermitted(t *testing.T) { Destinations: data.projDest, }, } - permitted, _ := proj.IsDestinationPermitted(data.appDest, func(project string) ([]*Cluster, error) { + permitted, _ := proj.IsDestinationPermitted(data.appDest, func(_ string) ([]*Cluster, error) { return []*Cluster{}, nil }) assert.Equalf(t, data.isPermitted, permitted, "appDest mismatch for %+v with project destinations %+v", data.appDest, data.projDest) diff --git a/reposerver/cache/cache_test.go b/reposerver/cache/cache_test.go index 18ead8aa9e52b..5f32d87066376 100644 --- a/reposerver/cache/cache_test.go +++ b/reposerver/cache/cache_test.go @@ -503,7 +503,7 @@ func TestGetOrLockGitReferences(t *testing.T) { t.Cleanup(fixtures.mockCache.StopRedisCallback) cache := fixtures.cache fixtures.mockCache.RedisClient.On("Get", mock.Anything, mock.Anything).Unset() - fixtures.mockCache.RedisClient.On("Get", mock.Anything, mock.Anything).Return(cacheutil.ErrCacheMiss).Once().Run(func(args mock.Arguments) { + fixtures.mockCache.RedisClient.On("Get", mock.Anything, mock.Anything).Return(cacheutil.ErrCacheMiss).Once().Run(func(_ mock.Arguments) { err := cache.SetGitReferences("test-repo", *GitRefCacheItemToReferences([][2]string{{"test-repo", "ref: test"}})) require.NoError(t, err) }).On("Get", mock.Anything, mock.Anything).Return(nil) diff --git a/reposerver/repository/repository.go b/reposerver/repository/repository.go index 2c408151bfa6c..f5a036fac6c16 100644 --- a/reposerver/repository/repository.go +++ b/reposerver/repository/repository.go @@ -182,7 +182,7 @@ func (s *Service) Init() error { } // ListRefs List a subset of the refs (currently, branches and tags) of a git repo -func (s *Service) ListRefs(ctx context.Context, q *apiclient.ListRefsRequest) (*apiclient.Refs, error) { +func (s *Service) ListRefs(_ context.Context, q *apiclient.ListRefsRequest) (*apiclient.Refs, error) { gitClient, err := s.newClient(q.Repo) if err != nil { return nil, fmt.Errorf("error creating git client: %w", err) @@ -239,7 +239,7 @@ func (s *Service) ListApps(ctx context.Context, q *apiclient.ListAppsRequest) (* } // ListPlugins lists the contents of a GitHub repo -func (s *Service) ListPlugins(ctx context.Context, _ *empty.Empty) (*apiclient.PluginList, error) { +func (s *Service) ListPlugins(_ context.Context, _ *empty.Empty) (*apiclient.PluginList, error) { pluginSockFilePath := common.GetPluginSockFilePath() sockFiles, err := os.ReadDir(pluginSockFilePath) @@ -2288,7 +2288,7 @@ func populatePluginAppDetails(ctx context.Context, res *apiclient.RepoAppDetails return nil } -func (s *Service) GetRevisionMetadata(ctx context.Context, q *apiclient.RepoServerRevisionMetadataRequest) (*v1alpha1.RevisionMetadata, error) { +func (s *Service) GetRevisionMetadata(_ context.Context, q *apiclient.RepoServerRevisionMetadataRequest) (*v1alpha1.RevisionMetadata, error) { if !(git.IsCommitSHA(q.Revision) || git.IsTruncatedCommitSHA(q.Revision)) { return nil, fmt.Errorf("revision %s must be resolved", q.Revision) } @@ -2365,7 +2365,7 @@ func (s *Service) GetRevisionMetadata(ctx context.Context, q *apiclient.RepoServ } // GetRevisionChartDetails returns the helm chart details of a given version -func (s *Service) GetRevisionChartDetails(ctx context.Context, q *apiclient.RepoServerRevisionChartDetailsRequest) (*v1alpha1.ChartDetails, error) { +func (s *Service) GetRevisionChartDetails(_ context.Context, q *apiclient.RepoServerRevisionChartDetailsRequest) (*v1alpha1.ChartDetails, error) { details, err := s.cache.GetRevisionChartDetails(q.Repo.Repo, q.Name, q.Revision) if err == nil { log.Infof("revision chart details cache hit: %s/%s/%s", q.Repo.Repo, q.Name, q.Revision) @@ -2552,7 +2552,7 @@ func checkoutRevision(gitClient git.Client, revision string, submoduleEnabled bo return err } -func (s *Service) GetHelmCharts(ctx context.Context, q *apiclient.HelmChartsRequest) (*apiclient.HelmChartsResponse, error) { +func (s *Service) GetHelmCharts(_ context.Context, q *apiclient.HelmChartsRequest) (*apiclient.HelmChartsResponse, error) { index, err := s.newHelmClient(q.Repo.Repo, q.Repo.GetHelmCreds(), q.Repo.EnableOCI, q.Repo.Proxy, q.Repo.NoProxy, helm.WithIndexCache(s.cache), helm.WithChartPaths(s.chartPaths)).GetIndex(true, s.initConstants.HelmRegistryMaxIndexSize) if err != nil { return nil, err @@ -2570,7 +2570,7 @@ func (s *Service) GetHelmCharts(ctx context.Context, q *apiclient.HelmChartsRequ return &res, nil } -func (s *Service) TestRepository(ctx context.Context, q *apiclient.TestRepositoryRequest) (*apiclient.TestRepositoryResponse, error) { +func (s *Service) TestRepository(_ context.Context, q *apiclient.TestRepositoryRequest) (*apiclient.TestRepositoryResponse, error) { repo := q.Repo // per Type doc, "git" should be assumed if empty or absent if repo.Type == "" { @@ -2603,7 +2603,7 @@ func (s *Service) TestRepository(ctx context.Context, q *apiclient.TestRepositor } // ResolveRevision resolves the revision/ambiguousRevision specified in the ResolveRevisionRequest request into a concrete revision. -func (s *Service) ResolveRevision(ctx context.Context, q *apiclient.ResolveRevisionRequest) (*apiclient.ResolveRevisionResponse, error) { +func (s *Service) ResolveRevision(_ context.Context, q *apiclient.ResolveRevisionRequest) (*apiclient.ResolveRevisionResponse, error) { repo := q.Repo app := q.App ambiguousRevision := q.AmbiguousRevision diff --git a/reposerver/repository/repository_test.go b/reposerver/repository/repository_test.go index 38196a1fdb33a..d733f122773c0 100644 --- a/reposerver/repository/repository_test.go +++ b/reposerver/repository/repository_test.go @@ -149,13 +149,13 @@ func newServiceWithOpt(t *testing.T, cf clientFunc, root string) (*Service, *git t.Cleanup(cacheMocks.mockCache.StopRedisCallback) service := NewService(metrics.NewMetricsServer(), cacheMocks.cache, RepoServerInitConstants{ParallelismLimit: 1}, argo.NewResourceTracking(), &git.NoopCredsStore{}, root) - service.newGitClient = func(rawRepoURL string, root string, creds git.Creds, insecure bool, enableLfs bool, proxy string, noProxy string, opts ...git.ClientOpts) (client git.Client, e error) { + service.newGitClient = func(_ string, _ string, _ git.Creds, _ bool, _ bool, _ string, _ string, _ ...git.ClientOpts) (client git.Client, e error) { return gitClient, nil } - service.newHelmClient = func(repoURL string, creds helm.Creds, enableOci bool, proxy string, noProxy string, opts ...helm.ClientOpts) helm.Client { + service.newHelmClient = func(_ string, _ helm.Creds, _ bool, _ string, _ string, _ ...helm.ClientOpts) helm.Client { return helmClient } - service.gitRepoInitializer = func(rootPath string) goio.Closer { + service.gitRepoInitializer = func(_ string) goio.Closer { return io.NopCloser } service.gitRepoPaths = paths @@ -183,7 +183,7 @@ func newServiceWithCommitSHA(t *testing.T, root, revision string) *Service { revisionErr = errors.New("not a commit SHA") } - service, gitClient, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + service, gitClient, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -195,7 +195,7 @@ func newServiceWithCommitSHA(t *testing.T, root, revision string) *Service { paths.On("GetPathIfExists", mock.Anything).Return(root, nil) }, root) - service.newGitClient = func(rawRepoURL string, root string, creds git.Creds, insecure bool, enableLfs bool, proxy string, noProxy string, opts ...git.ClientOpts) (client git.Client, e error) { + service.newGitClient = func(_ string, _ string, _ git.Creds, _ bool, _ bool, _ string, _ string, _ ...git.ClientOpts) (client git.Client, e error) { return gitClient, nil } @@ -370,12 +370,12 @@ func TestGenerateManifest_RefOnlyShortCircuit(t *testing.T) { service.newGitClient = func(rawRepoURL string, root string, creds git.Creds, insecure bool, enableLfs bool, proxy string, noProxy string, opts ...git.ClientOpts) (client git.Client, e error) { opts = append(opts, git.WithEventHandlers(git.EventHandlers{ // Primary check, we want to make sure ls-remote is not called when the item is in cache - OnLsRemote: func(repo string) func() { + OnLsRemote: func(_ string) func() { return func() { lsremoteCalled = true } }, - OnFetch: func(repo string) func() { + OnFetch: func(_ string) func() { return func() { assert.Fail(t, "Fetch should not be called from GenerateManifest when the source is ref only") } @@ -422,7 +422,7 @@ func TestGenerateManifestsHelmWithRefs_CachedNoLsRemote(t *testing.T) { t.Cleanup(func() { cacheMocks.mockCache.StopRedisCallback() err := filepath.WalkDir(dir, - func(path string, di fs.DirEntry, err error) error { + func(path string, _ fs.DirEntry, err error) error { if err == nil { return os.Chmod(path, 0o777) } @@ -436,7 +436,7 @@ func TestGenerateManifestsHelmWithRefs_CachedNoLsRemote(t *testing.T) { service.newGitClient = func(rawRepoURL string, root string, creds git.Creds, insecure bool, enableLfs bool, proxy string, noProxy string, opts ...git.ClientOpts) (client git.Client, e error) { opts = append(opts, git.WithEventHandlers(git.EventHandlers{ // Primary check, we want to make sure ls-remote is not called when the item is in cache - OnLsRemote: func(repo string) func() { + OnLsRemote: func(_ string) func() { return func() { assert.Fail(t, "LsRemote should not be called when the item is in cache") } @@ -518,7 +518,7 @@ func TestHelmChartReferencingExternalValues(t *testing.T) { {Ref: "ref", RepoURL: "https://git.example.com/test/repo"}, }, } - refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(ctx context.Context, url string, project string) (*v1alpha1.Repository, error) { + refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(_ context.Context, _ string, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{ Repo: "https://git.example.com/test/repo", }, nil @@ -554,7 +554,7 @@ func TestHelmChartReferencingExternalValues_InvalidRefs(t *testing.T) { // Empty refsource service := newService(t, ".") - getRepository := func(ctx context.Context, url string, project string) (*v1alpha1.Repository, error) { + getRepository := func(_ context.Context, _ string, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{ Repo: "https://git.example.com/test/repo", }, nil @@ -627,7 +627,7 @@ func TestHelmChartReferencingExternalValues_OutOfBounds_Symlink(t *testing.T) { {Ref: "ref", RepoURL: "https://git.example.com/test/repo"}, }, } - refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(ctx context.Context, url string, project string) (*v1alpha1.Repository, error) { + refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(_ context.Context, _ string, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{ Repo: "https://git.example.com/test/repo", }, nil @@ -2052,7 +2052,7 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { t.Run("Multi-source with source as ref only does not generate manifests", func(t *testing.T) { service := newService(t, ".") - runWithTempTestdata(t, "single-app-only", func(t *testing.T, path string) { + runWithTempTestdata(t, "single-app-only", func(t *testing.T, _ string) { t.Helper() manifests, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ Repo: &v1alpha1.Repository{}, @@ -3396,7 +3396,7 @@ func TestErrorGetGitDirectories(t *testing.T) { }, }, want: nil, wantErr: assert.Error}, {name: "InvalidResolveRevision", fields: fields{service: func() *Service { - s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", mock.Anything).Return("", errors.New("ah error")) gitClient.On("Root").Return(root) @@ -3413,7 +3413,7 @@ func TestErrorGetGitDirectories(t *testing.T) { }, }, want: nil, wantErr: assert.Error}, {name: "ErrorVerifyCommit", fields: fields{service: func() *Service { - s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", mock.Anything).Return("", errors.New("ah error")) gitClient.On("VerifyCommitSignature", mock.Anything).Return("", fmt.Errorf("revision %s is not signed", "sadfsadf")) @@ -3447,7 +3447,7 @@ func TestErrorGetGitDirectories(t *testing.T) { func TestGetGitDirectories(t *testing.T) { // test not using the cache root := "./testdata/git-files-dirs" - s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -3480,7 +3480,7 @@ func TestGetGitDirectories(t *testing.T) { func TestGetGitDirectoriesWithHiddenDirSupported(t *testing.T) { // test not using the cache root := "./testdata/git-files-dirs" - s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -3538,7 +3538,7 @@ func TestErrorGetGitFiles(t *testing.T) { }, }, want: nil, wantErr: assert.Error}, {name: "InvalidResolveRevision", fields: fields{service: func() *Service { - s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", mock.Anything).Return("", errors.New("ah error")) gitClient.On("Root").Return(root) @@ -3574,7 +3574,7 @@ func TestGetGitFiles(t *testing.T) { "./testdata/git-files-dirs/config.yaml", "./testdata/git-files-dirs/config.yaml", "./testdata/git-files-dirs/app/foo/bar/config.yaml", } root := "" - s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -3641,7 +3641,7 @@ func TestErrorUpdateRevisionForPaths(t *testing.T) { }, }, want: nil, wantErr: assert.Error}, {name: "InvalidResolveRevision", fields: fields{service: func() *Service { - s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", mock.Anything).Return("", errors.New("ah error")) gitClient.On("Root").Return(root) @@ -3659,7 +3659,7 @@ func TestErrorUpdateRevisionForPaths(t *testing.T) { }, }, want: nil, wantErr: assert.Error}, {name: "InvalidResolveSyncedRevision", fields: fields{service: func() *Service { - s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", "HEAD").Once().Return("632039659e542ed7de0c170a4fcc1c571b288fc0", nil) gitClient.On("LsRemote", mock.Anything).Return("", errors.New("ah error")) @@ -3712,7 +3712,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { cacheHit *cacheHit }{ {name: "NoPathAbort", fields: func() fields { - s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, _ *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) }, ".") return fields{ @@ -3727,7 +3727,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { }, }, want: &apiclient.UpdateRevisionForPathsResponse{}, wantErr: assert.NoError}, {name: "SameResolvedRevisionAbort", fields: func() fields { - s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", "HEAD").Once().Return("632039659e542ed7de0c170a4fcc1c571b288fc0", nil) gitClient.On("LsRemote", "SYNCEDHEAD").Once().Return("632039659e542ed7de0c170a4fcc1c571b288fc0", nil) @@ -3750,7 +3750,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { Revision: "632039659e542ed7de0c170a4fcc1c571b288fc0", }, wantErr: assert.NoError}, {name: "ChangedFilesDoNothing", fields: func() fields { - s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -3779,7 +3779,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { Changes: true, }, wantErr: assert.NoError}, {name: "NoChangesUpdateCache", fields: func() fields { - s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -3817,7 +3817,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { revision: "632039659e542ed7de0c170a4fcc1c571b288fc0", }}, {name: "NoChangesHelmMultiSourceUpdateCache", fields: func() fields { - s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) diff --git a/server/account/account.go b/server/account/account.go index 541401a731022..405966f137baa 100644 --- a/server/account/account.go +++ b/server/account/account.go @@ -180,7 +180,7 @@ func (s *Server) ensureHasAccountPermission(ctx context.Context, action string, } // ListAccounts returns the list of accounts -func (s *Server) ListAccounts(ctx context.Context, r *account.ListAccountRequest) (*account.AccountsList, error) { +func (s *Server) ListAccounts(ctx context.Context, _ *account.ListAccountRequest) (*account.AccountsList, error) { resp := account.AccountsList{} accounts, err := s.settingsMgr.GetAccounts() if err != nil { diff --git a/server/account/account_test.go b/server/account/account_test.go index 3028171cd3289..272a0297c9c4f 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 *corev1.ConfigMap, secret *corev1.Secret)) (*Server, *session.Server) { - return newTestAccountServerExt(ctx, func(claims jwt.Claims, rvals ...any) bool { + return newTestAccountServerExt(ctx, func(_ jwt.Claims, _ ...any) bool { return true }, opts...) } @@ -140,7 +140,7 @@ func TestUpdatePassword(t *testing.T) { } func TestUpdatePassword_AdminUpdatesAnotherUser(t *testing.T) { - accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := adminContext(context.Background()) @@ -153,12 +153,12 @@ func TestUpdatePassword_AdminUpdatesAnotherUser(t *testing.T) { } func TestUpdatePassword_DoesNotHavePermissions(t *testing.T) { - enforcer := func(claims jwt.Claims, rvals ...any) bool { + enforcer := func(_ jwt.Claims, _ ...any) bool { return false } t.Run("LocalAccountUpdatesAnotherAccount", func(t *testing.T) { - accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := adminContext(context.Background()) @@ -175,7 +175,7 @@ func TestUpdatePassword_DoesNotHavePermissions(t *testing.T) { } func TestUpdatePassword_ProjectToken(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := projTokenContext(context.Background()) @@ -184,7 +184,7 @@ func TestUpdatePassword_ProjectToken(t *testing.T) { } func TestUpdatePassword_OldSSOToken(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := ssoAdminContext(context.Background(), time.Now().Add(-2*common.ChangePasswordSSOTokenMaxAge)) @@ -194,7 +194,7 @@ func TestUpdatePassword_OldSSOToken(t *testing.T) { } func TestUpdatePassword_SSOUserUpdatesAnotherUser(t *testing.T) { - accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := ssoAdminContext(context.Background(), time.Now()) @@ -217,7 +217,7 @@ func TestListAccounts_NoAccountsConfigured(t *testing.T) { func TestListAccounts_AccountsAreConfigured(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" cm.Data["accounts.account2"] = "login, apiKey" cm.Data["accounts.account2.enabled"] = "false" @@ -235,7 +235,7 @@ func TestListAccounts_AccountsAreConfigured(t *testing.T) { func TestGetAccount(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" }) @@ -255,7 +255,7 @@ func TestGetAccount(t *testing.T) { func TestCreateToken_SuccessfullyCreated(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" }) @@ -270,7 +270,7 @@ func TestCreateToken_SuccessfullyCreated(t *testing.T) { func TestCreateToken_DoesNotHaveCapability(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.account1"] = "login" }) @@ -280,7 +280,7 @@ func TestCreateToken_DoesNotHaveCapability(t *testing.T) { func TestCreateToken_UserSpecifiedID(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" }) @@ -309,7 +309,7 @@ func TestDeleteToken_SuccessfullyRemoved(t *testing.T) { } func TestCanI_GetLogsAllowNoSwitch(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(_ *corev1.ConfigMap, _ *corev1.Secret) { }) ctx := projTokenContext(context.Background()) @@ -319,11 +319,11 @@ func TestCanI_GetLogsAllowNoSwitch(t *testing.T) { } func TestCanI_GetLogsDenySwitchOn(t *testing.T) { - enforcer := func(claims jwt.Claims, rvals ...any) bool { + enforcer := func(_ jwt.Claims, _ ...any) bool { return false } - accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["server.rbac.log.enforce.enable"] = "true" }) @@ -334,7 +334,7 @@ func TestCanI_GetLogsDenySwitchOn(t *testing.T) { } func TestCanI_GetLogsAllowSwitchOn(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["server.rbac.log.enforce.enable"] = "true" }) @@ -345,7 +345,7 @@ func TestCanI_GetLogsAllowSwitchOn(t *testing.T) { } func TestCanI_GetLogsAllowSwitchOff(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["server.rbac.log.enforce.enable"] = "false" }) diff --git a/server/application/application_test.go b/server/application/application_test.go index 51074a86cec65..55776c1f290b2 100644 --- a/server/application/application_test.go +++ b/server/application/application_test.go @@ -71,7 +71,7 @@ type broadcasterMock struct { objects []runtime.Object } -func (b broadcasterMock) Subscribe(ch chan *v1alpha1.ApplicationWatchEvent, filters ...func(event *v1alpha1.ApplicationWatchEvent) bool) func() { +func (b broadcasterMock) Subscribe(ch chan *v1alpha1.ApplicationWatchEvent, _ ...func(event *v1alpha1.ApplicationWatchEvent) bool) func() { // Simulate the broadcaster notifying the subscriber of an application update. // The second parameter to Subscribe is filters. For the purposes of tests, we ignore the filters. Future tests // might require implementing those. @@ -228,7 +228,7 @@ func newTestAppServerWithEnforcerConfigure(t *testing.T, f func(*rbac.Enforcer), objects = append(objects, defaultProj, myProj, projWithSyncWindows) fakeAppsClientset := apps.NewSimpleClientset(objects...) - factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) fakeProjLister := factory.Argoproj().V1alpha1().AppProjects().Lister().AppProjects(testNamespace) enforcer := rbac.NewEnforcer(kubeclientset, testNamespace, common.ArgoCDRBACConfigMapName, nil) @@ -391,7 +391,7 @@ func newTestAppServerWithEnforcerConfigureWithBenchmark(b *testing.B, f func(*rb objects = append(objects, defaultProj, myProj, projWithSyncWindows) fakeAppsClientset := apps.NewSimpleClientset(objects...) - factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) fakeProjLister := factory.Argoproj().V1alpha1().AppProjects().Lister().AppProjects(testNamespace) enforcer := rbac.NewEnforcer(kubeclientset, testNamespace, common.ArgoCDRBACConfigMapName, nil) @@ -582,15 +582,15 @@ func (t *TestServerStream) Context() context.Context { return t.ctx } -func (t *TestServerStream) SendMsg(m any) error { +func (t *TestServerStream) SendMsg(_ any) error { return nil } -func (t *TestServerStream) RecvMsg(m any) error { +func (t *TestServerStream) RecvMsg(_ any) error { return nil } -func (t *TestServerStream) SendAndClose(r *apiclient.ManifestResponse) error { +func (t *TestServerStream) SendAndClose(_ *apiclient.ManifestResponse) error { return nil } @@ -616,7 +616,7 @@ type TestResourceTreeServer struct { ctx context.Context } -func (t *TestResourceTreeServer) Send(tree *v1alpha1.ApplicationTree) error { +func (t *TestResourceTreeServer) Send(_ *v1alpha1.ApplicationTree) error { return nil } @@ -634,11 +634,11 @@ func (t *TestResourceTreeServer) Context() context.Context { return t.ctx } -func (t *TestResourceTreeServer) SendMsg(m any) error { +func (t *TestResourceTreeServer) SendMsg(_ any) error { return nil } -func (t *TestResourceTreeServer) RecvMsg(m any) error { +func (t *TestResourceTreeServer) RecvMsg(_ any) error { return nil } @@ -646,7 +646,7 @@ type TestPodLogsServer struct { ctx context.Context } -func (t *TestPodLogsServer) Send(log *application.LogEntry) error { +func (t *TestPodLogsServer) Send(_ *application.LogEntry) error { return nil } @@ -664,11 +664,11 @@ func (t *TestPodLogsServer) Context() context.Context { return t.ctx } -func (t *TestPodLogsServer) SendMsg(m any) error { +func (t *TestPodLogsServer) SendMsg(_ any) error { return nil } -func (t *TestPodLogsServer) RecvMsg(m any) error { +func (t *TestPodLogsServer) RecvMsg(_ any) error { return nil } @@ -1556,15 +1556,15 @@ func TestDeleteApp(t *testing.T) { fakeAppCs.ReactionChain = nil patched := false deleted := false - fakeAppCs.AddReactor("patch", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, nil, nil }) - fakeAppCs.AddReactor("delete", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("delete", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { deleted = true return true, nil, nil }) - fakeAppCs.AddReactor("get", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("get", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { return true, &v1alpha1.Application{Spec: v1alpha1.ApplicationSpec{Source: &v1alpha1.ApplicationSource{}}}, nil }) appServer.appclientset = fakeAppCs @@ -2014,7 +2014,7 @@ func TestGetCachedAppState(t *testing.T) { } appServer := newTestAppServer(t, testApp, testProj) fakeClientSet := appServer.appclientset.(*apps.Clientset) - fakeClientSet.AddReactor("get", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeClientSet.AddReactor("get", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { return true, &v1alpha1.Application{Spec: v1alpha1.ApplicationSpec{Source: &v1alpha1.ApplicationSource{}}}, nil }) t.Run("NoError", func(t *testing.T) { @@ -2033,18 +2033,18 @@ func TestGetCachedAppState(t *testing.T) { fakeClientSet.Lock() fakeClientSet.ReactionChain = nil fakeClientSet.WatchReactionChain = nil - fakeClientSet.AddReactor("patch", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeClientSet.AddReactor("patch", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true updated := testApp.DeepCopy() updated.ResourceVersion = "2" appServer.appBroadcaster.OnUpdate(testApp, updated) return true, testApp, nil }) - fakeClientSet.AddReactor("get", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeClientSet.AddReactor("get", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { return true, &v1alpha1.Application{Spec: v1alpha1.ApplicationSpec{Source: &v1alpha1.ApplicationSource{}}}, nil }) fakeClientSet.Unlock() - fakeClientSet.AddWatchReactor("applications", func(action kubetesting.Action) (handled bool, ret watch.Interface, err error) { + fakeClientSet.AddWatchReactor("applications", func(_ kubetesting.Action) (handled bool, ret watch.Interface, err error) { return true, watcher, nil }) } diff --git a/server/application/logs_test.go b/server/application/logs_test.go index 7a565e37efa79..fad125b33aa13 100644 --- a/server/application/logs_test.go +++ b/server/application/logs_test.go @@ -76,7 +76,7 @@ func TestMergeLogStreams(t *testing.T) { assert.Equal(t, []string{"1", "2", "3", "4"}, lines) } -func TestMergeLogStreams_RaceCondition(t *testing.T) { +func TestMergeLogStreams_RaceCondition(_ *testing.T) { // Test for regression of this issue: https://github.com/argoproj/argo-cd/issues/7006 for i := 0; i < 5000; i++ { first := make(chan logEntry) diff --git a/server/application/websocket.go b/server/application/websocket.go index 1bf5c8a2d96fe..8228726ee9a06 100644 --- a/server/application/websocket.go +++ b/server/application/websocket.go @@ -26,7 +26,7 @@ const ( var upgrader = func() websocket.Upgrader { upgrader := websocket.Upgrader{} upgrader.HandshakeTimeout = time.Second * 2 - upgrader.CheckOrigin = func(r *http.Request) bool { + upgrader.CheckOrigin = func(_ *http.Request) bool { return true } return upgrader diff --git a/server/application/websocket_test.go b/server/application/websocket_test.go index ab5011569bec0..b3b52fd14f046 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 ...any) bool { + enf.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...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 ...any) bool { + enf.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return false }) ts := newTestTerminalSession(w, r) diff --git a/server/applicationset/applicationset_test.go b/server/applicationset/applicationset_test.go index 10ec15c00c7ab..51934ff8c6990 100644 --- a/server/applicationset/applicationset_test.go +++ b/server/applicationset/applicationset_test.go @@ -115,7 +115,7 @@ func newTestAppSetServerWithEnforcerConfigure(f func(*rbac.Enforcer), namespace objects = append(objects, defaultProj, myProj) fakeAppsClientset := apps.NewSimpleClientset(objects...) - factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(namespace), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(namespace), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) fakeProjLister := factory.Argoproj().V1alpha1().AppProjects().Lister().AppProjects(testNamespace) enforcer := rbac.NewEnforcer(kubeclientset, testNamespace, common.ArgoCDRBACConfigMapName, nil) diff --git a/server/cluster/cluster_test.go b/server/cluster/cluster_test.go index 33aad37bc4f37..bae72906f2632 100644 --- a/server/cluster/cluster_test.go +++ b/server/cluster/cluster_test.go @@ -126,7 +126,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 ...any) bool { + enforcer.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return true }) return enforcer @@ -179,18 +179,18 @@ func TestUpdateCluster_RejectInvalidParams(t *testing.T) { } db.On("ListClusters", mock.Anything).Return( - func(ctx context.Context) *v1alpha1.ClusterList { + func(_ context.Context) *v1alpha1.ClusterList { return &v1alpha1.ClusterList{ ListMeta: metav1.ListMeta{}, Items: clusters, } }, - func(ctx context.Context) error { + func(_ context.Context) error { return nil }, ) db.On("UpdateCluster", mock.Anything, mock.Anything).Return( - func(ctx context.Context, c *v1alpha1.Cluster) *v1alpha1.Cluster { + func(_ context.Context, c *v1alpha1.Cluster) *v1alpha1.Cluster { for _, cluster := range clusters { if c.Server == cluster.Server { return c @@ -198,7 +198,7 @@ func TestUpdateCluster_RejectInvalidParams(t *testing.T) { } return nil }, - func(ctx context.Context, c *v1alpha1.Cluster) error { + func(_ context.Context, c *v1alpha1.Cluster) error { for _, cluster := range clusters { if c.Server == cluster.Server { return nil @@ -208,7 +208,7 @@ func TestUpdateCluster_RejectInvalidParams(t *testing.T) { }, ) db.On("GetCluster", mock.Anything, mock.Anything).Return( - func(ctx context.Context, server string) *v1alpha1.Cluster { + func(_ context.Context, server string) *v1alpha1.Cluster { for _, cluster := range clusters { if server == cluster.Server { return &cluster @@ -216,7 +216,7 @@ func TestUpdateCluster_RejectInvalidParams(t *testing.T) { } return nil }, - func(ctx context.Context, server string) error { + func(_ context.Context, server string) error { for _, cluster := range clusters { if server == cluster.Server { return nil diff --git a/server/extension/extension_test.go b/server/extension/extension_test.go index 7d870ea5d7c98..0063eec757f7f 100644 --- a/server/extension/extension_test.go +++ b/server/extension/extension_test.go @@ -415,12 +415,12 @@ func TestCallExtension(t *testing.T) { wg.Add(2) f.metricsMock. On("IncExtensionRequestCounter", mock.Anything, mock.Anything). - Run(func(args mock.Arguments) { + Run(func(_ mock.Arguments) { wg.Done() }) f.metricsMock. On("ObserveExtensionRequestDuration", mock.Anything, mock.Anything). - Run(func(args mock.Arguments) { + Run(func(_ mock.Arguments) { wg.Done() }) diff --git a/server/gpgkey/gpgkey.go b/server/gpgkey/gpgkey.go index 2332b6052f791..d967d4dd3cc6d 100644 --- a/server/gpgkey/gpgkey.go +++ b/server/gpgkey/gpgkey.go @@ -36,7 +36,7 @@ func NewServer( } // ListGnuPGPublicKeys returns a list of GnuPG public keys in the configuration -func (s *Server) List(ctx context.Context, q *gpgkeypkg.GnuPGPublicKeyQuery) (*appsv1.GnuPGPublicKeyList, error) { +func (s *Server) List(ctx context.Context, _ *gpgkeypkg.GnuPGPublicKeyQuery) (*appsv1.GnuPGPublicKeyList, error) { if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceGPGKeys, rbacpolicy.ActionGet, ""); err != nil { return nil, err } diff --git a/server/notification/notification.go b/server/notification/notification.go index e34520e97513e..1cc8ef72374ad 100644 --- a/server/notification/notification.go +++ b/server/notification/notification.go @@ -22,7 +22,7 @@ func NewServer(apiFactory api.Factory) notification.NotificationServiceServer { } // List returns list of notification triggers -func (s *Server) ListTriggers(ctx context.Context, q *notification.TriggersListRequest) (*notification.TriggerList, error) { +func (s *Server) ListTriggers(_ context.Context, _ *notification.TriggersListRequest) (*notification.TriggerList, error) { api, err := s.apiFactory.GetAPI() if err != nil { if apierrors.IsNotFound(err) { @@ -37,7 +37,7 @@ func (s *Server) ListTriggers(ctx context.Context, q *notification.TriggersListR } // List returns list of notification services -func (s *Server) ListServices(ctx context.Context, q *notification.ServicesListRequest) (*notification.ServiceList, error) { +func (s *Server) ListServices(_ context.Context, _ *notification.ServicesListRequest) (*notification.ServiceList, error) { api, err := s.apiFactory.GetAPI() if err != nil { if apierrors.IsNotFound(err) { @@ -53,7 +53,7 @@ func (s *Server) ListServices(ctx context.Context, q *notification.ServicesListR } // List returns list of notification templates -func (s *Server) ListTemplates(ctx context.Context, q *notification.TemplatesListRequest) (*notification.TemplateList, error) { +func (s *Server) ListTemplates(_ context.Context, _ *notification.TemplatesListRequest) (*notification.TemplateList, error) { api, err := s.apiFactory.GetAPI() if err != nil { if apierrors.IsNotFound(err) { diff --git a/server/project/project.go b/server/project/project.go index 47db95122f607..0fe0ae2a20608 100644 --- a/server/project/project.go +++ b/server/project/project.go @@ -285,7 +285,7 @@ func (s *Server) Create(ctx context.Context, q *project.ProjectCreateRequest) (* } // List returns list of projects -func (s *Server) List(ctx context.Context, q *project.ProjectQuery) (*v1alpha1.AppProjectList, error) { +func (s *Server) List(ctx context.Context, _ *project.ProjectQuery) (*v1alpha1.AppProjectList, error) { list, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).List(ctx, metav1.ListOptions{}) if list != nil { newItems := make([]v1alpha1.AppProject, 0) diff --git a/server/project/project_test.go b/server/project/project_test.go index 097e55624b251..dd8253510a2c1 100644 --- a/server/project/project_test.go +++ b/server/project/project_test.go @@ -79,7 +79,7 @@ func TestProjectServer(t *testing.T) { ctx := context.Background() fakeAppsClientset := apps.NewSimpleClientset() - factory := informer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, informer.WithNamespace(""), informer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := informer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, informer.WithNamespace(""), informer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) projInformer := factory.Argoproj().V1alpha1().AppProjects().Informer() go projInformer.Run(ctx.Done()) if !k8scache.WaitForCacheSync(ctx.Done(), projInformer.HasSynced) { @@ -713,7 +713,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 ...any) bool { + enforcer.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return true }) return enforcer diff --git a/server/repocreds/repocreds.go b/server/repocreds/repocreds.go index 4c3c2d1253db8..97bf3465451e8 100644 --- a/server/repocreds/repocreds.go +++ b/server/repocreds/repocreds.go @@ -42,7 +42,7 @@ func NewServer( } // ListRepositoryCredentials returns a list of all configured repository credential sets -func (s *Server) ListRepositoryCredentials(ctx context.Context, q *repocredspkg.RepoCredsQuery) (*appsv1.RepoCredsList, error) { +func (s *Server) ListRepositoryCredentials(ctx context.Context, _ *repocredspkg.RepoCredsQuery) (*appsv1.RepoCredsList, error) { urls, err := s.db.ListRepositoryCredentials(ctx) if err != nil { return nil, err @@ -66,7 +66,7 @@ func (s *Server) ListRepositoryCredentials(ctx context.Context, q *repocredspkg. } // ListWriteRepositoryCredentials returns a list of all configured repository credential sets -func (s *Server) ListWriteRepositoryCredentials(ctx context.Context, q *repocredspkg.RepoCredsQuery) (*appsv1.RepoCredsList, error) { +func (s *Server) ListWriteRepositoryCredentials(ctx context.Context, _ *repocredspkg.RepoCredsQuery) (*appsv1.RepoCredsList, error) { urls, err := s.db.ListRepositoryCredentials(ctx) if err != nil { return nil, err diff --git a/server/repository/repository_test.go b/server/repository/repository_test.go index fd3b56040921f..d6a45e9c6c487 100644 --- a/server/repository/repository_test.go +++ b/server/repository/repository_test.go @@ -232,7 +232,7 @@ var ( func newAppAndProjLister(objects ...runtime.Object) (applisters.ApplicationLister, k8scache.SharedIndexInformer) { fakeAppsClientset := fakeapps.NewSimpleClientset(objects...) - factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) projInformer := factory.Argoproj().V1alpha1().AppProjects() appsInformer := factory.Argoproj().V1alpha1().Applications() for _, obj := range objects { @@ -540,7 +540,7 @@ func TestRepositoryServerListApps(t *testing.T) { url := "https://test" db := &dbmocks.ArgoDB{} db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) repoServerClient.On("ListApps", context.TODO(), mock.Anything).Return(&apiclient.AppList{ Apps: map[string]string{ @@ -571,7 +571,7 @@ func TestRepositoryServerListApps(t *testing.T) { url := "https://test" db := &dbmocks.ArgoDB{} db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) repoServerClient.On("ListApps", context.TODO(), mock.Anything).Return(&apiclient.AppList{ Apps: map[string]string{ @@ -671,7 +671,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(nil, nil) db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Directory"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -696,7 +696,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { url := "https://test" db := &dbmocks.ArgoDB{} db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Directory"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -722,7 +722,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(nil, nil) db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Directory"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -747,7 +747,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(helmRepos, nil) db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Helm"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -786,7 +786,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(helmRepos, nil) db.On("GetRepository", context.TODO(), url0, "default").Return(&appsv1.Repository{Repo: url0}, nil) db.On("GetRepository", context.TODO(), url1, "default").Return(&appsv1.Repository{Repo: url1}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp0 := apiclient.RepoAppDetailsResponse{Type: "Plugin"} expectedResp1 := apiclient.RepoAppDetailsResponse{Type: "Helm"} @@ -865,7 +865,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(nil, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Directory"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -893,7 +893,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(helmRepos, nil) db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Helm"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -922,7 +922,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(nil, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Directory"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -963,7 +963,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 ...any) bool { + enforcer.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return true }) return enforcer @@ -985,7 +985,7 @@ func TestGetRepository(t *testing.T) { name: "empty project and no repos", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "something-else"}, @@ -1001,7 +1001,7 @@ func TestGetRepository(t *testing.T) { name: "empty project and no matching repos", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{}, nil }, q: &repository.RepoQuery{ @@ -1015,7 +1015,7 @@ func TestGetRepository(t *testing.T) { name: "empty project + matching repo with an empty project", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "foobar", Project: ""}, @@ -1037,7 +1037,7 @@ func TestGetRepository(t *testing.T) { name: "empty project + matching repo with a non-empty project", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "foobar", Project: "foobar"}, @@ -1059,7 +1059,7 @@ func TestGetRepository(t *testing.T) { name: "non-empty project + matching repo with an empty project", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "foobar", Project: ""}, @@ -1078,7 +1078,7 @@ func TestGetRepository(t *testing.T) { name: "non-empty project + matching repo with a matching project", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "foobar", Project: "foobar"}, @@ -1100,7 +1100,7 @@ func TestGetRepository(t *testing.T) { name: "non-empty project + matching repo with a non-matching project", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "foobar", Project: "something-else"}, diff --git a/server/server.go b/server/server.go index 412a48297258f..035142a6cf85e 100644 --- a/server/server.go +++ b/server/server.go @@ -304,8 +304,8 @@ func NewServer(ctx context.Context, opts ArgoCDServerOpts, appsetOpts Applicatio if len(opts.ApplicationNamespaces) > 0 { appInformerNs = "" } - projFactory := appinformer.NewSharedInformerFactoryWithOptions(opts.AppClientset, 0, appinformer.WithNamespace(opts.Namespace), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) - appFactory := appinformer.NewSharedInformerFactoryWithOptions(opts.AppClientset, 0, appinformer.WithNamespace(appInformerNs), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + projFactory := appinformer.NewSharedInformerFactoryWithOptions(opts.AppClientset, 0, appinformer.WithNamespace(opts.Namespace), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) + appFactory := appinformer.NewSharedInformerFactoryWithOptions(opts.AppClientset, 0, appinformer.WithNamespace(appInformerNs), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) projInformer := projFactory.Argoproj().V1alpha1().AppProjects().Informer() projLister := projFactory.Argoproj().V1alpha1().AppProjects().Lister().AppProjects(opts.Namespace) @@ -606,7 +606,7 @@ func (server *ArgoCDServer) Run(ctx context.Context, listeners *Listeners) { // gRPC clients know we support http2 for their communication. NextProtos: []string{"http/1.1", "h2"}, } - tlsConfig.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) { + tlsConfig.GetCertificate = func(_ *tls.ClientHelloInfo) (*tls.Certificate, error) { return server.settings.Certificate, nil } if server.TLSConfigCustomizer != nil { @@ -933,7 +933,7 @@ func (server *ArgoCDServer) newGRPCServer() (*grpc.Server, application.AppResour grpc_prometheus.StreamServerInterceptor, grpc_auth.StreamServerInterceptor(server.Authenticate), grpc_util.UserAgentStreamServerInterceptor(common.ArgoCDUserAgentName, clientConstraint), - grpc_util.PayloadStreamServerInterceptor(server.log, true, func(ctx context.Context, fullMethodName string, servingObject any) bool { + grpc_util.PayloadStreamServerInterceptor(server.log, true, func(_ context.Context, fullMethodName string, _ any) bool { return !sensitiveMethods[fullMethodName] }), grpc_util.ErrorCodeK8sStreamServerInterceptor(), @@ -947,7 +947,7 @@ func (server *ArgoCDServer) newGRPCServer() (*grpc.Server, application.AppResour grpc_prometheus.UnaryServerInterceptor, grpc_auth.UnaryServerInterceptor(server.Authenticate), grpc_util.UserAgentUnaryServerInterceptor(common.ArgoCDUserAgentName, clientConstraint), - grpc_util.PayloadUnaryServerInterceptor(server.log, true, func(ctx context.Context, fullMethodName string, servingObject any) bool { + grpc_util.PayloadUnaryServerInterceptor(server.log, true, func(_ context.Context, fullMethodName string, _ any) bool { return !sensitiveMethods[fullMethodName] }), grpc_util.ErrorCodeK8sUnaryServerInterceptor(), diff --git a/server/server_test.go b/server/server_test.go index 45426b2c6efcc..7906c1f899072 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -616,7 +616,7 @@ func getTestServer(t *testing.T, anonymousEnabled bool, withFakeSSO bool, useDex if anonymousEnabled { cm.Data["users.anonymous.enabled"] = "true" } - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { // Start with a placeholder. We need the server URL before setting up the real handler. })) ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -1603,7 +1603,7 @@ func TestReplaceBaseHRef(t *testing.T) { func Test_enforceContentTypes(t *testing.T) { getBaseHandler := func(t *testing.T, allow bool) http.Handler { t.Helper() - return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + return http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { assert.True(t, allow, "http handler was hit when it should have been blocked by content type enforcement") writer.WriteHeader(http.StatusOK) }) diff --git a/server/session/session.go b/server/session/session.go index 780d66c123779..d515ae50bd53b 100644 --- a/server/session/session.go +++ b/server/session/session.go @@ -74,7 +74,7 @@ func (s *Server) Create(_ context.Context, q *session.SessionCreateRequest) (*se } // Delete an authentication cookie from the client. This makes sense only for the Web client. -func (s *Server) Delete(ctx context.Context, q *session.SessionDeleteRequest) (*session.SessionResponse, error) { +func (s *Server) Delete(_ context.Context, _ *session.SessionDeleteRequest) (*session.SessionResponse, error) { return &session.SessionResponse{Token: ""}, nil } @@ -82,13 +82,13 @@ func (s *Server) Delete(ctx context.Context, q *session.SessionDeleteRequest) (* // Without this function here, ArgoCDServer.authenticate would be invoked and credentials checked. // Since this service is generally invoked when the user has _no_ credentials, that would create a // chicken-and-egg situation if we didn't place this here to allow traffic to pass through. -func (s *Server) AuthFuncOverride(ctx context.Context, fullMethodName string) (context.Context, error) { +func (s *Server) AuthFuncOverride(ctx context.Context, _ string) (context.Context, error) { // this authenticates the user, but ignores any error, so that we have claims populated ctx, _ = s.authenticator.Authenticate(ctx) return ctx, nil } -func (s *Server) GetUserInfo(ctx context.Context, q *session.GetUserInfoRequest) (*session.GetUserInfoResponse, error) { +func (s *Server) GetUserInfo(ctx context.Context, _ *session.GetUserInfoRequest) (*session.GetUserInfoResponse, error) { return &session.GetUserInfoResponse{ LoggedIn: sessionmgr.LoggedIn(ctx), Username: sessionmgr.Username(ctx), diff --git a/server/settings/settings.go b/server/settings/settings.go index 919ca89cc3f58..8455553cd9cff 100644 --- a/server/settings/settings.go +++ b/server/settings/settings.go @@ -37,7 +37,7 @@ func NewServer(mgr *settings.SettingsManager, repoClient apiclient.Clientset, au } // Get returns Argo CD settings -func (s *Server) Get(ctx context.Context, q *settingspkg.SettingsQuery) (*settingspkg.Settings, error) { +func (s *Server) Get(ctx context.Context, _ *settingspkg.SettingsQuery) (*settingspkg.Settings, error) { resourceOverrides, err := s.mgr.GetResourceOverrides() if err != nil { return nil, err @@ -152,7 +152,7 @@ func (s *Server) Get(ctx context.Context, q *settingspkg.SettingsQuery) (*settin } // GetPlugins returns a list of plugins -func (s *Server) GetPlugins(ctx context.Context, q *settingspkg.SettingsQuery) (*settingspkg.SettingsPluginsResponse, error) { +func (s *Server) GetPlugins(ctx context.Context, _ *settingspkg.SettingsQuery) (*settingspkg.SettingsPluginsResponse, error) { plugins, err := s.plugins(ctx) if err != nil { return nil, err diff --git a/server/version/version.go b/server/version/version.go index cc4eeb24152a6..66f84f0ae835a 100644 --- a/server/version/version.go +++ b/server/version/version.go @@ -73,7 +73,7 @@ func (s *Server) Version(ctx context.Context, _ *empty.Empty) (*version.VersionM } // AuthFuncOverride allows the version to be returned without auth -func (s *Server) AuthFuncOverride(ctx context.Context, fullMethodName string) (context.Context, error) { +func (s *Server) AuthFuncOverride(ctx context.Context, _ string) (context.Context, error) { if s.authenticator != nil { // this authenticates the user, but ignores any error, so that we have claims populated ctx, _ = s.authenticator.Authenticate(ctx) diff --git a/test/e2e/accounts_test.go b/test/e2e/accounts_test.go index dd56837dacd22..967abeec832b6 100644 --- a/test/e2e/accounts_test.go +++ b/test/e2e/accounts_test.go @@ -26,14 +26,14 @@ func TestCreateAndUseAccount(t *testing.T) { When(). Create(). Then(). - And(func(account *account.Account, err error) { + And(func(account *account.Account, _ error) { assert.Equal(t, account.Name, ctx.GetName()) assert.Equal(t, []string{"login"}, account.Capabilities) }). When(). Login(). Then(). - CurrentUser(func(user *session.GetUserInfoResponse, err error) { + CurrentUser(func(user *session.GetUserInfoResponse, _ error) { assert.True(t, user.LoggedIn) assert.Equal(t, user.Username, ctx.GetName()) }) @@ -48,7 +48,7 @@ func TestCanIGetLogsAllowNoSwitch(t *testing.T) { Login(). CanIGetLogs(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "yes") }) } @@ -63,7 +63,7 @@ func TestCanIGetLogsDenySwitchOn(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "true"). CanIGetLogs(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "no") }) } @@ -91,7 +91,7 @@ func TestCanIGetLogsAllowSwitchOn(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "true"). CanIGetLogs(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "yes") }) } @@ -106,7 +106,7 @@ func TestCanIGetLogsAllowSwitchOff(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "false"). CanIGetLogs(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "yes") }) } diff --git a/test/e2e/admin_test.go b/test/e2e/admin_test.go index 326e70debc484..d68dc45a24513 100644 --- a/test/e2e/admin_test.go +++ b/test/e2e/admin_test.go @@ -69,7 +69,7 @@ func TestBackupExportImport(t *testing.T) { When(). RunImport(exportRawOutput). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { require.NoError(t, err, "import finished with error") _, err = fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.TestNamespace()).Get(context.Background(), "exported-app1", metav1.GetOptions{}) require.NoError(t, err, "failed getting test namespace application after import") diff --git a/test/e2e/app_deletion_test.go b/test/e2e/app_deletion_test.go index c0332eb017f98..58d63e2da9ebb 100644 --- a/test/e2e/app_deletion_test.go +++ b/test/e2e/app_deletion_test.go @@ -58,7 +58,7 @@ func TestDeletingAppByLabel(t *testing.T) { Then(). // delete is unsuccessful since no selector match AndCLIOutput( - func(output string, err error) { + func(_ string, err error) { assert.ErrorContains(t, err, "no apps match selector foo=baz") }, ). diff --git a/test/e2e/app_management_ns_test.go b/test/e2e/app_management_ns_test.go index 2423ba5462413..023b733b80c11 100644 --- a/test/e2e/app_management_ns_test.go +++ b/test/e2e/app_management_ns_test.go @@ -43,7 +43,7 @@ import ( ) // This empty test is here only for clarity, to conform to logs rbac tests structure in account. This exact usecase is covered in the TestAppLogs test -func TestNamespacedGetLogsAllowNoSwitch(t *testing.T) { +func TestNamespacedGetLogsAllowNoSwitch(_ *testing.T) { } func TestNamespacedGetLogsDenySwitchOn(t *testing.T) { @@ -88,7 +88,7 @@ func TestNamespacedGetLogsDenySwitchOn(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "true"). Then(). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { _, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") assert.ErrorContains(t, err, "permission denied") }) @@ -141,17 +141,17 @@ func TestNamespacedGetLogsAllowSwitchOnNS(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "true"). Then(). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") require.NoError(t, err) assert.Contains(t, out, "Hi") }). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Pod") require.NoError(t, err) assert.Contains(t, out, "Hi") }). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Service") require.NoError(t, err) assert.NotContains(t, out, "Hi") @@ -199,17 +199,17 @@ func TestNamespacedGetLogsAllowSwitchOff(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "false"). Then(). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") require.NoError(t, err) assert.Contains(t, out, "Hi") }). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Pod") require.NoError(t, err) assert.Contains(t, out, "Hi") }). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Service") require.NoError(t, err) assert.NotContains(t, out, "Hi") @@ -289,7 +289,7 @@ func TestNamespacedAppCreation(t *testing.T) { assert.Equal(t, KubernetesInternalAPIServerAddr, app.Spec.Destination.Server) }). Expect(NamespacedEvent(fixture.AppNamespace(), EventReasonResourceCreated, "create")). - And(func(app *Application) { + And(func(_ *Application) { // app should be listed output, err := fixture.RunCli("app", "list") require.NoError(t, err) @@ -462,7 +462,7 @@ func TestNamespacedAppLabels(t *testing.T) { When(). CreateApp("-l", "foo=bar"). Then(). - And(func(app *Application) { + And(func(_ *Application) { assert.Contains(t, FailOnErr(fixture.RunCli("app", "list")), ctx.AppQualifiedName()) assert.Contains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=bar")), ctx.AppQualifiedName()) assert.NotContains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=rubbish")), ctx.AppQualifiedName()) @@ -701,7 +701,7 @@ func TestNamespacedAppWithSecrets(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { diffOutput := FailOnErr(fixture.RunCli("app", "diff", ctx.AppQualifiedName())).(string) assert.Empty(t, diffOutput) }). @@ -715,7 +715,7 @@ metadata: stringData: username: test-username`). Then(). - And(func(app *Application) { + And(func(_ *Application) { diffOutput := FailOnErr(fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local", "testdata/secrets")).(string) assert.Empty(t, diffOutput) }) @@ -732,7 +732,7 @@ func TestNamespacedResourceDiffing(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { // Patch deployment _, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Patch(context.Background(), "guestbook-ui", types.JSONPatchType, []byte(`[{ "op": "replace", "path": "/spec/template/spec/containers/0/image", "value": "test" }]`), metav1.PatchOptions{}) @@ -742,7 +742,7 @@ func TestNamespacedResourceDiffing(t *testing.T) { Refresh(RefreshTypeNormal). Then(). Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). - And(func(app *Application) { + And(func(_ *Application) { diffOutput, err := fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", "testdata/guestbook") require.Error(t, err) assert.Contains(t, diffOutput, fmt.Sprintf("===== apps/Deployment %s/guestbook-ui ======", fixture.DeploymentNamespace())) @@ -755,7 +755,7 @@ func TestNamespacedResourceDiffing(t *testing.T) { Refresh(RefreshTypeNormal). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { diffOutput, err := fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", "testdata/guestbook") require.NoError(t, err) assert.Empty(t, diffOutput) @@ -814,13 +814,13 @@ func TestNamespacedResourceDiffing(t *testing.T) { When().Refresh(RefreshTypeNormal). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) }). When().Sync().Then().Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) @@ -892,7 +892,7 @@ func testNSEdgeCasesApplicationResources(t *testing.T, appPath string, statusCod } expect. Expect(HealthIs(statusCode)). - And(func(app *Application) { + And(func(_ *Application) { diffOutput, err := fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", path.Join("testdata", appPath)) assert.Empty(t, diffOutput) require.NoError(t, err) @@ -969,7 +969,7 @@ func TestNamespacedSyncResourceByLabel(t *testing.T) { _, _ = fixture.RunCli("app", "sync", ctx.AppQualifiedName(), "--label", "app.kubernetes.io/instance="+app.Name) }). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { _, err := fixture.RunCli("app", "sync", ctx.AppQualifiedName(), "--label", "this-label=does-not-exist") assert.ErrorContains(t, err, "level=fatal") }) @@ -985,7 +985,7 @@ func TestNamespacedLocalManifestSync(t *testing.T) { CreateApp(). Sync(). Then(). - And(func(app *Application) { + And(func(_ *Application) { res, _ := fixture.RunCli("app", "manifests", ctx.AppQualifiedName()) assert.Contains(t, res, "containerPort: 80") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.2") @@ -996,7 +996,7 @@ func TestNamespacedLocalManifestSync(t *testing.T) { Sync("--local-repo-root", "."). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { res, _ := fixture.RunCli("app", "manifests", ctx.AppQualifiedName()) assert.Contains(t, res, "containerPort: 81") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.3") @@ -1007,7 +1007,7 @@ func TestNamespacedLocalManifestSync(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { res, _ := fixture.RunCli("app", "manifests", ctx.AppQualifiedName()) assert.Contains(t, res, "containerPort: 80") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.2") @@ -1852,7 +1852,7 @@ func TestNamespacedNamespaceAutoCreation(t *testing.T) { Delete(true). Then(). Expect(Success("")). - And(func(app *Application) { + And(func(_ *Application) { // Verify delete app does not delete the namespace auto created output, err := fixture.Run("", "kubectl", "get", "namespace", updatedNamespace) require.NoError(t, err) @@ -1991,7 +1991,7 @@ func TestNamespacedNamespaceAutoCreationWithMetadataAndNsManifest(t *testing.T) Sync(). Then(). Expect(Success("")). - Expect(Namespace(namespace, func(app *Application, ns *corev1.Namespace) { + Expect(Namespace(namespace, func(_ *Application, ns *corev1.Namespace) { delete(ns.Labels, "kubernetes.io/metadata.name") delete(ns.Labels, "argocd.argoproj.io/tracking-id") delete(ns.Labels, "kubectl.kubernetes.io/last-applied-configuration") @@ -2443,7 +2443,7 @@ func TestNamespacedDisableManifestGeneration(t *testing.T) { }). Refresh(RefreshTypeHard). Then(). - And(func(app *Application) { + And(func(_ *Application) { // Wait for refresh to complete time.Sleep(1 * time.Second) }). diff --git a/test/e2e/app_management_test.go b/test/e2e/app_management_test.go index 65d725fa0d97b..d1a4e3dbe0d4e 100644 --- a/test/e2e/app_management_test.go +++ b/test/e2e/app_management_test.go @@ -53,7 +53,7 @@ const ( ) // This empty test is here only for clarity, to conform to logs rbac tests structure in account. This exact usecase is covered in the TestAppLogs test -func TestGetLogsAllowNoSwitch(t *testing.T) { +func TestGetLogsAllowNoSwitch(_ *testing.T) { } func TestGetLogsDenySwitchOn(t *testing.T) { @@ -608,7 +608,7 @@ func TestAppLabels(t *testing.T) { When(). CreateApp("-l", "foo=bar"). Then(). - And(func(app *Application) { + And(func(_ *Application) { assert.Contains(t, FailOnErr(fixture.RunCli("app", "list")), fixture.Name()) assert.Contains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=bar")), fixture.Name()) assert.NotContains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=rubbish")), fixture.Name()) @@ -880,7 +880,7 @@ func TestResourceDiffing(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { // Patch deployment _, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Patch(context.Background(), "guestbook-ui", types.JSONPatchType, []byte(`[{ "op": "replace", "path": "/spec/template/spec/containers/0/image", "value": "test" }]`), metav1.PatchOptions{}) @@ -962,13 +962,13 @@ func TestResourceDiffing(t *testing.T) { When().Refresh(RefreshTypeNormal). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) }). When().Sync().Then().Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) @@ -1585,7 +1585,7 @@ func TestPermissions(t *testing.T) { Refresh(RefreshTypeNormal). Then(). // make sure application resource actiions are failing - And(func(app *Application) { + And(func(_ *Application) { assertResourceActions(t, "test-permissions", false) }) } @@ -2238,7 +2238,7 @@ func TestNamespaceAutoCreation(t *testing.T) { When(). CreateApp("--sync-option", "CreateNamespace=true"). Then(). - And(func(app *Application) { + And(func(_ *Application) { // Make sure the namespace we are about to update to does not exist _, err := fixture.Run("", "kubectl", "get", "namespace", updatedNamespace) assert.ErrorContains(t, err, "not found") @@ -2256,7 +2256,7 @@ func TestNamespaceAutoCreation(t *testing.T) { Delete(true). Then(). Expect(Success("")). - And(func(app *Application) { + And(func(_ *Application) { // Verify delete app does not delete the namespace auto created output, err := fixture.Run("", "kubectl", "get", "namespace", updatedNamespace) require.NoError(t, err) @@ -2558,7 +2558,7 @@ func TestDisableManifestGeneration(t *testing.T) { }). Refresh(RefreshTypeHard). Then(). - And(func(app *Application) { + And(func(_ *Application) { // Wait for refresh to complete time.Sleep(1 * time.Second) }). diff --git a/test/e2e/app_multiple_sources_test.go b/test/e2e/app_multiple_sources_test.go index e3118244e18d0..ba4952769634c 100644 --- a/test/e2e/app_multiple_sources_test.go +++ b/test/e2e/app_multiple_sources_test.go @@ -195,7 +195,7 @@ func TestMultiSourceAppWithSourceName(t *testing.T) { assert.Equal(t, KubernetesInternalAPIServerAddr, app.Spec.Destination.Server) }). Expect(Event(EventReasonResourceCreated, "create")). - And(func(app *Application) { + And(func(_ *Application) { // we remove the first source output, err := RunCli("app", "remove-source", Name(), "--source-name", sources[0].Name) require.NoError(t, err) @@ -257,7 +257,7 @@ func TestMultiSourceAppSetWithSourceName(t *testing.T) { assert.Equal(t, KubernetesInternalAPIServerAddr, app.Spec.Destination.Server) }). Expect(Event(EventReasonResourceCreated, "create")). - And(func(app *Application) { + And(func(_ *Application) { _, err := RunCli("app", "set", Name(), "--source-name", sources[1].Name, "--path", "deployment") require.NoError(t, err) }). @@ -284,12 +284,12 @@ func TestMultiSourceApptErrorWhenSourceNameAndSourcePosition(t *testing.T) { CreateMultiSourceAppFromFile(). Then(). Expect(Event(EventReasonResourceCreated, "create")). - And(func(app *Application) { + And(func(_ *Application) { _, err := RunCli("app", "get", Name(), "--source-name", sources[1].Name, "--source-position", "1") require.Error(t, err) assert.Contains(t, err.Error(), "Only one of source-position and source-name can be specified.") }). - And(func(app *Application) { + And(func(_ *Application) { _, err := RunCli("app", "manifests", Name(), "--revisions", "0.0.2", "--source-names", sources[0].Name, "--revisions", "0.0.2", "--source-positions", "1") require.Error(t, err) assert.Contains(t, err.Error(), "Only one of source-positions and source-names can be specified.") diff --git a/test/e2e/app_sync_options_test.go b/test/e2e/app_sync_options_test.go index 96dde8804e2d7..96456cfd36ba8 100644 --- a/test/e2e/app_sync_options_test.go +++ b/test/e2e/app_sync_options_test.go @@ -48,7 +48,7 @@ func TestNamespaceCreationWithSSA(t *testing.T) { Sync(). Then(). Expect(Success("")). - Expect(Namespace(namespace, func(app *Application, ns *corev1.Namespace) { + Expect(Namespace(namespace, func(_ *Application, ns *corev1.Namespace) { assert.NotContains(t, ns.Annotations, "kubectl.kubernetes.io/last-applied-configuration") })). Expect(SyncStatusIs(SyncStatusCodeSynced)). diff --git a/test/e2e/cluster_test.go b/test/e2e/cluster_test.go index d65bd1c4649bc..8fef8a41babac 100644 --- a/test/e2e/cluster_test.go +++ b/test/e2e/cluster_test.go @@ -42,7 +42,7 @@ https://kubernetes.default.svc in-cluster %v Successful `, fixtu When(). List(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { last = output }) if expected == last { @@ -65,7 +65,7 @@ func TestClusterAdd(t *testing.T) { Create(). List(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, fmt.Sprintf(`SERVER NAME VERSION STATUS MESSAGE PROJECT https://kubernetes.default.svc test-cluster-add %v Successful %s`, fixture.GetVersions().ServerVersion, fixture.ProjectName), output) }) @@ -88,7 +88,7 @@ func TestClusterAddPermissionDenied(t *testing.T) { IgnoreErrors(). Create(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied") }) } @@ -121,7 +121,7 @@ func TestClusterAddAllowed(t *testing.T) { Create(). List(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, fmt.Sprintf(`SERVER NAME VERSION STATUS MESSAGE PROJECT https://kubernetes.default.svc test-cluster-add-allowed %v Successful argo-project`, fixture.GetVersions().ServerVersion), output) }) @@ -150,7 +150,7 @@ func TestClusterListDenied(t *testing.T) { Create(). List(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, "SERVER NAME VERSION STATUS MESSAGE PROJECT", output) }) } @@ -168,7 +168,7 @@ func TestClusterSet(t *testing.T) { SetNamespaces(). GetByName("in-cluster"). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "namespace-edit-1") assert.Contains(t, output, "namespace-edit-2") }) @@ -253,7 +253,7 @@ func TestClusterDeleteDenied(t *testing.T) { Create(). DeleteByName(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied") }) @@ -267,7 +267,7 @@ func TestClusterDeleteDenied(t *testing.T) { Create(). DeleteByServer(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied") }) } @@ -317,7 +317,7 @@ func TestClusterDelete(t *testing.T) { clstAction.DeleteByName(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, "Cluster 'default' removed", output) }) diff --git a/test/e2e/custom_tool_test.go b/test/e2e/custom_tool_test.go index 41ab74e9426f1..fb7b22d7652dc 100644 --- a/test/e2e/custom_tool_test.go +++ b/test/e2e/custom_tool_test.go @@ -40,7 +40,7 @@ func TestCustomToolWithGitCreds(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitAskpass}") require.NoError(t, err) assert.Equal(t, "argocd", output) @@ -70,17 +70,17 @@ func TestCustomToolWithGitCredsTemplate(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitAskpass}") require.NoError(t, err) assert.Equal(t, "argocd", output) }). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitUsername}") require.NoError(t, err) assert.Empty(t, output) }). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitPassword}") require.NoError(t, err) assert.Empty(t, output) @@ -110,12 +110,12 @@ func TestCustomToolWithSSHGitCreds(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", fixture.Name(), "-o", "jsonpath={.metadata.annotations.GitSSHCommand}") require.NoError(t, err) assert.Regexp(t, `-i [^ ]+`, output, "test plugin expects $GIT_SSH_COMMAND to contain the option '-i '") }). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", fixture.Name(), "-o", "jsonpath={.metadata.annotations.GitSSHCredsFileSHA}") require.NoError(t, err) assert.Regexp(t, `\w+\s+[\/\w]+`, output, "git ssh credentials file should be able to be read, hashing the contents") @@ -171,23 +171,23 @@ func TestCustomToolWithEnv(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Bar}") require.NoError(t, err) assert.Equal(t, "baz", output) }). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Foo}") require.NoError(t, err) assert.Equal(t, "bar", output) }). - And(func(app *Application) { + And(func(_ *Application) { expectedKubeVersion := fixture.GetVersions().ServerVersion.Format("%s.%s") output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeVersion}") require.NoError(t, err) assert.Equal(t, expectedKubeVersion, output) }). - And(func(app *Application) { + And(func(_ *Application) { expectedApiVersion := fixture.GetApiResources() expectedApiVersionSlice := strings.Split(expectedApiVersion, ",") sort.Strings(expectedApiVersionSlice) @@ -222,10 +222,10 @@ func TestCustomToolSyncAndDiffLocal(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { FailOnErr(fixture.RunCli("app", "sync", ctx.AppName(), "--local", appPath, "--local-repo-root", testdataPath)) }). - And(func(app *Application) { + And(func(_ *Application) { FailOnErr(fixture.RunCli("app", "diff", ctx.AppName(), "--local", appPath, "--local-repo-root", testdataPath)) }) } @@ -320,18 +320,18 @@ func TestCMPDiscoverWithFindCommandWithEnv(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Bar}") require.NoError(t, err) assert.Equal(t, "baz", output) }). - And(func(app *Application) { + And(func(_ *Application) { expectedKubeVersion := fixture.GetVersions().ServerVersion.Format("%s.%s") output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeVersion}") require.NoError(t, err) assert.Equal(t, expectedKubeVersion, output) }). - And(func(app *Application) { + And(func(_ *Application) { expectedApiVersion := fixture.GetApiResources() expectedApiVersionSlice := strings.Split(expectedApiVersion, ",") sort.Strings(expectedApiVersionSlice) diff --git a/test/e2e/deployment_test.go b/test/e2e/deployment_test.go index 1e83a4494eebb..27b2c65142ede 100644 --- a/test/e2e/deployment_test.go +++ b/test/e2e/deployment_test.go @@ -67,7 +67,7 @@ func TestDeploymentWithAnnotationTrackingMode(t *testing.T) { Expect(HealthIs(health.HealthStatusHealthy)). When(). Then(). - And(func(app *Application) { + And(func(_ *Application) { out, err := RunCli("app", "manifests", ctx.AppName()) require.NoError(t, err) assert.Contains(t, out, fmt.Sprintf(`annotations: @@ -90,7 +90,7 @@ func TestDeploymentWithLabelTrackingMode(t *testing.T) { Expect(HealthIs(health.HealthStatusHealthy)). When(). Then(). - And(func(app *Application) { + And(func(_ *Application) { out, err := RunCli("app", "manifests", ctx.AppName()) require.NoError(t, err) assert.Contains(t, out, fmt.Sprintf(`labels: @@ -113,7 +113,7 @@ func TestDeploymentWithoutTrackingMode(t *testing.T) { Expect(HealthIs(health.HealthStatusHealthy)). When(). Then(). - And(func(app *Application) { + And(func(_ *Application) { out, err := RunCli("app", "manifests", ctx.AppName()) require.NoError(t, err) assert.Contains(t, out, fmt.Sprintf(`labels: diff --git a/test/e2e/fixture/app/expectation.go b/test/e2e/fixture/app/expectation.go index 02365ba69662b..7615fdc31c119 100644 --- a/test/e2e/fixture/app/expectation.go +++ b/test/e2e/fixture/app/expectation.go @@ -246,7 +246,7 @@ func DoesNotExistNow() Expectation { } func Pod(predicate func(p corev1.Pod) bool) Expectation { - return func(c *Consequences) (state, string) { + return func(_ *Consequences) (state, string) { pods, err := pods() if err != nil { return failed, err.Error() @@ -261,7 +261,7 @@ func Pod(predicate func(p corev1.Pod) bool) Expectation { } func NotPod(predicate func(p corev1.Pod) bool) Expectation { - return func(c *Consequences) (state, string) { + return func(_ *Consequences) (state, string) { pods, err := pods() if err != nil { return failed, err.Error() @@ -282,7 +282,7 @@ func pods() (*corev1.PodList, error) { } func NoNamespace(name string) Expectation { - return func(c *Consequences) (state, string) { + return func(_ *Consequences) (state, string) { _, err := namespace(name) if err != nil { return succeeded, "namespace not found" diff --git a/test/e2e/fixture/applicationsets/expectation.go b/test/e2e/fixture/applicationsets/expectation.go index fc8de495fe70c..a693320315c40 100644 --- a/test/e2e/fixture/applicationsets/expectation.go +++ b/test/e2e/fixture/applicationsets/expectation.go @@ -116,7 +116,7 @@ func ApplicationsDoNotExist(expectedApps []v1alpha1.Application) Expectation { // Pod checks whether a specified condition is true for any of the pods in the namespace func Pod(predicate func(p corev1.Pod) bool) Expectation { - return func(c *Consequences) (state, string) { + return func(_ *Consequences) (state, string) { pods, err := pods(utils.ApplicationsResourcesNamespace) if err != nil { return failed, err.Error() diff --git a/test/e2e/fixture/cluster/actions.go b/test/e2e/fixture/cluster/actions.go index ac114bad0cdf9..2e662825dcb9e 100644 --- a/test/e2e/fixture/cluster/actions.go +++ b/test/e2e/fixture/cluster/actions.go @@ -38,7 +38,7 @@ func (a *Actions) DoNotIgnoreErrors() *Actions { return a } -func (a *Actions) Create(args ...string) *Actions { +func (a *Actions) Create() *Actions { _, clusterClient, _ := fixture.ArgoCDClientset.NewClusterClient() _, err := clusterClient.Create(context.Background(), &clusterpkg.ClusterCreateRequest{ @@ -67,7 +67,7 @@ func (a *Actions) Create(args ...string) *Actions { return a } -func (a *Actions) CreateWithRBAC(args ...string) *Actions { +func (a *Actions) CreateWithRBAC() *Actions { pathOpts := clientcmd.NewDefaultPathOptions() config, err := pathOpts.GetStartingConfig() if err != nil { diff --git a/test/e2e/git_submodule_test.go b/test/e2e/git_submodule_test.go index 73329d12234e8..95008f5527535 100644 --- a/test/e2e/git_submodule_test.go +++ b/test/e2e/git_submodule_test.go @@ -18,7 +18,7 @@ func TestGitSubmoduleSSHSupport(t *testing.T) { CustomSSHKnownHostsAdded(). SubmoduleSSHRepoURLAdded(true). When(). - CreateFromFile(func(app *Application) {}). + CreateFromFile(func(_ *Application) {}). Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). @@ -33,7 +33,7 @@ func TestGitSubmoduleHTTPSSupport(t *testing.T) { CustomCACertAdded(). SubmoduleHTTPSRepoURLAdded(true). When(). - CreateFromFile(func(app *Application) {}). + CreateFromFile(func(_ *Application) {}). Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). @@ -48,7 +48,7 @@ func TestGitSubmoduleRemovalSupport(t *testing.T) { CustomSSHKnownHostsAdded(). SubmoduleSSHRepoURLAdded(true). When(). - CreateFromFile(func(app *Application) {}). + CreateFromFile(func(_ *Application) {}). Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). diff --git a/test/e2e/helm_test.go b/test/e2e/helm_test.go index 0ecb03e730e43..a30e880dca041 100644 --- a/test/e2e/helm_test.go +++ b/test/e2e/helm_test.go @@ -222,7 +222,7 @@ func TestHelmValuesLiteralFileRemote(t *testing.T) { // send back the address so that it can be used c <- listener.Addr().String() - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { // return the sentinel text at root URL fmt.Fprint(w, sentinel) }) @@ -326,7 +326,7 @@ func TestHelmSetEnv(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, fixture.Name(), FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) }) } @@ -341,7 +341,7 @@ func TestHelmSetStringEnv(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, fixture.Name(), FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) }) } @@ -356,7 +356,7 @@ func TestKubeVersion(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { kubeVersion := FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string) // Capabilities.KubeVersion defaults to 1.9.0, we assume here you are running a later version @@ -368,7 +368,7 @@ func TestKubeVersion(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, "v999.999.999", FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string)) }) @@ -384,7 +384,7 @@ func TestApiVersions(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { apiVersions := FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) // The v1 API shouldn't be going anywhere. @@ -396,7 +396,7 @@ func TestApiVersions(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { apiVersions := FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) assert.Contains(t, apiVersions, "v1/MyTestResource") diff --git a/test/e2e/jsonnet_test.go b/test/e2e/jsonnet_test.go index 3f1113b4207a5..c582ea4f8af29 100644 --- a/test/e2e/jsonnet_test.go +++ b/test/e2e/jsonnet_test.go @@ -83,7 +83,7 @@ func TestJsonnetTlaEnv(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, Name(), FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) assert.Equal(t, Name(), FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.bar}")).(string)) }) @@ -98,7 +98,7 @@ func TestJsonnetExtVarEnv(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, Name(), FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) assert.Equal(t, Name(), FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.bar}")).(string)) }) diff --git a/test/e2e/kustomize_test.go b/test/e2e/kustomize_test.go index a49c26b1e1ad5..22d7519c6c2fa 100644 --- a/test/e2e/kustomize_test.go +++ b/test/e2e/kustomize_test.go @@ -17,7 +17,7 @@ import ( func TestKustomize2AppSource(t *testing.T) { patchLabelMatchesFor := func(kind string) func(app *Application) { - return func(app *Application) { + return func(_ *Application) { name := "k2-patched-guestbook-ui-deploy1" labelValue, err := fixture.Run( "", "kubectl", "-n="+fixture.DeploymentNamespace(), @@ -184,7 +184,7 @@ func TestKustomizeReplicas2AppSource(t *testing.T) { deploymentName := "guestbook-ui" deploymentReplicas := 2 checkReplicasFor := func(kind string) func(app *Application) { - return func(app *Application) { + return func(_ *Application) { name := deploymentName replicas, err := fixture.Run( "", "kubectl", "-n="+fixture.DeploymentNamespace(), @@ -301,7 +301,7 @@ func TestKustomizeKubeVersion(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { kubeVersion := errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string) // Capabilities.KubeVersion defaults to 1.9.0, we assume here you are running a later version @@ -313,7 +313,7 @@ func TestKustomizeKubeVersion(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, "v999.999.999", errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string)) }) @@ -333,7 +333,7 @@ func TestKustomizeApiVersions(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { apiVersions := errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) // The v1 API shouldn't be going anywhere. @@ -345,7 +345,7 @@ func TestKustomizeApiVersions(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { apiVersions := errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) assert.Contains(t, apiVersions, "v1/MyTestResource") diff --git a/test/e2e/scoped_repository_test.go b/test/e2e/scoped_repository_test.go index 0075b6bd1b40a..08ecb4ad27edf 100644 --- a/test/e2e/scoped_repository_test.go +++ b/test/e2e/scoped_repository_test.go @@ -29,11 +29,11 @@ func TestCreateRepositoryWithProject(t *testing.T) { Project("argo-project"). Create(). Then(). - And(func(r *Repository, err error) { + And(func(r *Repository, _ error) { assert.Equal(t, r.Repo, path) assert.Equal(t, "argo-project", r.Project) - prjConsequence.And(func(projectResponse *project.DetailedProjectsResponse, err error) { + prjConsequence.And(func(projectResponse *project.DetailedProjectsResponse, _ error) { assert.Len(t, projectResponse.Repositories, 1) assert.Equal(t, projectResponse.Repositories[0].Repo, path) }) @@ -55,7 +55,7 @@ func TestCreateRepositoryNonAdminUserPermissionDenied(t *testing.T) { IgnoreErrors(). Create(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied: repositories, create") }) } @@ -82,7 +82,7 @@ func TestCreateRepositoryNonAdminUserWithWrongProject(t *testing.T) { IgnoreErrors(). Create(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied: repositories, create") }) } @@ -118,14 +118,14 @@ func TestDeleteRepositoryRbacAllowed(t *testing.T) { Project("argo-project"). Create(). Then(). - And(func(r *Repository, err error) { + And(func(r *Repository, _ error) { assert.Equal(t, r.Repo, path) assert.Equal(t, "argo-project", r.Project) }). When(). Delete(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "Repository 'https://github.com/argoproj/argo-cd.git' removed") }) } @@ -161,7 +161,7 @@ func TestDeleteRepositoryRbacDenied(t *testing.T) { Project("argo-project"). Create(). Then(). - And(func(r *Repository, err error) { + And(func(r *Repository, _ error) { assert.Equal(t, r.Repo, path) assert.Equal(t, "argo-project", r.Project) }). @@ -169,7 +169,7 @@ func TestDeleteRepositoryRbacDenied(t *testing.T) { IgnoreErrors(). Delete(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied: repositories, delete") }) } @@ -182,13 +182,13 @@ func TestDeleteRepository(t *testing.T) { Project("argo-project"). Create(). Then(). - And(func(r *Repository, err error) { + And(func(r *Repository, _ error) { assert.Equal(t, r.Repo, path) }). When(). Delete(). Then(). - And(func(r *Repository, err error) { + And(func(_ *Repository, err error) { assert.Equal(t, "repo not found", err.Error()) }) } @@ -201,13 +201,13 @@ func TestListRepoCLIOutput(t *testing.T) { Project("argo-project"). Create(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, `Repository 'https://github.com/argoproj/argo-cd.git' added`, output) }). When(). List(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, `TYPE NAME REPO INSECURE OCI LFS CREDS STATUS MESSAGE PROJECT git https://github.com/argoproj/argo-cd.git false false false false Successful argo-project`, output) }) @@ -221,13 +221,13 @@ func TestGetRepoCLIOutput(t *testing.T) { Project("argo-project"). Create(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, `Repository 'https://github.com/argoproj/argo-cd.git' added`, output) }). When(). Get(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, `TYPE NAME REPO INSECURE OCI LFS CREDS STATUS MESSAGE PROJECT git https://github.com/argoproj/argo-cd.git false false false false Successful argo-project`, output) }) diff --git a/test/manifests_test.go b/test/manifests_test.go index 9c30714041bcb..8d6807dffc9b2 100644 --- a/test/manifests_test.go +++ b/test/manifests_test.go @@ -22,7 +22,7 @@ func TestKustomizeVersion(t *testing.T) { // TestBuildManifests makes sure we are consistent in naming, and all kustomization.yamls are buildable func TestBuildManifests(t *testing.T) { - err := filepath.Walk("../manifests", func(path string, f os.FileInfo, err error) error { + err := filepath.Walk("../manifests", func(path string, _ os.FileInfo, err error) error { if err != nil { return err } diff --git a/test/testdata.go b/test/testdata.go index a9b1cfa72ad17..8e10050f5ce29 100644 --- a/test/testdata.go +++ b/test/testdata.go @@ -119,7 +119,7 @@ func NewFakeConfigMap() *corev1.ConfigMap { return &cm } -func NewFakeSecret(policy ...string) *corev1.Secret { +func NewFakeSecret() *corev1.Secret { secret := corev1.Secret{ TypeMeta: metav1.TypeMeta{ Kind: "Secret", @@ -163,7 +163,7 @@ func NewFakeProjListerFromInterface(appProjects appclient.AppProjectInterface) a func NewFakeProjLister(objects ...runtime.Object) applister.AppProjectNamespaceLister { fakeAppClientset := apps.NewSimpleClientset(objects...) - factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) projInformer := factory.Argoproj().V1alpha1().AppProjects().Informer() cancel := StartInformer(projInformer) defer cancel() diff --git a/util/argo/argo.go b/util/argo/argo.go index 810b9a5decaee..6faa2d99756b4 100644 --- a/util/argo/argo.go +++ b/util/argo/argo.go @@ -707,7 +707,7 @@ func GetAppProjectWithScopedResources(ctx context.Context, name string, projList if err != nil { return nil, nil, nil, fmt.Errorf("error getting project clusters: %w", err) } - repos, err := db.GetProjectRepositories(ctx, name) + repos, err := db.GetProjectRepositories(name) if err != nil { return nil, nil, nil, fmt.Errorf("error getting project repos: %w", err) } @@ -721,7 +721,7 @@ func GetAppProjectByName(ctx context.Context, name string, projLister applicatio return nil, fmt.Errorf("error getting app project %q: %w", name, err) } project := projOrig.DeepCopy() - repos, err := db.GetProjectRepositories(ctx, name) + repos, err := db.GetProjectRepositories(name) if err != nil { return nil, fmt.Errorf("error getting project repositories: %w", err) } diff --git a/util/argo/argo_test.go b/util/argo/argo_test.go index c45cab489cd9b..328b013f9f1e2 100644 --- a/util/argo/argo_test.go +++ b/util/argo/argo_test.go @@ -1302,7 +1302,7 @@ func Test_GetRefSources(t *testing.T) { {RepoURL: "file://" + repoPath}, }) - refSources, err := GetRefSources(context.Background(), argoSpec.Sources, argoSpec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { + refSources, err := GetRefSources(context.Background(), argoSpec.Sources, argoSpec.Project, func(_ context.Context, _ string, _ string) (*argoappv1.Repository, error) { return repo, nil }, []string{}, false) @@ -1322,7 +1322,7 @@ func Test_GetRefSources(t *testing.T) { {RepoURL: "file://" + repoPath}, }) - refSources, err := GetRefSources(context.Background(), argoSpec.Sources, argoSpec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { + refSources, err := GetRefSources(context.Background(), argoSpec.Sources, argoSpec.Project, func(_ context.Context, _ string, _ string) (*argoappv1.Repository, error) { return nil, errors.New("repo does not exist") }, []string{}, false) @@ -1336,7 +1336,7 @@ func Test_GetRefSources(t *testing.T) { {RepoURL: "file://" + repoPath}, }) - refSources, err := GetRefSources(context.TODO(), argoSpec.Sources, argoSpec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { + refSources, err := GetRefSources(context.TODO(), argoSpec.Sources, argoSpec.Project, func(_ context.Context, _ string, _ string) (*argoappv1.Repository, error) { return nil, err }, []string{}, false) @@ -1350,7 +1350,7 @@ func Test_GetRefSources(t *testing.T) { {RepoURL: "file://does-not-exist", Ref: "source1"}, }) - refSources, err := GetRefSources(context.TODO(), argoSpec.Sources, argoSpec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { + refSources, err := GetRefSources(context.TODO(), argoSpec.Sources, argoSpec.Project, func(_ context.Context, _ string, _ string) (*argoappv1.Repository, error) { return nil, err }, []string{}, false) diff --git a/util/argo/resource_tracking.go b/util/argo/resource_tracking.go index 3366d15208791..546aaa68e150b 100644 --- a/util/argo/resource_tracking.go +++ b/util/argo/resource_tracking.go @@ -29,7 +29,7 @@ var ( // ResourceTracking defines methods which allow setup and retrieve tracking information to resource type ResourceTracking interface { GetAppName(un *unstructured.Unstructured, key string, trackingMethod v1alpha1.TrackingMethod, installationID string) string - GetAppInstance(un *unstructured.Unstructured, key string, trackingMethod v1alpha1.TrackingMethod, installationID string) *AppInstanceValue + GetAppInstance(un *unstructured.Unstructured, trackingMethod v1alpha1.TrackingMethod, installationID string) *AppInstanceValue SetAppInstance(un *unstructured.Unstructured, key, val, namespace string, trackingMethod v1alpha1.TrackingMethod, instanceID string) error BuildAppInstanceValue(value AppInstanceValue) string ParseAppInstanceValue(value string) (*AppInstanceValue, error) @@ -111,7 +111,7 @@ func (rt *resourceTracking) GetAppName(un *unstructured.Unstructured, key string // GetAppInstance returns the representation of the app instance annotation. // If the tracking method does not support metadata, or the annotation could // not be parsed, it returns nil. -func (rt *resourceTracking) GetAppInstance(un *unstructured.Unstructured, key string, trackingMethod v1alpha1.TrackingMethod, instanceID string) *AppInstanceValue { +func (rt *resourceTracking) GetAppInstance(un *unstructured.Unstructured, trackingMethod v1alpha1.TrackingMethod, instanceID string) *AppInstanceValue { switch trackingMethod { case TrackingMethodAnnotation, TrackingMethodAnnotationAndLabel: return rt.getAppInstanceValue(un, instanceID) diff --git a/util/cache/inmemory.go b/util/cache/inmemory.go index 5f1544c20f4eb..f42a6bf537d28 100644 --- a/util/cache/inmemory.go +++ b/util/cache/inmemory.go @@ -89,11 +89,11 @@ func (i *InMemoryCache) Flush() { i.memCache.Flush() } -func (i *InMemoryCache) OnUpdated(ctx context.Context, key string, callback func() error) error { +func (i *InMemoryCache) OnUpdated(_ context.Context, _ string, _ func() error) error { return nil } -func (i *InMemoryCache) NotifyUpdated(key string) error { +func (i *InMemoryCache) NotifyUpdated(_ string) error { return nil } diff --git a/util/cache/redis.go b/util/cache/redis.go index 5f0de926f7dd2..cdc98138bfd94 100644 --- a/util/cache/redis.go +++ b/util/cache/redis.go @@ -196,7 +196,7 @@ func (rh *redisHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook { } } -func (redisHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { +func (redisHook) ProcessPipelineHook(_ redis.ProcessPipelineHook) redis.ProcessPipelineHook { return nil } diff --git a/util/cache/redis_hook.go b/util/cache/redis_hook.go index e7cc3f4bcc68e..5d30337e2d411 100644 --- a/util/cache/redis_hook.go +++ b/util/cache/redis_hook.go @@ -36,6 +36,6 @@ func (hook *argoRedisHooks) ProcessHook(next redis.ProcessHook) redis.ProcessHoo } } -func (hook *argoRedisHooks) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { +func (hook *argoRedisHooks) ProcessPipelineHook(_ redis.ProcessPipelineHook) redis.ProcessPipelineHook { return nil } diff --git a/util/cli/cli.go b/util/cli/cli.go index d1e8492ec4bfc..4ffbda988cf06 100644 --- a/util/cli/cli.go +++ b/util/cli/cli.go @@ -38,7 +38,7 @@ func NewVersionCmd(cliName string) *cobra.Command { versionCmd := cobra.Command{ Use: "version", Short: "Print version information", - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { version := common.GetVersion() fmt.Printf("%s: %s\n", cliName, version) if short { diff --git a/util/clusterauth/clusterauth_test.go b/util/clusterauth/clusterauth_test.go index 748519697b160..4ce14e36a0e12 100644 --- a/util/clusterauth/clusterauth_test.go +++ b/util/clusterauth/clusterauth_test.go @@ -191,7 +191,7 @@ func TestGenerateNewClusterManagerSecret(t *testing.T) { "token": []byte("fake-token"), } - kubeclientset.AddReactor("*", "secrets", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + kubeclientset.AddReactor("*", "secrets", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { return true, generatedSecret, nil }) diff --git a/util/config/reader_test.go b/util/config/reader_test.go index 7265aefb68d97..052e9c090b1e9 100644 --- a/util/config/reader_test.go +++ b/util/config/reader_test.go @@ -84,7 +84,7 @@ func TestUnmarshalRemoteFile(t *testing.T) { // send back the address so that it can be used c <- listener.Addr().String() - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { // return the sentinel text at root URL fmt.Fprint(w, sentinel) }) diff --git a/util/db/certificate.go b/util/db/certificate.go index 978c29f964eeb..1b45d68657889 100644 --- a/util/db/certificate.go +++ b/util/db/certificate.go @@ -56,7 +56,7 @@ type CertificateListSelector struct { // - For SSH keys, the SHA256 fingerprint of the key as string, prepended by // the string "SHA256:" // - For TLS certs, the Subject of the X509 cert as a string in DN notation -func (db *db) ListRepoCertificates(ctx context.Context, selector *CertificateListSelector) (*appsv1.RepositoryCertificateList, error) { +func (db *db) ListRepoCertificates(_ context.Context, selector *CertificateListSelector) (*appsv1.RepositoryCertificateList, error) { // selector may be given as nil, but we need at least an empty data structure // so we create it if necessary. if selector == nil { @@ -123,7 +123,7 @@ func (db *db) ListRepoCertificates(ctx context.Context, selector *CertificateLis } // Get a single certificate from the datastore -func (db *db) GetRepoCertificate(ctx context.Context, serverType string, serverName string) (*appsv1.RepositoryCertificate, error) { +func (db *db) GetRepoCertificate(_ context.Context, serverType string, serverName string) (*appsv1.RepositoryCertificate, error) { if serverType == "ssh" { sshKnownHostsList, err := db.getSSHKnownHostsData() if err != nil { diff --git a/util/db/cluster.go b/util/db/cluster.go index a17f72d2840b8..c09bc7e91bedd 100644 --- a/util/db/cluster.go +++ b/util/db/cluster.go @@ -57,7 +57,7 @@ func (db *db) getLocalCluster() *appv1.Cluster { } // ListClusters returns list of clusters -func (db *db) ListClusters(ctx context.Context) (*appv1.ClusterList, error) { +func (db *db) ListClusters(_ context.Context) (*appv1.ClusterList, error) { clusterSecrets, err := db.listSecretsByType(common.LabelValueSecretTypeCluster) if err != nil { return nil, err @@ -233,7 +233,7 @@ func (db *db) GetCluster(_ context.Context, server string) (*appv1.Cluster, erro } // GetProjectClusters return project scoped clusters by given project name -func (db *db) GetProjectClusters(ctx context.Context, project string) ([]*appv1.Cluster, error) { +func (db *db) GetProjectClusters(_ context.Context, project string) ([]*appv1.Cluster, error) { informer, err := db.settingsMgr.GetSecretsInformer() if err != nil { return nil, fmt.Errorf("failed to get secrets informer: %w", err) @@ -253,7 +253,7 @@ func (db *db) GetProjectClusters(ctx context.Context, project string) ([]*appv1. return res, nil } -func (db *db) GetClusterServersByName(ctx context.Context, name string) ([]string, error) { +func (db *db) GetClusterServersByName(_ context.Context, name string) ([]string, error) { informer, err := db.settingsMgr.GetSecretsInformer() if err != nil { return nil, err diff --git a/util/db/cluster_norace_test.go b/util/db/cluster_norace_test.go index 23b5beecef079..179463e9f6509 100644 --- a/util/db/cluster_norace_test.go +++ b/util/db/cluster_norace_test.go @@ -122,7 +122,7 @@ func TestWatchClusters_LocalClusterModifications(t *testing.T) { assert.NoError(t, db.DeleteCluster(context.Background(), v1alpha1.KubernetesInternalAPIServerAddr)) }, - func(old *v1alpha1.Cluster, new *v1alpha1.Cluster) { + func(_ *v1alpha1.Cluster, new *v1alpha1.Cluster) { assert.Equal(t, v1alpha1.KubernetesInternalAPIServerAddr, new.Server) assert.Equal(t, "in-cluster", new.Name) }, diff --git a/util/db/cluster_test.go b/util/db/cluster_test.go index 345dd6107e1bb..e68ca3a1ca72a 100644 --- a/util/db/cluster_test.go +++ b/util/db/cluster_test.go @@ -424,7 +424,7 @@ func TestListClusters(t *testing.T) { // TestClusterRaceConditionClusterSecrets reproduces a race condition // on the cluster secrets. The test isn't asserting anything because // before the fix it would cause a panic from concurrent map iteration and map write -func TestClusterRaceConditionClusterSecrets(t *testing.T) { +func TestClusterRaceConditionClusterSecrets(_ *testing.T) { clusterSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster", diff --git a/util/db/db.go b/util/db/db.go index 4114450631d8d..708354d119af0 100644 --- a/util/db/db.go +++ b/util/db/db.go @@ -55,7 +55,7 @@ type ArgoDB interface { // GetRepository returns a repository by URL GetRepository(ctx context.Context, url, project string) (*appv1.Repository, error) // GetProjectRepositories returns project scoped repositories by given project name - GetProjectRepositories(ctx context.Context, project string) ([]*appv1.Repository, error) + GetProjectRepositories(project string) ([]*appv1.Repository, error) // RepositoryExists returns whether a repository is configured for the given URL RepositoryExists(ctx context.Context, repoURL, project string) (bool, error) // UpdateRepository updates a repository @@ -68,7 +68,7 @@ type ArgoDB interface { // GetWriteRepository returns a repository by URL with write credentials GetWriteRepository(ctx context.Context, url, project string) (*appv1.Repository, error) // GetProjectWriteRepositories returns project scoped repositories from write credentials by given project name - GetProjectWriteRepositories(ctx context.Context, project string) ([]*appv1.Repository, error) + GetProjectWriteRepositories(project string) ([]*appv1.Repository, error) // WriteRepositoryExists returns whether a repository is configured for the given URL with write credentials WriteRepositoryExists(ctx context.Context, repoURL, project string) (bool, error) // UpdateWriteRepository updates a repository with write credentials diff --git a/util/db/gpgkeys.go b/util/db/gpgkeys.go index add5b4f4222b3..28b6934668f16 100644 --- a/util/db/gpgkeys.go +++ b/util/db/gpgkeys.go @@ -57,7 +57,7 @@ func validatePGPKey(keyData string) (*appsv1.GnuPGPublicKey, error) { } // ListConfiguredGPGPublicKeys returns a list of all configured GPG public keys from the ConfigMap -func (db *db) ListConfiguredGPGPublicKeys(ctx context.Context) (map[string]*appsv1.GnuPGPublicKey, error) { +func (db *db) ListConfiguredGPGPublicKeys(_ context.Context) (map[string]*appsv1.GnuPGPublicKey, error) { log.Debugf("Loading PGP public keys from config map") result := make(map[string]*appsv1.GnuPGPublicKey) keysCM, err := db.settingsMgr.GetConfigMapByName(common.ArgoCDGPGKeysConfigMapName) diff --git a/util/db/mocks/ArgoDB.go b/util/db/mocks/ArgoDB.go index 837f939a6f41c..173c7e5be0514 100644 --- a/util/db/mocks/ArgoDB.go +++ b/util/db/mocks/ArgoDB.go @@ -481,9 +481,9 @@ func (_m *ArgoDB) GetProjectClusters(ctx context.Context, project string) ([]*v1 return r0, r1 } -// GetProjectRepositories provides a mock function with given fields: ctx, project -func (_m *ArgoDB) GetProjectRepositories(ctx context.Context, project string) ([]*v1alpha1.Repository, error) { - ret := _m.Called(ctx, project) +// GetProjectRepositories provides a mock function with given fields: project +func (_m *ArgoDB) GetProjectRepositories(project string) ([]*v1alpha1.Repository, error) { + ret := _m.Called(project) if len(ret) == 0 { panic("no return value specified for GetProjectRepositories") @@ -491,19 +491,19 @@ func (_m *ArgoDB) GetProjectRepositories(ctx context.Context, project string) ([ var r0 []*v1alpha1.Repository var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string) ([]*v1alpha1.Repository, error)); ok { - return rf(ctx, project) + if rf, ok := ret.Get(0).(func(string) ([]*v1alpha1.Repository, error)); ok { + return rf(project) } - if rf, ok := ret.Get(0).(func(context.Context, string) []*v1alpha1.Repository); ok { - r0 = rf(ctx, project) + if rf, ok := ret.Get(0).(func(string) []*v1alpha1.Repository); ok { + r0 = rf(project) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*v1alpha1.Repository) } } - if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { - r1 = rf(ctx, project) + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(project) } else { r1 = ret.Error(1) } @@ -511,9 +511,9 @@ func (_m *ArgoDB) GetProjectRepositories(ctx context.Context, project string) ([ return r0, r1 } -// GetProjectWriteRepositories provides a mock function with given fields: ctx, project -func (_m *ArgoDB) GetProjectWriteRepositories(ctx context.Context, project string) ([]*v1alpha1.Repository, error) { - ret := _m.Called(ctx, project) +// GetProjectWriteRepositories provides a mock function with given fields: project +func (_m *ArgoDB) GetProjectWriteRepositories(project string) ([]*v1alpha1.Repository, error) { + ret := _m.Called(project) if len(ret) == 0 { panic("no return value specified for GetProjectWriteRepositories") @@ -521,19 +521,19 @@ func (_m *ArgoDB) GetProjectWriteRepositories(ctx context.Context, project strin var r0 []*v1alpha1.Repository var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string) ([]*v1alpha1.Repository, error)); ok { - return rf(ctx, project) + if rf, ok := ret.Get(0).(func(string) ([]*v1alpha1.Repository, error)); ok { + return rf(project) } - if rf, ok := ret.Get(0).(func(context.Context, string) []*v1alpha1.Repository); ok { - r0 = rf(ctx, project) + if rf, ok := ret.Get(0).(func(string) []*v1alpha1.Repository); ok { + r0 = rf(project) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*v1alpha1.Repository) } } - if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { - r1 = rf(ctx, project) + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(project) } else { r1 = ret.Error(1) } diff --git a/util/db/repository.go b/util/db/repository.go index fd2d5e6a68c2b..f7d59cbd4a3b9 100644 --- a/util/db/repository.go +++ b/util/db/repository.go @@ -118,11 +118,11 @@ func (db *db) GetWriteRepository(ctx context.Context, repoURL, project string) ( return repository, err } -func (db *db) GetProjectRepositories(ctx context.Context, project string) ([]*v1alpha1.Repository, error) { +func (db *db) GetProjectRepositories(project string) ([]*v1alpha1.Repository, error) { return db.getRepositories(settings.ByProjectRepoIndexer, project) } -func (db *db) GetProjectWriteRepositories(ctx context.Context, project string) ([]*v1alpha1.Repository, error) { +func (db *db) GetProjectWriteRepositories(project string) ([]*v1alpha1.Repository, error) { return db.getRepositories(settings.ByProjectRepoWriteIndexer, project) } diff --git a/util/db/repository_legacy.go b/util/db/repository_legacy.go index d0bfaf4321a05..f84333ba5a27c 100644 --- a/util/db/repository_legacy.go +++ b/util/db/repository_legacy.go @@ -27,13 +27,13 @@ type legacyRepositoryBackend struct { db *db } -func (l *legacyRepositoryBackend) CreateRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) { +func (l *legacyRepositoryBackend) CreateRepository(_ context.Context, _ *appsv1.Repository) (*appsv1.Repository, error) { // This strategy only kept to preserve backward compatibility, but is deprecated. // Therefore, no new repositories can be added with this backend. panic("creating new repositories is not supported for the legacy repository backend") } -func (l *legacyRepositoryBackend) GetRepository(ctx context.Context, repoURL, project string) (*appsv1.Repository, error) { +func (l *legacyRepositoryBackend) GetRepository(_ context.Context, repoURL, _ string) (*appsv1.Repository, error) { repository, err := l.tryGetRepository(repoURL) if err != nil { return nil, fmt.Errorf("unable to get repository: %w", err) @@ -41,7 +41,7 @@ func (l *legacyRepositoryBackend) GetRepository(ctx context.Context, repoURL, pr return repository, nil } -func (l *legacyRepositoryBackend) ListRepositories(ctx context.Context, repoType *string) ([]*appsv1.Repository, error) { +func (l *legacyRepositoryBackend) ListRepositories(_ context.Context, repoType *string) ([]*appsv1.Repository, error) { inRepos, err := l.db.settingsMgr.GetRepositories() if err != nil { return nil, err @@ -71,7 +71,7 @@ func (l *legacyRepositoryBackend) ListRepositories(ctx context.Context, repoType return repos, nil } -func (l *legacyRepositoryBackend) UpdateRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) { +func (l *legacyRepositoryBackend) UpdateRepository(_ context.Context, r *appsv1.Repository) (*appsv1.Repository, error) { repos, err := l.db.settingsMgr.GetRepositories() if err != nil { return nil, err @@ -102,7 +102,7 @@ func (l *legacyRepositoryBackend) UpdateRepository(ctx context.Context, r *appsv return r, nil } -func (l *legacyRepositoryBackend) DeleteRepository(ctx context.Context, repoURL, project string) error { +func (l *legacyRepositoryBackend) DeleteRepository(_ context.Context, repoURL, _ string) error { repos, err := l.db.settingsMgr.GetRepositories() if err != nil { return err @@ -127,7 +127,7 @@ func (l *legacyRepositoryBackend) DeleteRepository(ctx context.Context, repoURL, return l.db.settingsMgr.SaveRepositories(repos) } -func (l *legacyRepositoryBackend) RepositoryExists(ctx context.Context, repoURL, project string, allowFallback bool) (bool, error) { +func (l *legacyRepositoryBackend) RepositoryExists(_ context.Context, repoURL, _ string, _ bool) (bool, error) { repos, err := l.db.settingsMgr.GetRepositories() if err != nil { return false, fmt.Errorf("unable to get repositories: %w", err) @@ -137,13 +137,13 @@ func (l *legacyRepositoryBackend) RepositoryExists(ctx context.Context, repoURL, return index >= 0, nil } -func (l *legacyRepositoryBackend) CreateRepoCreds(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { +func (l *legacyRepositoryBackend) CreateRepoCreds(_ context.Context, _ *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { // This strategy only kept to preserve backward compatibility, but is deprecated. // Therefore, no new repositories can be added with this backend. panic("creating new repository credentials is not supported for the legacy repository backend") } -func (l *legacyRepositoryBackend) GetRepoCreds(ctx context.Context, repoURL string) (*appsv1.RepoCreds, error) { +func (l *legacyRepositoryBackend) GetRepoCreds(_ context.Context, repoURL string) (*appsv1.RepoCreds, error) { var credential *appsv1.RepoCreds repoCredentials, err := l.db.settingsMgr.GetRepositoryCredentials() @@ -161,7 +161,7 @@ func (l *legacyRepositoryBackend) GetRepoCreds(ctx context.Context, repoURL stri return credential, err } -func (l *legacyRepositoryBackend) ListRepoCreds(ctx context.Context) ([]string, error) { +func (l *legacyRepositoryBackend) ListRepoCreds(_ context.Context) ([]string, error) { repos, err := l.db.settingsMgr.GetRepositoryCredentials() if err != nil { return nil, err @@ -175,7 +175,7 @@ func (l *legacyRepositoryBackend) ListRepoCreds(ctx context.Context) ([]string, return urls, nil } -func (l *legacyRepositoryBackend) UpdateRepoCreds(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { +func (l *legacyRepositoryBackend) UpdateRepoCreds(_ context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { repos, err := l.db.settingsMgr.GetRepositoryCredentials() if err != nil { return nil, err @@ -200,7 +200,7 @@ func (l *legacyRepositoryBackend) UpdateRepoCreds(ctx context.Context, r *appsv1 return r, nil } -func (l *legacyRepositoryBackend) DeleteRepoCreds(ctx context.Context, name string) error { +func (l *legacyRepositoryBackend) DeleteRepoCreds(_ context.Context, name string) error { repos, err := l.db.settingsMgr.GetRepositoryCredentials() if err != nil { return err @@ -225,7 +225,7 @@ func (l *legacyRepositoryBackend) DeleteRepoCreds(ctx context.Context, name stri return l.db.settingsMgr.SaveRepositoryCredentials(repos) } -func (l *legacyRepositoryBackend) RepoCredsExists(ctx context.Context, repoURL string) (bool, error) { +func (l *legacyRepositoryBackend) RepoCredsExists(_ context.Context, repoURL string) (bool, error) { creds, err := l.db.settingsMgr.GetRepositoryCredentials() if err != nil { return false, err @@ -235,7 +235,7 @@ func (l *legacyRepositoryBackend) RepoCredsExists(ctx context.Context, repoURL s return index >= 0, nil } -func (l *legacyRepositoryBackend) GetAllHelmRepoCreds(ctx context.Context) ([]*appsv1.RepoCreds, error) { +func (l *legacyRepositoryBackend) GetAllHelmRepoCreds(_ context.Context) ([]*appsv1.RepoCreds, error) { var allCredentials []*appsv1.RepoCreds repoCredentials, err := l.db.settingsMgr.GetRepositoryCredentials() if err != nil { diff --git a/util/db/repository_secrets.go b/util/db/repository_secrets.go index 6d5d0ad3a21bf..fbe44d1fd1d49 100644 --- a/util/db/repository_secrets.go +++ b/util/db/repository_secrets.go @@ -83,7 +83,7 @@ func (s *secretsRepositoryBackend) GetRepoCredsBySecretName(_ context.Context, n return s.secretToRepoCred(secret) } -func (s *secretsRepositoryBackend) GetRepository(ctx context.Context, repoURL, project string) (*appsv1.Repository, error) { +func (s *secretsRepositoryBackend) GetRepository(_ context.Context, repoURL, project string) (*appsv1.Repository, error) { secret, err := s.getRepositorySecret(repoURL, project, true) if err != nil { if status.Code(err) == codes.NotFound { @@ -101,7 +101,7 @@ func (s *secretsRepositoryBackend) GetRepository(ctx context.Context, repoURL, p return repository, err } -func (s *secretsRepositoryBackend) ListRepositories(ctx context.Context, repoType *string) ([]*appsv1.Repository, error) { +func (s *secretsRepositoryBackend) ListRepositories(_ context.Context, repoType *string) ([]*appsv1.Repository, error) { var repos []*appsv1.Repository secrets, err := s.db.listSecretsByType(s.getSecretType()) @@ -166,7 +166,7 @@ func (s *secretsRepositoryBackend) DeleteRepository(ctx context.Context, repoURL return s.db.settingsMgr.ResyncInformers() } -func (s *secretsRepositoryBackend) RepositoryExists(ctx context.Context, repoURL, project string, allowFallback bool) (bool, error) { +func (s *secretsRepositoryBackend) RepositoryExists(_ context.Context, repoURL, project string, allowFallback bool) (bool, error) { secret, err := s.getRepositorySecret(repoURL, project, allowFallback) if err != nil { if status.Code(err) == codes.NotFound { @@ -201,7 +201,7 @@ func (s *secretsRepositoryBackend) CreateRepoCreds(ctx context.Context, repoCred return repoCreds, s.db.settingsMgr.ResyncInformers() } -func (s *secretsRepositoryBackend) GetRepoCreds(ctx context.Context, repoURL string) (*appsv1.RepoCreds, error) { +func (s *secretsRepositoryBackend) GetRepoCreds(_ context.Context, repoURL string) (*appsv1.RepoCreds, error) { secret, err := s.getRepoCredsSecret(repoURL) if err != nil { if status.Code(err) == codes.NotFound { @@ -214,7 +214,7 @@ func (s *secretsRepositoryBackend) GetRepoCreds(ctx context.Context, repoURL str return s.secretToRepoCred(secret) } -func (s *secretsRepositoryBackend) ListRepoCreds(ctx context.Context) ([]string, error) { +func (s *secretsRepositoryBackend) ListRepoCreds(_ context.Context) ([]string, error) { var repoURLs []string secrets, err := s.db.listSecretsByType(common.LabelValueSecretTypeRepoCreds) @@ -266,7 +266,7 @@ func (s *secretsRepositoryBackend) DeleteRepoCreds(ctx context.Context, name str return s.db.settingsMgr.ResyncInformers() } -func (s *secretsRepositoryBackend) RepoCredsExists(ctx context.Context, repoURL string) (bool, error) { +func (s *secretsRepositoryBackend) RepoCredsExists(_ context.Context, repoURL string) (bool, error) { _, err := s.getRepoCredsSecret(repoURL) if err != nil { if status.Code(err) == codes.NotFound { @@ -279,7 +279,7 @@ func (s *secretsRepositoryBackend) RepoCredsExists(ctx context.Context, repoURL return true, nil } -func (s *secretsRepositoryBackend) GetAllHelmRepoCreds(ctx context.Context) ([]*appsv1.RepoCreds, error) { +func (s *secretsRepositoryBackend) GetAllHelmRepoCreds(_ context.Context) ([]*appsv1.RepoCreds, error) { var helmRepoCreds []*appsv1.RepoCreds secrets, err := s.db.listSecretsByType(common.LabelValueSecretTypeRepoCreds) diff --git a/util/db/repository_secrets_test.go b/util/db/repository_secrets_test.go index 1d91dd32937a0..4905eb6ad1990 100644 --- a/util/db/repository_secrets_test.go +++ b/util/db/repository_secrets_test.go @@ -88,7 +88,7 @@ func TestSecretsRepositoryBackend_CreateRepository(t *testing.T) { delete(secret.Labels, common.LabelKeySecretType) f := setupWithK8sObjects(secret) f.clientSet.ReactionChain = nil - f.clientSet.AddReactor("create", "secrets", func(action k8stesting.Action) (handled bool, ret runtime.Object, err error) { + f.clientSet.AddReactor("create", "secrets", func(_ k8stesting.Action) (handled bool, ret runtime.Object, err error) { gr := schema.GroupResource{ Group: "v1", Resource: "secrets", @@ -125,7 +125,7 @@ func TestSecretsRepositoryBackend_CreateRepository(t *testing.T) { f := setupWithK8sObjects(secret) f.clientSet.ReactionChain = nil f.clientSet.WatchReactionChain = nil - f.clientSet.AddReactor("create", "secrets", func(action k8stesting.Action) (handled bool, ret runtime.Object, err error) { + f.clientSet.AddReactor("create", "secrets", func(_ k8stesting.Action) (handled bool, ret runtime.Object, err error) { gr := schema.GroupResource{ Group: "v1", Resource: "secrets", @@ -134,7 +134,7 @@ func TestSecretsRepositoryBackend_CreateRepository(t *testing.T) { }) watcher := watch.NewFakeWithChanSize(1, true) watcher.Add(secret) - f.clientSet.AddWatchReactor("secrets", func(action k8stesting.Action) (handled bool, ret watch.Interface, err error) { + f.clientSet.AddWatchReactor("secrets", func(_ k8stesting.Action) (handled bool, ret watch.Interface, err error) { return true, watcher, nil }) diff --git a/util/db/repository_test.go b/util/db/repository_test.go index a0601815e901f..4f7d40ec35af8 100644 --- a/util/db/repository_test.go +++ b/util/db/repository_test.go @@ -357,7 +357,7 @@ func Test_GetProjectRepositories(t *testing.T) { clientset := getClientset(map[string]string{}, repoSecretWithProject, repoSecretWithoutProject) argoDB := NewDB(testNamespace, settings.NewSettingsManager(context.TODO(), clientset, testNamespace), clientset) - repos, err := argoDB.GetProjectRepositories(context.TODO(), "some-project") + repos, err := argoDB.GetProjectRepositories("some-project") require.NoError(t, err) assert.Len(t, repos, 1) assert.Equal(t, "git@github.com:argoproj/argo-cd", repos[0].Repo) diff --git a/util/dex/dex.go b/util/dex/dex.go index a24d2d18f54f5..b91f0f4d8bac9 100644 --- a/util/dex/dex.go +++ b/util/dex/dex.go @@ -45,7 +45,7 @@ func TLSConfig(tlsConfig *DexTLSConfig) *tls.Config { return &tls.Config{ InsecureSkipVerify: false, RootCAs: tlsConfig.RootCAs, - VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { + VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error { if !bytes.Equal(rawCerts[0], tlsConfig.Certificate) { return stderrors.New("dex server certificate does not match") } diff --git a/util/dex/dex_test.go b/util/dex/dex_test.go index 3bca3134bd917..8151d460147bd 100644 --- a/util/dex/dex_test.go +++ b/util/dex/dex_test.go @@ -481,7 +481,7 @@ func Test_DexReverseProxy(t *testing.T) { }) t.Run("Bad case", func(t *testing.T) { - fakeDex := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + fakeDex := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusInternalServerError) })) defer fakeDex.Close() @@ -490,7 +490,7 @@ func Test_DexReverseProxy(t *testing.T) { fmt.Printf("Fake API Server listening on %s\n", server.URL) defer server.Close() client := &http.Client{ - CheckRedirect: func(req *http.Request, via []*http.Request) error { + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }, } @@ -511,7 +511,7 @@ func Test_DexReverseProxy(t *testing.T) { }) t.Run("Round Tripper", func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) { assert.Equal(t, "/", req.URL.String()) })) defer server.Close() diff --git a/util/git/client.go b/util/git/client.go index 300646e22cfcb..3625edbbdac95 100644 --- a/util/git/client.go +++ b/util/git/client.go @@ -211,7 +211,7 @@ func GetRepoHTTPClient(repoURL string, insecure bool, creds Creds, proxyURL stri // 15 second timeout by default Timeout: gitClientTimeout, // don't follow redirect - CheckRedirect: func(req *http.Request, via []*http.Request) error { + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }, } @@ -220,7 +220,7 @@ func GetRepoHTTPClient(repoURL string, insecure bool, creds Creds, proxyURL stri // Callback function to return any configured client certificate // We never return err, but an empty cert instead. - clientCertFunc := func(req *tls.CertificateRequestInfo) (*tls.Certificate, error) { + clientCertFunc := func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) { var err error cert := tls.Certificate{} diff --git a/util/git/creds.go b/util/git/creds.go index de84fc42dc0af..6cdf40c50a12d 100644 --- a/util/git/creds.go +++ b/util/git/creds.go @@ -61,14 +61,14 @@ func init() { type NoopCredsStore struct{} -func (d NoopCredsStore) Add(username string, password string) string { +func (d NoopCredsStore) Add(_ string, _ string) string { return "" } -func (d NoopCredsStore) Remove(id string) { +func (d NoopCredsStore) Remove(_ string) { } -func (d NoopCredsStore) Environ(id string) []string { +func (d NoopCredsStore) Environ(_ string) []string { return []string{} } @@ -101,7 +101,7 @@ func (c NopCreds) Environ() (io.Closer, []string, error) { } // GetUserInfo returns empty strings for user info -func (c NopCreds) GetUserInfo(ctx context.Context) (name string, email string, err error) { +func (c NopCreds) GetUserInfo(_ context.Context) (name string, email string, err error) { return "", "", nil } @@ -156,7 +156,7 @@ func NewHTTPSCreds(username string, password string, clientCertData string, clie } // GetUserInfo returns the username and email address for the credentials, if they're available. -func (creds HTTPSCreds) GetUserInfo(ctx context.Context) (string, string, error) { +func (creds HTTPSCreds) GetUserInfo(_ context.Context) (string, string, error) { // Email not implemented for HTTPS creds. return creds.username, "", nil } @@ -269,7 +269,7 @@ func NewSSHCreds(sshPrivateKey string, caPath string, insecureIgnoreHostKey bool // GetUserInfo returns empty strings for user info. // TODO: Implement this method to return the username and email address for the credentials, if they're available. -func (c SSHCreds) GetUserInfo(ctx context.Context) (string, string, error) { +func (c SSHCreds) GetUserInfo(_ context.Context) (string, string, error) { // User info not implemented for SSH creds. return "", "", nil } @@ -586,7 +586,7 @@ func NewGoogleCloudCreds(jsonData string, store CredsStore) GoogleCloudCreds { // GetUserInfo returns the username and email address for the credentials, if they're available. // TODO: implement getting email instead of just username. -func (c GoogleCloudCreds) GetUserInfo(ctx context.Context) (string, string, error) { +func (c GoogleCloudCreds) GetUserInfo(_ context.Context) (string, string, error) { username, err := c.getUsername() if err != nil { return "", "", fmt.Errorf("failed to get username from creds: %w", err) diff --git a/util/git/creds_test.go b/util/git/creds_test.go index 303ac2f8f4752..322a79cd0429b 100644 --- a/util/git/creds_test.go +++ b/util/git/creds_test.go @@ -43,7 +43,7 @@ func (s *memoryCredsStore) Remove(id string) { delete(s.creds, id) } -func (s *memoryCredsStore) Environ(id string) []string { +func (s *memoryCredsStore) Environ(_ string) []string { return nil } diff --git a/util/gpg/gpg.go b/util/gpg/gpg.go index 6b8cefbeea82f..b3cf979b608b3 100644 --- a/util/gpg/gpg.go +++ b/util/gpg/gpg.go @@ -704,7 +704,7 @@ func SyncKeyRingFromDirectory(basePath string) ([]string, []string, error) { } // Collect configuration, i.e. files in basePath - err = filepath.Walk(basePath, func(path string, fi os.FileInfo, err error) error { + err = filepath.Walk(basePath, func(_ string, fi os.FileInfo, err error) error { if err != nil { return err } diff --git a/util/grpc/errors.go b/util/grpc/errors.go index 4af523852135a..141c76e7b1c6f 100644 --- a/util/grpc/errors.go +++ b/util/grpc/errors.go @@ -103,7 +103,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 any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { resp, err = handler(ctx, req) return resp, gitErrToGRPC(err) } @@ -111,7 +111,7 @@ func ErrorCodeGitUnaryServerInterceptor() grpc.UnaryServerInterceptor { // ErrorCodeGitStreamServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any. func ErrorCodeGitStreamServerInterceptor() grpc.StreamServerInterceptor { - return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { err := handler(srv, ss) return gitErrToGRPC(err) } @@ -119,7 +119,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 any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { resp, err = handler(ctx, req) return resp, kubeErrToGRPC(err) } @@ -127,7 +127,7 @@ func ErrorCodeK8sUnaryServerInterceptor() grpc.UnaryServerInterceptor { // ErrorCodeK8sStreamServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any. func ErrorCodeK8sStreamServerInterceptor() grpc.StreamServerInterceptor { - return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, _ *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 bc6526a6f4739..7216f3c9b5505 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 any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ any, err error) { + return func(ctx context.Context, req any, _ *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 any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { + return func(srv any, stream grpc.ServerStream, _ *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()) diff --git a/util/grpc/logging_test.go b/util/grpc/logging_test.go index b7d30b0c62d86..cd9c05aae4dc1 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 any) (any, error) { + handler := func(_ context.Context, _ any) (any, error) { return nil, nil } - decider := func(ctx context.Context, fullMethodName string, servingObject any) bool { + decider := func(_ context.Context, _ string, _ 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 any) (any, error) { + handler := func(_ context.Context, _ any) (any, error) { return nil, nil } - decider := func(ctx context.Context, fullMethodName string, servingObject any) bool { + decider := func(_ context.Context, _ string, _ any) bool { return true } diff --git a/util/grpc/sanitizer.go b/util/grpc/sanitizer.go index 45bd8f82ac7f2..1afae682fbfe1 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 any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { + return func(ctx context.Context, req any, _ *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 ba016a1cd38d1..9f7ac92f4a6d6 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 any) (any, error) { + _, err := interceptor(context.Background(), nil, nil, func(ctx context.Context, _ 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 a05d51c669499..54ecdde7697cb 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 any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + return func(ctx context.Context, req any, _ *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 any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if err := userAgentEnforcer(stream.Context(), clientName, constraintStr, semVerConstraint); err != nil { return err } diff --git a/util/healthz/healthz_test.go b/util/healthz/healthz_test.go index d2724686dde1e..c76a284c67807 100644 --- a/util/healthz/healthz_test.go +++ b/util/healthz/healthz_test.go @@ -23,7 +23,7 @@ func TestHealthCheck(t *testing.T) { c <- listener.Addr().String() mux := http.NewServeMux() - ServeHealthCheck(mux, func(r *http.Request) error { + ServeHealthCheck(mux, func(_ *http.Request) error { if sentinel { return errors.New("This is a dummy error") } diff --git a/util/helm/cmd.go b/util/helm/cmd.go index 28b458fa51c88..0f5abca86fd37 100644 --- a/util/helm/cmd.go +++ b/util/helm/cmd.go @@ -120,7 +120,7 @@ func (c *Cmd) RegistryLogin(repo string, creds Creds) (string, error) { return out, nil } -func (c *Cmd) RegistryLogout(repo string, creds Creds) (string, error) { +func (c *Cmd) RegistryLogout(repo string, _ Creds) (string, error) { args := []string{"registry", "logout"} args = append(args, repo) out, _, err := c.run(args...) diff --git a/util/kube/failureretrywrapper.go b/util/kube/failureretrywrapper.go index f9d66e89105fd..9cacc6d0c734a 100644 --- a/util/kube/failureretrywrapper.go +++ b/util/kube/failureretrywrapper.go @@ -17,7 +17,7 @@ type failureRetryRoundTripper struct { } // nolint:unparam -func shouldRetry(counter int, r *http.Request, response *http.Response, err error) bool { +func shouldRetry(counter int, _ *http.Request, response *http.Response, err error) bool { if counter <= 0 { return false } diff --git a/util/kube/util.go b/util/kube/util.go index b5e4c2498fff7..684e5a1e0259e 100644 --- a/util/kube/util.go +++ b/util/kube/util.go @@ -70,7 +70,7 @@ func (ku *kubeUtil) CreateOrUpdateSecret(ns string, name string, update updateFn // CreateOrUpdateSecretField creates or updates a secret name in namespace ns, with given value for given field func (ku *kubeUtil) CreateOrUpdateSecretField(ns string, name string, field string, value string) error { - err := ku.CreateOrUpdateSecret(ns, name, func(s *corev1.Secret, new bool) error { + err := ku.CreateOrUpdateSecret(ns, name, func(s *corev1.Secret, _ bool) error { s.Data[field] = []byte(value) return nil }) diff --git a/util/lua/custom_actions_test.go b/util/lua/custom_actions_test.go index dc8662bc5e294..8df7c78975e93 100644 --- a/util/lua/custom_actions_test.go +++ b/util/lua/custom_actions_test.go @@ -103,7 +103,7 @@ type IndividualActionTest struct { } func TestLuaResourceActionsScript(t *testing.T) { - err := filepath.Walk("../../resource_customizations", func(path string, f os.FileInfo, err error) error { + err := filepath.Walk("../../resource_customizations", func(path string, _ os.FileInfo, err error) error { if !strings.Contains(path, "action_test.yaml") { return nil } diff --git a/util/lua/health_test.go b/util/lua/health_test.go index c2e4e6766343d..caf28e84ff3fb 100644 --- a/util/lua/health_test.go +++ b/util/lua/health_test.go @@ -34,7 +34,7 @@ func getObj(path string) *unstructured.Unstructured { } func TestLuaHealthScript(t *testing.T) { - err := filepath.Walk("../../resource_customizations", func(path string, f os.FileInfo, err error) error { + err := filepath.Walk("../../resource_customizations", func(path string, _ os.FileInfo, err error) error { if !strings.Contains(path, "health.lua") { return nil } diff --git a/util/notification/expression/strings/strings_test.go b/util/notification/expression/strings/strings_test.go index 76cb57606b2f6..c84ba4f374608 100644 --- a/util/notification/expression/strings/strings_test.go +++ b/util/notification/expression/strings/strings_test.go @@ -49,7 +49,7 @@ func TestUpperAndLower(t *testing.T) { exprs := NewExprs() for _, testCase := range testCases { - t.Run("With success case: Func: "+testCase.fn, func(tc *testing.T) { + t.Run("With success case: Func: "+testCase.fn, func(t *testing.T) { toUpperFn, ok := exprs[testCase.fn].(func(s string) string) assert.True(t, ok) diff --git a/util/oidc/oidc_test.go b/util/oidc/oidc_test.go index 2b35cef92697c..b31bb407af5ad 100644 --- a/util/oidc/oidc_test.go +++ b/util/oidc/oidc_test.go @@ -644,7 +644,7 @@ func TestGetUserInfo(t *testing.T) { }, }, idpClaims: jwt.MapClaims{"sub": "randomUser", "exp": float64(time.Now().Add(5 * time.Minute).Unix())}, - idpHandler: func(w http.ResponseWriter, r *http.Request) { + idpHandler: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotFound) }, cache: cache.NewInMemoryCache(24 * time.Hour), @@ -678,7 +678,7 @@ func TestGetUserInfo(t *testing.T) { }, }, idpClaims: jwt.MapClaims{"sub": "randomUser", "exp": float64(time.Now().Add(5 * time.Minute).Unix())}, - idpHandler: func(w http.ResponseWriter, r *http.Request) { + idpHandler: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusUnauthorized) }, cache: cache.NewInMemoryCache(24 * time.Hour), @@ -712,7 +712,7 @@ func TestGetUserInfo(t *testing.T) { }, }, idpClaims: jwt.MapClaims{"sub": "randomUser", "exp": float64(time.Now().Add(5 * time.Minute).Unix())}, - idpHandler: func(w http.ResponseWriter, r *http.Request) { + idpHandler: func(w http.ResponseWriter, _ *http.Request) { userInfoBytes := ` notevenJsongarbage ` @@ -754,7 +754,7 @@ func TestGetUserInfo(t *testing.T) { }, }, idpClaims: jwt.MapClaims{"sub": "randomUser", "exp": float64(time.Now().Add(5 * time.Minute).Unix())}, - idpHandler: func(w http.ResponseWriter, r *http.Request) { + idpHandler: func(w http.ResponseWriter, _ *http.Request) { userInfoBytes := ` { "groups":["githubOrg:engineers"] @@ -789,7 +789,7 @@ func TestGetUserInfo(t *testing.T) { }, }, idpClaims: jwt.MapClaims{"sub": "randomUser", "exp": float64(time.Now().Add(5 * time.Minute).Unix())}, - idpHandler: func(w http.ResponseWriter, r *http.Request) { + idpHandler: func(w http.ResponseWriter, _ *http.Request) { userInfoBytes := ` { "groups":["githubOrg:engineers"] diff --git a/util/rbac/rbac.go b/util/rbac/rbac.go index 77a8a4cbbdca6..300de8c92fb0c 100644 --- a/util/rbac/rbac.go +++ b/util/rbac/rbac.go @@ -519,18 +519,18 @@ func loadPolicyLine(line string, model model.Model) error { return nil } -func (a *argocdAdapter) SavePolicy(model model.Model) error { +func (a *argocdAdapter) SavePolicy(_ model.Model) error { return errors.New("not implemented") } -func (a *argocdAdapter) AddPolicy(sec string, ptype string, rule []string) error { +func (a *argocdAdapter) AddPolicy(_ string, _ string, _ []string) error { return errors.New("not implemented") } -func (a *argocdAdapter) RemovePolicy(sec string, ptype string, rule []string) error { +func (a *argocdAdapter) RemovePolicy(_ string, _ string, _ []string) error { return errors.New("not implemented") } -func (a *argocdAdapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { +func (a *argocdAdapter) RemoveFilteredPolicy(_ string, _ string, _ int, _ ...string) error { return errors.New("not implemented") } diff --git a/util/rbac/rbac_norace_test.go b/util/rbac/rbac_norace_test.go index a35d29ceba64d..97735a2ef643b 100644 --- a/util/rbac/rbac_norace_test.go +++ b/util/rbac/rbac_norace_test.go @@ -32,7 +32,7 @@ func TestPolicyInformer(t *testing.T) { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() - go enf.runInformer(ctx, func(cm *corev1.ConfigMap) error { + go enf.runInformer(ctx, func(_ *corev1.ConfigMap) error { return nil }) diff --git a/util/rbac/rbac_test.go b/util/rbac/rbac_test.go index 8e8b54f44ce0b..4b4cce17d9d1f 100644 --- a/util/rbac/rbac_test.go +++ b/util/rbac/rbac_test.go @@ -22,7 +22,7 @@ const ( fakeNamespace = "fake-ns" ) -var noOpUpdate = func(cm *corev1.ConfigMap) error { +var noOpUpdate = func(_ *corev1.ConfigMap) error { return nil } @@ -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 ...any) bool { + enf.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...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 ...any) bool { + enf.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...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 ...any) bool { + enf.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return true }) assert.True(t, enf.EnforceRuntimePolicy("", runtimePolicy, claims, "applications", "get", "foo/bar")) diff --git a/util/session/sessionmanager_test.go b/util/session/sessionmanager_test.go index 82d3472f3f3e0..1fe50fb74a843 100644 --- a/util/session/sessionmanager_test.go +++ b/util/session/sessionmanager_test.go @@ -225,7 +225,7 @@ type tokenVerifierMock struct { err error } -func (tm *tokenVerifierMock) VerifyToken(token string) (jwt.Claims, string, error) { +func (tm *tokenVerifierMock) VerifyToken(_ string) (jwt.Claims, string, error) { if tm.claims == nil { return nil, "", tm.err } @@ -238,7 +238,7 @@ func strPointer(str string) *string { func TestSessionManager_WithAuthMiddleware(t *testing.T) { handlerFunc := func() func(http.ResponseWriter, *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, _ *http.Request) { t.Helper() w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/text") diff --git a/util/settings/settings.go b/util/settings/settings.go index 0fec981957713..47893e4185eef 100644 --- a/util/settings/settings.go +++ b/util/settings/settings.go @@ -1388,14 +1388,14 @@ func (mgr *SettingsManager) initialize(ctx context.Context) error { } eventHandler := cache.ResourceEventHandlerFuncs{ - UpdateFunc: func(oldObj, newObj any) { + UpdateFunc: func(_, _ any) { mgr.invalidateCache() mgr.onRepoOrClusterChanged() }, - AddFunc: func(obj any) { + AddFunc: func(_ any) { mgr.onRepoOrClusterChanged() }, - DeleteFunc: func(obj any) { + DeleteFunc: func(_ any) { mgr.onRepoOrClusterChanged() }, } diff --git a/util/swagger/swagger.go b/util/swagger/swagger.go index 44cf8b0a52eb4..05099391292c8 100644 --- a/util/swagger/swagger.go +++ b/util/swagger/swagger.go @@ -15,7 +15,7 @@ const redocScriptName = "redoc.standalone.js" func ServeSwaggerUI(mux *http.ServeMux, swaggerJSON string, uiPath string, rootPath string) { prefix := path.Dir(uiPath) swaggerPath := path.Join(prefix, "swagger.json") - mux.HandleFunc(swaggerPath, func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc(swaggerPath, func(w http.ResponseWriter, _ *http.Request) { _, _ = fmt.Fprint(w, swaggerJSON) }) diff --git a/util/test/testutil.go b/util/test/testutil.go index 61fa0e74616fe..0da029fdae023 100644 --- a/util/test/testutil.go +++ b/util/test/testutil.go @@ -139,7 +139,7 @@ func dexMockHandler(t *testing.T, url string) func(http.ResponseWriter, *http.Re func GetDexTestServer(t *testing.T) *httptest.Server { t.Helper() - ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewTLSServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { // Start with a placeholder. We need the server URL before setting up the real handler. })) ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -204,7 +204,7 @@ func oidcMockHandler(t *testing.T, url string) func(http.ResponseWriter, *http.R func GetOIDCTestServer(t *testing.T) *httptest.Server { t.Helper() - ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewTLSServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { // Start with a placeholder. We need the server URL before setting up the real handler. })) ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { From 947a7b84d7b5096fd986cff3a60c0bc5905ffa4b Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Tue, 7 Jan 2025 16:25:22 +0100 Subject: [PATCH 35/41] chore: enable indent-error-flow from revive (#21394) Signed-off-by: Matthieu MOREL --- .golangci.yaml | 11 +- applicationset/generators/matrix.go | 3 +- applicationset/generators/merge.go | 3 +- applicationset/generators/pull_request.go | 6 +- cmd/argocd-dex/commands/argocd_dex.go | 3 +- cmd/argocd/commands/admin/settings_rbac.go | 3 +- cmd/argocd/commands/project.go | 38 ++-- common/common.go | 12 +- controller/appcontroller.go | 34 ++-- controller/sharding/sharding.go | 97 +++++----- controller/state.go | 17 +- controller/sync.go | 5 +- pkg/apiclient/grpcproxy.go | 3 +- .../application/v1alpha1/app_project_types.go | 5 +- .../v1alpha1/applicationset_types.go | 3 +- pkg/apis/application/v1alpha1/types.go | 27 +-- reposerver/repository/lock.go | 7 +- reposerver/repository/repository.go | 180 +++++++++--------- server/account/account.go | 3 +- server/application/application.go | 88 ++++----- server/application/application_test.go | 5 +- server/applicationset/applicationset.go | 3 +- server/server.go | 5 +- test/e2e/fixture/app/context.go | 6 +- test/e2e/fixture/app/expectation.go | 6 +- test/e2e/fixture/fixture.go | 6 +- util/argo/argo.go | 3 +- .../normalizers/knowntypes_normalizer_test.go | 6 +- util/cache/cache.go | 3 +- util/cache/redis.go | 6 +- util/cert/cert.go | 12 +- util/db/certificate.go | 17 +- util/db/gpgkeys.go | 3 +- util/db/repository_legacy.go | 9 +- util/dex/dex.go | 10 +- util/git/client.go | 23 +-- util/gpg/gpg.go | 20 +- util/helm/client.go | 3 +- util/io/path/resolved.go | 3 +- util/lua/custom_actions_test.go | 3 +- util/lua/oslib_safe.go | 29 ++- util/security/rbac.go | 3 +- util/settings/accounts.go | 6 +- util/tls/tls.go | 15 +- 44 files changed, 337 insertions(+), 416 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 2f7c742c1c186..2b4076acdf8a0 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -123,9 +123,11 @@ linters-settings: # incrementing an integer variable by 1 is recommended to be done using the `++` operator - name: increment-decrement disabled: false - # highlights redundant else-blocks that can be eliminated from the code + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#indent-error-flow - name: indent-error-flow - disabled: true + disabled: false + arguments: + - "preserveScope" # This rule suggests a shorter way of writing ranges that do not use the second value. - name: range disabled: false @@ -135,12 +137,15 @@ linters-settings: # redefining built in names (true, false, append, make) can lead to bugs very difficult to detect. - name: redefines-builtin-id disabled: true + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#redundant-import-alias - name: redundant-import-alias disabled: false # redundant else-blocks that can be eliminated from the code. - name: superfluous-else disabled: false - # prevent confusing name for variables when using `time` package + arguments: + - "preserveScope" + # 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. diff --git a/applicationset/generators/matrix.go b/applicationset/generators/matrix.go index 2ddf87f9d6cdd..0bc2c172d6917 100644 --- a/applicationset/generators/matrix.go +++ b/applicationset/generators/matrix.go @@ -169,9 +169,8 @@ func (m *MatrixGenerator) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.Ap if found { return res - } else { - return NoRequeueAfter } + return NoRequeueAfter } func getMatrixGenerator(r argoprojiov1alpha1.ApplicationSetNestedGenerator) (*argoprojiov1alpha1.MatrixGenerator, error) { diff --git a/applicationset/generators/merge.go b/applicationset/generators/merge.go index dfd826ab2df7e..231ce676027ab 100644 --- a/applicationset/generators/merge.go +++ b/applicationset/generators/merge.go @@ -224,9 +224,8 @@ func (m *MergeGenerator) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.App if found { return res - } else { - return NoRequeueAfter } + return NoRequeueAfter } func getMergeGenerator(r argoprojiov1alpha1.ApplicationSetNestedGenerator) (*argoprojiov1alpha1.MergeGenerator, error) { diff --git a/applicationset/generators/pull_request.go b/applicationset/generators/pull_request.go index ffc0b7ddf6145..f76ee05e37e4e 100644 --- a/applicationset/generators/pull_request.go +++ b/applicationset/generators/pull_request.go @@ -176,9 +176,8 @@ func (g *PullRequestGenerator) selectServiceProvider(ctx context.Context, genera return nil, fmt.Errorf("error fetching Secret token: %w", err) } return pullrequest.NewBitbucketServiceBasicAuth(ctx, providerConfig.BasicAuth.Username, password, providerConfig.API, providerConfig.Project, providerConfig.Repo, g.scmRootCAPath, providerConfig.Insecure, caCerts) - } else { - return pullrequest.NewBitbucketServiceNoAuth(ctx, providerConfig.API, providerConfig.Project, providerConfig.Repo, g.scmRootCAPath, providerConfig.Insecure, caCerts) } + return pullrequest.NewBitbucketServiceNoAuth(ctx, providerConfig.API, providerConfig.Project, providerConfig.Repo, g.scmRootCAPath, providerConfig.Insecure, caCerts) } if generatorConfig.Bitbucket != nil { providerConfig := generatorConfig.Bitbucket @@ -194,9 +193,8 @@ func (g *PullRequestGenerator) selectServiceProvider(ctx context.Context, genera return nil, fmt.Errorf("error fetching Secret token: %w", err) } return pullrequest.NewBitbucketCloudServiceBasicAuth(providerConfig.API, providerConfig.BasicAuth.Username, password, providerConfig.Owner, providerConfig.Repo) - } else { - return pullrequest.NewBitbucketCloudServiceNoAuth(providerConfig.API, providerConfig.Owner, providerConfig.Repo) } + return pullrequest.NewBitbucketCloudServiceNoAuth(providerConfig.API, providerConfig.Owner, providerConfig.Repo) } if generatorConfig.AzureDevOps != nil { providerConfig := generatorConfig.AzureDevOps diff --git a/cmd/argocd-dex/commands/argocd_dex.go b/cmd/argocd-dex/commands/argocd_dex.go index 62a785460489d..fc103157e4d96 100644 --- a/cmd/argocd-dex/commands/argocd_dex.go +++ b/cmd/argocd-dex/commands/argocd_dex.go @@ -242,9 +242,8 @@ func redactor(dirtyString string) string { iterateStringFields(config, func(name string, val string) string { if name == "clientSecret" || name == "secret" || name == "bindPW" { return "********" - } else { - return val } + return val }) data, err := yaml.Marshal(config) errors.CheckError(err) diff --git a/cmd/argocd/commands/admin/settings_rbac.go b/cmd/argocd/commands/admin/settings_rbac.go index 50246c22849f8..88a85bd088339 100644 --- a/cmd/argocd/commands/admin/settings_rbac.go +++ b/cmd/argocd/commands/admin/settings_rbac.go @@ -463,9 +463,8 @@ func checkPolicy(subject, action, resource, subResource, builtinPolicy, userPoli func resolveRBACResourceName(name string) string { if res, ok := resourceMap[name]; ok { return res - } else { - return name } + return name } // validateRBACResourceAction checks whether a given resource is a valid RBAC resource. diff --git a/cmd/argocd/commands/project.go b/cmd/argocd/commands/project.go index 9332b4474771c..942d25e32f4b5 100644 --- a/cmd/argocd/commands/project.go +++ b/cmd/argocd/commands/project.go @@ -599,22 +599,21 @@ func modifyResourcesList(list *[]metav1.GroupKind, add bool, listDesc string, gr fmt.Printf("Group '%s' and kind '%s' is added to %s resources\n", group, kind, listDesc) *list = append(*list, metav1.GroupKind{Group: group, Kind: kind}) return true - } else { - index := -1 - for i, item := range *list { - if item.Group == group && item.Kind == kind { - index = i - break - } - } - if index == -1 { - fmt.Printf("Group '%s' and kind '%s' not in %s resources\n", group, kind, listDesc) - return false + } + index := -1 + for i, item := range *list { + if item.Group == group && item.Kind == kind { + index = i + break } - *list = append((*list)[:index], (*list)[index+1:]...) - fmt.Printf("Group '%s' and kind '%s' is removed from %s resources\n", group, kind, listDesc) - return true } + if index == -1 { + fmt.Printf("Group '%s' and kind '%s' not in %s resources\n", group, kind, listDesc) + return false + } + *list = append((*list)[:index], (*list)[index+1:]...) + fmt.Printf("Group '%s' and kind '%s' is removed from %s resources\n", group, kind, listDesc) + return true } func modifyResourceListCmd(cmdUse, cmdDesc, examples string, clientOpts *argocdclient.ClientOptions, allow bool, namespacedList bool) *cobra.Command { @@ -1111,12 +1110,11 @@ func NewProjectAddDestinationServiceAccountCommand(clientOpts *argocdclient.Clie Namespace: namespace, DefaultServiceAccount: fmt.Sprintf("%s:%s", serviceAccountNamespace, serviceAccount), } - } else { - return v1alpha1.ApplicationDestinationServiceAccount{ - Server: destination, - Namespace: namespace, - DefaultServiceAccount: serviceAccount, - } + } + return v1alpha1.ApplicationDestinationServiceAccount{ + Server: destination, + Namespace: namespace, + DefaultServiceAccount: serviceAccount, } } diff --git a/common/common.go b/common/common.go index c44fa3ca96ee6..30ddc279e349d 100644 --- a/common/common.go +++ b/common/common.go @@ -354,20 +354,20 @@ const ( // GetGnuPGHomePath retrieves the path to use for GnuPG home directory, which is either taken from GNUPGHOME environment or a default value func GetGnuPGHomePath() string { - if gnuPgHome := os.Getenv(EnvGnuPGHome); gnuPgHome == "" { + gnuPgHome := os.Getenv(EnvGnuPGHome) + if gnuPgHome == "" { return DefaultGnuPgHomePath - } else { - return gnuPgHome } + return gnuPgHome } // GetPluginSockFilePath retrieves the path of plugin sock file, which is either taken from PluginSockFilePath environment or a default value func GetPluginSockFilePath() string { - if pluginSockFilePath := os.Getenv(EnvPluginSockFilePath); pluginSockFilePath == "" { + pluginSockFilePath := os.Getenv(EnvPluginSockFilePath) + if pluginSockFilePath == "" { return DefaultPluginSockFilePath - } else { - return pluginSockFilePath } + return pluginSockFilePath } // GetCMPChunkSize will return the env var EnvCMPChunkSize value if defined or DefaultCMPChunkSize otherwise. diff --git a/controller/appcontroller.go b/controller/appcontroller.go index ebb52582be456..00ae0cf3de16c 100644 --- a/controller/appcontroller.go +++ b/controller/appcontroller.go @@ -400,9 +400,8 @@ func (ctrl *ApplicationController) getAppProj(app *appv1.Application) (*appv1.Ap if err != nil { if apierrors.IsNotFound(err) { return nil, err - } else { - return nil, fmt.Errorf("could not retrieve AppProject '%s' from cache: %w", app.Spec.Project, err) } + return nil, fmt.Errorf("could not retrieve AppProject '%s' from cache: %w", app.Spec.Project, err) } if !proj.IsAppNamespacePermitted(app, ctrl.namespace) { return nil, argo.ErrProjectNotPermitted(app.GetName(), app.GetNamespace(), proj.GetName()) @@ -1052,12 +1051,12 @@ func (ctrl *ApplicationController) processAppComparisonTypeQueueItem() (processN if parts := strings.Split(key, "/"); len(parts) != 3 { log.Warnf("Unexpected key format in appComparisonTypeRefreshTypeQueue. Key should consists of namespace/name/comparisonType but got: %s", key) } else { - if compareWith, err := strconv.Atoi(parts[2]); err != nil { + compareWith, err := strconv.Atoi(parts[2]) + if err != nil { log.Warnf("Unable to parse comparison type: %v", err) return - } else { - ctrl.requestAppRefresh(ctrl.toAppQualifiedName(parts[1], parts[0]), CompareWith(compareWith).Pointer(), nil) } + ctrl.requestAppRefresh(ctrl.toAppQualifiedName(parts[1], parts[0]), CompareWith(compareWith).Pointer(), nil) } return } @@ -1112,9 +1111,8 @@ func (ctrl *ApplicationController) finalizeProjectDeletion(proj *appv1.AppProjec } if appsCount == 0 { return ctrl.removeProjectFinalizer(proj) - } else { - log.Infof("Cannot remove project '%s' finalizer as is referenced by %d applications", proj.Name, appsCount) } + log.Infof("Cannot remove project '%s' finalizer as is referenced by %d applications", proj.Name, appsCount) return nil } @@ -1398,14 +1396,13 @@ func (ctrl *ApplicationController) processRequestedAppOperation(app *appv1.Appli logCtx.Infof("Skipping retrying in-progress operation. Attempting again at: %s", retryAt.Format(time.RFC3339)) ctrl.requestAppRefresh(app.QualifiedName(), CompareWithLatest.Pointer(), &retryAfter) return - } else { - // retrying operation. remove previous failure time in app since it is used as a trigger - // that previous failed and operation should be retried - state.FinishedAt = nil - ctrl.setOperationState(app, state) - // Get rid of sync results and null out previous operation completion time - state.SyncResult = nil } + // retrying operation. remove previous failure time in app since it is used as a trigger + // that previous failed and operation should be retried + state.FinishedAt = nil + ctrl.setOperationState(app, state) + // Get rid of sync results and null out previous operation completion time + state.SyncResult = nil } else if ctrl.syncTimeout != time.Duration(0) && time.Now().After(state.StartedAt.Add(ctrl.syncTimeout)) && !terminating { state.Phase = synccommon.OperationTerminating state.Message = "operation is terminating due to timeout" @@ -2169,9 +2166,8 @@ func (ctrl *ApplicationController) autoSync(app *appv1.Application, syncStatus * logCtx.Errorf("Failed to initiate auto-sync to %s: %v", desiredCommitSHA, err) return &appv1.ApplicationCondition{Type: appv1.ApplicationConditionSyncError, Message: err.Error()}, setOpTime - } else { - ctrl.writeBackToInformer(updatedApp) } + ctrl.writeBackToInformer(updatedApp) ts.AddCheckpoint("write_back_to_informer_ms") var target string @@ -2213,9 +2209,8 @@ func alreadyAttemptedSync(app *appv1.Application, commitSHA string, commitSHAsMS if hasMultipleSources { return reflect.DeepEqual(app.Spec.Sources, app.Status.OperationState.SyncResult.Sources), app.Status.OperationState.Phase - } else { - return reflect.DeepEqual(app.Spec.GetSource(), app.Status.OperationState.SyncResult.Source), app.Status.OperationState.Phase } + return reflect.DeepEqual(app.Spec.GetSource(), app.Status.OperationState.SyncResult.Source), app.Status.OperationState.Phase } func (ctrl *ApplicationController) shouldSelfHeal(app *appv1.Application) (bool, time.Duration) { @@ -2502,9 +2497,8 @@ func (ctrl *ApplicationController) toAppKey(appName string) string { return ctrl.namespace + "/" + appName } else if strings.Contains(appName, "/") { return appName - } else { - return strings.ReplaceAll(appName, "_", "/") } + return strings.ReplaceAll(appName, "_", "/") } func (ctrl *ApplicationController) toAppQualifiedName(appName, appNamespace string) string { diff --git a/controller/sharding/sharding.go b/controller/sharding/sharding.go index 4c087cd169a79..ccfd15e5145ae 100644 --- a/controller/sharding/sharding.go +++ b/controller/sharding/sharding.go @@ -122,13 +122,12 @@ func LegacyDistributionFunction(replicas int) DistributionFunction { log.Debugf("Calculating cluster shard for cluster id: %s", id) if id == "" { return 0 - } else { - h := fnv.New32a() - _, _ = h.Write([]byte(id)) - shard := int32(h.Sum32() % uint32(replicas)) - log.Debugf("Cluster with id=%s will be processed by shard %d", id, shard) - return int(shard) } + h := fnv.New32a() + _, _ = h.Write([]byte(id)) + shard := int32(h.Sum32() % uint32(replicas)) + log.Debugf("Cluster with id=%s will be processed by shard %d", id, shard) + return int(shard) } } @@ -149,17 +148,16 @@ func RoundRobinDistributionFunction(clusters clusterAccessor, replicas int) Dist // then its value is returned otherwise it is the default calculated value if c.Shard != nil && int(*c.Shard) < replicas { return int(*c.Shard) - } else { - clusterIndexdByClusterIdMap := createClusterIndexByClusterIdMap(clusters) - clusterIndex, ok := clusterIndexdByClusterIdMap[c.ID] - if !ok { - log.Warnf("Cluster with id=%s not found in cluster map.", c.ID) - return -1 - } - shard := int(clusterIndex % replicas) - log.Debugf("Cluster with id=%s will be processed by shard %d", c.ID, shard) - return shard } + clusterIndexdByClusterIdMap := createClusterIndexByClusterIdMap(clusters) + clusterIndex, ok := clusterIndexdByClusterIdMap[c.ID] + if !ok { + log.Warnf("Cluster with id=%s not found in cluster map.", c.ID) + return -1 + } + shard := int(clusterIndex % replicas) + log.Debugf("Cluster with id=%s will be processed by shard %d", c.ID, shard) + return shard } log.Warnf("The number of replicas (%d) is lower than 1", replicas) return -1 @@ -181,22 +179,21 @@ func ConsistentHashingWithBoundedLoadsDistributionFunction(clusters clusterAcces // then its value is returned otherwise it is the default calculated value if c.Shard != nil && int(*c.Shard) < replicas { return int(*c.Shard) - } else { - // if the cluster is not in the clusters list anymore, we should unassign it from any shard, so we - // return the reserved value of -1 - if !slices.Contains(clusters(), c) { - log.Warnf("Cluster with id=%s not found in cluster map.", c.ID) - return -1 - } - shardIndexedByCluster := createConsistentHashingWithBoundLoads(replicas, clusters, apps) - shard, ok := shardIndexedByCluster[c.ID] - if !ok { - log.Warnf("Cluster with id=%s not found in cluster map.", c.ID) - return -1 - } - log.Debugf("Cluster with id=%s will be processed by shard %d", c.ID, shard) - return shard } + // if the cluster is not in the clusters list anymore, we should unassign it from any shard, so we + // return the reserved value of -1 + if !slices.Contains(clusters(), c) { + log.Warnf("Cluster with id=%s not found in cluster map.", c.ID) + return -1 + } + shardIndexedByCluster := createConsistentHashingWithBoundLoads(replicas, clusters, apps) + shard, ok := shardIndexedByCluster[c.ID] + if !ok { + log.Warnf("Cluster with id=%s not found in cluster map.", c.ID) + return -1 + } + log.Debugf("Cluster with id=%s will be processed by shard %d", c.ID, shard) + return shard } log.Warnf("The number of replicas (%d) is lower than 1", replicas) return -1 @@ -311,7 +308,6 @@ func GetOrUpdateShardFromConfigMap(kubeClient kubernetes.Interface, settingsMgr // fetch the shard mapping configMap shardMappingCM, err := kubeClient.CoreV1().ConfigMaps(settingsMgr.GetNamespace()).Get(context.Background(), common.ArgoCDAppControllerShardConfigMapName, metav1.GetOptions{}) - if err != nil { if !apierrors.IsNotFound(err) { return -1, fmt.Errorf("error getting sharding config map: %w", err) @@ -331,28 +327,27 @@ func GetOrUpdateShardFromConfigMap(kubeClient kubernetes.Interface, settingsMgr } // return 0 as the controller is assigned to shard 0 while generating default shard mapping ConfigMap return shard, nil - } else { - // Identify the available shard and update the ConfigMap - data := shardMappingCM.Data[ShardControllerMappingKey] - var shardMappingData []shardApplicationControllerMapping - err := json.Unmarshal([]byte(data), &shardMappingData) - if err != nil { - return -1, fmt.Errorf("error unmarshalling shard config map data: %w", err) - } + } + // Identify the available shard and update the ConfigMap + data := shardMappingCM.Data[ShardControllerMappingKey] + var shardMappingData []shardApplicationControllerMapping + err = json.Unmarshal([]byte(data), &shardMappingData) + if err != nil { + return -1, fmt.Errorf("error unmarshalling shard config map data: %w", err) + } - shard, shardMappingData := getOrUpdateShardNumberForController(shardMappingData, hostname, replicas, shard) - updatedShardMappingData, err := json.Marshal(shardMappingData) - if err != nil { - return -1, fmt.Errorf("error marshalling data of shard mapping ConfigMap: %w", err) - } - shardMappingCM.Data[ShardControllerMappingKey] = string(updatedShardMappingData) + shard, shardMappingData = getOrUpdateShardNumberForController(shardMappingData, hostname, replicas, shard) + updatedShardMappingData, err := json.Marshal(shardMappingData) + if err != nil { + return -1, fmt.Errorf("error marshalling data of shard mapping ConfigMap: %w", err) + } + shardMappingCM.Data[ShardControllerMappingKey] = string(updatedShardMappingData) - _, err = kubeClient.CoreV1().ConfigMaps(settingsMgr.GetNamespace()).Update(context.Background(), shardMappingCM, metav1.UpdateOptions{}) - if err != nil { - return -1, err - } - return shard, nil + _, err = kubeClient.CoreV1().ConfigMaps(settingsMgr.GetNamespace()).Update(context.Background(), shardMappingCM, metav1.UpdateOptions{}) + if err != nil { + return -1, err } + return shard, nil } // getOrUpdateShardNumberForController takes list of shardApplicationControllerMapping and performs computation to find the matching or empty shard number diff --git a/controller/state.go b/controller/state.go index d4c822ce66b38..3140a49ea1c6f 100644 --- a/controller/state.go +++ b/controller/state.go @@ -488,16 +488,15 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1 }, healthStatus: &v1alpha1.HealthStatus{Status: health.HealthStatusUnknown, LastTransitionTime: &now}, }, nil - } else { - return &comparisonResult{ - syncStatus: &v1alpha1.SyncStatus{ - ComparedTo: app.Spec.BuildComparedToStatus(), - Status: v1alpha1.SyncStatusCodeUnknown, - Revision: revisions[0], - }, - healthStatus: &v1alpha1.HealthStatus{Status: health.HealthStatusUnknown, LastTransitionTime: &now}, - }, nil } + return &comparisonResult{ + syncStatus: &v1alpha1.SyncStatus{ + ComparedTo: app.Spec.BuildComparedToStatus(), + Status: v1alpha1.SyncStatusCodeUnknown, + Revision: revisions[0], + }, + healthStatus: &v1alpha1.HealthStatus{Status: health.HealthStatusUnknown, LastTransitionTime: &now}, + }, nil } // When signature keys are defined in the project spec, we need to verify the signature on the Git revision diff --git a/controller/sync.go b/controller/sync.go index a54d0b4d9b0f7..a7c6be5d4ab43 100644 --- a/controller/sync.go +++ b/controller/sync.go @@ -621,10 +621,9 @@ func deriveServiceAccountToImpersonate(project *v1alpha1.AppProject, application } else if strings.Contains(item.DefaultServiceAccount, ":") { // service account is specified along with its namespace. return "system:serviceaccount:" + item.DefaultServiceAccount, nil - } else { - // service account needs to be prefixed with a namespace - return fmt.Sprintf("system:serviceaccount:%s:%s", serviceAccountNamespace, item.DefaultServiceAccount), nil } + // service account needs to be prefixed with a namespace + return fmt.Sprintf("system:serviceaccount:%s:%s", serviceAccountNamespace, item.DefaultServiceAccount), nil } } // if there is no match found in the AppProject.Spec.DestinationServiceAccounts, use the default service account of the destination namespace. diff --git a/pkg/apiclient/grpcproxy.go b/pkg/apiclient/grpcproxy.go index 97a8be3449fc5..cf0535ed11a07 100644 --- a/pkg/apiclient/grpcproxy.go +++ b/pkg/apiclient/grpcproxy.go @@ -169,9 +169,8 @@ func (c *client) startGRPCProxy() (*grpc.Server, net.Listener, error) { return err } else if read < length { return io.ErrUnexpectedEOF - } else { - return nil } + return nil } if err := stream.SendMsg(data); err != nil { diff --git a/pkg/apis/application/v1alpha1/app_project_types.go b/pkg/apis/application/v1alpha1/app_project_types.go index 081b4bb178803..ff511a319e916 100644 --- a/pkg/apis/application/v1alpha1/app_project_types.go +++ b/pkg/apis/application/v1alpha1/app_project_types.go @@ -152,10 +152,9 @@ func (proj AppProject) RemoveJWTToken(roleIndex int, issuedAt int64, id string) if err1 == nil || err2 == nil { // If we find this token from either places, we can say there are no error return nil - } else { - // If we could not locate this taken from either places, we can return any of the errors - return err2 } + // If we could not locate this taken from either places, we can return any of the errors + return err2 } // TODO: document this method diff --git a/pkg/apis/application/v1alpha1/applicationset_types.go b/pkg/apis/application/v1alpha1/applicationset_types.go index 1497dd54f41dd..3e79d4466c0ef 100644 --- a/pkg/apis/application/v1alpha1/applicationset_types.go +++ b/pkg/apis/application/v1alpha1/applicationset_types.go @@ -960,7 +960,6 @@ func (status *ApplicationSetStatus) SetApplicationStatus(newStatus ApplicationSe func (a *ApplicationSet) QualifiedName() string { if a.Namespace == "" { return a.Name - } else { - return a.Namespace + "/" + a.Name } + return a.Namespace + "/" + a.Name } diff --git a/pkg/apis/application/v1alpha1/types.go b/pkg/apis/application/v1alpha1/types.go index fe2a17f920b0c..48dbdc292b081 100644 --- a/pkg/apis/application/v1alpha1/types.go +++ b/pkg/apis/application/v1alpha1/types.go @@ -167,9 +167,8 @@ func (e Env) Envsubst(s string) string { // allow escaping $ with $$ if s == "$" { return "$" - } else { - return valByEnv[s] } + return valByEnv[s] }) } @@ -677,14 +676,13 @@ type KustomizeReplicas []KustomizeReplica // If parsing error occurs, returns 0 and error. func (kr KustomizeReplica) GetIntCount() (int, error) { if kr.Count.Type == intstr.String { - if count, err := strconv.Atoi(kr.Count.StrVal); err != nil { + count, err := strconv.Atoi(kr.Count.StrVal) + if err != nil { return 0, fmt.Errorf("expected integer value for count. Received: %s", kr.Count.StrVal) - } else { - return count, nil } - } else { - return kr.Count.IntValue(), nil + return count, nil } + return kr.Count.IntValue(), nil } // NewKustomizeReplica parses a string in format name=count into a KustomizeReplica object and returns it @@ -814,9 +812,8 @@ func NewJsonnetVar(s string, code bool) JsonnetVar { parts := strings.SplitN(s, "=", 2) if len(parts) == 2 { return JsonnetVar{Name: parts[0], Value: parts[1], Code: code} - } else { - return JsonnetVar{Name: s, Code: code} } + return JsonnetVar{Name: s, Code: code} } // ApplicationSourceJsonnet holds options specific to applications of type Jsonnet @@ -1527,9 +1524,8 @@ func (m *SyncStrategy) Force() bool { return m.Apply.Force } else if m.Hook != nil { return m.Hook.Force - } else { - return false } + return false } // SyncStrategyApply uses `kubectl apply` to perform the apply @@ -2761,9 +2757,8 @@ func (w *SyncWindows) CanSync(isManual bool) (bool, error) { if hasActiveDeny { if isManual && manualEnabled { return true, nil - } else { - return false, nil } + return false, nil } if active.hasAllow() { @@ -2777,9 +2772,8 @@ func (w *SyncWindows) CanSync(isManual bool) (bool, error) { if inactiveAllows.HasWindows() { if isManual && inactiveAllows.manualEnabled() { return true, nil - } else { - return false, nil } + return false, nil } return true, nil @@ -3553,9 +3547,8 @@ func (app *Application) InstanceName(defaultNs string) string { func (app *Application) QualifiedName() string { if app.Namespace == "" { return app.Name - } else { - return app.Namespace + "/" + app.Name } + return app.Namespace + "/" + app.Name } // RBACName returns the full qualified RBAC resource name for the application diff --git a/reposerver/repository/lock.go b/reposerver/repository/lock.go index fa8da9c3e5089..1cb62e07667b1 100644 --- a/reposerver/repository/lock.go +++ b/reposerver/repository/lock.go @@ -68,11 +68,10 @@ func (r *repositoryLock) Lock(path string, revision string, allowConcurrent bool state.processCount++ state.cond.L.Unlock() return closer, nil - } else { - state.cond.Wait() - // wait when all in-flight processes of this revision complete and try again - state.cond.L.Unlock() } + state.cond.Wait() + // wait when all in-flight processes of this revision complete and try again + state.cond.L.Unlock() } } diff --git a/reposerver/repository/repository.go b/reposerver/repository/repository.go index f5a036fac6c16..00b62d42ed49c 100644 --- a/reposerver/repository/repository.go +++ b/reposerver/repository/repository.go @@ -370,86 +370,83 @@ func (s *Service) runRepoOperation( "file": oobError.File, }).Warn("chart contains out-of-bounds symlink") return fmt.Errorf("chart contains out-of-bounds symlinks. file: %s", oobError.File) - } else { - return err } + return err } } return operation(chartPath, revision, revision, func() (*operationContext, error) { return &operationContext{chartPath, ""}, nil }) - } else { - closer, err := s.repoLock.Lock(gitClient.Root(), revision, settings.allowConcurrent, func() (goio.Closer, error) { - return s.checkoutRevision(gitClient, revision, s.initConstants.SubmoduleEnabled) - }) - if err != nil { - return err - } + } + closer, err := s.repoLock.Lock(gitClient.Root(), revision, settings.allowConcurrent, func() (goio.Closer, error) { + return s.checkoutRevision(gitClient, revision, s.initConstants.SubmoduleEnabled) + }) + if err != nil { + return err + } - defer io.Close(closer) + defer io.Close(closer) - if !s.initConstants.AllowOutOfBoundsSymlinks { - err := apppathutil.CheckOutOfBoundsSymlinks(gitClient.Root()) - if err != nil { - oobError := &apppathutil.OutOfBoundsSymlinkError{} - if errors.As(err, &oobError) { - log.WithFields(log.Fields{ - common.SecurityField: common.SecurityHigh, - "repo": repo.Repo, - "revision": revision, - "file": oobError.File, - }).Warn("repository contains out-of-bounds symlink") - return fmt.Errorf("repository contains out-of-bounds symlinks. file: %s", oobError.File) - } else { - return err - } + if !s.initConstants.AllowOutOfBoundsSymlinks { + err := apppathutil.CheckOutOfBoundsSymlinks(gitClient.Root()) + if err != nil { + oobError := &apppathutil.OutOfBoundsSymlinkError{} + if errors.As(err, &oobError) { + log.WithFields(log.Fields{ + common.SecurityField: common.SecurityHigh, + "repo": repo.Repo, + "revision": revision, + "file": oobError.File, + }).Warn("repository contains out-of-bounds symlink") + return fmt.Errorf("repository contains out-of-bounds symlinks. file: %s", oobError.File) } + return err } + } - var commitSHA string - if hasMultipleSources { - commitSHA = revision - } else { - commit, err := gitClient.CommitSHA() - if err != nil { - return fmt.Errorf("failed to get commit SHA: %w", err) - } - commitSHA = commit + var commitSHA string + if hasMultipleSources { + commitSHA = revision + } else { + commit, err := gitClient.CommitSHA() + if err != nil { + return fmt.Errorf("failed to get commit SHA: %w", err) } + commitSHA = commit + } - // double-check locking - if !settings.noCache { - if ok, err := cacheFn(revision, repoRefs, false); ok { - return err - } + // double-check locking + if !settings.noCache { + if ok, err := cacheFn(revision, repoRefs, false); ok { + return err } + } - // Here commitSHA refers to the SHA of the actual commit, whereas revision refers to the branch/tag name etc - // We use the commitSHA to generate manifests and store them in cache, and revision to retrieve them from cache - return operation(gitClient.Root(), commitSHA, revision, func() (*operationContext, error) { - var signature string - if verifyCommit { - // When the revision is an annotated tag, we need to pass the unresolved revision (i.e. the tag name) - // to the verification routine. For everything else, we work with the SHA that the target revision is - // pointing to (i.e. the resolved revision). - var rev string - if gitClient.IsAnnotatedTag(revision) { - rev = unresolvedRevision - } else { - rev = revision - } - signature, err = gitClient.VerifyCommitSignature(rev) - if err != nil { - return nil, err - } + // Here commitSHA refers to the SHA of the actual commit, whereas revision refers to the branch/tag name etc + // We use the commitSHA to generate manifests and store them in cache, and revision to retrieve them from cache + return operation(gitClient.Root(), commitSHA, revision, func() (*operationContext, error) { + var signature string + if verifyCommit { + // When the revision is an annotated tag, we need to pass the unresolved revision (i.e. the tag name) + // to the verification routine. For everything else, we work with the SHA that the target revision is + // pointing to (i.e. the resolved revision). + var rev string + if gitClient.IsAnnotatedTag(revision) { + rev = unresolvedRevision + } else { + rev = revision } - appPath, err := apppathutil.Path(gitClient.Root(), source.Path) + signature, err = gitClient.VerifyCommitSignature(rev) if err != nil { return nil, err } - return &operationContext{appPath, signature}, nil - }) - } + } + appPath, err := apppathutil.Path(gitClient.Root(), source.Path) + if err != nil { + return nil, err + } + return &operationContext{appPath, signature}, nil + }) } func getRepoSanitizerRegex(rootDir string) *regexp.Regexp { @@ -612,9 +609,8 @@ func (s *Service) GenerateManifestWithFiles(stream apiclient.RepoServerService_G "file": oobError.File, }).Warn("streamed files contains out-of-bounds symlink") return fmt.Errorf("streamed files contains out-of-bounds symlinks. file: %s", oobError.File) - } else { - return err } + return err } } @@ -793,10 +789,9 @@ func (s *Service) runManifestGenAsync(ctx context.Context, repoRoot, commitSHA, }).Warn("repository contains out-of-bounds symlink") ch.errCh <- fmt.Errorf("repository contains out-of-bounds symlinks. file: %s", oobError.File) return - } else { - ch.errCh <- err - return } + ch.errCh <- err + return } } @@ -2370,12 +2365,11 @@ func (s *Service) GetRevisionChartDetails(_ context.Context, q *apiclient.RepoSe if err == nil { log.Infof("revision chart details cache hit: %s/%s/%s", q.Repo.Repo, q.Name, q.Revision) return details, nil + } + if errors.Is(err, cache.ErrCacheMiss) { + log.Infof("revision metadata cache miss: %s/%s/%s", q.Repo.Repo, q.Name, q.Revision) } else { - if errors.Is(err, cache.ErrCacheMiss) { - log.Infof("revision metadata cache miss: %s/%s/%s", q.Repo.Repo, q.Name, q.Revision) - } else { - log.Warnf("revision metadata cache error %s/%s/%s: %v", q.Repo.Repo, q.Name, q.Revision, err) - } + log.Warnf("revision metadata cache error %s/%s/%s: %v", q.Repo.Repo, q.Name, q.Revision, err) } helmClient, revision, err := s.newHelmClientResolveRevision(q.Repo, q.Revision, q.Name, true) if err != nil { @@ -2587,10 +2581,9 @@ func (s *Service) TestRepository(_ context.Context, q *apiclient.TestRepositoryR } _, err := helm.NewClient(repo.Repo, repo.GetHelmCreds(), repo.EnableOCI, repo.Proxy, repo.NoProxy).TestHelmOCI() return err - } else { - _, err := helm.NewClient(repo.Repo, repo.GetHelmCreds(), repo.EnableOCI, repo.Proxy, repo.NoProxy).GetIndex(false, s.initConstants.HelmRegistryMaxIndexSize) - return err } + _, err := helm.NewClient(repo.Repo, repo.GetHelmCreds(), repo.EnableOCI, repo.Proxy, repo.NoProxy).GetIndex(false, s.initConstants.HelmRegistryMaxIndexSize) + return err }, } check := checks[repo.Type] @@ -2618,21 +2611,20 @@ func (s *Service) ResolveRevision(_ context.Context, q *apiclient.ResolveRevisio Revision: revision, AmbiguousRevision: fmt.Sprintf("%v (%v)", ambiguousRevision, revision), }, nil - } else { - gitClient, err := git.NewClient(repo.Repo, repo.GetGitCreds(s.gitCredsStore), repo.IsInsecure(), repo.IsLFSEnabled(), repo.Proxy, repo.NoProxy) - if err != nil { - return &apiclient.ResolveRevisionResponse{Revision: "", AmbiguousRevision: ""}, err - } - revision, err = gitClient.LsRemote(ambiguousRevision) - if err != nil { - s.metricsServer.IncGitLsRemoteFail(gitClient.Root(), revision) - return &apiclient.ResolveRevisionResponse{Revision: "", AmbiguousRevision: ""}, err - } - return &apiclient.ResolveRevisionResponse{ - Revision: revision, - AmbiguousRevision: fmt.Sprintf("%s (%s)", ambiguousRevision, revision), - }, nil } + gitClient, err := git.NewClient(repo.Repo, repo.GetGitCreds(s.gitCredsStore), repo.IsInsecure(), repo.IsLFSEnabled(), repo.Proxy, repo.NoProxy) + if err != nil { + return &apiclient.ResolveRevisionResponse{Revision: "", AmbiguousRevision: ""}, err + } + revision, err = gitClient.LsRemote(ambiguousRevision) + if err != nil { + s.metricsServer.IncGitLsRemoteFail(gitClient.Root(), revision) + return &apiclient.ResolveRevisionResponse{Revision: "", AmbiguousRevision: ""}, err + } + return &apiclient.ResolveRevisionResponse{ + Revision: revision, + AmbiguousRevision: fmt.Sprintf("%s (%s)", ambiguousRevision, revision), + }, nil } func (s *Service) GetGitFiles(_ context.Context, request *apiclient.GitFilesRequest) (*apiclient.GitFilesResponse, error) { @@ -2713,14 +2705,12 @@ func verifyCommitSignature(verifyCommit bool, gitClient git.Client, revision str if cs == "" { return fmt.Errorf("revision %s is not signed", revision) - } else { - vr := gpg.ParseGitCommitVerification(cs) - if vr.Result == gpg.VerifyResultUnknown { - return fmt.Errorf("UNKNOWN signature: %s", vr.Message) - } else { - log.Debugf("%s signature from %s key %s", vr.Result, vr.Cipher, gpg.KeyID(vr.KeyID)) - } } + vr := gpg.ParseGitCommitVerification(cs) + if vr.Result == gpg.VerifyResultUnknown { + return fmt.Errorf("UNKNOWN signature: %s", vr.Message) + } + log.Debugf("%s signature from %s key %s", vr.Result, vr.Cipher, gpg.KeyID(vr.KeyID)) } return nil } diff --git a/server/account/account.go b/server/account/account.go index 405966f137baa..94394e323ed63 100644 --- a/server/account/account.go +++ b/server/account/account.go @@ -143,9 +143,8 @@ func (s *Server) CanI(ctx context.Context, r *account.CanIRequest) (*account.Can ok := s.enf.Enforce(ctx.Value("claims"), r.Resource, r.Action, r.Subresource) if ok { return &account.CanIResponse{Value: "yes"}, nil - } else { - return &account.CanIResponse{Value: "no"}, nil } + return &account.CanIResponse{Value: "no"}, nil } func toApiAccount(name string, a settings.Account) *account.Account { diff --git a/server/application/application.go b/server/application/application.go index 1e24c59ad333d..438e9c34064f1 100644 --- a/server/application/application.go +++ b/server/application/application.go @@ -1689,12 +1689,12 @@ func (s *Server) PodLogs(q *application.ApplicationPodLogsQuery, ws application. } var untilTime *metav1.Time if q.GetUntilTime() != "" { - if val, err := time.Parse(time.RFC3339Nano, q.GetUntilTime()); err != nil { + val, err := time.Parse(time.RFC3339Nano, q.GetUntilTime()) + if err != nil { return fmt.Errorf("invalid untilTime parameter value: %w", err) - } else { - untilTimeVal := metav1.NewTime(val) - untilTime = &untilTimeVal } + untilTimeVal := metav1.NewTime(val) + untilTime = &untilTimeVal } literal := "" @@ -1796,37 +1796,35 @@ func (s *Server) PodLogs(q *application.ApplicationPodLogsQuery, ws application. if entry.err != nil { done <- entry.err return - } else { - if q.Filter != nil { - lineContainsFilter := strings.Contains(entry.line, literal) - if (inverse && lineContainsFilter) || (!inverse && !lineContainsFilter) { - continue - } - } - ts := metav1.NewTime(entry.timeStamp) - if untilTime != nil && entry.timeStamp.After(untilTime.Time) { - done <- ws.Send(&application.LogEntry{ - Last: ptr.To(true), - PodName: &entry.podName, - Content: &entry.line, - TimeStampStr: ptr.To(entry.timeStamp.Format(time.RFC3339Nano)), - TimeStamp: &ts, - }) - return - } else { - sentCount++ - if err := ws.Send(&application.LogEntry{ - PodName: &entry.podName, - Content: &entry.line, - TimeStampStr: ptr.To(entry.timeStamp.Format(time.RFC3339Nano)), - TimeStamp: &ts, - Last: ptr.To(false), - }); err != nil { - done <- err - break - } + } + if q.Filter != nil { + lineContainsFilter := strings.Contains(entry.line, literal) + if (inverse && lineContainsFilter) || (!inverse && !lineContainsFilter) { + continue } } + ts := metav1.NewTime(entry.timeStamp) + if untilTime != nil && entry.timeStamp.After(untilTime.Time) { + done <- ws.Send(&application.LogEntry{ + Last: ptr.To(true), + PodName: &entry.podName, + Content: &entry.line, + TimeStampStr: ptr.To(entry.timeStamp.Format(time.RFC3339Nano)), + TimeStamp: &ts, + }) + return + } + sentCount++ + if err := ws.Send(&application.LogEntry{ + PodName: &entry.podName, + Content: &entry.line, + TimeStampStr: ptr.To(entry.timeStamp.Format(time.RFC3339Nano)), + TimeStamp: &ts, + Last: ptr.To(false), + }); err != nil { + done <- err + break + } } now := time.Now() nowTS := metav1.NewTime(now) @@ -2036,19 +2034,18 @@ func (s *Server) resolveSourceRevisions(ctx context.Context, a *v1alpha1.Applica displayRevisions[index] = displayRevision } return "", "", sourceRevisions, displayRevisions, nil - } else { - source := a.Spec.GetSource() - if a.Spec.SyncPolicy != nil && a.Spec.SyncPolicy.Automated != nil && !syncReq.GetDryRun() { - if syncReq.GetRevision() != "" && syncReq.GetRevision() != text.FirstNonEmpty(source.TargetRevision, "HEAD") { - return "", "", nil, nil, status.Errorf(codes.FailedPrecondition, "Cannot sync to %s: auto-sync currently set to %s", syncReq.GetRevision(), source.TargetRevision) - } - } - revision, displayRevision, err := s.resolveRevision(ctx, a, syncReq, -1) - if err != nil { - return "", "", nil, nil, status.Error(codes.FailedPrecondition, err.Error()) + } + source := a.Spec.GetSource() + if a.Spec.SyncPolicy != nil && a.Spec.SyncPolicy.Automated != nil && !syncReq.GetDryRun() { + if syncReq.GetRevision() != "" && syncReq.GetRevision() != text.FirstNonEmpty(source.TargetRevision, "HEAD") { + return "", "", nil, nil, status.Errorf(codes.FailedPrecondition, "Cannot sync to %s: auto-sync currently set to %s", syncReq.GetRevision(), source.TargetRevision) } - return revision, displayRevision, nil, nil, nil } + revision, displayRevision, err := s.resolveRevision(ctx, a, syncReq, -1) + if err != nil { + return "", "", nil, nil, status.Error(codes.FailedPrecondition, err.Error()) + } + return revision, displayRevision, nil, nil, nil } func (s *Server) Rollback(ctx context.Context, rollbackReq *application.ApplicationRollbackRequest) (*v1alpha1.Application, error) { @@ -2700,9 +2697,8 @@ func getPropagationPolicyFinalizer(policy string) string { func (s *Server) appNamespaceOrDefault(appNs string) string { if appNs == "" { return s.ns - } else { - return appNs } + return appNs } func (s *Server) isNamespaceEnabled(namespace string) bool { diff --git a/server/application/application_test.go b/server/application/application_test.go index 55776c1f290b2..b1a4d88ec082c 100644 --- a/server/application/application_test.go +++ b/server/application/application_test.go @@ -2262,10 +2262,9 @@ func createAppServerWithMaxLodLogs(t *testing.T, podNumber int, maxPodLogsToRend formatInt := strconv.FormatInt(maxPodLogsToRender[0], 10) appServer := newTestAppServerWithEnforcerConfigure(t, f, map[string]string{"server.maxPodLogsToRender": formatInt}, runtimeObjects...) return appServer, adminCtx - } else { - appServer := newTestAppServer(t, runtimeObjects...) - return appServer, adminCtx } + appServer := newTestAppServer(t, runtimeObjects...) + return appServer, adminCtx } // refreshAnnotationRemover runs an infinite loop until it detects and removes refresh annotation or given context is done diff --git a/server/applicationset/applicationset.go b/server/applicationset/applicationset.go index 87d23df72a472..a3e399a22e875 100644 --- a/server/applicationset/applicationset.go +++ b/server/applicationset/applicationset.go @@ -508,9 +508,8 @@ func (s *Server) logAppSetEvent(ctx context.Context, a *v1alpha1.ApplicationSet, func (s *Server) appsetNamespaceOrDefault(appNs string) string { if appNs == "" { return s.ns - } else { - return appNs } + return appNs } func (s *Server) isNamespaceEnabled(namespace string) bool { diff --git a/server/server.go b/server/server.go index 035142a6cf85e..63d935fe5c893 100644 --- a/server/server.go +++ b/server/server.go @@ -1500,10 +1500,9 @@ func (server *ArgoCDServer) Authenticate(ctx context.Context) (context.Context, } if !argoCDSettings.AnonymousUserEnabled { return ctx, claimsErr - } else { - // nolint:staticcheck - ctx = context.WithValue(ctx, "claims", "") } + // nolint:staticcheck + ctx = context.WithValue(ctx, "claims", "") } return ctx, nil diff --git a/test/e2e/fixture/app/context.go b/test/e2e/fixture/app/context.go index b013f7fbd4bde..585ddeda30222 100644 --- a/test/e2e/fixture/app/context.go +++ b/test/e2e/fixture/app/context.go @@ -98,17 +98,15 @@ func (c *Context) AppName() string { func (c *Context) AppQualifiedName() string { if c.appNamespace != "" { return c.appNamespace + "/" + c.AppName() - } else { - return c.AppName() } + return c.AppName() } func (c *Context) AppNamespace() string { if c.appNamespace != "" { return c.appNamespace - } else { - return fixture.TestNamespace() } + return fixture.TestNamespace() } func (c *Context) SetAppNamespace(namespace string) *Context { diff --git a/test/e2e/fixture/app/expectation.go b/test/e2e/fixture/app/expectation.go index 7615fdc31c119..a5a4791ab163f 100644 --- a/test/e2e/fixture/app/expectation.go +++ b/test/e2e/fixture/app/expectation.go @@ -53,9 +53,8 @@ func OperationMessageContains(text string) Expectation { func simple(success bool, message string) (state, string) { if success { return succeeded, message - } else { - return pending, message } + return pending, message } func SyncStatusIs(expected SyncStatusCode) Expectation { @@ -176,9 +175,8 @@ func ResourceResultNumbering(num int) Expectation { return pending, fmt.Sprintf("not enough results yet, want %d, got %d", num, actualNum) } else if actualNum == num { return succeeded, fmt.Sprintf("right number of results, want %d, got %d", num, actualNum) - } else { - return failed, fmt.Sprintf("too many results, want %d, got %d", num, actualNum) } + return failed, fmt.Sprintf("too many results, want %d, got %d", num, actualNum) } } diff --git a/test/e2e/fixture/fixture.go b/test/e2e/fixture/fixture.go index 2c8a3fab1566c..9400a077e7433 100644 --- a/test/e2e/fixture/fixture.go +++ b/test/e2e/fixture/fixture.go @@ -220,9 +220,8 @@ func init() { if err != nil { if stderrors.Is(err, os.ErrNotExist) { return - } else { - panic(fmt.Sprintf("Could not read record file %s: %v", rf, err)) } + panic(fmt.Sprintf("Could not read record file %s: %v", rf, err)) } defer func() { err := f.Close() @@ -1220,9 +1219,8 @@ func RestartAPIServer() { func LocalOrRemotePath(base string) string { if IsRemote() { return base + "/remote" - } else { - return base + "/local" } + return base + "/local" } // SkipOnEnv allows to skip a test when a given environment variable is set. diff --git a/util/argo/argo.go b/util/argo/argo.go index 6faa2d99756b4..f94cea6f36628 100644 --- a/util/argo/argo.go +++ b/util/argo/argo.go @@ -1158,9 +1158,8 @@ func ParseInstanceName(appName string, defaultNs string) (string, string) { func AppInstanceName(appName, appNs, defaultNs string) string { if appNs == "" || appNs == defaultNs { return appName - } else { - return appNs + "_" + appName } + return appNs + "_" + appName } // InstanceNameFromQualified returns the value to be used for app diff --git a/util/argo/normalizers/knowntypes_normalizer_test.go b/util/argo/normalizers/knowntypes_normalizer_test.go index 432eaf5a9b883..634920dbd40f3 100644 --- a/util/argo/normalizers/knowntypes_normalizer_test.go +++ b/util/argo/normalizers/knowntypes_normalizer_test.go @@ -61,11 +61,11 @@ func nestedSliceMap(obj map[string]any, i int, path ...string) (map[string]any, 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]any); !ok { + item, ok := items[i].(map[string]any) + if !ok { return nil, fmt.Errorf("field %s[%d] is not map", strings.Join(path, "."), i) - } else { - return item, nil } + return item, nil } func TestNormalize_MapField(t *testing.T) { diff --git a/util/cache/cache.go b/util/cache/cache.go index 8ffe21b93a0e5..6965ad34b6f54 100644 --- a/util/cache/cache.go +++ b/util/cache/cache.go @@ -280,9 +280,8 @@ func (c *Cache) SetItem(key string, item any, opts *CacheActionOpts) error { client := c.GetClient() if opts.Delete { return client.Delete(fullKey) - } else { - return client.Set(&Item{Key: fullKey, Object: item, CacheActionOpts: *opts}) } + return client.Set(&Item{Key: fullKey, Object: item, CacheActionOpts: *opts}) } func (c *Cache) GetItem(key string, item any) error { diff --git a/util/cache/redis.go b/util/cache/redis.go index cdc98138bfd94..9ae75f8192f6e 100644 --- a/util/cache/redis.go +++ b/util/cache/redis.go @@ -91,11 +91,11 @@ func (r *redisCache) unmarshal(data []byte, obj any) error { buf := bytes.NewReader(data) var reader io.Reader = buf if r.redisCompressionType == RedisCompressionGZip { - if gzipReader, err := gzip.NewReader(buf); err != nil { + gzipReader, err := gzip.NewReader(buf) + if err != nil { return err - } else { - reader = gzipReader } + reader = gzipReader } if err := json.NewDecoder(reader).Decode(obj); err != nil { return fmt.Errorf("failed to decode cached data: %w", err) diff --git a/util/cert/cert.go b/util/cert/cert.go index 27e4231cf5e8c..61333eda4dd90 100644 --- a/util/cert/cert.go +++ b/util/cert/cert.go @@ -80,9 +80,8 @@ var validFQDNRegexp = regexp.MustCompile(`^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{ func IsValidHostname(hostname string, fqdn bool) bool { if !fqdn { return validHostNameRegexp.Match([]byte(hostname)) || validIPv6Regexp.Match([]byte(hostname)) - } else { - return validFQDNRegexp.Match([]byte(hostname)) } + return validFQDNRegexp.Match([]byte(hostname)) } // Get the configured path to where TLS certificates are stored on the local @@ -91,9 +90,8 @@ func IsValidHostname(hostname string, fqdn bool) bool { func GetTLSCertificateDataPath() string { if envPath := os.Getenv(common.EnvVarTLSDataPath); envPath != "" { return envPath - } else { - return common.DefaultPathTLSConfig } + return common.DefaultPathTLSConfig } // Get the configured path to where SSH certificates are stored on the local @@ -102,9 +100,8 @@ func GetTLSCertificateDataPath() string { func GetSSHKnownHostsDataPath() string { if envPath := os.Getenv(common.EnvVarSSHDataPath); envPath != "" { return filepath.Join(envPath, common.DefaultSSHKnownHostsName) - } else { - return filepath.Join(common.DefaultPathSSHConfig, common.DefaultSSHKnownHostsName) } + return filepath.Join(common.DefaultPathSSHConfig, common.DefaultSSHKnownHostsName) } // Decode a certificate in PEM format to X509 data structure @@ -326,9 +323,8 @@ func GetCertificateForConnect(serverName string) ([]string, error) { if err != nil { if os.IsNotExist(err) { return nil, nil - } else { - return nil, err } + return nil, err } if len(certificates) == 0 { diff --git a/util/db/certificate.go b/util/db/certificate.go index 1b45d68657889..4a7b7c2f50fb1 100644 --- a/util/db/certificate.go +++ b/util/db/certificate.go @@ -204,16 +204,15 @@ func (db *db) CreateRepoCertificate(ctx context.Context, certificates *appsv1.Re if entry.Host == certificate.ServerName && entry.SubType == certificate.CertSubType { if !upsert && entry.Data != string(certificate.CertData) { return nil, fmt.Errorf("Key for '%s' (subtype: '%s') already exist and upsert was not specified.", entry.Host, entry.SubType) - } else { - // Do not add an entry on upsert, but remember if we actual did an - // upsert. - newEntry = false - if entry.Data != string(certificate.CertData) { - entry.Data = string(certificate.CertData) - upserted = true - } - break } + // Do not add an entry on upsert, but remember if we actual did an + // upsert. + newEntry = false + if entry.Data != string(certificate.CertData) { + entry.Data = string(certificate.CertData) + upserted = true + } + break } } diff --git a/util/db/gpgkeys.go b/util/db/gpgkeys.go index 28b6934668f16..a28740a30be80 100644 --- a/util/db/gpgkeys.go +++ b/util/db/gpgkeys.go @@ -51,9 +51,8 @@ func validatePGPKey(keyData string) (*appsv1.GnuPGPublicKey, error) { if retKey != nil { retKey.KeyData = keyData return retKey, nil - } else { - return nil, errors.New("Could not find the GPG key") } + return nil, errors.New("Could not find the GPG key") } // ListConfiguredGPGPublicKeys returns a list of all configured GPG public keys from the ConfigMap diff --git a/util/db/repository_legacy.go b/util/db/repository_legacy.go index f84333ba5a27c..24aff4da5dc99 100644 --- a/util/db/repository_legacy.go +++ b/util/db/repository_legacy.go @@ -341,11 +341,10 @@ func (l *legacyRepositoryBackend) upsertSecret(name string, data map[string][]by return l.db.kubeclientset.CoreV1().Secrets(l.db.ns).Delete(context.Background(), name, metav1.DeleteOptions{}) } return nil - } else { - _, err = l.db.kubeclientset.CoreV1().Secrets(l.db.ns).Update(context.Background(), secret, metav1.UpdateOptions{}) - if err != nil { - return err - } + } + _, err = l.db.kubeclientset.CoreV1().Secrets(l.db.ns).Update(context.Background(), secret, metav1.UpdateOptions{}) + if err != nil { + return err } } return nil diff --git a/util/dex/dex.go b/util/dex/dex.go index b91f0f4d8bac9..4e3148965a321 100644 --- a/util/dex/dex.go +++ b/util/dex/dex.go @@ -129,11 +129,9 @@ func (s DexRewriteURLRoundTripper) RoundTrip(r *http.Request) (*http.Response, e func DexServerAddressWithProtocol(orig string, tlsConfig *DexTLSConfig) string { if strings.Contains(orig, "://") { return orig - } else { - if tlsConfig == nil || tlsConfig.DisableTLS { - return "http://" + orig - } else { - return "https://" + orig - } } + if tlsConfig == nil || tlsConfig.DisableTLS { + return "http://" + orig + } + return "https://" + orig } diff --git a/util/git/client.go b/util/git/client.go index 3625edbbdac95..e648324ba34b2 100644 --- a/util/git/client.go +++ b/util/git/client.go @@ -381,9 +381,8 @@ func (m *nativeGitClient) IsRevisionPresent(revision string) bool { out, err := m.runCmdOutput(cmd, runOpts{SkipErrorLogging: true}) if out == "commit" && err == nil { return true - } else { - return false } + return false } // Fetch fetches latest updates from origin @@ -438,16 +437,15 @@ func (m *nativeGitClient) LsFiles(path string, enableNewGitFileGlobbing bool) ([ } } return files, nil - } else { - // This is the old and default way - out, err := m.runCmd("ls-files", "--full-name", "-z", "--", path) - if err != nil { - return nil, err - } - // remove last element, which is blank regardless of whether we're using nullbyte or newline - ss := strings.Split(out, "\000") - return ss[:len(ss)-1], nil } + // This is the old and default way + out, err := m.runCmd("ls-files", "--full-name", "-z", "--", path) + if err != nil { + return nil, err + } + // remove last element, which is blank regardless of whether we're using nullbyte or newline + ss := strings.Split(out, "\000") + return ss[:len(ss)-1], nil } // LsLargeFiles lists all files that have references to LFS storage @@ -795,9 +793,8 @@ func (m *nativeGitClient) IsAnnotatedTag(revision string) bool { out, err := m.runCmdOutput(cmd, runOpts{SkipErrorLogging: true}) if out != "" && err == nil { return true - } else { - return false } + return false } // ChangedFiles returns a list of files changed between two revisions diff --git a/util/gpg/gpg.go b/util/gpg/gpg.go index b3cf979b608b3..9d93bc787db6e 100644 --- a/util/gpg/gpg.go +++ b/util/gpg/gpg.go @@ -66,11 +66,7 @@ type PGPKeyID string func isHexString(s string) bool { _, err := hex.DecodeString(s) - if err != nil { - return false - } else { - return true - } + return err == nil } // KeyID get the actual correct (short) key ID from either a fingerprint or the key ID. Returns the empty string if k seems not to be a PGP key ID. @@ -88,18 +84,16 @@ func KeyID(k string) string { func IsLongKeyID(k string) bool { if len(k) == 40 && isHexString(k) { return true - } else { - return false } + return false } // IsShortKeyID returns true if the string represents a short key ID func IsShortKeyID(k string) bool { if len(k) == 16 && isHexString(k) { return true - } else { - return false } + return false } // Result of a git commit verification @@ -186,9 +180,8 @@ func removeKeyRing(path string) error { if err != nil { if os.IsNotExist(err) { return fmt.Errorf("refusing to remove directory %s: it's not initialized by Argo CD", path) - } else { - return err } + return err } rd, err := os.Open(path) if err != nil { @@ -679,10 +672,9 @@ func ParseGitCommitVerification(signature string) PGPVerifyResult { } else if linesParsed >= MaxVerificationLinesToParse { // Too many output lines, return error return unknownResult("Too many lines of gpg verify-commit output, abort.") - } else { - // No data found, return error - return unknownResult("Could not parse output of verify-commit, no verification data found.") } + // No data found, return error + return unknownResult("Could not parse output of verify-commit, no verification data found.") } // SyncKeyRingFromDirectory will sync the GPG keyring with files in a directory. This is a one-way sync, diff --git a/util/helm/client.go b/util/helm/client.go index d9972adb04968..fad942f1195c4 100644 --- a/util/helm/client.go +++ b/util/helm/client.go @@ -113,9 +113,8 @@ func fileExist(filePath string) (bool, error) { if _, err := os.Stat(filePath); err != nil { if os.IsNotExist(err) { return false, nil - } else { - return false, fmt.Errorf("error checking file existence for %s: %w", filePath, err) } + return false, fmt.Errorf("error checking file existence for %s: %w", filePath, err) } return true, nil } diff --git a/util/io/path/resolved.go b/util/io/path/resolved.go index 94ce9288db48e..f4411d3c98c9d 100644 --- a/util/io/path/resolved.go +++ b/util/io/path/resolved.go @@ -119,9 +119,8 @@ func ResolveValueFilePathOrUrl(appPath, repoRoot, valueFile string, allowedURLSc if url.Scheme != "" { if isURLSchemeAllowed(url.Scheme, allowedURLSchemes) { return ResolvedFilePath(valueFile), true, nil - } else { - return "", false, fmt.Errorf("the URL scheme '%s' is not allowed", url.Scheme) } + return "", false, fmt.Errorf("the URL scheme '%s' is not allowed", url.Scheme) } } diff --git a/util/lua/custom_actions_test.go b/util/lua/custom_actions_test.go index 8df7c78975e93..8329ce2efbb2a 100644 --- a/util/lua/custom_actions_test.go +++ b/util/lua/custom_actions_test.go @@ -165,9 +165,8 @@ func TestLuaResourceActionsScript(t *testing.T) { // TODO: maybe this should use a normalizer function instead of hard-coding the resource specifics here if (result.GetKind() == "Job" && sourceObj.GetKind() == "CronJob") || (result.GetKind() == "Workflow" && (sourceObj.GetKind() == "CronWorkflow" || sourceObj.GetKind() == "WorkflowTemplate")) { return u.GroupVersionKind() == result.GroupVersionKind() && strings.HasPrefix(u.GetName(), sourceObj.GetName()) && u.GetNamespace() == result.GetNamespace() - } else { - return u.GroupVersionKind() == result.GroupVersionKind() && u.GetName() == result.GetName() && u.GetNamespace() == result.GetNamespace() } + return u.GroupVersionKind() == result.GroupVersionKind() && u.GetName() == result.GetName() && u.GetNamespace() == result.GetNamespace() }) assert.NotNil(t, expectedObj) diff --git a/util/lua/oslib_safe.go b/util/lua/oslib_safe.go index 2d5a94e9463f2..1e9b1418002dc 100644 --- a/util/lua/oslib_safe.go +++ b/util/lua/oslib_safe.go @@ -162,22 +162,21 @@ func (fs *flagScanner) Next() (byte, bool) { fs.AppendString(fs.end) } return c, true - } else { - c = fs.str[fs.Pos] - if c == fs.flag { - if fs.Pos < (fs.Length-1) && fs.str[fs.Pos+1] == fs.flag { - fs.HasFlag = false - fs.AppendChar(fs.flag) - fs.Pos += 2 - return fs.Next() - } else if fs.Pos != fs.Length-1 { - if fs.HasFlag { - fs.AppendString(fs.end) - } - fs.AppendString(fs.start) - fs.ChangeFlag = true - fs.HasFlag = true + } + c = fs.str[fs.Pos] + if c == fs.flag { + if fs.Pos < (fs.Length-1) && fs.str[fs.Pos+1] == fs.flag { + fs.HasFlag = false + fs.AppendChar(fs.flag) + fs.Pos += 2 + return fs.Next() + } else if fs.Pos != fs.Length-1 { + if fs.HasFlag { + fs.AppendString(fs.end) } + fs.AppendString(fs.start) + fs.ChangeFlag = true + fs.HasFlag = true } } fs.Pos++ diff --git a/util/security/rbac.go b/util/security/rbac.go index d80cbbadb3817..dbb56eeb121aa 100644 --- a/util/security/rbac.go +++ b/util/security/rbac.go @@ -8,7 +8,6 @@ import ( func RBACName(defaultNS string, project string, namespace string, name string) string { if defaultNS != "" && namespace != defaultNS && namespace != "" { return fmt.Sprintf("%s/%s/%s", project, namespace, name) - } else { - return fmt.Sprintf("%s/%s", project, name) } + return fmt.Sprintf("%s/%s", project, name) } diff --git a/util/settings/accounts.go b/util/settings/accounts.go index e3408b20e7a8a..ac38502d969ab 100644 --- a/util/settings/accounts.go +++ b/util/settings/accounts.go @@ -296,11 +296,11 @@ func parseAccounts(secret *corev1.Secret, cm *corev1.ConfigMap) (map[string]Acco account.PasswordHash = string(passwordHash) } if passwordMtime, ok := secret.Data[fmt.Sprintf("%s.%s.%s", accountsKeyPrefix, name, accountPasswordMtimeSuffix)]; ok { - if mTime, err := time.Parse(time.RFC3339, string(passwordMtime)); err != nil { + mTime, err := time.Parse(time.RFC3339, string(passwordMtime)) + if err != nil { return nil, err - } else { - account.PasswordMtime = &mTime } + account.PasswordMtime = &mTime } if tokensStr, ok := secret.Data[fmt.Sprintf("%s.%s.%s", accountsKeyPrefix, name, accountTokensSuffix)]; ok { account.Tokens = make([]Token, 0) diff --git a/util/tls/tls.go b/util/tls/tls.go index 09a15ff08c3a5..53e6eff024b13 100644 --- a/util/tls/tls.go +++ b/util/tls/tls.go @@ -345,14 +345,13 @@ func LoadX509CertPool(paths ...string) (*x509.CertPool, error) { } // ...but everything else is considered an error return nil, fmt.Errorf("could not load TLS certificate: %w", err) - } else { - f, err := os.ReadFile(path) - if err != nil { - return nil, fmt.Errorf("failure to load TLS certificates from %s: %w", path, err) - } - if ok := pool.AppendCertsFromPEM(f); !ok { - return nil, fmt.Errorf("invalid cert data in %s", path) - } + } + f, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("failure to load TLS certificates from %s: %w", path, err) + } + if ok := pool.AppendCertsFromPEM(f); !ok { + return nil, fmt.Errorf("invalid cert data in %s", path) } } return pool, nil From a807c0eb69c8a5744792557f54908073d5805582 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 7 Jan 2025 16:24:51 +0000 Subject: [PATCH 36/41] chore(deps): bump golang.org/x/net from 0.33.0 to 0.34.0 (#21396) Bumps [golang.org/x/net](https://github.com/golang/net) from 0.33.0 to 0.34.0. - [Commits](https://github.com/golang/net/compare/v0.33.0...v0.34.0) --- updated-dependencies: - dependency-name: golang.org/x/net dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Ishita Sequeira <46771830+ishitasequeira@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 457f21529c330..363ed59309bf5 100644 --- a/go.mod +++ b/go.mod @@ -85,7 +85,7 @@ require ( go.opentelemetry.io/otel/sdk v1.33.0 golang.org/x/crypto v0.32.0 golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f - golang.org/x/net v0.33.0 + golang.org/x/net v0.34.0 golang.org/x/oauth2 v0.25.0 golang.org/x/sync v0.10.0 golang.org/x/term v0.28.0 diff --git a/go.sum b/go.sum index 0621735e87970..ad1123332b949 100644 --- a/go.sum +++ b/go.sum @@ -1136,8 +1136,8 @@ golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= -golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= -golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= +golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= From 4fee6b51e071b0a33da262b6d86327db4709dc01 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 7 Jan 2025 13:42:44 -0500 Subject: [PATCH 37/41] chore(deps): update dependency pymdown-extensions to v10.14 (#21403) Signed-off-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- docs/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/requirements.txt b/docs/requirements.txt index f6b11bb0a0a31..6bcc922643596 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -6,4 +6,4 @@ markdown_include==0.8.1 pygments==2.19.1 jinja2==3.1.5 markdown==3.7 -pymdown-extensions==10.13 \ No newline at end of file +pymdown-extensions==10.14 \ No newline at end of file From 77ad48aa09c301b41fdbaee5908a5b18b3f93a26 Mon Sep 17 00:00:00 2001 From: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> Date: Tue, 7 Jan 2025 14:38:51 -0500 Subject: [PATCH 38/41] chore(ci): run codegen as part of version bump job (#21404) * chore(ci): run codegen as part of version bump Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * preserve go.mod changes Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * more logging Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * add more excluded paths Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * git status Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * more debugging Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * maybe Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * remove debugging stuff Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> --------- Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> --- .github/workflows/bump-major-version.yaml | 36 +++++++++++++++++++++++ hack/bump-major-version.sh | 12 ++++---- 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/.github/workflows/bump-major-version.yaml b/.github/workflows/bump-major-version.yaml index b9dc0d77f7cb2..3a21886eb118e 100644 --- a/.github/workflows/bump-major-version.yaml +++ b/.github/workflows/bump-major-version.yaml @@ -30,6 +30,42 @@ jobs: run: | hack/bump-major-version.sh + - name: Setup Golang + uses: actions/setup-go@3041bf56c941b39c61721a86cd11f3bb1338122a # v5.2.0 + with: + go-version: ${{ env.GOLANG_VERSION }} + - name: Create symlink in GOPATH + run: | + mkdir -p ~/go/src/github.com/argoproj + cp -a ../argo-cd ~/go/src/github.com/argoproj + - name: Add ~/go/bin to PATH + run: | + echo "/home/runner/go/bin" >> $GITHUB_PATH + - name: Add /usr/local/bin to PATH + run: | + echo "/usr/local/bin" >> $GITHUB_PATH + - name: Download & vendor dependencies + run: | + # We need to vendor go modules for codegen yet + go mod download + go mod vendor -v + working-directory: /home/runner/go/src/github.com/argoproj/argo-cd + - name: Install toolchain for codegen + run: | + make install-codegen-tools-local + make install-go-tools-local + working-directory: /home/runner/go/src/github.com/argoproj/argo-cd + # We install kustomize in the dist directory + - name: Add dist to PATH + run: | + echo "/home/runner/work/argo-cd/argo-cd/dist" >> $GITHUB_PATH + - name: Run codegen + run: | + set -x + export GOPATH=$(go env GOPATH) + make codegen-local + working-directory: /home/runner/go/src/github.com/argoproj/argo-cd + - name: Create pull request uses: peter-evans/create-pull-request@5e914681df9dc83aa4e4905692ca88beb2f9e91f # v7.0.5 with: diff --git a/hack/bump-major-version.sh b/hack/bump-major-version.sh index c15693e55450c..931bb57ef5b9b 100755 --- a/hack/bump-major-version.sh +++ b/hack/bump-major-version.sh @@ -11,22 +11,22 @@ echo "Upgrading from v${CURRENT_VERSION} to v$((CURRENT_VERSION + 1))..." for file in .golangci.yaml .goreleaser.yaml .mockery.yaml Makefile Procfile; do echo "Incrementing the major version in $file..." - sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" "$file" && rm "$file.bak" + sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" "$file" && echo " Updated $file" && rm "$file.bak" done for file in hack/generate-proto.sh hack/update-codegen.sh hack/update-openapi.sh; do echo "Incrementing the major version in $file..." - sed -i.bak "s/v${CURRENT_VERSION}/v$((CURRENT_VERSION + 1))/g" "$file" && rm "$file.bak" + sed -i.bak "s/v${CURRENT_VERSION}/v$((CURRENT_VERSION + 1))/g" "$file" && echo " Update $file" && rm "$file.bak" done echo "Incrementing the major version in proto files..." -find . -name '*.proto' -exec sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" {} \; -exec rm {}.bak \; -find . -name '*.proto' -exec sed -i.bak "s/github\.com.\argoproj\.argo_cd\.v${CURRENT_VERSION}/github\.com.\argoproj\.argo_cd\.v$((CURRENT_VERSION + 1))/g" {} \; -exec rm {}.bak \; +find . -name '*.proto' -not -path "./vendor/*" -not -path "./dist/*" -exec sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" {} \; -exec echo " Updated" {} \; -exec rm {}.bak \; +find . -name '*.proto' -not -path "./vendor/*" -not -path "./dist/*" -exec sed -i.bak "s/github\.com\.argoproj\.argo_cd\.v${CURRENT_VERSION}/github\.com\.argoproj\.argo_cd\.v$((CURRENT_VERSION + 1))/g" {} \; -exec echo " Updated" {} \; -exec rm {}.bak \; echo "Incrementing the major version in go files..." -find . -name '*.go' -exec sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" {} \; -exec rm {}.bak \; +find . -name '*.go' -not -path "./vendor/*" -not -path "./dist/*" -exec sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" {} \; -exec echo " Updated" {} \; -exec rm {}.bak \; echo "Incrementing the major version in go.mod..." -sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" go.mod && rm go.mod.bak +sed -i.bak "s/github\.com\/argoproj\/argo-cd\/v${CURRENT_VERSION}/github\.com\/argoproj\/argo-cd\/v$((CURRENT_VERSION + 1))/g" go.mod && echo " Updated go.mod" && rm go.mod.bak echo 'Finished! Now run `make codegen-local && make lint-local && make test-local` to ensure everything is working as expected.' From fe8bab0406467112e7d52466900717b8cf21bbfb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 7 Jan 2025 14:41:26 -0500 Subject: [PATCH 39/41] chore(deps): bump library/redis from 7.4.1 to 7.4.2 in /test/container (#21395) Bumps library/redis from 7.4.1 to 7.4.2. --- updated-dependencies: - dependency-name: library/redis dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- test/container/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/container/Dockerfile b/test/container/Dockerfile index cd9179aeb9857..10ef98bf2feb5 100644 --- a/test/container/Dockerfile +++ b/test/container/Dockerfile @@ -1,4 +1,4 @@ -FROM docker.io/library/redis:7.4.1@sha256:05f99264e2928ad472f2751b3a8d1f65c9c2cc1819be04548b2261c08e2e026b as redis +FROM docker.io/library/redis:7.4.2@sha256:cd13b924409d740ea8abe6677a7d1accf696898408d330a3d7c8234fa7545775 as redis # There are libraries we will want to copy from here in the final stage of the # build, but the COPY directive does not have a way to determine system From 05c76253f0574c3a98134bca6319a71f257f5705 Mon Sep 17 00:00:00 2001 From: rumstead <37445536+rumstead@users.noreply.github.com> Date: Tue, 7 Jan 2025 16:39:14 -0500 Subject: [PATCH 40/41] fix(ci): updating action-gh-release after upstream fix (#21407) Signed-off-by: rumstead <37445536+rumstead@users.noreply.github.com> --- .github/workflows/release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 9629af2581fa2..7d5796949ee8e 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -195,7 +195,7 @@ jobs: echo "hashes=$(sha256sum /tmp/sbom.tar.gz | base64 -w0)" >> "$GITHUB_OUTPUT" - name: Upload SBOM - uses: softprops/action-gh-release@7b4da11513bf3f43f9999e90eabced41ab8bb048 # v2.2.0 + uses: softprops/action-gh-release@c95fe1489396fe8a9eb87c0abf8aa5b2ef267fda # v2.2.1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: From 06bd2ad10f5124ba98364a85ff1ec42947d34706 Mon Sep 17 00:00:00 2001 From: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> Date: Tue, 7 Jan 2025 17:46:31 -0500 Subject: [PATCH 41/41] fix(ci): all version bump changes go in the PR (#21409) * chore(ci): fix version bump codegen Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * link, not copy Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * make directory Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * maybe backwards Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * what's up Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * what's up Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * what's up Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * I give up Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * remove silliness Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * somehow Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * frustration Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * who knows Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> * oops Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> --------- Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com> --- .github/workflows/bump-major-version.yaml | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/.github/workflows/bump-major-version.yaml b/.github/workflows/bump-major-version.yaml index 3a21886eb118e..b7fbf7101a34d 100644 --- a/.github/workflows/bump-major-version.yaml +++ b/.github/workflows/bump-major-version.yaml @@ -26,18 +26,20 @@ jobs: CURRENT_VERSION=$(grep 'module github.com/argoproj/argo-cd' go.mod | awk '{print $2}' | sed 's/.*\/v//') echo "TARGET_VERSION=$((CURRENT_VERSION + 1))" >> $GITHUB_OUTPUT + - name: Copy source code to GOPATH + run: | + mkdir -p ~/go/src/github.com/argoproj + cp -a ../argo-cd ~/go/src/github.com/argoproj + - name: Run script to bump the version run: | hack/bump-major-version.sh + working-directory: /home/runner/go/src/github.com/argoproj/argo-cd - name: Setup Golang uses: actions/setup-go@3041bf56c941b39c61721a86cd11f3bb1338122a # v5.2.0 with: go-version: ${{ env.GOLANG_VERSION }} - - name: Create symlink in GOPATH - run: | - mkdir -p ~/go/src/github.com/argoproj - cp -a ../argo-cd ~/go/src/github.com/argoproj - name: Add ~/go/bin to PATH run: | echo "/home/runner/go/bin" >> $GITHUB_PATH @@ -66,6 +68,11 @@ jobs: make codegen-local working-directory: /home/runner/go/src/github.com/argoproj/argo-cd + - name: Copy changes back + run: | + # Copy the contents back, but skip the .git directory + rsync -a --exclude=.git /home/runner/go/src/github.com/argoproj/argo-cd/ ../argo-cd + - name: Create pull request uses: peter-evans/create-pull-request@5e914681df9dc83aa4e4905692ca88beb2f9e91f # v7.0.5 with: @@ -79,4 +86,4 @@ jobs: - [ ] Add an upgrade guide to the docs for this version branch: bump-major-version branch-suffix: random - signoff: true + signoff: true \ No newline at end of file